text
stringlengths 0
3.34M
|
---|
<a href="https://colab.research.google.com/github/tsai-jiewen/N4EM/blob/main/docs/Untitled9.ipynb" target="_parent"></a>
```python
%load_ext rpy2.ipython
```
```r
%%R
install.packages('psych')
```
```python
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 1000)
plt.plot(x, np.sin(x));
plt.show()
```
```python
!pip3 install http://download.pytorch.org/whl/cu80/torch-0.3.0.post4-cp36-cp36m-linux_x86_64.whl
!pip3 install torchvision
```
[31mERROR: torch-0.3.0.post4-cp36-cp36m-linux_x86_64.whl is not a supported wheel on this platform.[0m
Requirement already satisfied: torchvision in /usr/local/lib/python3.7/dist-packages (0.11.1+cu111)
Requirement already satisfied: pillow!=8.3.0,>=5.3.0 in /usr/local/lib/python3.7/dist-packages (from torchvision) (7.1.2)
Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from torchvision) (1.19.5)
Requirement already satisfied: torch==1.10.0 in /usr/local/lib/python3.7/dist-packages (from torchvision) (1.10.0+cu111)
Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch==1.10.0->torchvision) (3.10.0.2)
```python
from sympy import Integral, sqrt, symbols, init_printing
init_printing()
x = symbols('x')
Integral(sqrt(1 / x), x)
```
```r
%%R
library(tidyverse)
library(psych)
dat_loan <- read.table('loan.txt', header=T)
```
```r
%%R
des <- psych::describe(dat_loan)
```
```r
%%R
c(1:10) |> sum()
```
[1] 55
```r
%%R
sessionInfo()
```
R version 4.1.2 (2021-11-01)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 18.04.5 LTS
Matrix products: default
BLAS: /usr/lib/x86_64-linux-gnu/openblas/libblas.so.3
LAPACK: /usr/lib/x86_64-linux-gnu/openblas/liblapack.so.3
locale:
[1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
[3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
[5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
[7] LC_PAPER=en_US.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] tools stats graphics grDevices utils datasets methods
[8] base
other attached packages:
[1] forcats_0.5.1 stringr_1.4.0 dplyr_1.0.7 purrr_0.3.4
[5] readr_2.1.1 tidyr_1.1.4 tibble_3.1.6 ggplot2_3.3.5
[9] tidyverse_1.3.1
loaded via a namespace (and not attached):
[1] Rcpp_1.0.7 cellranger_1.1.0 pillar_1.6.4 compiler_4.1.2
[5] dbplyr_2.1.1 jsonlite_1.7.2 lubridate_1.8.0 lifecycle_1.0.1
[9] gtable_0.3.0 pkgconfig_2.0.3 rlang_0.4.12 reprex_2.0.1
[13] cli_3.1.0 rstudioapi_0.13 DBI_1.1.2 haven_2.4.3
[17] xml2_1.3.3 withr_2.4.3 httr_1.4.2 fs_1.5.2
[21] generics_0.1.1 vctrs_0.3.8 hms_1.1.1 grid_4.1.2
[25] tidyselect_1.1.1 glue_1.6.0 R6_2.5.1 fansi_0.5.0
[29] readxl_1.3.1 tzdb_0.2.0 modelr_0.1.8 magrittr_2.0.1
[33] backports_1.4.1 scales_1.1.1 ellipsis_0.3.2 rvest_1.0.2
[37] assertthat_0.2.1 colorspace_2.0-2 utf8_1.2.2 stringi_1.7.6
[41] munsell_0.5.0 broom_0.7.10 crayon_1.4.2
```python
%%shell
jupyter nbconvert --to html /content/Untitled9.ipynb
```
[NbConvertApp] Converting notebook /content/Untitled9.ipynb to html
[NbConvertApp] Writing 302251 bytes to /content/Untitled9.html
|
Require Extraction.
Set Implicit Arguments.
(** * Extraction of Standard Types to Ocaml *)
(* ===================================== *)
Extract Inductive bool => "bool" [ "true" "false" ].
Extract Inductive sumbool => "bool" [ "true" "false" ].
Extract Inductive sumor => option [ Some None ].
Extract Inductive unit => unit [ "()" ].
Extract Inductive list => "list" [ "[]" "(::)" ].
Extract Inductive option => option [ Some None ].
Extract Inductive prod => "( * )" [ "" ]. (* "" instead of "(,)" *)
Extract Inlined Constant andb => "(&&)".
Extract Inlined Constant orb => "(||)".
(** * Propositions *)
(* ============ *)
Definition ex_falso {A:Type} (p:False):A :=
match p with end.
Module And.
Theorem make3 {A B C:Prop} (a:A) (b:B) (c:C) : A /\ B /\ C.
Proof
conj a (conj b c).
Theorem make4 {A B C D:Prop} (a:A) (b:B) (c:C) (d:D) : A /\ B /\ C /\ D.
Proof
conj a (conj b (conj c d)).
Theorem use {A B C:Prop} (p:A/\B) (f:A->B->C): C.
Proof
match p with
conj a b => f a b
end.
Theorem use3 {A B C D:Prop} (p:A/\B/\C) (f:A->B->C->D): D.
Proof
match p with
conj a (conj b c) => f a b c
end.
Theorem use4 {A B C D E:Prop} (p:A/\B/\C/\D) (f:A->B->C->D->E): E.
Proof
match p with
conj a (conj b (conj c d)) => f a b c d
end.
Theorem use8
{A B C D E F G H R:Prop}
(p:A/\B/\C/\D/\E/\F/\G/\H)
(q:A -> B -> C -> D -> E -> F -> G -> H -> R) : R.
Proof
match p with
conj a (conj b (conj c (conj d (conj e (conj f (conj g h)))))) =>
q a b c d e f g h
end.
Theorem use9
{A B C D E F G H K R:Prop}
(p:A/\B/\C/\D/\E/\F/\G/\H/\K)
(q:A -> B -> C -> D -> E -> F -> G -> H -> K -> R) : R.
Proof
match p with
conj a (conj b (conj c (conj d (conj e (conj f (conj g (conj h k))))))) =>
q a b c d e f g h k
end.
Theorem proj1 {A B:Prop} (p:A/\B): A.
Proof
use p (fun a b => a).
Theorem proj2 {A B:Prop} (p:A/\B): B.
Proof
use p (fun a b => b).
End And.
Module Or.
Definition use {A B C:Prop} (p:A\/B) (f:A->C) (g:B->C): C :=
match p with
| or_introl a => f a
| or_intror b => g b
end.
End Or.
Module Sigma.
Definition value {A:Type} {P:A->Prop} (s:sig P): A :=
match s with
exist _ v _ => v
end.
Definition proof {A:Type} {P:A->Prop} (s:sig P): P (value s) :=
match s with
exist _ _ p => p
end.
Definition use {A B:Type} {P:A->Prop} (s:sig P) (f:forall a, P a -> B): B :=
match s with
exist _ v p => f v p
end.
Definition use2 {A B:Type} {P1 P2:A->Prop}
(s:sig (fun a => P1 a /\ P2 a))
(f:forall a, P1 a -> P2 a -> B): B :=
match s with
exist _ v (conj p1 p2) => f v p1 p2
end.
Definition use3 {A B:Type} {P1 P2 P3:A->Prop}
(s:sig (fun a => P1 a /\ P2 a /\ P3 a))
(f:forall a, P1 a -> P2 a -> P3 a -> B): B :=
match s with
exist _ v (conj p1 (conj p2 p3)) => f v p1 p2 p3
end.
Definition use4 {A B:Type} {P1 P2 P3 P4:A->Prop}
(s:sig (fun a => P1 a /\ P2 a /\ P3 a /\ P4 a))
(f:forall a, P1 a -> P2 a -> P3 a -> P4 a -> B): B :=
match s with
exist _ v (conj p1 (conj p2 (conj p3 p4))) => f v p1 p2 p3 p4
end.
End Sigma.
Module Exist.
Definition
make2
{A B:Type} {P:A->B->Prop} {a:A} {b:B} (p: P a b) : exists a b, P a b :=
ex_intro _ a (ex_intro _ b p).
Definition use {A:Type} {P:A->Prop} {B:Prop}
(e:exists a, P a) (f:forall a, P a -> B): B :=
match e with
ex_intro _ v p => f v p
end.
Definition use2 {A B:Type} {P:A->B->Prop} {C:Prop}
(e:exists a b, P a b) (f:forall a b, P a b -> C): C :=
match e with
ex_intro _ a e2 =>
match e2 with
ex_intro _ b p => f a b p
end
end.
End Exist.
(** * Equality *)
(* ======== *)
Module Equal.
Section equal_basics.
Variables A B C: Type.
Theorem use {a b:A} (eq:a=b) (T:A->Type) (pa:T a): T b.
Proof
match eq with
eq_refl => pa
end.
Theorem use2 {a1 b1:A} {a2 b2:B}
(eq1:a1=b1) (eq2:a2=b2) (T:A->B->Type) (p: T a1 a2)
: T b1 b2.
Proof
match eq1 with
eq_refl =>
match eq2 with
eq_refl => p
end
end.
Theorem use3 {a1 b1:A} {a2 b2:B} {a3 b3:C}
(eq1:a1=b1) (eq2:a2=b2) (eq3:a3=b3) (T:A->B->C->Type) (p: T a1 a2 a3)
: T b1 b2 b3.
Proof
match eq1 with
eq_refl =>
match eq2 with
eq_refl =>
match eq3 with
eq_refl => p
end
end
end.
Theorem
rewrite0 (a b:A) (p:a = b) (P:A->Type) (pa:P a): P b.
Proof
match p in (_ = x) return P x with
| eq_refl => pa
end.
Theorem
rewrite {a b:A} (P:A->Type) (p:a = b) (pa:P a): P b.
Proof
match p in (_ = x) return P x with
| eq_refl => pa
end.
Theorem
inject {a b:A} (p:a=b) (f:A->B): f a = f b.
Proof
match p in (_ = x) return f a = f x with
| eq_refl => eq_refl
end.
Theorem inject2 {a1 a2:A} {b1 b2:B}
(pa:a1=a2) (pb:b1=b2) (f:A->B->C): f a1 b1 = f a2 b2.
Proof
match pa in (_ = x), pb in (_ = y) return f a1 b1 = f x y with
eq_refl, eq_refl => eq_refl
end.
Theorem
flip {a b:A} (p:a=b): b=a.
Proof
rewrite0 p (fun x => x=a) eq_refl.
Theorem
join (a b c:A) (pab:a=b) (pbc:b=c): a=c.
Proof
rewrite0 pbc (fun x => a=x) pab.
Theorem
flip_not_equal {a b:A} (p:a<>b): b<>a.
Proof
(* p: a=b -> False
goal: b=a -> False
*)
fun q:b=a => p (flip q).
Theorem use_bwd {a b:A} (eq:a=b) (T:A->Type) (pb:T b): T a.
Proof
use (flip eq) T pb.
Theorem
rewrite_bwd {a b:A} (P:A->Type) (p:a = b) (pb:P b): P a.
Proof
rewrite P (flip p) pb.
Definition Decider: Type := forall a b:A, {a = b} + {a <> b}.
End equal_basics.
Section application.
Variables A B: Type.
Theorem application:
forall (f g: A -> B) (a b:A), f = g -> a = b -> f a = g b.
Proof
fun f g a b eqfg eqab =>
join
((join
(eq_refl: f a = f a)
(inject eqab _: f a = f b)): f a = f b)
(rewrite0 eqfg (fun g => f b = g b) eq_refl: f b = g b).
End application.
Module Notations.
Notation "( 'equality_chain:' x , y , .. , z )" :=
(Equal.join .. (Equal.join x y) .. z) (at level 0): equality_scope.
Notation "( 'equal_arguments:' eq1 , .. , eqn )" :=
(Equal.application .. (Equal.application eq_refl eq1) .. eqn)
(at level 0): equality_scope.
Open Scope equality_scope.
End Notations.
End Equal.
(** * Predicate *)
(* ========= *)
(** A predicate represents an arbitrary set of elements of a certain type.*)
Module Predicate.
Section predicate_basic.
Variable A: Type.
Definition Decider (P:A->Prop): Type :=
forall a:A, {P a} + {~ P a}.
Definition Empty (P:A->Prop): Prop := forall x, ~ P x.
Definition Universal (P:A->Prop): Prop := forall x, P x.
Definition Add (a:A) (P:A->Prop): A->Prop :=
fun x => x = a \/ P x.
Definition Remove (a:A) (P:A->Prop): A->Prop :=
fun x => x <> a /\ P x.
Definition Union (P Q:A->Prop): A->Prop :=
fun x => P x \/ Q x.
Definition Intersection (P Q:A->Prop): A->Prop :=
fun x => P x /\ Q x.
Definition Subset (P Q:A->Prop): Prop :=
forall x, P x -> Q x.
Definition Not (P:A->Prop): A->Prop :=
fun x => ~ (P x).
End predicate_basic.
End Predicate.
(** * Relations *)
(* ========= *)
Module Relation.
Section basics.
Definition Binary (A:Type) (B:Type):Type := A -> B -> Prop.
Definition Endo (A:Type) :Type := A -> A -> Prop.
End basics.
Section binary_relation.
Variable A B: Type.
Variable R: A -> B -> Prop.
Definition Decider: Type := forall (a:A) (b:B), {R a b} + {~ R a b}.
Definition Domain (a:A): Prop :=
exists b:B, R a b.
Definition Range (b:B): Prop :=
exists a:A, R a b.
Definition Left_total: Prop :=
forall a, Domain a.
Definition Right_total: Prop :=
forall b, Range b.
Definition Total: Prop :=
Left_total /\ Right_total.
Theorem total_all_in_domain:
Total -> forall a, Domain a.
Proof
fun total a =>
match total with
| conj left_total _ =>
left_total a
end.
Theorem total_all_in_range:
Total -> forall a, Range a.
Proof
fun total a =>
match total with
| conj _ right_total =>
right_total a
end.
Definition Sub (S:A->B->Prop): Prop :=
forall x y, R x y -> S x y.
Definition is_Partial_function: Prop :=
forall x y z,
R x y ->
R x z ->
y = z.
End binary_relation.
Section endorelation.
Variable A:Type.
Definition Reflexive (R:Endo A): Prop :=
forall a:A, R a a.
Definition Transitive (R:Endo A): Prop :=
forall a b c:A, R a b -> R b c -> R a c.
Definition Symmetric (R:Endo A): Prop :=
forall a b:A, R a b -> R b a.
Definition Antisymmetric (R:Endo A): Prop :=
forall a b:A, R a b -> R b a -> a = b.
Definition Complete (R:Endo A): Prop :=
forall a b:A, R a b \/ R b a.
Theorem complete_is_reflexive:
forall (R:Endo A), Complete R -> Reflexive R.
Proof
fun R d a =>
match d a a with
or_introl p => p
| or_intror p => p
end.
Inductive Comparison2 (R:Endo A) (a b:A): Set :=
| LE: R a b -> Comparison2 R a b
| GE: R b a -> Comparison2 R a b.
Inductive Comparison3 (R:Endo A) (a b:A): Set :=
| LT: R a b -> ~ R b a -> Comparison3 R a b
| EQV: R a b -> R b a -> Comparison3 R a b
| GT: R b a -> ~ R a b -> Comparison3 R a b.
Definition Comparer2 (R:Endo A): Type :=
forall a b:A, Comparison2 R a b.
Definition Comparer3 (R:Endo A): Type :=
forall a b:A, Comparison3 R a b.
Theorem comparable2_is_complete:
forall (R:Endo A) (c:Comparer2 R), Complete R.
Proof
fun R c a b =>
match c a b with
| LE _ _ _ p => or_introl p
| GE _ _ _ p => or_intror p
end.
Theorem comparable3_is_complete:
forall (R:Endo A) (c:Comparer3 R), Complete R.
Proof
fun R c a b =>
match c a b with
| LT _ _ _ p _ => or_introl p
| EQV _ _ _ p1 p2 => or_introl p1
| GT _ _ _ p _ => or_intror p
end.
Section closures.
Inductive Plus (R:Endo A): Endo A :=
| plus_start: forall x y, R x y -> Plus R x y
| plus_next: forall x y z, Plus R x y -> R y z -> Plus R x z.
Arguments plus_start [_ _ _] _.
Arguments plus_next [_ _ _ _] _ _.
Theorem use_plus:
forall {R:Endo A} {x y:A} (p:Plus R x y) (P: Endo A),
(forall x y, R x y -> P x y)
-> (forall x y z, Plus R x y -> R y z -> P x y -> P x z)
-> P x y.
Proof
fix f R x y pxy P :=
match pxy with
| plus_start rab => fun f1 f2 => f1 _ _ rab
| plus_next pab rbc =>
fun f1 f2 =>
f2 _ _ _ pab rbc
(f _ _ _ pab P f1 f2)
end.
Theorem plus_transitive:
forall (R:Endo A), Transitive (Plus R).
Proof
fun R a b c plus_ab plus_bc =>
let P b c := forall a, Plus R a b -> Plus R a c in
(use_plus
plus_bc
P
(fun b c rbc a plus_ab => plus_next plus_ab rbc)
(fun b c d plus_bc (rcd: R c d)
(ihbc:forall a, Plus R a b -> Plus R a c)
a
(plus_ab: Plus R a b) =>
plus_next (ihbc a plus_ab) rcd)
:P b c) a plus_ab.
Inductive Star (R:Endo A): Endo A :=
| star_start: forall x, Star R x x
| star_next: forall x y z, Star R x y -> R y z -> Star R x z.
Arguments star_start [_] _.
Arguments star_next [_ _ _ _] _ _.
Theorem use_star:
forall {R:Endo A} {x y:A} (p:Star R x y) (P: Endo A),
(forall x, P x x)
-> (forall x y z, Star R x y -> R y z -> P x y -> P x z)
-> P x y.
Proof
fix f R x y xy P :=
match xy with
| star_start a => fun f1 f2 => f1 a
| star_next pab rbc =>
fun f1 f2 =>
f2 _ _ _ pab rbc
(f R _ _ pab P f1 f2)
end.
Theorem star_transitive:
forall (R:Endo A), Transitive (Star R).
Proof
fun R a b c star_ab star_bc =>
let P b c := forall a, Star R a b -> Star R a c in
(use_star
star_bc
P
(fun x _ p => p)
(fun b c d star_bc rcd ih_bc a star_ab =>
star_next (ih_bc a star_ab) rcd)
:P b c) a star_ab.
Inductive Equi_close (R:A -> A -> Prop): A -> A -> Prop :=
| equi_start: forall x, Equi_close R x x
| equi_fwd: forall x y z, Equi_close R x y -> R y z -> Equi_close R x z
| equi_bwd: forall x y z, Equi_close R x y -> R z y -> Equi_close R x z.
Arguments equi_start [_] _.
Arguments equi_fwd [_ _ _ _] _ _.
Arguments equi_bwd [_ _ _ _] _ _.
Theorem use_equi_close:
forall {R:Endo A} {x y} (p:Equi_close R x y) (P:Endo A),
(forall x, P x x)
-> (forall x y z, R y z -> P x y -> P x z)
-> (forall x y z, R z y -> P x y -> P x z)
-> P x y.
Proof
fix f R x y xy P :=
match xy with
| equi_start a => fun f1 f2 f3 => f1 a
| equi_fwd pab rbc =>
fun f1 f2 f3 =>
f2 _ _ _ rbc (f R _ _ pab P f1 f2 f3)
| equi_bwd pab rcb =>
fun f1 f2 f3 =>
f3 _ _ _ rcb (f R _ _ pab P f1 f2 f3)
end.
Theorem equi_close_transitive:
forall (R:Endo A), Transitive (Equi_close R).
Proof
fun R a b c eab ebc =>
let P b c := forall a, Equi_close R a b -> Equi_close R a c
in
(use_equi_close
ebc
P
(fun x c p => p)
(fun b c d rcd pbc a eab =>
equi_fwd (pbc a eab: Equi_close R a c) (rcd: R c d))
(fun b c d rdc pbc a eab =>
equi_bwd (pbc a eab: Equi_close R a c) (rdc: R d c))
) a eab.
Theorem equi_close_symmetric:
forall (R:Endo A), Symmetric (Equi_close R).
Proof
fun R =>
let lemma1 a b (rab:R a b): Equi_close R a b :=
equi_fwd (equi_start a) rab
in
let lemma2 a b (rab:R a b): Equi_close R b a :=
equi_bwd (equi_start b) rab
in
fun a b equi_ab =>
let P a b := Equi_close R b a in
use_equi_close
equi_ab
(fun a b => Equi_close R b a)
(fun x => equi_start x)
(fun x y z ryz (ihxy: Equi_close R y x) =>
equi_close_transitive
(lemma2 y z ryz:Equi_close R z y)
(ihxy:Equi_close R y x)
:Equi_close R z x)
(fun x y z rzy (ihxy: Equi_close R y x) =>
equi_close_transitive
(lemma1 z y rzy:Equi_close R z y)
(ihxy:Equi_close R y x)
:Equi_close R z x)
.
End closures.
End endorelation.
Arguments LT [_] [_] [_] [_] _.
Arguments EQV [_] [_] [_] [_] _ _.
Arguments GT [_] [_] [_] [_] _.
Arguments LE [_ _ _ _] _.
Arguments GE [_ _ _ _] _.
Arguments star_start [_ _] _.
Arguments star_next [_ _ _ _ _] _ _.
Section well_founded_relation.
Variable A:Type.
Variable R: A -> A -> Prop.
Variable P: A -> Prop.
Theorem accessible_induction:
(forall x, Acc R x -> (forall y, R y x -> P y) -> P x)
->
forall x, Acc R x -> P x.
Proof
fun hypo =>
(fix f x acc_x :=
match acc_x with
Acc_intro _ h =>
hypo x acc_x (fun y Ryx => f y (h y Ryx))
end
)
.
Theorem wf_subrelation:
forall (S:A->A->Prop),
Sub S R -> well_founded R -> well_founded S.
Proof
fun S sub =>
let lemma: forall x, Acc R x -> Acc S x :=
fix f x accRx {struct accRx}: Acc S x:=
match accRx with
Acc_intro _ pr =>
(* pr: forall y, R y x -> Acc R y All direct conclusions of 'pr'
are syntactically smaller than 'accRx', i.e. can be used to
recursively call 'f'. *)
Acc_intro
_
(fun y Syx =>
let Ryx: R y x := sub y x Syx in
let accRy: Acc R y := pr y Ryx in
let accSy: Acc S y := f y accRy in
f y accRy)
end
in
fun wfR a => lemma a (wfR a).
End well_founded_relation.
Section order_relation.
Variable A:Type.
Variable R: A -> A -> Prop.
Definition Preorder: Prop :=
Reflexive R /\ Transitive R.
Definition Linear_preorder: Prop :=
Complete R /\ Transitive R.
Definition Partial_preorder: Prop :=
Reflexive R /\ Transitive R /\ Antisymmetric R.
Definition Linear_order: Prop :=
Complete R /\ Transitive R /\ Antisymmetric R.
Definition Equivalence: Prop :=
Reflexive R /\ Transitive R /\ Symmetric R.
End order_relation.
Section diamond.
Variable A:Type.
Definition Diamond (R:Endo A): Prop :=
forall a b c, R a b -> R a c -> exists d, R b d /\ R c d.
Theorem use_diamond
{R:Endo A}
(dia:Diamond R) (a b c:A) (rab:R a b) (rac:R a c)
(P:Prop)
(f:forall d, R b d -> R c d -> P): P.
Proof
match dia a b c rab rac with
| ex_intro _ d (conj rbd rcd) =>
f d rbd rcd
end.
Definition Confluent (R:Endo A): Prop :=
Diamond (Star R).
Theorem use_confluent
{R:Endo A}
(confl:Confluent R) (a b c:A) (sab: Star R a b) (sac: Star R a c)
(P: Prop)
(f: forall d, Star R b d -> Star R c d -> P): P.
Proof
use_diamond confl a b c sab sac f.
Theorem confluent_equivalent_meet:
forall {R:Endo A} {a b:A},
Confluent R ->
Equi_close R a b ->
exists c, Star R a c /\ Star R b c.
Proof
fun R a b confl e_ab =>
let P a b := exists c, Star R a c /\ Star R b c in
let useP a b (pab:P a b)
(B:Prop) (f:forall c, Star R a c -> Star R b c -> B): B :=
match pab with
| ex_intro _ c (conj sac sbc) =>
f c sac sbc
end
in
use_equi_close
e_ab
P
(fun x =>
let star_xx: Star R x x := star_start x in
ex_intro _ x (conj star_xx star_xx))
(fun a b c rbc ih_ab =>
(* a ->eq b -> c
\ | |
\* v* v*
> some d ->* some e
d exists by induction hypothesis
e exists by confluence
*)
useP _ _ ih_ab _
(fun d star_ad star_bd =>
use_confluent
confl
(star_next (star_start b) rbc)
star_bd
(fun e star_ce star_de =>
ex_intro
_ e
(conj (star_transitive star_ad star_de) star_ce))
))
(fun a b c rcb ih_ab =>
(* a ->eq b <- c
\ | |
\* v* v*
> some d ->* some e
d exists by induction hypothesis
e exists by confluence
*)
useP _ _ ih_ab _
(fun d star_ad star_bd =>
use_confluent
confl
(star_start c)
(star_transitive
(star_next (star_start c) rcb)
star_bd)
(fun e star_ce star_de =>
ex_intro
_ e
(conj (star_transitive star_ad star_de) star_ce)))
).
End diamond.
End Relation.
(** * Either: Two Possible Results *)
(* ============================ *)
Module Either.
Inductive t (A B:Type): Type :=
| Left: A -> t A B
| Right: B -> t A B.
Arguments Left [A] [B] _.
Arguments Right [A] [B] _.
End Either.
(** * Tristate: Three Possible Results *)
(* ================================ *)
Module Tristate.
Inductive t (A B C:Type): Type :=
| Left: A -> t A B C
| Middle: B -> t A B C
| Right: C -> t A B C.
Arguments Left [A] [B] [C] _.
Arguments Middle [A] [B] [C] _.
Arguments Right [A] [B] [C] _.
End Tristate.
(** * Any Type *)
(* ======== *)
Module Type ANY.
Parameter t: Type.
End ANY.
(** * Sortable Types *)
(* ============== *)
Module Type SORTABLE <: ANY.
Import Relation.
Parameter t: Set.
Parameter Less_equal: t -> t -> Prop.
Axiom transitive: Transitive Less_equal.
Parameter compare2: Comparer2 Less_equal.
Parameter compare3: Comparer3 Less_equal.
End SORTABLE.
Module Sortable_plus (S:SORTABLE).
Import Relation.
Include S.
Definition Equivalent (a b:t): Prop := Less_equal a b /\ Less_equal b a.
Theorem complete: Complete Less_equal.
Proof
comparable2_is_complete compare2.
Theorem reflexive: Reflexive Less_equal.
Proof
complete_is_reflexive complete.
Module Notations.
Notation "a <= b" := (Less_equal a b) (at level 70).
Notation "( 'transitivity_chain:' x , y , .. , z )" :=
(transitive .. (transitive x y) .. z) (at level 0).
End Notations.
Import Notations.
Definition max (a b:t): {m:t | a <= m /\ b <= m /\ (m = a \/ m = b)}.
Proof.
exact(
match compare2 a b with
| LE le =>
exist _ b (And.make3 le (reflexive b) (or_intror eq_refl))
| GE ge =>
exist _ a (And.make3 (reflexive a) ge (or_introl eq_refl))
end
).
Defined.
Definition min (a b:t): {m:t | m <= a /\ m <= b /\ (m = a \/ m = b)}.
Proof.
exact(
match compare2 a b with
| LE le =>
exist _ a (And.make3 (reflexive a) le (or_introl eq_refl))
| GE ge =>
exist _ b (And.make3 ge (reflexive b) (or_intror eq_refl))
end
).
Defined.
End Sortable_plus.
(** * Finite Set *)
(* ========== *)
Module Type FINITE_SET.
Import Predicate.
Parameter A: Set.
Parameter T: Set->Set.
Parameter Domain: T A -> A -> Prop.
Parameter is_in:
forall (a:A) (s:T A), {Domain s a} + {~ Domain s a}.
Parameter empty:
{s:T A | Empty (Domain s)}.
Parameter add:
forall (a:A) (s:T A), {t:T A| Domain t = Add a (Domain s)}.
Parameter remove:
forall (a:A) (s:T A), {t:T A| Domain t = Remove a (Domain s)}.
End FINITE_SET.
(** * Finite Map *)
(* ========== *)
Module Type FINITE_MAP.
Parameter Key: Set.
Parameter Value: Type.
Parameter T: Type.
Parameter empty: T.
Parameter find: forall (e:Key) (m:T), option Value.
Parameter add: forall (e:Key) (v:Value) (m:T), T.
Axiom empty_is_empty: forall k, find k empty = None.
Axiom add_is_in:
forall k v m, find k (add k v m) = Some v.
Axiom add_others_unchanged:
forall k1 k2 v m,
k1 <> k2 ->
find k2 (add k1 v m) = find k2 m.
End FINITE_MAP.
|
{-
this file is taken from the hommage library
-}
{-# LANGUAGE FlexibleContexts #-}
module WavFile
(
-- * Binary Files
writeDataFile
, readDataFile
, openDataFile
-- * WAV-Files
, writeWavFile
, writeWavFileMono
, writeWavFileStereo
, readWavFile
, openWavFile
, writeWavFiles
-- * Cast between Int16 and Double representation of WAV-data
, wavInt16ToDouble
, wavDoubleToInt16
-- * Low-Level implemetation
-- ** Arrays and Files
, readArrayFromFile
, writeArrayToFileWithHeader
, writeArrayToFile
-- ** Single Stream
, openSingleInputFile
, openSingleOutputFile
, openSingleInputWavFile
, openSingleOutputWavFileMono
, openSingleOutputWavFileStereo
-- ** Buffered Stream
, openInputFile
, openOutputFile
, openOutputFileWithHeader
, openInputWavFile
, openOutputWavFileMono
, openOutputWavFileStereo
-- ** Header Stuff and others
, HeaderFun
, HeaderSize
, noHeader
, wavHeaderFunMono
, wavHeaderFunStereo
, wavHeaderSize
, initWriteWavHeaderMono
, initWriteWavHeaderStereo
, initReadWavHeader
, closeWriteWavHeader
, encode
, decode
, encodeWavLengt
, initWavHeaderMono
, initWavHeaderStereo
, sizeOfArrayElements
, inferSizeOfArrayElements
, inferSizeOfArrayElements'
)
where
import System.IO
import Control.Monad
import Control.Monad.Fix
import Data.Char
import Data.Int
import GHC.IO.Handle
import GHC.IO
import GHC.Base hiding (mapM)
import Data.Complex
import Foreign.Storable
import Data.Array.Storable
import Data.Array.IArray
import Data.IORef
import System.IO.Unsafe
import GHC.Weak
---------------------------------------------------------------------------------------------------
wavInt16ToDouble :: Int16 -> Double
wavInt16ToDouble i = (fromIntegral i) / 32768.0
wavDoubleToInt16 :: Double -> Int16
wavDoubleToInt16 d = round (d * 32767.0)
---------------------------------------------------------------------------------------------------
readDataFile :: Storable a => FilePath -> IO [a]
readDataFile fp = init
where
init = do (c,r,_) <- openSingleInputFile 10000 0 fp
mkWeak r () (Just c)
loop r
loop r = r >>= maybe (return []) (\a -> return (a : unsafePerformIO (loop r)))
openDataFile :: Storable a => FilePath -> [a]
openDataFile fp = unsafePerformIO $ readDataFile fp
writeDataFile :: Storable a => FilePath -> [a] -> IO ()
writeDataFile fp xs = do
(c,w) <- openSingleOutputFile 4000 fp
let loop (x:r) = w x >> loop r
loop [] = c
loop xs
---------------------------------------------------------------------------------------------------
readWavFile :: FilePath -> IO (Either [Int16] [(Int16,Int16)])
readWavFile fp = {- putStrLn ("opening " ++ fp) >> -} init
where
init = do (c,r,_) <- openSingleInputWavFile 100000 fp
either (\rm -> do mkWeak rm () (Just c) --(putStrLn ("close " ++ fp) >> c))
fmap Left $ loop rm)
(\rs -> do mkWeak rs () (Just c) --(putStrLn ("close " ++ fp) >> c))
fmap Right $ loop rs)
r
loop r = r >>= maybe (return []) (\a -> return (a : unsafePerformIO (loop r)))
openWavFile :: FilePath -> Either [Int16] [(Int16,Int16)]
openWavFile fp = unsafePerformIO $ readWavFile fp
writeWavFile :: FilePath -> Either [Int16] [(Int16, Int16)] -> IO ()
writeWavFile fp (Left w) = writeWavFileMono fp w
writeWavFile fp (Right w) = writeWavFileStereo fp w
writeWavFileMono :: FilePath -> [Int16] -> IO ()
writeWavFileMono fp xs = do
(c,w) <- openSingleOutputWavFileMono 100000 fp
let loop (x:r) = w x >> loop r
loop [] = c
loop xs
writeWavFileStereo :: FilePath -> [(Int16,Int16)] -> IO ()
writeWavFileStereo fp xs = do
(c,w) <- openSingleOutputWavFileStereo 100000 fp
let loop (x:r) = w x >> loop r
loop [] = c
loop xs
writeWavFiles :: FilePath -> String -> [Either [Int16] [(Int16, Int16)]] -> IO ()
writeWavFiles fp fn sns = do
let init count (Left x : xs) = do (c,w) <- openSingleOutputWavFileMono 100000 (fp ++ fn ++ "_" ++ show count ++ ".wav")
r <- init (count+1) xs
return (Left (c,w,x) : r)
init count (Right x : xs) = do (c,w) <- openSingleOutputWavFileStereo 100000 (fp ++ fn ++ "_" ++ show count ++ ".wav")
r <- init (count+1) xs
return (Right (c,w,x) : r)
init _ _ = return []
ss <- init 0 sns
let step (Left (c,w,x:xs) : r) = do w x
r <- step r
return (Left (c,w,xs) : r)
step (Left (c,w,[]) : r) = c >> step r
step (Right (c,w,x:xs) : r) = do w x
r <- step r
return (Right (c,w,xs) : r)
step (Right (c,w,[]) : r) = c >> step r
step [] = return []
loop [] = return ()
loop xs = step xs >>= loop
loop ss
---------------------------------------------------------------------------------------------------
-- Header
-- | The first Action is applied after opening the file. Then the data
-- bytes are written. The second Action is then called with the number of
-- bytes of the data. It must close the handle.
type HeaderFun = (Handle -> IO (), Handle -> Int -> IO ())
type HeaderSize = Int
noHeader :: HeaderFun
noHeader = (const $ return (), \h _ -> return ())
-------------------------------------------------
-- WavHeader
-- | The first Action writes the Header of the wav-file.
-- Then the wav-data is written. The second action moves
-- the Handle to the positions where the lenght of the wav-file
-- are encoded (in the header) and writes the right number, which
-- is unknown before all data is written.
-- Afterwards it closes the file.
wavHeaderFunMono :: HeaderFun
wavHeaderFunMono = (initWriteWavHeaderMono, closeWriteWavHeader)
wavHeaderFunStereo :: HeaderFun
wavHeaderFunStereo = (initWriteWavHeaderStereo, closeWriteWavHeader)
wavHeaderSize :: HeaderSize
wavHeaderSize = 44
-------------------------------------------------
initWriteWavHeaderMono :: Handle -> IO ()
initWriteWavHeaderMono h = mapM_ (hPutChar h) initWavHeaderMono
initWriteWavHeaderStereo :: Handle -> IO ()
initWriteWavHeaderStereo h = mapM_ (hPutChar h) initWavHeaderStereo
initReadWavHeader :: Handle -> IO (Maybe (Bool, Int, Int, Int))
initReadWavHeader handle =
let check [] = return True
check (x:xs) = hGetChar handle >>= \y -> if x /= ord y then return False else check xs
m >>? n = m >>= \b -> if b then n else return Nothing
in hSeek handle AbsoluteSeek 0 >>
check [82,73,70,70] >>?
(replicateM 4 (hGetChar handle) >>= \l1 ->
check [87, 65, 86, 69, 102,109,116,32, 16, 0, 0, 0, 1, 0] >>?
(hGetChar handle >>= \s1 ->
check [0, 68, 172, 0, 0] >>?
(replicateM 4 (hGetChar handle) >>= \x1 ->
(hGetChar handle >>= \s2 ->
check [0, 16, 0, 100, 97,116,97] >>?
(replicateM 4 (hGetChar handle) >>= \l2 ->
let b | ord s1 == 1 && ord s2 == 2 = False
| ord s1 == 2 && ord s2 == 4 = True
| otherwise = error ("invalid wav file " ++ show s1 ++ ", " ++ show s2)
in return $ Just (b, decode l1, decode l2, decode x1) ) ) ) ) )
closeWriteWavHeader :: Handle -> Int -> IO ()
closeWriteWavHeader h len = do
let (sa,sb) = encodeWavLengt len
hSeek h AbsoluteSeek 4
mapM (hPutChar h) sa
hSeek h AbsoluteSeek 40
mapM (hPutChar h) sb
hClose h
encode :: Int -> String
encode a = map chr
[ mod a 256
, mod (div a 256) 256
, mod (div a 65536) 256
, mod (div a 16777216) 256
]
decode :: String -> Int
decode [a0,a1,a2,a3] = sum
[ord a0, 256 * ord a1, 65536 * ord a2, 16777216 * ord a3]
encodeWavLengt :: Int -> (String, String)
encodeWavLengt len = (encode (len + 8), encode len)
initWavHeaderMono :: [Char]
initWavHeaderMono =
map chr
[82,73,70,70,
0,0,0,0,
87, 65, 86, 69,
102,109,116,32,
16, 0, 0, 0,
1, 0, 1, 0,
68, 172,0, 0,
136,88, 1, 0,
2, 0, 16, 0,
100, 97,116,97,
0,0,0,0]
initWavHeaderStereo :: [Char]
initWavHeaderStereo =
map chr
[82,73,70,70,
0,0,0,0,
87, 65, 86, 69,
102,109,116,32,
16, 0, 0, 0,
1, 0, 2, 0,
68, 172,0, 0,
16,177, 2, 0,
4, 0, 16, 0,
100, 97,116,97,
0,0,0,0]
---------------------------------------------------------------------------------------------------
sizeOfArrayElements :: Storable a => StorableArray Int a -> Int
sizeOfArrayElements x = sizeOf (foo x)
where
foo :: StorableArray Int a -> a
foo x = undefined
inferSizeOfArrayElements :: Storable a => (StorableArray Int a -> IO Int) -> StorableArray Int a -> Int
inferSizeOfArrayElements _ arr = sizeOfArrayElements arr
inferSizeOfArrayElements' :: Storable a => (StorableArray Int a -> Int -> IO ()) -> StorableArray Int a -> Int
inferSizeOfArrayElements' _ arr = sizeOfArrayElements arr
inferSizeOfArrayElements'' :: Storable a => (StorableArray Int a -> Int -> IO Int) -> StorableArray Int a -> Int
inferSizeOfArrayElements'' _ arr = sizeOfArrayElements arr
---------------------------------------------------------------------------------------------------
-- Array / File
---------------------------------------------------------------------------------------------------
readArrayFromFile :: Storable a => HeaderSize -> FilePath -> IO (StorableArray Int a, Int)
readArrayFromFile offset filepath = do
handle <- openBinaryFile filepath ReadMode
hSeek handle AbsoluteSeek $ fromIntegral offset
bytes <- hFileSize handle
let bytesize = fromIntegral bytes - offset
arr <- mfix $ \arr -> do let bufsize = div bytesize (sizeOfArrayElements arr)
newArray_ (0, bufsize-1)
withStorableArray arr $ \ptr -> hGetBuf handle ptr bytesize
hClose handle
return (arr, div bytesize (sizeOfArrayElements arr))
writeArrayToFileWithHeader :: (MArray StorableArray a IO, Storable a) => HeaderFun -> FilePath -> StorableArray Int a -> IO ()
writeArrayToFileWithHeader (initH, closeH) filepath arr = do
handle <- openBinaryFile filepath WriteMode
initH handle
(0, n) <- getBounds arr
let elemsize = sizeOfArrayElements arr
bytesize = (1+n) * elemsize
withStorableArray arr (\ptr -> hPutBuf handle ptr bytesize)
closeH handle bytesize
writeArrayToFile :: (MArray StorableArray a IO, Storable a) => FilePath -> StorableArray Int a -> IO ()
writeArrayToFile filepath arr = do
handle <- openBinaryFile filepath WriteMode
(0, n) <- getBounds arr
let elemsize = sizeOfArrayElements arr
bytesize = (1+n) * elemsize
withStorableArray arr (\ptr -> hPutBuf handle ptr bytesize)
hClose handle
{-
writeArrayToFileWithHeader :: Storable a => HeaderFun -> FilePath -> StorableArray Int a -> IO ()
writeArrayToFileWithHeader (initH, closeH) filepath arr = do
handle <- openBinaryFile filepath WriteMode
initH handle
let (0,n) = bounds arr
elemsize = sizeOfArrayElements arr
bytesize = (1+n) * elemsize
withStorableArray arr (\ptr -> hPutBuf handle ptr bytesize)
closeH handle bytesize
writeArrayToFile :: Storable a => FilePath -> StorableArray Int a -> IO ()
writeArrayToFile filepath arr = do
handle <- openBinaryFile filepath WriteMode
let (0,n) = bounds arr
elemsize = sizeOfArrayElements arr
bytesize = (1+n) * elemsize
withStorableArray arr (\ptr -> hPutBuf handle ptr bytesize)
hClose handle
-}
---------------------------------------------------------------------------------------------------
-- Single Wav
---------------------------------------------------------------------------------------------------
openSingleInputWavFile :: Int -> FilePath -> IO (IO (), Either (IO (Maybe Int16)) (IO (Maybe (Int16,Int16))), Int)
openSingleInputWavFile n filepath = do
handle <- openBinaryFile filepath ReadMode
initReadWavHeader handle >>= maybe (error "unknown wav format") (\(isstereo, len1, len2, x) -> do
hSeek handle AbsoluteSeek 44
let stereo = do let bufsize = n*2
rpos <- newIORef bufsize
rmax <- newIORef bufsize
buf <- newArray_ (0, bufsize-1)
let elemsize = sizeOfArrayElements buf
bytesize = elemsize * bufsize
next = readIORef rpos >>= \pos ->
readIORef rmax >>= \max ->
if pos >= max
then if max < bufsize
then return Nothing
else withStorableArray buf (\ptr -> hGetBuf handle ptr bytesize) >>= \bts ->
writeIORef rmax (div bts elemsize) >>
writeIORef rpos 0 >>
next
else readArray buf pos >>= \v1 ->
readArray buf (pos+1) >>= \v2 ->
writeIORef rpos (pos + 2) >>
return (Just (v1,v2))
close = hClose handle
return (close, Right next,div len2 4)
mono = do let bufsize = n
rpos <- newIORef bufsize
rmax <- newIORef bufsize
buf <- newArray_ (0, bufsize-1)
let elemsize = sizeOfArrayElements buf
bytesize = elemsize * bufsize
next = readIORef rpos >>= \pos ->
readIORef rmax >>= \max ->
if pos >= max
then if max < bufsize
then return Nothing
else withStorableArray buf (\ptr -> hGetBuf handle ptr bytesize) >>= \bts ->
writeIORef rmax (div bts elemsize) >>
writeIORef rpos 0 >>
next
else readArray buf pos >>= \v ->
writeIORef rpos (pos + 1) >>
return (Just v)
close = hClose handle
return (close, Left next,div len2 2)
if isstereo then stereo else mono )
---------------------------------------------------------------------------------------------------
openSingleOutputWavFileMono :: Int -> FilePath -> IO (IO (), Int16 -> IO ())
openSingleOutputWavFileMono bufsize filepath = do
handle <- openBinaryFile filepath WriteMode
rpos <- newIORef 0
buf <- newArray_ (0, bufsize-1)
rcnt <- newIORef 0
let elemsize = sizeOfArrayElements buf
bytesize = elemsize * bufsize
write v = readIORef rpos >>= \pos ->
if pos >= bufsize
then withStorableArray buf (\ptr -> hPutBuf handle ptr bytesize) >>
modifyIORef rcnt (+bytesize) >>
writeIORef rpos 1 >> writeArray buf 0 v
else writeArray buf pos v >> writeIORef rpos (pos+1)
close = readIORef rpos >>= \pos ->
withStorableArray buf (\ptr -> hPutBuf handle ptr (pos*elemsize)) >>
readIORef rcnt >>= \cnt -> closeWriteWavHeader handle (elemsize*pos+cnt)
initWriteWavHeaderMono handle
return (close, write)
---------------------------------------------------------------------------------------------------
openSingleOutputWavFileStereo :: Int -> FilePath -> IO (IO (), (Int16, Int16) -> IO ())
openSingleOutputWavFileStereo bufsizearg filepath = do
let bufsize | bufsizearg < 2 = 4
| even bufsizearg = bufsizearg
| otherwise = bufsizearg + 1
handle <- openBinaryFile filepath WriteMode
rpos <- newIORef 0
buf <- newArray_ (0, bufsize-1)
rcnt <- newIORef 0
let elemsize = sizeOfArrayElements buf
bytesize = elemsize * bufsize
write (v1,v2) = readIORef rpos >>= \pos ->
if pos >= bufsize
then withStorableArray buf (\ptr -> hPutBuf handle ptr bytesize) >>
modifyIORef rcnt (+bytesize) >>
writeIORef rpos 2 >> writeArray buf 0 v1 >> writeArray buf 1 v2
else writeArray buf pos v1 >> writeArray buf (pos+1) v2 >> writeIORef rpos (pos+2)
close = readIORef rpos >>= \pos ->
withStorableArray buf (\ptr -> hPutBuf handle ptr (pos*elemsize)) >>
readIORef rcnt >>= \cnt -> closeWriteWavHeader handle (elemsize*pos+cnt)
initWriteWavHeaderStereo handle
return (close, write)
---------------------------------------------------------------------------------------------------
-- Single Storable
---------------------------------------------------------------------------------------------------
openSingleInputFile :: Storable a => Int -> HeaderSize -> FilePath -> IO (IO (), IO (Maybe a), Int)
openSingleInputFile bufsize offset filepath = do
handle <- openBinaryFile filepath ReadMode
bytes <- hFileSize handle
hSeek handle AbsoluteSeek $ fromIntegral offset
rpos <- newIORef bufsize
rmax <- newIORef bufsize
buf <- newArray_ (0, bufsize-1)
let elemsize = sizeOfArrayElements buf
bytesize = elemsize * bufsize
next = readIORef rpos >>= \pos ->
readIORef rmax >>= \max ->
if pos >= max
then if max < bufsize
then return Nothing
else withStorableArray buf (\ptr -> hGetBuf handle ptr bytesize) >>= \bts ->
writeIORef rmax (div bts elemsize) >>
writeIORef rpos 0 >>
next
else readArray buf pos >>= \v ->
writeIORef rpos (pos + 1) >>
return (Just v)
close = hClose handle
return (close, next,div (fromIntegral bytes - offset) elemsize)
---------------------------------------------------------------------------------------------------
openSingleOutputFile :: Storable a => Int -> FilePath -> IO (IO (), a -> IO ())
openSingleOutputFile bufsize filepath = do
handle <- openBinaryFile filepath WriteMode
rpos <- newIORef 0
buf <- newArray_ (0, bufsize-1)
let elemsize = sizeOfArrayElements buf
bytesize = elemsize * bufsize
write v = readIORef rpos >>= \pos ->
if pos >= bufsize
then withStorableArray buf (\ptr -> hPutBuf handle ptr bytesize) >>
writeIORef rpos 1 >> writeArray buf 0 v
else writeArray buf pos v >> writeIORef rpos (pos+1)
close = readIORef rpos >>= \pos ->
withStorableArray buf (\ptr -> hPutBuf handle ptr (pos*elemsize)) >>
hClose handle
return (close, write)
---------------------------------------------------------------------------------------------------
-- Buffered Storable
---------------------------------------------------------------------------------------------------
openInputFile :: Storable a => HeaderSize -> FilePath -> Int -> IO (IO (), StorableArray Int a -> Int -> IO Int, Int)
openInputFile offset filepath arrsize = do
handle <- openBinaryFile filepath ReadMode
hSeek handle AbsoluteSeek $ fromIntegral offset
bytes <- hFileSize handle
let nr_bytes = fromIntegral bytes - offset
elemsize = inferSizeOfArrayElements'' read undefined
read arr k = withStorableArray arr $ \ptr ->
hGetBuf handle ptr (k * elemsize) >>= return . flip div elemsize
close = hClose handle
return $ (close, read, div nr_bytes elemsize)
openOutputFile :: Storable a => FilePath -> IO (IO (), StorableArray Int a -> Int -> IO ())
openOutputFile filepath = do
handle <- openBinaryFile filepath WriteMode
let elemsize = inferSizeOfArrayElements' write undefined
write arr k = withStorableArray arr (\ptr -> hPutBuf handle ptr (k*elemsize))
close = hClose handle
return $ (close, write)
openOutputFileWithHeader :: Storable a => HeaderFun -> FilePath -> IO (IO (), StorableArray Int a -> Int -> IO ())
openOutputFileWithHeader (initH, closeH) filepath = do
handle <- openBinaryFile filepath WriteMode
rlen <- newIORef 0
initH handle
let elemsize = inferSizeOfArrayElements' write undefined
write arr k = modifyIORef rlen (+k) >> withStorableArray arr (\ptr -> hPutBuf handle ptr (k*elemsize))
close = readIORef rlen >>= \l -> closeH handle (elemsize*l)
return $ (close, write)
---------------------------------------------------------------------------------------------------
-- Buffered Wav
---------------------------------------------------------------------------------------------------
openInputWavFile :: FilePath -> IO (IO (), StorableArray Int Int16 -> Int -> IO (), Int, Bool)
openInputWavFile filepath = do
handle <- openBinaryFile filepath ReadMode
initReadWavHeader handle >>= maybe (error "unknown wav format") (\(isstereo, len1, len2, x) -> do
hSeek handle AbsoluteSeek 44
let elemsize = inferSizeOfArrayElements' read undefined
read arr k = withStorableArray arr $ \ptr ->
hGetBuf handle ptr (k * elemsize) >> return ()
close = hClose handle
return $ (close, read, div len2 2, isstereo) )
openOutputWavFileMono :: FilePath -> IO (IO (), StorableArray Int Int16 -> Int -> IO ())
openOutputWavFileMono filepath = do
handle <- openBinaryFile filepath WriteMode
rlen <- newIORef 0
let elemsize = inferSizeOfArrayElements' write undefined
write arr k = withStorableArray arr (\ptr -> hPutBuf handle ptr (k*elemsize)) >> modifyIORef rlen (+k)
close = readIORef rlen >>= \l -> closeWriteWavHeader handle (elemsize*l)
initWriteWavHeaderMono handle
return $ (close, write)
openOutputWavFileStereo :: FilePath -> IO (IO (), StorableArray Int Int16 -> Int -> IO ())
openOutputWavFileStereo filepath = do
handle <- openBinaryFile filepath WriteMode
rlen <- newIORef 0
let elemsize = inferSizeOfArrayElements' write undefined
write arr k = withStorableArray arr (\ptr -> hPutBuf handle ptr (k*elemsize)) >> modifyIORef rlen (+k)
close = readIORef rlen >>= \l -> closeWriteWavHeader handle (elemsize*l)
initWriteWavHeaderStereo handle
return $ (close, write)
---------------------------------------------------------------------------------------------------
|
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdint.h>
#include <math.h>
#include <assert.h>
#include <gsl/gsl_math.h>
#include "com3.h"
// #define debugmode 1
int unit_tests(void);
const int64_t comr = 2; // Radius of com filter in pixels
// The filter will be (2*comr+1)^3 pixels
int pointInDomain(int64_t * restrict Point, size_t * Domain, int nDim)
// Check if a point is in the domain of a 3D image
{
for(int kk = 0; kk<nDim; kk++)
if(Point[kk]<0 || Point[kk]>= (int64_t) Domain[kk])
return 0;
return 1;
}
int checkBounds(int64_t * restrict D,
const size_t M, const size_t N, const size_t P)
{
if(D[0]>=comr && D[0]+comr<(int64_t) M &&
D[1]>=comr && D[1]+comr<(int64_t) N &&
D[2]>=comr && D[2]+comr<(int64_t) P)
return 1; // ok
return 0;
}
void com3_localw(double * restrict V, double * restrict W, const size_t M, const size_t N, const size_t P,
int64_t * restrict D, double * restrict C)
{
#ifdef debugmode
printf("D: [%u %u %u]\n", D[0], D[1], D[2]);
printf("M: %lu N: %lu P: %lu\n", M, N, P);
#endif
double sum = 0;
double dx = 0;
double dy = 0;
double dz = 0;
#ifdef debugmode
printf("sum: %f\n", sum);
#endif
if(checkBounds(D, M, N, P))
{
double val = V[D[0] + D[1]*M + D[2]*M*N];
for(int kk = -comr; kk<=comr; kk++) {
for(int ll = -comr; ll<=comr; ll++) {
for(int mm = -comr; mm<=comr; mm++) {
size_t pos = (D[0]+kk) + (D[1]+ll)*M + (D[2]+mm)*M*N;
// printf("pos: %lu V[pos]: %f\n", pos, V[pos]);
dx += kk*V[pos]*val/W[pos];
dy += ll*V[pos]*val/W[pos];
dz += mm*V[pos]*val/W[pos];
sum += V[pos];
} } }
//printf("sum: %f\n", sum);
}
if(sum>0)
{
#ifdef debugmode
printf("sum: %f (%f, %f, %f)\n", sum, dx, dy, dz);
#endif
C[0] = D[0] + dx/sum;
C[1] = D[1] + dy/sum;
C[2] = D[2] + dz/sum;
}
else
{
#ifdef debugmode
printf("No com calculation\n");
#endif
C[0] = D[0];
C[1] = D[1];
C[2] = D[2];
}
}
void com3_local(double * restrict V, const size_t M, const size_t N, const size_t P,
int64_t * restrict D, double * restrict C)
{
#ifdef debugmode
printf("D: [%u %u %u]\n", D[0], D[1], D[2]);
printf("M: %lu N: %lu P: %lu\n", M, N, P);
#endif
double sum = 0;
double dx = 0;
double dy = 0;
double dz = 0;
#ifdef debugmode
printf("sum: %f\n", sum);
#endif
if(checkBounds(D, M, N, P))
{
for(int kk = -comr; kk<=comr; kk++) {
for(int ll = -comr; ll<=comr; ll++) {
for(int mm = -comr; mm<=comr; mm++) {
size_t pos = (D[0]+kk) + (D[1]+ll)*M + (D[2]+mm)*M*N;
// printf("pos: %lu V[pos]: %f\n", pos, V[pos]);
dx += kk*V[pos];
dy += ll*V[pos];
dz += mm*V[pos];
sum += V[pos];
} } }
//printf("sum: %f\n", sum);
}
if(sum>0)
{
#ifdef debugmode
printf("sum: %f (%f, %f, %f)\n", sum, dx, dy, dz);
#endif
C[0] = D[0] + dx/sum;
C[1] = D[1] + dy/sum;
C[2] = D[2] + dz/sum;
}
else
{
#ifdef debugmode
printf("No com calculation\n");
#endif
C[0] = D[0];
C[1] = D[1];
C[2] = D[2];
}
}
void setLmax(double *V, double * W, size_t * Domain, int64_t * Dot)
// Adds V(dot) to all W within comr of dot
// uses global value comr
{
uint32_t m = Dot[0];
uint32_t n = Dot[1];
uint32_t p = Dot[2];
size_t M = Domain[0];
size_t N = Domain[1];
size_t P = Domain[2];
double val = V[m + n*M + p*M*N];
for(uint32_t pp = GSL_MAX(p-comr,0) ; pp<= GSL_MIN(p+comr, P-1) ; pp++) {
for(uint32_t nn = GSL_MAX(n-comr,0) ; nn<= GSL_MIN(n+comr, N-1) ; nn++) {
for(uint32_t mm = GSL_MAX(m-comr,0) ; mm<= GSL_MIN(m+comr, M-1) ; mm++) {
W[mm + nn*M + pp*M*N] += val;
}
}
}
}
void setWeights(double * V, double * W, size_t M, size_t N, size_t P, double * D, size_t nD)
{
size_t Domain[] = {M, N, P};
int64_t Dot[] = {0,0,0};
for(size_t kk = 0; kk<nD; kk++) {
Dot[0] = D[kk*3 + 0];
Dot[1] = D[kk*3 + 1];
Dot[2] = D[kk*3 + 2];
setLmax(V, W, Domain, Dot);
}
}
void com3(double * V, size_t M, size_t N, size_t P,
double * D, double * C, size_t L, int weighted) {
/* Centre of mass
*
* V: MxNxP image
* P 3xL list of dots
* C 3xL list of fitted dots
*/
int64_t Dround[] = {0,0,0};
size_t Domain[] = {M, N, P};
double * W;
if(weighted == 1)
// Set up the weighting matrix
{
W = (double *) calloc(M*N*P, sizeof(double));
for(size_t kk = 0; kk<L; kk++)
{
Dround[0] = nearbyint(D[kk*3]-1);
Dround[1] = nearbyint(D[kk*3+1]-1);
Dround[2] = nearbyint(D[kk*3+2]-1);
if(pointInDomain(Dround, Domain, 3))
setLmax(V, W, Domain, Dround);
}
}
if(weighted == 1)
for(size_t kk = 0; kk<L; kk++)
{
Dround[0] = nearbyint(D[kk*3]-1);
Dround[1] = nearbyint(D[kk*3+1]-1);
Dround[2] = nearbyint(D[kk*3+2]-1);
// printf("%d %d %d\n", Dround[0], Dround[1], Dround[2]);
com3_localw(V, W, M, N, P, Dround, C+kk*3);
}
if(weighted ==0)
for(size_t kk = 0; kk<L; kk++)
{
Dround[0] = nearbyint(D[kk*3]-1);
Dround[1] = nearbyint(D[kk*3+1]-1);
Dround[2] = nearbyint(D[kk*3+2]-1);
// printf("%d %d %d\n", Dround[0], Dround[1], Dround[2]);
com3_local(V, M, N, P, Dround, C+kk*3);
}
if(weighted == 1){
// This was used for debugging
//for(size_t xx = 0; xx<M*N*P; xx++)
// V[xx] = W[xx];
free(W);
}
}
#ifdef standalone
int unit_tests() {
// Size of image
uint32_t M = 100;
uint32_t N = 100;
uint32_t P = 100;
uint32_t L = 2; // number of dots
double * V = malloc(M*N*P*sizeof(double));
double * D = malloc(L*3*sizeof(double));
double * C = malloc(L*3*sizeof(double));
memset(V, 0, M*N*P*sizeof(double));
memset(C, 0, 3*L*sizeof(double));
for(size_t kk = 0; kk<M*N*P; kk++)
V[kk] = 0;
D[0] = 11; D[1] = 12; D[2] = 13;
D[3] = 0; D[4] = 15; D[5] = 16;
size_t pos = D[0] + M*D[1] + M*N*D[2];
V[pos] = 3;
// V[pos+1] = 1;
// V[pos + M] = 1;
V[pos + M*N] = 1;
// Ordinary
com3(V, M, N, P,
D, C, L, 0);
// Weighted
com3(V, M, N, P,
D, C, L, 1);
for(uint32_t kk=0; kk<L; kk++) {
printf("%d [%f %f %f] -> ", kk, D[3*kk], D[3*kk+1], D[3*kk+2]);
printf(" [%f %f %f]\n", C[3*kk], C[3*kk+1], C[3*kk+2]);
}
free(C);
free(D);
free(V);
return 0;
}
int main(int argc, char ** argv)
{
printf("%s\n", argv[0]);
if(argc == 1)
return unit_tests();
}
#endif
|
theory AbstractLock_Proof_Rules
imports AbstractLock_Lib OpSem_Proof_Rules Lib_ProofRules
begin
lemma lock_acqure_wfs_pres:
assumes "wfs cs"
and "lib_wfs ls cs"
and "lock_acquire_step t x ls cs ls' cs' res ver"
shows "wfs cs'"
using assms
apply(simp add: lock_acquire_step_def lock_acquire_def lib_update_def lib_read_def)
apply(elim exE conjE)
apply(subgoal_tac "a = x", simp)
defer
apply(simp add: lib_writes_on_def lib_visible_writes_def)
apply(case_tac "even (lib_value ls (x, b))", simp_all)
apply(simp add: lib_writes_on_def lib_value_def lib_valid_fresh_ts_def lib_visible_writes_def)
apply(unfold wfs_def lib_update_def, simp)
apply(simp add: lib_add_cv_def lib_update_thrView_def lib_update_modView_def lib_update_mods_def lib_lastWr_def lib_writes_on_def)
apply(elim conjE)
apply(case_tac "\<not>lib_releasing ls (x, b)", simp_all)
apply(simp add: update_thrView_def)
apply(simp add: update_thrView_def)
apply(unfold writes_on_def ts_oride_def, simp)
apply(intro allI impI conjI)
apply(simp add: var_def lib_wfs_def)
apply (simp add: var_def writes_on_def)
apply(simp add: lib_wfs_def)
by (metis (no_types, lifting) mem_Collect_eq writes_on_def)
lemma lock_release_lib_wfs_pres:
assumes "wfs cs"
and "lib_wfs ls cs"
and "lock_release_step t x ls cs ls' cs'"
shows "lib_wfs ls' cs'"
using assms
apply(simp add: lib_wfs_def lock_release_step_def lib_writes_on_def lock_release_def lib_write_def)
apply(elim exE conjE)
apply(simp add: lib_update_mods_def lib_update_modView_def lib_update_thrView_def lib_lastWr_def lib_writes_on_def)
apply(intro conjI allI impI)
apply(case_tac "xa=a", simp_all)
using finite_lib_writes apply blast
using finite_lib_writes_2 apply blast
apply blast
apply(case_tac "aa=a", simp_all)
apply(case_tac "lib_lastWr ls a = (a, b)")
apply(subgoal_tac "Max (tst `
{w. var w = a \<and> (w = (a, ts') \<or> w \<in> lib_writes ls)}) = ts'", simp_all)
apply(simp add: lib_valid_fresh_ts_def lib_writes_on_def)
apply blast
apply(simp add: lib_lastWr_def lib_writes_on_def tst_def var_def)
apply(subgoal_tac "finite ({w. fst w = a \<and> w \<in> lib_writes ls})")
apply(subgoal_tac "{w. fst w = a \<and> w \<in> lib_writes ls} \<noteq> {}")
apply(subgoal_tac "{w. fst w = a \<and> (w = (a, ts') \<or> w \<in> lib_writes ls)} = {w. fst w = a \<and> (w \<in> lib_writes ls)} \<union> {(a,ts')}")
apply simp
apply(subgoal_tac "ts' > Max (snd ` {w. fst w = a \<and> w \<in> lib_writes ls}) ")
apply linarith
apply(simp add: lib_valid_fresh_ts_def lib_writes_on_def)
apply simp
apply auto[1]
apply blast+
defer
apply(simp add: tst_def var_def)
apply(subgoal_tac "{w. fst w = aa \<and> (w = (a, ts') \<or> w \<in> lib_writes ls)} = {w. fst w = aa \<and> ( w \<in> lib_writes ls)}")
apply auto[1]
apply auto[1]
apply(simp add: tst_def var_def)
apply(unfold wfs_def writes_on_def lastWr_def)
using tst_def apply auto[1]
apply(simp add: var_def tst_def lib_lastWr_def lib_valid_fresh_ts_def lib_writes_on_def)
apply(subgoal_tac " Max (snd `
{w. fst w = a \<and> (w = (a, ts') \<or> w \<in> lib_writes ls)}) = Max (snd `
{w. fst w = a \<and> (w \<in> lib_writes ls)})")
apply simp
apply(subgoal_tac "{w. fst w = a \<and> (w = (a, ts') \<or> w \<in> lib_writes ls)} = {w. fst w = a \<and> (w \<in> lib_writes ls)} \<union> {(a,ts')}")
defer
apply auto[1]
apply simp
apply(subgoal_tac "b < Max (snd ` {w. fst w = a \<and> w \<in> lib_writes ls}) ")
defer
apply(subgoal_tac "snd ` {w. fst w = a \<and> w \<in> lib_writes ls} \<noteq> {}")
apply(subgoal_tac "finite (snd ` {w. fst w = a \<and> w \<in> lib_writes ls})")
apply(subgoal_tac "b \<in> (snd ` {w. fst w = a \<and> w \<in> lib_writes ls}) ")
apply (simp add: member_less_max)
apply(simp add: lib_visible_writes_def lib_writes_on_def)
defer apply simp
apply blast
apply(subgoal_tac "ts' < Max (snd ` {w. fst w = a \<and> w \<in> lib_writes ls}) ")
apply(subgoal_tac "snd ` {w. fst w = a \<and> w \<in> lib_writes ls} \<noteq> {}")
apply(subgoal_tac "finite (snd ` {w. fst w = a \<and> w \<in> lib_writes ls})")
apply auto[1]
apply auto[1]
apply blast
apply(elim conjE)
apply(erule_tac x = " Max (snd ` {w. fst w = a \<and> w \<in> lib_writes ls})" in allE)
apply(subgoal_tac " (a, Max (snd ` {w. fst w = a \<and> w \<in> lib_writes ls}))
\<in> lib_writes ls")
apply blast
apply(subgoal_tac "snd ` {w. fst w = a \<and> w \<in> lib_writes ls} \<noteq> {}")
apply(subgoal_tac "finite (snd ` {w. fst w = a \<and> w \<in> lib_writes ls})")
apply(subgoal_tac "Max (snd ` {w. fst w = a \<and> w \<in> lib_writes ls}) \<in> (snd ` {w. fst w = a \<and> w \<in> lib_writes ls})")
apply force
apply auto[1]
apply blast+
proof -
fix a :: nat and b :: rat and ts' :: rat and aa :: nat
assume a1: "a = x \<and> (a, b) \<in> lib_writes ls \<and> tst (lib_thrView ls t x) \<le> b"
assume "\<forall>a b. (a, b) \<in> lib_writes ls \<longrightarrow> lib_modView ls (a, b) LVARS a = (a, b)"
assume "\<forall>a b x. fst (lib_modView ls (a, b) LVARS x) = x \<and> lib_modView ls (a, b) LVARS x \<in> lib_writes ls"
have "(x, b) \<in> {p. fst p = x \<and> p \<in> lib_writes ls}"
using a1 by auto
then show "b \<in> snd ` {p. fst p = x \<and> p \<in> lib_writes ls}"
by (metis (no_types) rev_image_eqI snd_conv)
qed
lemma lock_release_wfs_pres:
assumes "wfs cs"
and "lib_wfs ls cs"
and "lock_release_step t x ls cs ls' cs'"
shows "wfs cs"
using assms
apply(simp add: lib_wfs_def lock_release_step_def lib_writes_on_def lock_release_def lib_write_def)
done
lemma lock_acqure_unsuccessfulib_pres_d_obs:
assumes "wfs cs"
and "lib_wfs ls cs"
and "[lib(x) =\<^sub>t u] ls"
and "lock_acquire_step t x ls cs ls' cs' False ver"
shows "[lib(x) =\<^sub>t u] ls'"
using assms
apply (simp add: lock_acquire_step_def lock_acquire_def lib_d_obs_t_def lib_d_obs_def)
apply(elim exE conjE)
apply(subgoal_tac "a = x", simp_all)
apply safe
apply(case_tac "even (lib_value ls (x, b))", simp)
apply simp
apply(simp add: lib_read_def lib_value_def lib_update_thrView_def)
by(simp add: lib_visible_writes_def lib_writes_on_def)
lemma lock_acqure_successful_pres_d_obs:
assumes "wfs cs"
and "lib_wfs ls cs"
and "[lib(x) =\<^sub>t u] ls"
and "lock_acquire_step t x ls cs ls' cs' True ver"
shows "[lib(x) =\<^sub>t (u + 1) ] ls'"
using assms
apply(simp add: lib_d_obs_t_def lib_d_obs_def lock_acquire_step_def lock_acquire_def lib_update_def)
apply(elim conjE exE)
apply(simp add: lib_update_def all_updates_l var_def tst_def lib_lastWr_def lib_writes_on_def)
apply(case_tac "even (lib_value ls (a, b))", simp_all)
apply(subgoal_tac "finite {w. fst w = a \<and> w \<in> lib_writes ls}")
apply(subgoal_tac " {w. fst w = a \<and> w \<in> lib_writes ls} \<noteq> {}")
apply(subgoal_tac " {w. fst w = a \<and> (w = (a, ts') \<or> w \<in> lib_writes ls)} = {w. fst w = a \<and> w \<in> lib_writes ls} \<union> {(a, ts')}")
defer
apply(simp add: lib_wfs_def lib_writes_on_def)
using Collect_cong apply auto[1]
apply(simp add: lib_wfs_def lib_writes_on_def)
apply (metis prod.collapse var_def)
apply(simp add: lib_wfs_def lib_writes_on_def)
using var_def apply auto[1]
apply(subgoal_tac "lib_visible_writes ls t x = {lib_lastWr ls x}")
apply(simp add: lib_value_def ts_oride_def lib_releasing_def tst_def var_def lib_visible_writes_def lib_writes_on_def lib_valid_fresh_ts_def )
apply(intro conjI impI allI)
apply(simp_all add: lib_wfs_def lib_writes_on_def var_def tst_def)
using max.absorb2 apply auto[1]
apply auto[1]
using less_eq_rat_def apply auto[1]
defer
using less_eq_rat_def apply auto[1]
using less_eq_rat_def apply auto[1]
using less_eq_rat_def apply auto[1]
apply (metis (no_types, lifting) max.absorb1 max.coboundedI2 max.strict_order_iff)
apply (meson assms(2) assms(3) d_obs_vw)
apply(simp add: lib_lastWr_def lib_writes_on_def)
apply(case_tac "b = Max (snd ` {w. fst w = x \<and> w \<in> lib_writes ls})", simp_all)
apply(simp add: tst_def var_def)
by (metis (no_types, lifting) antisym mem_Collect_eq singletonI snd_conv)
lemma lock_acqure_unsuccessful_client_pres_d_obs:
assumes "wfs cs"
and "lib_wfs ls cs"
and "[x =\<^sub>t v] cs"
and "lock_acquire_step t y ls cs ls' cs' False ver"
shows "[x =\<^sub>t v ] cs'"
using assms
apply (simp add: lock_acquire_step_def lock_acquire_def )
apply (elim exE conjE)
apply(subgoal_tac "a = y", simp_all)
apply (case_tac "even (lib_value ls (y, b))", simp_all)
by (simp add: lib_visible_writes_def lib_writes_on_def)
lemma last_client_lock_acquire:
assumes "wfs cs"
and "lib_wfs ls cs"
and "lock_acquire_step t y ls cs ls' cs' res ver"
shows "lastWr cs' x = lastWr cs x"
using assms
apply(simp add: lock_acquire_step_def lastWr_def)
apply(simp add: lock_acquire_def)
apply(elim exE conjE)
apply(case_tac " even (lib_value ls (a, b))", simp_all)
apply(simp add: lib_update_def)
apply(simp add: update_thrView_def lib_add_cv_def lib_update_thrView_def lib_update_modView_def lib_update_mods_def lib_writes_on_def)
apply safe
apply(case_tac "lib_releasing ls (a, b)", simp_all)
apply(unfold writes_on_def)[1]
by simp
lemma writes_client_lock_acquire:
assumes "wfs cs"
and "lib_wfs ls cs"
and "lock_acquire_step t y ls cs ls' cs' res ver"
shows "writes_on cs x = writes_on cs' x"
using assms
apply(simp add: lock_acquire_step_def)
apply (elim exE conjE)
apply(simp add: lock_acquire_def)
apply(case_tac " even (lib_value ls (a,b))", simp_all)
apply(simp add: lib_update_def)
apply(unfold writes_on_def)
by(simp add: update_thrView_def lib_add_cv_def lib_update_thrView_def lib_update_modView_def lib_update_mods_def lib_writes_on_def)
lemma mods_client_lock_acquire:
assumes "wfs cs"
and "lib_wfs ls cs"
and "lock_acquire_step t y ls cs ls' cs' res ver"
shows "mods cs = mods cs'"
using assms
apply(simp add: lock_acquire_step_def)
apply (elim exE conjE)
apply(simp add: lock_acquire_def)
apply(case_tac " even (lib_value ls (a,b))", simp_all)
by(simp add: lib_update_def update_thrView_def)
lemma lock_acqure_successfulib_client_pres_d_obs:
assumes "wfs cs"
and "lib_wfs ls cs"
and "[x =\<^sub>t v] cs"
and "lock_acquire_step t y ls cs ls' cs' True ver"
shows "[x =\<^sub>t v ] cs'"
using assms
apply(simp add: d_obs_t_def d_obs_def)
apply safe
apply(simp add: lastWr_def)
apply(subgoal_tac "writes_on cs' x = writes_on cs x")
defer
using writes_client_lock_acquire apply blast
apply (simp add: last_client_lock_acquire mods_client_lock_acquire value_def)
apply simp
apply (simp add: lock_acquire_step_def lock_acquire_def lib_update_def)
apply (elim conjE exE)
apply(case_tac "even (lib_value ls (a, b))", simp_all)
apply(simp add: lib_update_def all_updates_l)
apply(case_tac "lib_releasing ls (a, b)", simp_all)
apply(subgoal_tac "tst (thrView cs t x) \<ge> tst ((lib_modView ls (a, b) CVARS) x)")
defer
apply (simp add: lib_wfs_def)
apply(subgoal_tac "ts_oride (thrView cs t) (lib_modView ls (a, b) CVARS) x = thrView cs t x")
apply simp
apply(simp add: ts_oride_def)
apply(intro impI)
apply(unfold wfs_def writes_on_def, simp)
by (metis (no_types, lifting) antisym assms(1) lib_pair lib_wfs_def writes_on_var)
lemma lock_acquire_unsuccessful_p_obs:
assumes "wfs cs"
and "lib_wfs ls cs"
and "[lib(x) =\<^sub>t v] ls"
and "\<not>[lib(x) \<approx>\<^sub>t' u] ls"
and "u\<noteq>v "
and "lock_acquire_step t x ls cs ls' cs' False ver"
shows "\<not>[lib(x) \<approx>\<^sub>t' u] ls'"
using assms
apply (simp add: lock_acquire_step_def lib_read_def lock_acquire_def)
apply safe
by(case_tac "even (lib_value ls (a, b))", simp_all)
lemma lock_acquire_unsuccessful_d_obs_pres:
assumes "wfs cs"
and "lib_wfs ls cs"
and "[lib(x) =\<^sub>t' v] ls"
and "lock_acquire_step t x ls cs ls' cs' False ver"
shows "[lib(x) =\<^sub>t' v] ls'"
using assms
apply (simp add: lock_acquire_step_def lib_read_def lock_acquire_def)
apply(elim exE conjE)
by(case_tac "even (lib_value ls (a,b))", simp_all)
lemma lock_acquire_unsuccessfulib_c_obs_pres:
assumes "wfs cs"
and "lib_wfs ls cs"
and "[lib(y) = v]\<lparr>x =\<^sub>t u\<rparr> ls cs"
and "lock_acquire_step t' y ls cs ls' cs' False ver"
shows "[lib(y) = v]\<lparr>x =\<^sub>t u\<rparr> ls' cs'"
using assms
apply (simp add: lock_acquire_step_def lib_read_def lock_acquire_def)
apply safe
by(case_tac "even (lib_value ls (a,b))", simp_all)
lemma lock_acquire_successfulib_version:
assumes "wfs cs"
and "lib_wfs ls cs"
and "odd m"
and "even n"
and "\<forall> z . z\<notin>{m,n} \<longrightarrow> \<not>[lib(x) \<approx>\<^sub>t z] ls "
and "lock_acquire_step t x ls cs ls' cs' True ver"
shows "ver = n"
using assms
apply (simp add: lock_acquire_step_def lock_acquire_def)
apply safe
apply(case_tac "even (lib_value ls (a,b))", simp_all)
apply(simp add: lib_update_def)
apply(case_tac "lib_releasing ls (a,b)", simp_all)
apply(simp add: lib_add_cv_def lib_update_modView_def lib_update_mods_def lib_update_thrView_def update_thrView_def)
apply(simp add: lib_visible_writes_def lib_valid_fresh_ts_def lib_writes_on_def lib_p_obs_def lib_value_def)
apply safe
apply metis
by (metis lib_p_obs_def)
lemma lock_acquire_successful_c_o_s:
assumes "wfs cs"
and "lib_wfs ls cs"
and "[lib(y) = n]\<lparr>x =\<^sub>t u\<rparr> ls cs"
and "lock_acquire_step t y ls cs ls' cs' True n"
shows "[x =\<^sub>t u] cs'"
using assms
apply (simp add: lock_acquire_step_def lock_acquire_def)
apply safe
apply(case_tac "even (lib_value ls (a,b))", simp_all)
apply(simp add: lib_update_def)
apply(simp add: lib_add_cv_def lib_update_modView_def lib_update_mods_def lib_update_thrView_def update_thrView_def)
apply(simp add: lib_visible_writes_def lib_valid_fresh_ts_def lib_writes_on_def lib_p_obs_def lib_value_def lib_c_obs_def d_obs_def d_obs_t_def)
apply(simp add: lastWr_def lib_writes_on_def ts_oride_def)
apply safe
apply(unfold writes_on_def)
apply simp_all
apply(simp_all add: value_def)
apply(simp add: lib_wfs_def lib_writes_on_def)
apply(simp add: tst_def var_def)
apply(unfold wfs_def writes_on_def, simp)
apply clarsimp
apply(subgoal_tac "tst (thrView cs t x) \<le> tst (lastWr cs x)")
defer
apply (meson assms(1) last_write_max wfs_def)
by(simp add: tst_def var_def lastWr_def)
lemma lock_acquire_successful_c_o:
assumes "wfs cs"
and "lib_wfs ls cs"
and "odd m"
and "even n"
and "\<forall> z . z\<notin>{m,n} \<longrightarrow> \<not>[lib(x) \<approx>\<^sub>t z] ls "
and "lock_acquire_step t x ls cs ls' cs' True ver"
and "[lib(x) = n]\<lparr>x =\<^sub>t u\<rparr> ls cs"
shows "[x =\<^sub>t u] cs'"
using assms
apply (simp add: lock_acquire_step_def lock_acquire_def)
apply safe
apply(case_tac "even (lib_value ls (a,b))", simp_all)
apply(simp add: lib_update_def)
apply(case_tac "ver \<noteq> n", simp_all)
apply (metis OpSem.null_def assms(3) lib_p_obs_def numeral_2_eq_2)
apply(case_tac "lib_releasing ls (a,b)", simp_all)
using assms(6) lock_acquire_successful_c_o_s apply blast
using lib_c_obs_def by blast
lemma lock_acquire_successful_not_p_obs_pres:
assumes "wfs cs"
and "lib_wfs ls cs"
and "\<not>[lib(x) \<approx>\<^sub>t u] ls"
and "lock_acquire_step t x ls cs ls' cs' False ver"
shows "\<not>[lib(x) \<approx>\<^sub>t u] ls'"
using assms
apply (simp add: lock_acquire_step_def lock_acquire_def)
apply safe
by(case_tac "even (lib_value ls (a,b))", simp_all)
lemma lock_acquire_unsuccessful_diff_t_d_p_obs_pres:
assumes "wfs cs"
and "lib_wfs ls cs"
and "[x =\<^sub>t u] cs"
and "t \<noteq> t'"
and "lock_acquire_step t' y ls cs ls' cs' False ver"
shows "[x =\<^sub>t u] cs'"
using assms
apply (simp add: lock_acquire_step_def lock_acquire_def)
apply safe
by(case_tac "even (lib_value ls (a,b))", simp_all)
lemma lock_acquire_successfulib_diff_t_d_p_obs_pres:
assumes "wfs cs"
and "lib_wfs ls cs"
and "[x =\<^sub>t u] cs"
and "t \<noteq> t'"
and "lock_acquire_step t' y ls cs ls' cs' True ver"
shows "[x =\<^sub>t u] cs'"
using assms
apply (simp add: lock_acquire_step_def lock_acquire_def)
apply safe
apply(case_tac "even (lib_value ls (a,b))", simp_all)
apply(simp add: d_obs_t_def d_obs_def lastWr_def lib_read_def)
apply safe
apply(simp_all add: lib_update_def update_thrView_def)
apply safe
apply(unfold writes_on_def)
apply(case_tac "lib_releasing ls (a,b)", simp_all)
by (simp add: value_def)
lemma lock_acquire_unsuccessfulib_cvd_pres:
assumes "wfs cs"
and "lib_wfs ls cs"
and "cvd[lib(x), u] ls"
and "lock_acquire_step t' x ls cs ls' cs' False ver"
shows "cvd[lib(x), u] ls'"
using assms
apply(simp add: lock_acquire_step_def lock_acquire_def)
apply(elim exE)
by(case_tac "even (lib_value ls (a,b))", simp_all)
lemma lock_acquire_successfulib_cvd:
assumes "wfs cs"
and "lib_wfs ls cs"
and "cvd[lib(x), u] ls"
and "lock_acquire_step t' x ls cs ls' cs' True ver"
shows "cvd[lib(x), (u+1)] ls'"
using assms
apply(simp add: lock_acquire_step_def lock_acquire_def)
apply(elim exE conjE)
apply(case_tac "(a, b) \<noteq> lib_lastWr ls a")
apply(simp add: lib_update_def all_updates_l lib_covered_v_def lib_visible_writes_def lib_writes_on_def lib_lastWr_def)
apply blast
apply(case_tac "even (lib_value ls (a, b))", simp_all)
apply(simp add: lib_update_def all_updates_l lib_covered_v_def)
apply(simp_all add: lib_writes_on_def lib_lastWr_def var_def tst_def lib_valid_fresh_ts_def)
apply(subgoal_tac "a = x", simp_all)
apply(subgoal_tac "finite {w. fst w = x \<and> w \<in> lib_writes ls}")
apply(subgoal_tac "{w. fst w = x \<and> w \<in> lib_writes ls} \<noteq> {}")
defer
apply(simp add: lib_visible_writes_def lib_writes_on_def)
apply blast
apply(simp add: lib_wfs_def lib_writes_on_def)
using var_def apply auto[1]
apply(simp add: lib_visible_writes_def lib_writes_on_def)
apply(subgoal_tac "{w. fst w = x \<and>
(w = (x, ts') \<or> w \<in> lib_writes ls)} = {w. fst w = x \<and>
(w \<in> lib_writes ls)} \<union> {(x, ts')}")
defer
apply auto[1]
apply simp
apply(intro allI conjI impI, case_tac "lib_releasing ls
(x, Max (snd ` {w. fst w = x \<and> w \<in> lib_writes ls}))", simp_all)
apply(elim conjE)
apply(subgoal_tac "Max (snd ` {w. fst w = x \<and> w \<in> lib_writes ls}) < ts'")
apply(subgoal_tac "Max (snd ` {w. fst w = x \<and> w \<in> lib_writes ls}) \<in> (snd ` {w. fst w = x \<and> w \<in> lib_writes ls})")
apply (meson max.strict_order_iff)
apply(subgoal_tac "finite (snd `{w. fst w = x \<and> w \<in> lib_writes ls})")
apply(subgoal_tac "(snd `{w. fst w = x \<and> w \<in> lib_writes ls}) \<noteq> {}")
apply (meson Max_in)
apply force
apply blast
apply(subgoal_tac "Max (snd ` {w. fst w = x \<and> w \<in> lib_writes ls}) \<in> (snd ` {w. fst w = x \<and> w \<in> lib_writes ls})")
apply simp
apply(subgoal_tac "finite (snd `{w. fst w = x \<and> w \<in> lib_writes ls})")
apply(subgoal_tac "(snd `{w. fst w = x \<and> w \<in> lib_writes ls}) \<noteq> {}")
apply auto[1]
apply simp
apply blast
apply(simp add: lib_value_def lib_wfs_def lib_writes_on_def lib_visible_writes_def )
apply(intro conjI impI, elim conjE)
apply blast
apply(elim conjE disjE)
apply(simp add: lib_value_def lib_wfs_def lib_writes_on_def lib_visible_writes_def )
apply (simp add: max.strict_order_iff)
apply(simp add: lib_value_def lib_wfs_def lib_writes_on_def lib_visible_writes_def )
apply(simp add: lib_value_def lib_wfs_def lib_writes_on_def lib_visible_writes_def )
by auto
lemma lock_acquire_cvd_odd_false:
assumes "wfs cs"
and "lib_wfs ls cs"
and "cvd[lib(x), u] ls"
and "odd u"
and "lock_acquire_step t' x ls cs ls' cs' res ver"
shows "\<not>res"
using assms
apply(simp add: lock_acquire_step_def lib_covered_v_def lock_acquire_def)
apply(elim conjE exE)
apply(case_tac "even (lib_value ls (a,b))")
apply(simp add: lib_visible_writes_def lib_writes_on_def lib_value_def)
by auto
lemma lock_rel_c_obs_intro:
assumes "wfs cs"
and "lib_wfs ls cs"
and "\<not> [lib(y) \<approx>\<^sub>t' u] ls"
and "[x =\<^sub>t m] cs"
and "cvd[lib(y), v] ls"
and "t \<noteq> t'"
and "lock_release_step t y ls cs ls' cs'"
shows "[lib(y) = u]\<lparr>x =\<^sub>t' m\<rparr> ls' cs'"
using assms
apply(simp add: lock_release_step_def lib_p_obs_def lib_d_obs_def lib_d_obs_t_def d_obs_def d_obs_t_def)
apply(elim exE conjE)
apply(simp add: lock_release_def lib_write_def lib_update_mods_def lib_update_modView_def lib_update_thrView_def)
apply(simp add: lib_valid_fresh_ts_def lib_writes_on_def lib_visible_writes_def lib_c_obs_def d_obs_def)
apply safe
apply(simp add: lib_releasing_def)
apply(simp add: lastWr_def value_def lib_value_def)
apply(unfold writes_on_def)
apply blast
apply(simp add: lib_releasing_def lib_value_def)
by blast
lemma lock_acqure_lib_wfs_pres:
assumes "wfs cs"
and "lib_wfs ls cs"
and "lock_acquire_step t x ls cs ls' cs' res ver"
shows "lib_wfs ls' cs'"
using assms
apply(simp add: lock_acquire_step_def)
apply(elim exE conjE)
apply(simp add: lock_acquire_def)
apply(case_tac "even (lib_value ls (a, b))")
apply(simp add: lib_update_def all_updates_l)
apply(case_tac "lib_releasing ls (a, b)")
apply(simp add: lib_wfs_def lib_writes_on_def)
apply(intro allI conjI impI)
apply(simp add: var_def ts_oride_def)
apply (simp add: ts_oride_def)
apply(unfold writes_on_def var_def wfs_def ts_oride_def, simp)[1]
apply(unfold writes_on_def var_def wfs_def ts_oride_def, simp)[1]
apply(simp add: var_def ts_oride_def)
apply (simp add: ts_oride_def)
defer
apply (metis (no_types, lifting) lib_visible_writes_def lib_writes_on_def mem_Collect_eq)
apply blast
apply(simp add: lib_valid_fresh_ts_def ts_oride_def)
apply(intro impI)
apply(subgoal_tac "lib_modView ls (a, b) LVARS a = (a,b)")
apply(simp add: tst_def)
apply (metis (no_types, lifting) lib_visible_writes_def lib_writes_on_def mem_Collect_eq)
apply(simp add: lib_valid_fresh_ts_def ts_oride_def)
apply(intro impI)
apply(subgoal_tac "lib_modView ls (a, b) LVARS a = (a,b)")
apply(simp add: tst_def)
apply (metis (no_types, lifting) lib_visible_writes_def lib_writes_on_def mem_Collect_eq)
apply blast
apply(simp add: lib_lastWr_def lib_writes_on_def)
apply(intro impI)
apply(subgoal_tac "ts'>b")
apply(subgoal_tac "ts' \<in> tst ` {w. var w = a \<and> (w = (a, ts') \<or> w \<in> lib_writes ls)}")
apply(subgoal_tac "finite (tst ` {w. var w = a \<and> (w = (a, ts') \<or> w \<in> lib_writes ls)})")
apply(simp add: var_def tst_def)
using Max_less_iff not_max apply blast
apply (simp add: finite_lib_writes)
apply(simp add: tst_def var_def)
apply(subgoal_tac " (a, ts')\<in>{w. fst w = a \<and> (w = (a, ts') \<or> w \<in> lib_writes ls)}")
apply (simp add: image_iff)
apply auto[1]
apply(simp add: lib_valid_fresh_ts_def)
apply(simp add: lib_lastWr_def lib_writes_on_def)
apply(case_tac "xa \<noteq> a", simp_all)
apply(subgoal_tac "{w. var w = xa \<and> (w = (a, ts') \<or> w \<in> lib_writes ls)} = {w. var w = xa \<and> w \<in> lib_writes ls}")
apply simp
apply(simp add: var_def)
apply auto[1]
defer
apply(simp add: tst_def lastWr_def ts_oride_def var_def)
apply(unfold writes_on_def var_def wfs_def, simp)[1]
apply(simp add: tst_def lastWr_def ts_oride_def var_def)
apply(unfold writes_on_def var_def wfs_def, simp)[1]
apply(simp add: lib_wfs_def lib_writes_on_def)
apply(intro conjI impI allI)
defer
apply(simp add: lib_visible_writes_def)
using lib_writes_on_def apply auto[1]
apply blast
apply(simp add: lib_lastWr_def lib_writes_on_def)
apply(intro impI)
apply(simp add: tst_def var_def lib_visible_writes_def lib_writes_on_def)
defer
apply(simp add: lib_lastWr_def lib_writes_on_def)
apply(simp add: tst_def var_def lib_visible_writes_def lib_writes_on_def)
defer
apply(unfold wfs_def writes_on_def, simp)[1]
apply (meson assms(1) last_write_max wfs_def)
defer
apply(case_tac "lib_lastWr ls a = (a,b)")
apply(subgoal_tac "b = Max (tst ` {w. var w = a \<and> w \<in> lib_writes ls})", simp_all)
apply(subgoal_tac "ts' > b", simp_all)
apply(subgoal_tac "ts'= Max (tst ` {w. var w = a \<and> (w = (a, ts') \<or> w \<in> lib_writes ls)})", simp_all)
apply(simp add: lib_valid_fresh_ts_def lib_writes_on_def)
apply blast
apply(simp add: lib_valid_fresh_ts_def lib_writes_on_def)
apply(subgoal_tac "ts' > Max (tst ` {w. var w = a \<and> w \<in> lib_writes ls})", simp_all)
apply(subgoal_tac " {w. var w = a \<and> (w = (a, ts') \<or> w \<in> lib_writes ls)} = {w. var w = a \<and> ( w \<in> lib_writes ls)} \<union> {(a, ts')}")
apply(subgoal_tac " finite {w. var w = a \<and> ( w \<in> lib_writes ls)}")
apply(subgoal_tac "{w. var w = a \<and> ( w \<in> lib_writes ls)} \<noteq> {}")
apply simp
apply (metis (no_types, lifting) lib_visible_writes_def lib_writes_on_def max.strict_order_iff mem_Collect_eq)
apply blast
apply blast
apply(simp add: var_def lib_valid_fresh_ts_def lib_writes_on_def)
apply auto[1]
apply(simp add: var_def lib_valid_fresh_ts_def lib_writes_on_def)
apply (simp add: lib_lastWr_def lib_writes_on_def)
apply(subgoal_tac "lib_lastWr ls a \<in> lib_writes_on ls a")
apply(subgoal_tac "b < tst (lib_lastWr ls a)")
apply(subgoal_tac "ts' < tst (lib_lastWr ls a)")
apply(simp add: lib_valid_fresh_ts_def lib_writes_on_def)
apply(subgoal_tac "Max (tst ` {w. var w = a \<and> (w = (a, ts') \<or> w \<in> lib_writes ls)})
= Max (tst ` {w. var w = a \<and> w \<in> lib_writes ls})")
apply simp
apply(subgoal_tac " {w. var w = a \<and> (w = (a, ts') \<or> w \<in> lib_writes ls)} = {w. var w = a \<and> ( w \<in> lib_writes ls)} \<union> {(a, ts')}")
apply(subgoal_tac " finite {w. var w = a \<and> ( w \<in> lib_writes ls)}")
apply(subgoal_tac "{w. var w = a \<and> ( w \<in> lib_writes ls)} \<noteq> {}")
apply (simp add: var_def tst_def lib_lastWr_def lib_writes_on_def)
apply (simp add: var_def tst_def lib_lastWr_def lib_writes_on_def)
apply blast
apply blast
apply (simp add: var_def tst_def lib_lastWr_def lib_writes_on_def)
using Collect_cong apply auto[1]
apply (simp add: var_def tst_def lib_lastWr_def lib_writes_on_def lib_valid_fresh_ts_def)
apply (simp add: var_def tst_def lib_visible_writes_def lib_lastWr_def lib_writes_on_def lib_valid_fresh_ts_def)
apply(elim conjE, simp add: lib_value_def)
apply(erule_tac x = "Max (snd ` {w. fst w = x \<and> w \<in> lib_writes ls})" in allE, simp)
apply(subgoal_tac "finite {w. fst w = x \<and> w \<in> lib_writes ls}")
apply(subgoal_tac "{w. fst w = x \<and> w \<in> lib_writes ls} \<noteq> {}")
apply(subgoal_tac "b \<in> snd `{w. fst w = x \<and> w \<in> lib_writes ls}")
apply(subgoal_tac "Max (snd ` {w. fst w = x \<and> w \<in> lib_writes ls}) \<in> snd `{w. fst w = x \<and> w \<in> lib_writes ls}")
apply simp
apply (simp add: member_less_max)
using Max_in apply blast
apply (simp add: image_iff)
apply blast
apply blast
apply(simp add: lib_lastWr_def lib_writes_on_def)
apply(simp add: var_def tst_def lib_visible_writes_def lib_writes_on_def)
apply(elim conjE)
apply(subgoal_tac "finite( snd ` {w. fst w = x \<and> w \<in> lib_writes ls})")
apply(subgoal_tac "snd ` {w. fst w = x \<and> w \<in> lib_writes ls} \<noteq> {}")
defer
apply blast
apply blast
apply(case_tac "xa = a", simp_all)
apply (simp add: finite_lib_writes)
apply (simp add: finite_lib_writes_2)
apply(simp add: lib_valid_fresh_ts_def lib_writes_on_def)
apply(elim conjE)
apply(case_tac "lib_lastWr ls x = (x,b)")
apply(subgoal_tac "b = Max (tst ` {w. var w = x \<and> w \<in> lib_writes ls})", simp_all)
apply(subgoal_tac "ts' > b")
apply(subgoal_tac "ts'= Max (tst ` {w. var w = x \<and> (w = (x, ts') \<or> w \<in> lib_writes ls)})", simp_all)
using tst_def var_def apply force
apply(subgoal_tac "ts' > Max (tst ` {w. var w = x \<and> w \<in> lib_writes ls})")
apply(subgoal_tac " {w. var w = x \<and> (w = (x, ts') \<or> w \<in> lib_writes ls)} = {w. var w = x \<and> ( w \<in> lib_writes ls)} \<union> {(x, ts')}")
apply(subgoal_tac " finite {w. var w = x \<and> ( w \<in> lib_writes ls)}")
apply(subgoal_tac "{w. var w = x \<and> ( w \<in> lib_writes ls)} \<noteq> {}")
apply simp
apply (metis (no_types, lifting) max.strict_order_iff )
apply auto[1]
using var_def apply auto[1]
apply(simp add: var_def tst_def)
apply auto[1]
apply(simp add: var_def tst_def)
apply(simp add: lib_lastWr_def lib_writes_on_def tst_def var_def)
apply(subgoal_tac "lib_lastWr ls x \<in> lib_writes_on ls x")
apply(subgoal_tac "b < tst (lib_lastWr ls x)")
apply(subgoal_tac "ts' < tst (lib_lastWr ls x)")
apply(simp add: lib_valid_fresh_ts_def lib_writes_on_def)
apply(subgoal_tac "Max (tst ` {w. var w = x \<and> (w = (x, ts') \<or> w \<in> lib_writes ls)})
= Max (tst ` {w. var w = x \<and> w \<in> lib_writes ls})")
apply simp
apply(subgoal_tac " {w. var w = x \<and> (w = (x, ts') \<or> w \<in> lib_writes ls)} = {w. var w = x \<and> ( w \<in> lib_writes ls)} \<union> {(x, ts')}")
apply(subgoal_tac " finite {w. var w = x \<and> ( w \<in> lib_writes ls)}")
apply(subgoal_tac "{w. var w = x \<and> ( w \<in> lib_writes ls)} \<noteq> {}")
apply (simp add: var_def tst_def lib_lastWr_def lib_writes_on_def)
apply (simp add: var_def tst_def lib_lastWr_def lib_writes_on_def)
apply blast
apply(simp add: var_def) apply auto[1]
apply(subgoal_tac " {w. var w = x \<and> (w = (x, ts') \<or> w \<in> lib_writes ls)} = {w. var w = x \<and> ( w \<in> lib_writes ls)} \<union> {(x, ts')}")
apply(subgoal_tac " finite {w. var w = x \<and> ( w \<in> lib_writes ls)}")
apply(subgoal_tac "{w. var w = x \<and> ( w \<in> lib_writes ls)} \<noteq> {}")
apply (simp add: var_def tst_def lib_lastWr_def lib_writes_on_def)
apply blast+
apply (simp add: var_def)
apply (simp add: var_def tst_def )
apply auto[1]
apply (simp add: var_def tst_def lib_lastWr_def lib_writes_on_def)
apply(simp add: tst_def lib_lastWr_def lib_writes_on_def var_def)
apply(subgoal_tac " finite {w. fst w = x \<and> ( w \<in> lib_writes ls)}")
apply(subgoal_tac "{w. fst w = x \<and> ( w \<in> lib_writes ls)} \<noteq> {}")
apply (simp add: image_iff member_less_max)
apply blast+
apply(simp add: lib_lastWr_def lib_writes_on_def tst_def var_def)
apply(subgoal_tac "finite ( (snd ` {w. fst w = x \<and> w \<in> lib_writes ls}))")
apply(subgoal_tac " (snd ` {w. fst w = x \<and> w \<in> lib_writes ls}) \<noteq> {}")
defer
apply blast+
apply(case_tac "xa = x")
apply(elim conjE, simp)
apply(subgoal_tac "finite ((snd ` {w. fst w = x \<and> (w = (x, ts') \<or> w \<in> lib_writes ls)}))")
apply(subgoal_tac "((snd ` {w. fst w = x \<and> (w = (x, ts') \<or> w \<in> lib_writes ls)})) \<noteq> {}")
apply(subgoal_tac " {w. var w = x \<and> (w = (x, ts') \<or> w \<in> lib_writes ls)} = {w. var w = x \<and> ( w \<in> lib_writes ls)} \<union> {(x, ts')}")
apply(case_tac "lib_lastWr ls x = (x, b)", simp_all)
apply(case_tac "ts' = Max (snd ` {w. fst w = x \<and> (w = (x, ts') \<or> w \<in> lib_writes ls)})", simp_all)
apply(simp add: lib_valid_fresh_ts_def lib_writes_on_def)
apply blast
apply(simp add: lib_valid_fresh_ts_def lib_writes_on_def)
apply(case_tac "ts' < Max (snd ` {w. fst w = x \<and> w \<in> lib_writes ls})")
apply(simp add: lib_lastWr_def lib_writes_on_def var_def tst_def)
apply (simp add: var_def tst_def lib_lastWr_def lib_writes_on_def)
apply(subgoal_tac "ts' > Max (snd ` {w. fst w = x \<and> w \<in> lib_writes ls})", simp)
apply(subgoal_tac "ts' = Max (insert ts' (snd ` {w. fst w = x \<and> w \<in> lib_writes ls}))")
apply linarith
using max_of_union [where s = "(snd ` {w. fst w = x \<and> w \<in> lib_writes ls})"]
apply simp
apply (metis (no_types, lifting) Max_insert Max_singleton finite_imageI)
apply blast+
apply(simp add: lib_lastWr_def lib_writes_on_def tst_def var_def)
apply(subgoal_tac "Max (insert ts' (snd ` {w. fst w = x \<and> w \<in> lib_writes ls})) = Max (snd ` {w. fst w = x \<and> w \<in> lib_writes ls})")
apply simp
apply(subgoal_tac "ts' < Max (snd ` {w. fst w = x \<and> w \<in> lib_writes ls})")
apply(subgoal_tac "finite ( (snd ` {w. fst w = x \<and> w \<in> lib_writes ls}))")
apply(subgoal_tac " (snd ` {w. fst w = x \<and> w \<in> lib_writes ls}) \<noteq> {}")
using member_less_max apply auto[1]
apply blast+
apply(simp add: lib_valid_fresh_ts_def lib_writes_on_def)
apply(elim conjE)
apply(erule_tac x = "Max (snd ` {w. fst w = x \<and> w \<in> lib_writes ls})" in allE)
apply simp
apply(subgoal_tac " (x, Max (snd ` {w. fst w = x \<and> w \<in> lib_writes ls})) \<in> lib_writes ls")
apply(subgoal_tac " b < Max (snd ` {w. fst w = x \<and> w \<in> lib_writes ls})")
apply(subgoal_tac "finite ( (snd ` {w. fst w = x \<and> w \<in> lib_writes ls}))")
apply(subgoal_tac " (snd ` {w. fst w = x \<and> w \<in> lib_writes ls}) \<noteq> {}")
apply blast
using image_is_empty apply blast
apply blast
apply(subgoal_tac "b\<in> (snd ` {w. fst w = x \<and> w \<in> lib_writes ls})")
apply(subgoal_tac "finite ( (snd ` {w. fst w = x \<and> w \<in> lib_writes ls}))")
apply(subgoal_tac " (snd ` {w. fst w = x \<and> w \<in> lib_writes ls}) \<noteq> {}")
apply (simp add: member_less_max)
apply blast+
apply(subgoal_tac "(x,b)\<in> {w. fst w = x \<and> w \<in> lib_writes ls} ")
apply (simp add: image_iff)
apply simp
apply(subgoal_tac "finite ( (snd ` {w. fst w = x \<and> w \<in> lib_writes ls}))")
apply(subgoal_tac " (snd ` {w. fst w = x \<and> w \<in> lib_writes ls}) \<noteq> {}")
apply(subgoal_tac "(x, Max (snd ` {w. fst w = x \<and> w \<in> lib_writes ls}))\<in>{w. fst w = x \<and> w \<in> lib_writes ls}")
apply blast
apply(subgoal_tac "finite ( ( {w. fst w = x \<and> w \<in> lib_writes ls}))")
apply(subgoal_tac " ( {w. fst w = x \<and> w \<in> lib_writes ls}) \<noteq> {}")
apply(subgoal_tac "Max (snd ` {w. fst w = x \<and> w \<in> lib_writes ls})\<in>snd ` {w. fst w = x \<and> w \<in> lib_writes ls}")
apply (simp add: image_iff)
apply(subgoal_tac "finite ( (snd ` {w. fst w = x \<and> w \<in> lib_writes ls}))")
apply(subgoal_tac " (snd ` {w. fst w = x \<and> w \<in> lib_writes ls}) \<noteq> {}")
apply simp
apply blast+
apply(simp add: var_def tst_def lib_valid_fresh_ts_def lib_writes_on_def)
apply auto[1]
apply blast
apply auto[1]
apply(simp add: var_def tst_def lib_valid_fresh_ts_def lib_writes_on_def)
defer
apply(subgoal_tac "{w. fst w = xa \<and> (w = (x, ts') \<or> w \<in> lib_writes ls)} = {w. fst w = xa \<and> (w \<in> lib_writes ls)}")
apply simp
apply auto[1]
apply(case_tac "xa = a")
apply (simp add: finite_lib_writes)
apply (simp add: finite_lib_writes_2)
defer
defer
apply(subgoal_tac "finite (snd `{w. fst w = x \<and> (w \<in> lib_writes ls)})")
apply(case_tac "(x, ts')\<in>{w. fst w = x \<and> (w \<in> lib_writes ls)}")
apply blast
apply(subgoal_tac " {w. var w = x \<and> (w = (x, ts') \<or> w \<in> lib_writes ls)} = {w. var w = x \<and> ( w \<in> lib_writes ls)} \<union> {(x, ts')}")
apply simp
using var_def apply auto[1]
apply auto[1]
apply blast
apply(subgoal_tac "(x, Max (snd ` {w. fst w = x \<and> w \<in> lib_writes ls}))\<in> {w. fst w = x \<and> w \<in> lib_writes ls}")
apply blast
apply(subgoal_tac "finite ( snd`{w. fst w = x \<and> w \<in> lib_writes ls})")
apply(subgoal_tac "snd` {w. fst w = x \<and> w \<in> lib_writes ls}\<noteq>{}")
defer
apply blast+
apply(subgoal_tac "finite ( snd`{w. fst w = x \<and> w \<in> lib_writes ls})")
apply(subgoal_tac "snd` {w. fst w = x \<and> w \<in> lib_writes ls}\<noteq>{}")
defer
apply blast+
defer
proof -
fix a :: nat and b :: rat and ts' :: rat and aa :: nat and ba :: rat and xa :: nat
assume a1: "finite (snd ` {w. fst w = x \<and> w \<in> lib_writes ls})"
assume a2: "snd ` {w. fst w = x \<and> w \<in> lib_writes ls} \<noteq> {}"
obtain pp :: "(nat \<times> rat) set \<Rightarrow> (nat \<times> rat \<Rightarrow> rat) \<Rightarrow> rat \<Rightarrow> nat \<times> rat" where
"\<forall>x0 x1 x2. (\<exists>v3. x2 = x1 v3 \<and> v3 \<in> x0) = (x2 = x1 (pp x0 x1 x2) \<and> pp x0 x1 x2 \<in> x0)"
by moura
then have f3: "Max (snd ` {p. fst p = x \<and> p \<in> lib_writes ls}) = snd (pp {p. fst p = x \<and> p \<in> lib_writes ls} snd (Max (snd ` {p. fst p = x \<and> p \<in> lib_writes ls}))) \<and> pp {p. fst p = x \<and> p \<in> lib_writes ls} snd (Max (snd ` {p. fst p = x \<and> p \<in> lib_writes ls})) \<in> {p. fst p = x \<and> p \<in> lib_writes ls}"
using a2 a1 by (meson Max_in imageE)
then have "fst (pp {p. fst p = x \<and> p \<in> lib_writes ls} snd (Max (snd ` {p. fst p = x \<and> p \<in> lib_writes ls}))) = x \<and> pp {p. fst p = x \<and> p \<in> lib_writes ls} snd (Max (snd ` {p. fst p = x \<and> p \<in> lib_writes ls})) \<in> lib_writes ls"
by blast
then show "(x, Max (snd ` {p. fst p = x \<and> p \<in> lib_writes ls})) \<in> lib_writes ls"
using f3 by (metis (no_types) prod.collapse)
next
fix a :: nat and b :: rat and ts' :: rat and aa :: nat and ba :: rat and xa :: nat
assume a1: "finite (snd ` {w. fst w = x \<and> w \<in> lib_writes ls})"
assume a2: "snd ` {w. fst w = x \<and> w \<in> lib_writes ls} \<noteq> {}"
obtain pp :: "(nat \<times> rat) set \<Rightarrow> (nat \<times> rat \<Rightarrow> rat) \<Rightarrow> rat \<Rightarrow> nat \<times> rat" where
"\<forall>x0 x1 x2. (\<exists>v3. x2 = x1 v3 \<and> v3 \<in> x0) = (x2 = x1 (pp x0 x1 x2) \<and> pp x0 x1 x2 \<in> x0)"
by moura
then have f3: "Max (snd ` {p. fst p = x \<and> p \<in> lib_writes ls}) = snd (pp {p. fst p = x \<and> p \<in> lib_writes ls} snd (Max (snd ` {p. fst p = x \<and> p \<in> lib_writes ls}))) \<and> pp {p. fst p = x \<and> p \<in> lib_writes ls} snd (Max (snd ` {p. fst p = x \<and> p \<in> lib_writes ls})) \<in> {p. fst p = x \<and> p \<in> lib_writes ls}"
using a2 a1 by (meson Max_in imageE)
then have "fst (pp {p. fst p = x \<and> p \<in> lib_writes ls} snd (Max (snd ` {p. fst p = x \<and> p \<in> lib_writes ls}))) = x \<and> pp {p. fst p = x \<and> p \<in> lib_writes ls} snd (Max (snd ` {p. fst p = x \<and> p \<in> lib_writes ls})) \<in> lib_writes ls"
by blast
then have "(x, Max (snd ` {p. fst p = x \<and> p \<in> lib_writes ls})) = pp {p. fst p = x \<and> p \<in> lib_writes ls} snd (Max (snd ` {p. fst p = x \<and> p \<in> lib_writes ls}))"
using f3 by (metis (no_types) prod.collapse)
then show "(x, Max (snd ` {p. fst p = x \<and> p \<in> lib_writes ls})) \<in> {p. fst p = x \<and> p \<in> lib_writes ls}"
using f3 by presburger
qed
lemma lock_acquire_successful_p_obs:
assumes "wfs cs"
and "lib_wfs ls cs"
and "[lib(x) =\<^sub>t v] ls"
and "\<not>[lib(x) \<approx>\<^sub>t' u] ls"
and "u \<ge> v + 2 "
and "lock_acquire_step t x ls cs ls' cs' True ver"
shows "\<not>[lib(x) \<approx>\<^sub>t' u] ls'"
using assms
apply(subgoal_tac "[lib(x) =\<^sub>t (v+1)] ls'")
defer
using lock_acqure_successful_pres_d_obs apply blast
apply (case_tac "t = t'", simp_all)
using d_obs_vw [where ls = ls' and t = t and x = x and u = "(Suc v)" and cs = cs']
apply simp
apply(simp add: lib_d_obs_t_def lib_d_obs_def lib_p_obs_def)
apply(intro allI impI, elim conjE)
apply(case_tac "(a, b) = lib_lastWr ls' x")
apply simp
using lock_acqure_lib_wfs_pres lock_acqure_wfs_pres apply blast
apply(simp add: lock_acquire_step_def lock_acquire_def)
apply(elim conjE exE)
apply(case_tac "even (lib_value ls (a, b))")
apply(simp add: lib_update_def all_updates_l)
apply(case_tac "lib_releasing ls (a, b)", simp_all)
apply(simp add: lib_p_obs_def lib_visible_writes_def lib_writes_on_def)
apply(simp add: lib_value_def lib_d_obs_t_def lib_d_obs_def)
apply(intro impI)
apply(subgoal_tac "(x, b) = lib_lastWr ls x")
apply simp
apply(elim conjE, simp)
using ts_ge_last_is_last apply blast
apply(simp add: lib_p_obs_def lib_visible_writes_def lib_writes_on_def)
apply(simp add: lib_value_def lib_d_obs_t_def lib_d_obs_def)
apply(intro impI)
apply(subgoal_tac "(x, b) = lib_lastWr ls x")
apply simp
apply(elim conjE, simp)
using ts_ge_last_is_last by blast
lemma cvd_cvv_val:
assumes "wfs cs"
and "lib_wfs ls cs"
and "cvd[lib(l),x] ls"
and "lock_acquire_step t l ls cs ls' cs' True ver"
shows "cvv[lib(l),x] ls'"
using assms
apply (simp add: lock_acquire_step_def lock_acquire_def all_updates_l lib_covered_v_def lib_covered_val_def lib_d_obs_t_def lib_d_obs_def)
apply(elim exE conjE)
apply(case_tac "even (lib_value ls (a, b))", simp_all)
apply(simp add: lib_update_def)
apply(simp add: all_updates_l lib_lastWr_def lib_writes_on_def)
apply(case_tac "lib_releasing ls (a,b)", simp_all)
apply(intro conjI)
apply(simp add: lib_value_def)
apply(rule_tac x="b" in exI)
apply(intro conjI impI)
apply(simp add: lib_valid_fresh_ts_def)
apply(simp add: lib_visible_writes_def)
apply (metis (no_types, lifting) assms(3) lib_covered_v_def lib_lastWr_def lib_writes_on_def mem_Collect_eq prod.inject)
apply(simp add: lib_visible_writes_def)
apply (metis assms(3) lib_covered_v_def lib_lastWr_def lib_value_def prod.inject)
apply(intro allI conjI impI)
apply(simp add: lib_value_def)
apply(intro conjI impI)
apply(simp add: lib_visible_writes_def)
using lib_writes_on_def apply blast
apply(simp add: lib_visible_writes_def lib_writes_on_def)
using lib_writes_on_def apply blast
apply(intro conjI)
apply(simp add: lib_value_def)
apply(rule_tac x=b in exI)
apply(intro conjI impI)
apply(simp add: lib_valid_fresh_ts_def)
apply(simp add: lib_visible_writes_def lib_writes_on_def)
using lib_writes_on_def apply blast
apply(simp add: lib_visible_writes_def lib_writes_on_def)
using lib_writes_on_def apply blast
apply(intro allI conjI impI)
apply(simp add: lib_value_def)
apply(intro conjI impI)
apply(simp add: lib_visible_writes_def)
using lib_writes_on_def apply blast
apply(simp add: lib_visible_writes_def lib_writes_on_def)
using lib_writes_on_def by blast
lemma cvv_lock_acquire_pres:
assumes "wfs cs"
and "l_wfs ls cs"
and "cvv[lib(l),x] ls"
and "lock_acquire_step t l ls cs ls' cs' b ver"
shows "cvv[lib(l),x] ls'"
using assms
apply (simp add: lock_acquire_step_def lock_acquire_def lib_update_def lib_covered_v_def lib_covered_val_def lib_d_obs_t_def lib_d_obs_def)
apply(elim exE conjE)
apply(case_tac "even (lib_value ls (a, ba))", simp_all)
apply(simp add: lib_update_def)
apply(simp add: all_updates_l lib_lastWr_def lib_writes_on_def)
apply(case_tac "lib_releasing ls (a, ba)", simp_all)
apply(intro conjI)
apply(rule_tac x = baa in exI)
apply(intro conjI)
apply blast
apply(simp add: lib_value_def lib_valid_fresh_ts_def lib_visible_writes_def lib_writes_on_def)
apply(intro impI)
using lib_writes_on_def apply blast
apply(intro allI impI conjI)
apply(simp add: lib_value_def lib_valid_fresh_ts_def lib_visible_writes_def)
using lib_writes_on_def less_Suc_eq apply blast
apply(intro allI impI conjI)
apply(rule_tac x = baa in exI)
apply(intro conjI)
apply blast
apply(simp add: lib_value_def lib_valid_fresh_ts_def lib_visible_writes_def lib_writes_on_def)
apply(intro impI)
using lib_writes_on_def apply blast
apply(simp add: lib_value_def lib_valid_fresh_ts_def lib_visible_writes_def)
using lib_writes_on_def less_Suc_eq apply blast
by blast
lemma lock_acquire_successful_rv:
assumes "wfs cs"
and "lib_wfs ls cs"
and "[lib(l) =\<^sub>t u] ls"
and "lock_acquire_step t l ls cs ls' cs' True ver"
shows "ver = u"
using assms
apply (simp add: lock_acquire_step_def lock_acquire_def)
apply safe
apply(case_tac "even (lib_value ls (a,b))", simp_all)
apply(simp_all add: lib_update_def update_thrView_def)
apply(case_tac "lib_releasing ls (a,b)", simp_all)
apply(simp_all add:all_updates_l lib_value_def )
apply(simp_all add: lib_d_obs_t_def lib_d_obs_def lastWr_def lib_read_def)
apply (metis assms(3) lib_dobs_visible_writes_last lib_value_def)
by (metis assms(3) lib_dobs_visible_writes_last lib_value_def)
lemma cvv_val:
assumes "wfs cs"
and "lib_wfs ls cs"
and "cvv[lib(l),x] ls"
and "lock_acquire_step t l ls cs ls' cs' True ver"
shows "ver \<noteq> x"
using assms
apply (simp add: lock_acquire_step_def lock_acquire_def lib_d_obs_t_def lib_d_obs_def)
apply(simp add: lib_covered_val_def)
apply (elim exE conjE)
apply(case_tac "even (lib_value ls (a,b))", simp_all)
apply(simp add: lib_update_def)
apply(simp add: all_updates_l lib_lastWr_def lib_writes_on_def)
apply(case_tac "lib_releasing ls (a,b)", simp_all)
apply(simp add: lib_value_def lib_visible_writes_def lib_writes_on_def)
using lib_writes_on_def apply blast
apply(case_tac "lib_releasing ls (a,b)", simp_all)
apply(simp add: lib_value_def lib_visible_writes_def lib_writes_on_def)
using lib_writes_on_def by blast
lemma cvv_release:
assumes "lib_wfs ls cs"
and "wfs cs"
and "cvv[lib(l),x] ls"
and "lock_release_step t l ls cs ls' cs'"
shows "cvv[lib(l),x] ls'"
using assms
apply (simp add: lock_release_step_def lock_release_def lib_covered_val_def lib_d_obs_t_def lib_d_obs_def)
apply(elim conjE exE, intro conjI allI)
apply(rule_tac x = a in exI)
apply(rule_tac x = ba in exI)
apply(intro conjI)
apply(simp add: lib_write_def all_updates_l)
apply(simp add: lib_lastWr_def lib_writes_on_def)
apply(simp add: lib_value_def lib_lastWr_def lib_writes_on_def)
using a_is_x lib_visible_writes_def lib_writes_on_def apply blast
apply(simp add: lib_write_def all_updates_l)
apply(simp add: lib_valid_fresh_ts_def lib_writes_on_def lib_value_def lib_visible_writes_def tst_def var_def)
apply safe
using lib_writes_on_def apply blast
apply(simp add: lib_write_def all_updates_l)
apply(simp add: lib_valid_fresh_ts_def lib_writes_on_def lib_value_def lib_visible_writes_def tst_def var_def)
using less_SucI by blast
end
|
C THIS IS A TEST PROGRAM FOR THE FORTRAN CALLABLE PORTION OF THE
C GTPRCS SUBROUTINE
SUBROUTINE TGTPRCS()
CHARACTER*8 B
CHARACTER*30 MSG
CALL GTPRCS(B)
WRITE(MSG,100) B
100 FORMAT(A8)
CALL XVMESSAGE(MSG,' ')
CALL XVMESSAGE(' ',' ')
RETURN
END
|
Elements of the game appeared in the Mega Man comic series from Archie Comics before it went on hiatus . Most notably , King appeared during a time travel story in issue 20 , while issue 55 saw Dr. Light experiencing a vision of the events of the game among other yet @-@ to @-@ be @-@ adapted games .
|
Since 1977, the Neighborhood Community Development Center (NCDC) has kept its ear attuned to the needs of the community. As a result, NCDC has offered programs ranging from AIDS prevention to leadership development to health and wellness camps for our community’s youth.
Currently NCDC hosts a series of events during Minority Health Month, ongoing education and programming for individuals with Lupus and Diabetes, a Youth Wellness program, coat and shoe give-a-ways, and a Back to School Celebration. Through each event, community members are given the necessary tools and training to develop leadership skills to implement these programs.
Contact our Community Developer, Ms. Cynthia Smith at 740.282.8010 ext. 210 or [email protected] to find out more about the exciting opportunities offered through NCDC.
|
Set Implicit Arguments.
Unset Strict Implicit.
Require Import QArith String Ascii.
(*The computable state representation is an FMap over
player indices, represented as positive.*)
Require Import Coq.FSets.FMapAVL Coq.FSets.FMapFacts.
Require Import Structures.Orders NArith.
Require Import mathcomp.ssreflect.ssreflect.
From mathcomp Require Import all_ssreflect.
From mathcomp Require Import all_algebra.
Require Import OUVerT.strings compile OUVerT.orderedtypes
OUVerT.dyadic OUVerT.numerics OUVerT.dist games.
Definition upd {A : finType} {T : Type}
(a : A) (t : T) (s : {ffun A -> T}) :=
finfun (fun b => if a==b then t else s b).
Module Index.
Section index.
Variable n : N.t.
Variable n_gt0 : (0 < N.to_nat n)%N.
Record t : Type :=
mk { val : N.t;
pf : (N.to_nat val < N.to_nat n)%N }.
Program Definition pred (i : t) : t :=
@mk (N.pred (val i)) _.
Next Obligation.
move: (pf i); rewrite N2Nat.inj_pred.
move: (N.to_nat (val i)) => n0 => H.
apply/leP; apply: le_lt_trans; first by apply/leP; apply: leq_pred.
by apply/leP.
Qed.
Program Definition max : t := @mk (N.pred n) _.
Next Obligation.
rewrite N2Nat.inj_pred; apply/ltP.
move: (ltP n_gt0) => H.
omega.
Qed.
End index.
End Index.
(** Unnormalized functional weight distributions efficiently supporting:
- sampling
- weight update *)
Module AM.
Record t (A : Type) : Type :=
mk {
size : N.t;
map :> M.t A;
(* [wmap]: a map from positive indices in range
[0, size) to values [a] *)
pf :
forall i : N.t,
(N.to_nat i < N.to_nat size)%nat ->
exists a, M.find i map = Some a
}.
Fixpoint Nlength (A : Type) (l : list A) : N.t :=
match l with
| nil => 0
| _ :: l' => N.succ (Nlength l')
end.
Section functions0.
Variable A : Type.
Program Definition init (a : A) : t A :=
@mk _ 1 (M.add N0 a (M.empty _)) _.
Next Obligation.
exists a.
rewrite Pos2Nat.inj_1 in H.
have H2: i = N0.
{ case: i H => //.
move => p; rewrite positive_N_nat => H.
have H2: Pos.to_nat p = 0%nat.
{ move: H; move: (Pos.to_nat p) => n.
elim: n => //. }
apply: N2Nat.inj.
rewrite positive_N_nat H2 //. }
rewrite {}H2 MProps.F.add_eq_o //.
Qed.
Fixpoint map_from_list (l : list A) : N.t * M.t A :=
List.fold_left
(fun acc a =>
let (i, m) := (acc : N.t * M.t A) in
(N.succ i, M.add i a m))
l
(N0, M.empty _).
Fixpoint map_from_keylist (l : list (M.key * A)) : M.t A :=
match l with
| nil => M.empty _
| (i, a) :: l' => M.add i a (map_from_keylist l')
end.
Lemma map_from_list_fold_right l :
map_from_list l =
List.fold_right
(fun a acc =>
let (i, m) := (acc : N.t * M.t A) in
(N.succ i, M.add i a m))
(N0, M.empty _)
(List.rev l).
Proof.
rewrite fold_left_rev_right.
rewrite /map_from_list.
elim: l => //.
Qed.
Fixpoint seq_upto (n : nat) : list N.t :=
match n with
| O => nil
| S n' => rcons (seq_upto n') (N.of_nat n')
end.
Lemma seq_upto_length n : seq.size (seq_upto n) = n.
Proof. by elim: n => // n /=; rewrite size_rcons => ->. Qed.
Lemma seq_upto_nth (n m : nat) :
(m < n)%nat ->
nth N0 (seq_upto n) m = N.of_nat m.
Proof.
elim: n m => // n IH m H /=; rewrite nth_rcons.
case H2: (m < seq.size (seq_upto n))%N.
{ rewrite IH => //.
by rewrite seq_upto_length in H2. }
case H3: (_ == _).
{ move: (eqP H3) => ->.
by rewrite seq_upto_length. }
rewrite seq_upto_length in H2, H3.
elimtype False.
move: {H}(ltP H); move/lt_n_Sm_le/le_lt_or_eq; case.
{ by move/ltP; rewrite H2. }
by move => H4; subst m; rewrite eq_refl in H3.
Qed.
(** WORK-IN-PROGRESS:
Lemma map_from_list_keylist l i :
M.find i (snd (map_from_list l)) =
M.find i (map_from_keylist (zip (seq_upto (seq.size l)) l)).
Proof.
rewrite map_from_list_fold_right.
rewrite /map_from_keylist.
move: (M.empty A) i 0%num.
elim: l => // a l IH m i n /=.
rewrite fold_right_app /= IH /=.
(** NoDupA !!! *)
Abort.
Lemma map_from_list_index_gt l (n n' : N.t) m m' :
List.fold_right
(fun a acc =>
let (i, m) := (acc : N.t * M.t A) in
(N.succ i, M.add i a m))
(n, m)
l = (n', m') ->
Lemma map_from_list_fold_right'_aux l (n : N.t) m :
List.fold_right
(fun a acc =>
let (i, m) := (acc : N.t * M.t A) in
(N.succ i, M.add i a m))
(n, m)
(List.rev l) =
List.fold_right
(fun a acc =>
let (i, m) := (acc : N.t * M.t A) in
(N.pred i, M.add i a m))
(n + Nlength l, m)%num
l.
Proof.
elim: l n m => /=.
{ by move => n m; rewrite N.add_0_r. }
move => a l IH n m; rewrite fold_right_app /= IH.
have ->: (N.succ n + Nlength l = n + N.succ (Nlength l))%num.
{ rewrite N.add_succ_l; symmetry; rewrite [(n + _)%num]N.add_comm N.add_succ_l.
by rewrite [(Nlength l + _)%num]N.add_comm. }
case: (fold_right
(fun (a0 : A) (acc : N.t * M.t A) =>
let (i, m0) := acc in (N.pred i, M.add i a0 m0))
((n + N.succ (Nlength l))%num, M.add n a m) l) => //.
rewrite IH.
rewrite fold_left_rev_right.
rewrite /map_from_list.
elim: l => //.
Qed.
Lemma map_from_list_domain_default l (i : N.t) (a : A) :
(i < fst (map_from_list l))%nat ->
M.find i (snd (map_from_list l)) = Some (List.nth (N.to_nat i) l a).
Proof.
rewrite map_from_list_fold_right.
elim: (List.rev l) i => // ax l' IH i /= H.
move: H IH; case: (fold_right _ (0%num, M.empty A) l') => a0 b /= H IH.
case H2: (N.eq_dec a0 i) => [Hx|Hx].
{ subst i; move {H2 H}.
rewrite MProps.F.add_eq_o => //.
have H3: (i < a0)%N.
{ rewrite nat_of_bin_succ in H.
apply/ltP; move: (ltP H) => H3. clear - H3 Hx.
have H4: nat_of_bin a0 <> nat_of_bin i.
{ by move => H4; apply: Hx; apply: nat_of_bin_inj. }
omega. }
case: (IH _ H3) => x H4; exists x.
rewrite MProps.F.add_neq_o => //.
Qed.
*)
Lemma map_from_list_domain l (i : N.t) :
(i < fst (map_from_list l))%nat ->
exists a, M.find i (snd (map_from_list l)) = Some a.
Proof.
rewrite map_from_list_fold_right; elim: (List.rev l) i => // a l' IH i /= H.
move: H IH; case: (fold_right _ (0%num, M.empty A) l') => a0 b /= H IH.
case H2: (N.eq_dec a0 i) => [Hx|Hx].
{ subst i; move {H2 H}.
by rewrite MProps.F.add_eq_o => //; exists a. }
have H3: (i < a0)%N.
{ rewrite nat_of_bin_succ in H.
apply/ltP; move: (ltP H) => H3. clear - H3 Hx.
have H4: nat_of_bin a0 <> nat_of_bin i.
{ by move => H4; apply: Hx; apply: nat_of_bin_inj. }
omega. }
case: (IH _ H3) => x H4; exists x.
rewrite MProps.F.add_neq_o => //.
Qed.
Program Definition from_list (l : list A) : t A :=
@mk _ (fst (map_from_list l)) (snd (map_from_list l)) _.
Next Obligation.
apply: map_from_list_domain.
by apply: N2Nat_lt.
Qed.
Definition empty : t A := from_list nil.
End functions0.
Section functions.
Variable A : Type.
Variable w : t A.
Definition index : Type := Index.t (size w).
Definition index_key : index -> M.key := @Index.val (size w).
Definition index_nat : index -> nat := @Index.val (size w).
Definition ordinal_of_index (i : index) : 'I_(N.to_nat (size w)) :=
Ordinal (Index.pf i).
Coercion index_key : index >-> M.key.
Program Definition lookup (i : index) : A :=
match M.find i (map w) with
| None => _
| Some a => a
end.
Next Obligation.
move: (Index.pf i) => H.
move: (pf H) => H2.
elimtype False.
by case: H2 => x H3; rewrite H3 in Heq_anonymous.
Qed.
Program Definition update
(i : index)
(a': A)
: t A :=
@mk
_
(size w)
(M.add i a' (map w))
_.
Next Obligation.
case (N.eqb_spec (index_key i) i0).
{ move => H2; subst i0; exists a'.
rewrite MProps.F.add_eq_o => //. }
move => Hneq; rewrite MProps.F.add_neq_o => //.
by apply pf.
Qed.
Program Definition bump (n : N.t) : Index.t (N.succ n) :=
@Index.mk _ n _.
Next Obligation.
rewrite N2Nat.inj_succ; apply/ltP; omega.
Qed.
(* Append [a] at the end of array map [w]. *)
Program Definition add (a : A) : t A :=
@mk
A
(N.succ (size w))
(M.add (Index.val (bump (size w))) a (map w))
_.
Next Obligation.
case: (N.eqb_spec (size w) i).
{ move => H2; subst i.
exists a; rewrite MProps.F.add_eq_o //. }
move => H2; rewrite MProps.F.add_neq_o => //.
apply pf.
have H3: N.to_nat (size w) <> N.to_nat i.
{ by rewrite N2Nat.inj_iff. }
rewrite N2Nat.inj_succ in H.
move: H H3; move: (N.to_nat (size w)) => x; move: (N.to_nat i) => y.
move/ltP => H H3; apply/ltP; omega.
Qed.
(** Add [a] at level [i], regardless whether [i] is already
present in the array map. If [i >= size], then this operation
may require the addition of a new array cell at index [size]. *)
Program Definition update_add (i : N.t) (a : A) : t A :=
(match N.ltb i (size w) as o return _ = o -> _ with
| true => fun pf => update (@Index.mk _ i _) a
| false => fun _ => add a
end) erefl.
Next Obligation.
move: pf0; rewrite N.ltb_lt => H.
apply/ltP; rewrite /N.lt N2Nat.inj_compare in H.
by rewrite nat_compare_lt.
Qed.
Program Definition swap (i j : index) : t A :=
let a := lookup i in
let b := lookup j in
@mk
_
(size w)
(M.add i b (M.add j a (map w)))
_.
Next Obligation.
case: (N.eqb_spec (index_key i) i0).
{ move => H2; subst i0; exists (lookup j).
rewrite MProps.F.add_eq_o => //. }
move => H2.
case: (N.eqb_spec (index_key j) i0).
{ move => H3; subst i0; exists (lookup i).
rewrite MProps.F.add_neq_o => //.
rewrite MProps.F.add_eq_o => //. }
move => H3.
rewrite MProps.F.add_neq_o => //.
rewrite MProps.F.add_neq_o => //.
by apply pf.
Qed.
Definition split_aux
(f : M.key -> A -> bool) : list A * list A :=
M.fold
(fun i a (p : list A * list A) =>
match p with
| (trues, falses) =>
if f i a then (a :: trues, falses)
else (trues, a :: falses)
end)
(map w)
(nil, nil).
Definition split (f : M.key -> A -> bool) : (t A * t A) :=
let (trues, falses) := split_aux f in
(from_list trues, from_list falses).
Program Definition fmapi
(B : Type)
(f : M.key -> A -> B)
(f_pf : forall (x y : M.key) (e : A), N.eq x y -> f x e = f y e)
: t B :=
@mk
_
(size w)
(M.mapi f (map w))
_.
Next Obligation.
rewrite MFacts.mapi_o => //.
case: (pf H) => x ->; exists (f i x) => //.
Qed.
Program Definition fmap
(B : Type)
(f : A -> B)
: t B := @fmapi _ (fun (_ : M.key) (a : A) => f a) _.
Definition fold
(B : Type)
(f : N.t -> A -> B -> B)
(acc : B)
: B := M.fold f (map w) acc.
Definition to_list : list (M.key * A) := M.elements (map w).
End functions.
(** Representation invariant wrt. functions of type {ffun 'I_size -> A} *)
Section rep.
Variable A : Type.
Definition rep (w : t A) (f : {ffun 'I_(N.to_nat (size w)) -> A}) : Prop :=
forall (i : index w), lookup i = f (ordinal_of_index i).
Variable w : t A.
Variable f : {ffun 'I_(N.to_nat (size w)) -> A}.
Hypothesis w_rep : rep f.
Lemma lookup_ok : forall i : index w, lookup i = f (ordinal_of_index i).
Proof. apply: w_rep. Qed.
(** WIP Lemma empty_ok : *)
End rep.
End AM.
Module DIST.
Record row (A : Type) : Type :=
mkRow { row_weight : D;
row_max : D;
row_arraymap : AM.t (A*D) }.
Record t (A : Type) : Type :=
mk {
cpmf :> M.t (row A)
(* [cpmf]: a map from
- LEVEL 1: weight level i = [2^i, 2^{i+1})
- LEVEL 2: weight array containing weights (a,d)
in the range of weight level i, along
with the total probability mass for that level *)
}.
Section functions.
Variable A : Type.
Definition empty : t A := mk (M.empty _).
(** We assume all weights are between 0 and 1. *)
Definition level_of (d : D) : N.t :=
match d with
| Dmake (Zpos x) y => N.sub (N.pos y) (N.log2 (N.pos x))
| Dmake 0 _ => 0
| Dmake (Zneg _) _ => 0
end.
Compute level_of (Dmake 1 1). (*=1*)
Compute level_of (Dmake 1 2). (*=2*)
(* level_of spec: forall d, 2^{-(level_of d)} <= d < 2^{-(level_of d) - 1}*)
Program Definition add_weight (a : A) (d : D) (w : t A) : t A :=
let r :=
match M.find (level_of d) w with
| None => mkRow 0%D 0%D (AM.empty _)
| Some m => m
end
in
let r' :=
mkRow (Dadd d r.(row_weight))
(Dmax d r.(row_max))
(AM.add r.(row_arraymap) (a,d))
in mk (M.add (level_of d) r' (cpmf w)).
Fixpoint add_weights
(l : list (A*D))
(w : t A)
: t A :=
match l with
| nil => w
| (a,d) :: l' => add_weights l' (add_weight a d w)
end.
Definition sum_weights (m : AM.t (A*D)) : D :=
AM.fold m
(fun _ (p : A*D) acc => let (a,d') := p in Dadd acc d')
0%D.
Definition max_weight (m : AM.t (A*D)) : D :=
AM.fold m
(fun _ (p : A*D) acc => let (a,d') := p in Dmax acc d')
0%D.
(** Updates [w] according to [f], returning the new array map
together with any pairs (a,d) that are now mis-leveled (stored
in the proj2 array map). *)
Definition update_level
(f : A -> D -> D)
(level : N.t)
(m : row A)
: (row A * AM.t (A*D)) :=
(* w': the updated weights *)
let w' := AM.fmap m.(row_arraymap) (fun p : (A*D) => let (a,d) := p in (a, f a d)) in
(* split the entries that are now mis-leveled *)
let g := fun i (p : (A*D)) => let (a,d') := p in N.eqb (level_of d') level in
let (stay, go) := AM.split w' g in
(mkRow (sum_weights stay) (max_weight stay) stay, go).
Lemma update_level_pf f (x y : M.key) w :
N.eq x y -> update_level f x w = update_level f y w.
Proof. by move => ->. Qed.
Definition update_weights
(f : A -> D -> D)
(w : M.t (row A))
: t A :=
let w'':= M.mapi (update_level f) w in
let w' := M.map fst w'' in
let removed := M.fold (fun i p l0 => AM.to_list (snd p) ++ l0) w'' nil in
add_weights
(List.map snd removed) (mk w').
(** The distribution's total weight *)
Definition weight (w : t A) : D :=
M.fold (fun i r d0 => Dadd r.(row_weight) d0) w D0.
End functions.
End DIST.
Section sampling.
Variable T : Type. (* randomness oracle state *)
Variable rand : T -> D*T.
Variable rand_range : T -> N.t -> N.t*T. (* generate a random integer in range *)
Hypothesis rand_range_ok :
forall t n,
let (n', t') := rand_range t n in
(N.to_nat n' < N.to_nat n)%N.
Fixpoint cdf_sample_aux
(A : Type) (a0 : A)
(acc r : D) (l : list (D*A))
: (D * A) :=
match l with
| nil => (D0, a0) (*should never occur*)
| (w, a) :: l' =>
if Dle_bool acc r && Dle_bool r (Dadd acc w) then
(w, a)
else cdf_sample_aux a0 (Dadd acc w) r l'
end.
(** Use inverse transform sampling to select row. *)
Definition cdf_sample_row
(A : Type)
(w : DIST.t A)
(t : T)
: (DIST.row A * T) :=
let sum := DIST.weight w in
let (r, t') := rand t in
let r' := Dmult r sum in
let w := cdf_sample_aux
(DIST.mkRow D0 D0 (AM.empty _))
D0
r'
(map (fun (p : M.key * DIST.row A) =>
let (_, r) := p in
(r.(DIST.row_weight), r))
(M.elements (DIST.cpmf w))) in
(snd w, t').
(** Sample a value in range [0..size-1] *)
Program Definition sample_index
(t : T)
(size : N.t)
: (Index.t size * T) :=
(@Index.mk size (fst (rand_range t size)) _, snd (rand_range t size)).
Next Obligation.
move: (rand_range_ok t size).
case: (rand_range t size) => //.
Qed.
(** Rejection-sample within row. *)
Fixpoint rejection_sample_row_aux
(A : Type)
(a0 : A)
(r : DIST.row A)
(t : T)
(n : nat)
: (A * T) :=
let w_max := r.(DIST.row_max) in
let w := r.(DIST.row_arraymap) in
let size := w.(AM.size) in
match n with
| O => (a0, t)
| S n' =>
let (i, t2) := sample_index t size in
let (a, d) := AM.lookup i in
let (u, t') := rand t2 in
if Dle_bool (Dmult u w_max) d then
(a, t')
else rejection_sample_row_aux a0 r t' n'
end.
Definition rejection_sample_row
(A : Type)
(a0 : A)
(r : DIST.row A)
(t : T)
: (A * T) :=
rejection_sample_row_aux a0 r t 1000.
(** The overall sampling procedure. *)
Definition sample
(A : Type)
(a0 : A)
(w : DIST.t A)
(t : T)
: (A * T) :=
let (r, t2) := cdf_sample_row w t in
rejection_sample_row a0 r t2.
Fixpoint prod_sample_aux
(A : Type)
(a0 : A)
(acc : M.t A * T)
(n : nat)
(p : nat -> DIST.t A)
: (M.t A * T) :=
match n with
| O => acc
| S n' =>
let (a, t) := sample a0 (p n') (snd acc) in
prod_sample_aux a0 (M.add (N.of_nat n') a (fst acc), t) n' p
end.
Definition prod_sample
(num_players : nat)
(A : Type)
(a0 : A)
(p : nat -> DIST.t A)
(t : T)
: (M.t A * T) :=
prod_sample_aux a0 (M.empty _, t) num_players p.
End sampling.
Axiom rand_state : Type.
Extract Constant rand_state => "unit".
Axiom init_rand_state : rand_state.
Extract Constant init_rand_state => "()".
Axiom rand : rand_state -> (D*rand_state). (*in range [0,1]*)
Extract Constant rand =>
"fun _ ->
let _ = Random.self_init () in
let d = Random.int 256 in
let zn = Big.of_int d in
let peight = Big.of_int 8 in
let q = { num = zn; den = peight }
in
Printf.eprintf ""Generated random r = %d"" d; prerr_newline ();
(q, ())".
(** PRECONDITION: [rand_range t n]: n is Npos p for some p *)
Axiom rand_range : rand_state -> N.t -> (N.t*rand_state). (*in range [0,size-1]*)
Extract Constant rand_range =>
"fun _ size ->
let _ = Random.self_init () in
let d = Random.int (Big.to_int size)
in
Printf.eprintf ""Generated in-range random i = %d"" d; prerr_newline ();
(Big.of_int d, ())".
Axiom rand_range_ok :
forall t n,
let (n', t') := rand_range t n in
(N.to_nat n' < N.to_nat n)%N.
Definition rsample A (a0 : A) (c : DIST.t A) : A :=
fst (sample rand rand_range_ok a0 c init_rand_state).
Definition rprod_sample A (a0 : A) (num_players : nat) (p : nat -> DIST.t A) : M.t A :=
fst (prod_sample rand rand_range_ok num_players a0 p init_rand_state).
Section rsample_cost.
Context {A : Type} (a0 : A) {num_players : nat}.
Context `{CCostInstance : CCostClass num_players A}.
Definition rsample_ccost (i : N.t) (a : A) (p : nat -> DIST.t A) : D :=
let m := rprod_sample a0 num_players p in
ccost i (M.add i a m).
End rsample_cost.
Section expected_rsample_cost.
Context {A : finType} {Aeq : A -> A -> bool}.
(*Aeq: not necessarily the equality associated with A's eqType instance.*)
Context (a0 : A) {num_players : nat}.
Context `{CGameInstance : cgame num_players A}.
Variable (p : nat -> DIST.t A).
Variable (f : {ffun 'I_num_players -> dist A rat_realFieldType}).
(* TO BE UPDATED:
Hypothesis dists_match : forall i : 'I_num_players, dist_cdist_match Aeq (p i) (f i).
Axiom rsample_ccost_expected :
forall (i : 'I_num_players) (a : A),
D_to_Q (rsample_ccost a0 (N.of_nat i) a p) =
rat_to_Q (expectedValue (prod_dist f) (fun x => cost i (upd i a x))).*)
End expected_rsample_cost.
(* Definition fun_of_t *)
(* (A : Type) *)
(* (Aeq : A -> A -> bool) *)
(* (c : t A) : A -> Q := *)
(* fun a => *)
(* match findA (Aeq a) c with *)
(* | None => 0 *)
(* | Some d => D_to_Q d *)
(* end. *)
(* Definition dist_t_match *)
(* (A : finType) *)
(* (Aeq : A -> A -> bool) *)
(* (c : t A) *)
(* (d : dist A rat_realFieldType) *)
(* : Prop := *)
(* pmf d = finfun (fun a => Q_to_rat (fun_of_t Aeq c a)). *)
|
{-# LANGUAGE RankNTypes, BangPatterns, GADTs #-}
{-# OPTIONS -Wall #-}
module Language.Hakaru.Distribution where
import Control.Monad
import Control.Monad.Primitive
import Control.Monad.Loops
import qualified System.Random.MWC as MWC
import Language.Hakaru.Mixture
import Language.Hakaru.Types
import Data.Ix
import Data.Maybe (fromMaybe)
import Data.List (findIndex, foldl')
import Numeric.SpecFunctions
import qualified Data.Map.Strict as M
import qualified Data.Number.LogFloat as LF
mapFst :: (t -> s) -> (t, u) -> (s, u)
mapFst f (a,b) = (f a, b)
dirac :: (Eq a) => a -> Dist a
dirac theta = Dist {logDensity = (\ (Discrete x) -> if x == theta then 0 else log 0),
distSample = (\ _ -> return $ Discrete theta)}
bern :: Double -> Dist Bool
bern p = Dist {logDensity = (\ (Discrete x) -> log (if x then p else 1 - p)),
distSample = (\ g -> do t <- MWC.uniformR (0,1) g
return $ Discrete (t <= p))}
uniform :: Double -> Double -> Dist Double
uniform lo hi =
let uniformLogDensity lo' hi' x | lo' <= x && x <= hi' = log (recip (hi' - lo'))
uniformLogDensity _ _ _ = log 0
in Dist {logDensity = (\ (Lebesgue x) -> uniformLogDensity lo hi x),
distSample = (\ g -> liftM Lebesgue $ MWC.uniformR (lo, hi) g)}
uniformD :: (Ix a, MWC.Variate a) => a -> a -> Dist a
uniformD lo hi =
let uniformLogDensity lo' hi' x | lo' <= x && x <= hi' = log density
uniformLogDensity _ _ _ = log 0
density = recip (fromInteger (toInteger (rangeSize (lo,hi))))
in Dist {logDensity = (\ (Discrete x) -> uniformLogDensity lo hi x),
distSample = (\ g -> liftM Discrete $ MWC.uniformR (lo, hi) g)}
marsaglia :: (MWC.Variate a, Ord a, Floating a, PrimMonad m) => PRNG m -> m (a, a)
marsaglia g = do -- "Marsaglia polar method"
x <- MWC.uniformR (-1,1) g
y <- MWC.uniformR (-1,1) g
let s = x * x + y * y
q = sqrt ((-2) * log s / s)
if 1 >= s && s > 0 then return (x * q, y * q) else marsaglia g
choose :: (PrimMonad m) => Mixture k -> PRNG m -> m (k, Prob)
choose (Mixture m) g = do
let peak = maximum (M.elems m)
unMix = M.map (LF.fromLogFloat . (/peak)) m
total = M.foldl' (+) (0::Double) unMix
p <- MWC.uniformR (0, total) g
let f !k !v b !p0 = let p1 = p0 + v in if p <= p1 then k else b p1
err p0 = error ("choose: failure p0=" ++ show p0 ++
" total=" ++ show total ++
" size=" ++ show (M.size m))
return $ (M.foldrWithKey f err unMix 0, LF.logFloat total * peak)
chooseIndex :: (PrimMonad m) => [Double] -> PRNG m -> m Int
chooseIndex probs g = do
p <- MWC.uniform g
return $ fromMaybe (error ("chooseIndex: failure p=" ++ show p))
(findIndex (p <=) (scanl1 (+) probs))
normal_rng :: (Real a, Floating a, MWC.Variate a, PrimMonad m) =>
a -> a -> PRNG m -> m a
normal_rng mu sd g | sd > 0 = do (x, _) <- marsaglia g
return (mu + sd * x)
normal_rng _ _ _ = error "normal: invalid parameters"
normalLogDensity :: Floating a => a -> a -> a -> a
normalLogDensity mu sd x = (-tau * square (x - mu)
+ log (tau / pi / 2)) / 2
where square y = y * y
tau = 1 / square sd
normal :: Double -> Double -> Dist Double
normal mu sd = Dist {logDensity = normalLogDensity mu sd . fromLebesgue,
distSample = (\g -> liftM Lebesgue $ normal_rng mu sd g)}
categoricalLogDensity :: (Eq b, Floating a) => [(b, a)] -> b -> a
categoricalLogDensity list x = log $ fromMaybe 0 (lookup x list)
categoricalSample :: (Num b, Ord b, PrimMonad m, MWC.Variate b) =>
[(t,b)] -> PRNG m -> m t
categoricalSample list g = do
let total = sum $ map snd list
p <- MWC.uniformR (0, total) g
let sumList = scanl1 (\acc (a, b) -> (a, b + snd(acc))) list
elem' = fst $ head $ filter (\(_,p0) -> p <= p0) sumList
return elem'
categorical :: Eq a => [(a,Double)] -> Dist a
categorical list = Dist {logDensity = categoricalLogDensity list . fromDiscrete,
distSample = (\g -> liftM Discrete $ categoricalSample list g)}
lnFact :: Int -> Double
lnFact = logFactorial
-- Makes use of Atkinson's algorithm as described in:
-- Monte Carlo Statistical Methods pg. 55
--
-- Further discussion at:
-- http://www.johndcook.com/blog/2010/06/14/generating-poisson-random-values/
poisson_rng :: (PrimMonad m) => Double -> PRNG m -> m Int
poisson_rng lambda g' = make_poisson g'
where smu = sqrt lambda
b = 0.931 + 2.53*smu
a = -0.059 + 0.02483*b
vr = 0.9277 - 3.6224/(b - 2)
arep = 1.1239 + 1.1368/(b-3.4)
lnlam = log lambda
make_poisson :: (PrimMonad m) => PRNG m -> m Int
make_poisson g = do u <- MWC.uniformR (-0.5,0.5) g
v <- MWC.uniformR (0,1) g
let us = 0.5 - abs u
k = floor $ (2*a / us + b)*u + lambda + 0.43
case () of
() | us >= 0.07 && v <= vr -> return k
() | k < 0 -> make_poisson g
() | us <= 0.013 && v > us -> make_poisson g
() | accept_region us v k -> return k
_ -> make_poisson g
accept_region :: Double -> Double -> Int -> Bool
accept_region us v k = log (v * arep / (a/(us*us)+b)) <=
-lambda + (fromIntegral k)*lnlam - lnFact k
poisson :: Double -> Dist Int
poisson l =
let poissonLogDensity l' x | l' > 0 && x> 0 = (fromIntegral x)*(log l') - lnFact x - l'
poissonLogDensity l' x | x==0 = -l'
poissonLogDensity _ _ = log 0
in Dist {logDensity = poissonLogDensity l . fromDiscrete,
distSample = (\g -> liftM Discrete $ poisson_rng l g)}
-- Direct implementation of "A Simple Method for Generating Gamma Variables"
-- by George Marsaglia and Wai Wan Tsang.
gamma_rng :: (PrimMonad m) => Double -> Double -> PRNG m -> m Double
gamma_rng shape _ _ | shape <= 0.0 = error "gamma: got a negative shape paramater"
gamma_rng _ scl _ | scl <= 0.0 = error "gamma: got a negative scale paramater"
gamma_rng shape scl g | shape < 1.0 = do gvar1 <- gamma_rng (shape + 1) scl g
w <- MWC.uniformR (0,1) g
return $ scl * gvar1 * (w ** recip shape)
gamma_rng shape scl g = do
let d = shape - 1/3
c = recip $ sqrt $ 9*d
-- Algorithm recommends inlining normal generator
-- n = normal_rng 1 c
v <- iterateUntil (> 0.0) $ normal_rng 1 c g
-- (v, g2) = until (\y -> fst y > 0.0) (\ (_, g') -> normal_rng 1 c g') (n g)
let x = (v - 1) / c
sqr = x * x
v3 = v * v * v
u <- MWC.uniformR (0.0, 1.0) g
let accept = u < 1.0 - 0.0331*(sqr*sqr) || log u < 0.5*sqr + d*(1.0 - v3 + log v3)
case accept of
True -> return $ scl*d*v3
False -> gamma_rng shape scl g
gammaLogDensity :: Double -> Double -> Double -> Double
gammaLogDensity shape scl x | x>= 0 && shape > 0 && scl > 0 =
scl * log shape - scl * x + (shape - 1) * log x - logGamma shape
gammaLogDensity _ _ _ = log 0
gamma :: Double -> Double -> Dist Double
gamma shape scl = Dist {logDensity = gammaLogDensity shape scl . fromLebesgue,
distSample = (\g -> liftM Lebesgue $ gamma_rng shape scl g)}
beta_rng :: (PrimMonad m) => Double -> Double -> PRNG m -> m Double
beta_rng a b g | a <= 1.0 && b <= 1.0 = do
u <- MWC.uniformR (0.0, 1.0) g
v <- MWC.uniformR (0.0, 1.0) g
let x = u ** (recip a)
y = v ** (recip b)
case (x+y) <= 1.0 of
True -> return $ x / (x + y)
False -> beta_rng a b g
beta_rng a b g = do ga <- gamma_rng a 1 g
gb <- gamma_rng b 1 g
return $ ga / (ga + gb)
betaLogDensity :: Double -> Double -> Double -> Double
betaLogDensity _ _ x | x < 0 || x > 1 = error "beta: value must be between 0 and 1"
betaLogDensity a b _ | a <= 0 || b <= 0 = error "beta: parameters must be positve"
betaLogDensity a b x = (logGamma (a + b)
- logGamma a
- logGamma b
+ (a - 1) * log x
+ (b - 1) * log (1 - x))
beta :: Double -> Double -> Dist Double
beta a b = Dist {logDensity = betaLogDensity a b . fromLebesgue,
distSample = (\g -> liftM Lebesgue $ beta_rng a b g)}
laplace_rng :: (PrimMonad m) => Double -> Double -> PRNG m -> m Double
laplace_rng mu sd g = MWC.uniformR (0.0, 1.0) g >>= sample
where sample u = return $ case u < 0.5 of
True -> mu + sd * log (u + u)
False -> mu - sd * log (2.0 - u - u)
laplaceLogDensity :: Floating a => a -> a -> a -> a
laplaceLogDensity mu sd x = - log (2 * sd) - abs (x - mu) / sd
laplace :: Double -> Double -> Dist Double
laplace mu sd = Dist {logDensity = laplaceLogDensity mu sd . fromLebesgue,
distSample = (\g -> liftM Lebesgue $ laplace_rng mu sd g)}
-- Consider having dirichlet return Vector
-- Note: This is actually symmetric dirichlet
dirichlet_rng :: (PrimMonad m) => Int -> Double -> PRNG m -> m [Double]
dirichlet_rng n' a g' = liftM normalize $ gammas g' n'
where gammas _ 0 = return ([], 0)
gammas g n = do (xs, total) <- gammas g (n-1)
x <- gamma_rng a 1 g
return ((x : xs), x+total)
normalize (b, total) = map (/ total) b
dirichletLogDensity :: [Double] -> [Double] -> Double
dirichletLogDensity a x | all (> 0) x = sum' (zipWith logTerm a x) + logGamma (sum a)
where sum' = foldl' (+) 0
logTerm b y = (b-1) * log y - logGamma b
dirichletLogDensity _ _ = error "dirichlet: all values must be between 0 and 1"
|
import .tab
open tactic
variable {p : Prop}
example : p :=
by do proof_by_contradiction
#exit
#check @classical.by_contradiction
example : p :=
by do refine ``(classical.by_contradiction _),
-- trace "After refine : ", trace_state,
intro `_,
-- trace "After intro : ", trace_state,
skip
|
{-# OPTIONS --prop --without-K --rewriting #-}
-- The basic CBPV metalanguage.
open import Calf.CostMonoid
module Calf.Metalanguage where
open import Calf.Prelude
open import Relation.Binary.PropositionalEquality
open import Data.Product
postulate
mode : □
pos : mode
neg : mode
tp : mode → □
val : tp pos → □
F : tp pos → tp neg
U : tp neg → tp pos
-- This is equivalent to adding "thunk / force" operations. But less bureaucratic.
cmp : tp neg → □
cmp X = val (U X)
postulate
ret : ∀ {A} → val A → cmp (F A)
tbind : ∀ {A} → cmp (F A) → (val A → tp neg) → tp neg
tbind_ret : ∀ {A} {X : val A → tp neg} {v : val A} → tbind (ret v) X ≡ X v
{-# REWRITE tbind_ret #-}
dbind : ∀ {A} (X : val A → tp neg) (e : cmp (F A)) (f : (x : val A) → cmp (X x)) → cmp (tbind e X)
-- note that bind is not a special case of dbind: in general, one does not expect (tbind e (λ _ → m)) ≡ m.
-- This would hold, however, in the case of a language where there are no true effects. But we don't want
-- to assume that.
bind : ∀ {A} X → cmp (F A) → (val A → cmp X) → cmp X
bind/ret : ∀ {A X} {v : val A} {f : (x : val A) → cmp X} → bind X (ret v) f ≡ f v
dbind/ret : ∀ {A} {X : val A → tp neg} {v : val A} {f : (x : val A) → cmp (X x)} → dbind X (ret v) f ≡ f v
{-# REWRITE bind/ret dbind/ret #-}
tbind/assoc : ∀ {A B X} {e : cmp (F A)} {f : val A → cmp (F B)} →
tbind {B} (bind (F B) e f) X ≡ tbind {A} e (λ v → tbind {B} (f v) X)
bind/assoc : ∀ {A B C} {e : cmp (F A)} {f1 : val A → cmp (F B)} {f2 : val B → cmp C} →
bind C (bind (F B) e f1) f2 ≡ bind C e (λ v → bind C (f1 v) f2)
{-# REWRITE tbind/assoc bind/assoc #-}
-- dependent product
Π : (A : tp pos) (X : val A → tp neg) → tp neg
Π/decode : ∀ {A} {X : val A → tp neg} → val (U (Π A X)) ≡ ((x : val A) → cmp (X x))
{-# REWRITE Π/decode #-}
-- mixed polarity dependent sum
Σ+- : (A : tp pos) (X : val A → tp neg) → tp neg
Σ+-/decode : ∀ {A} {X : val A → tp neg} → val (U (Σ+- A X)) ≡ Σ (val A) λ x → cmp (X x)
{-# REWRITE Σ+-/decode #-}
-- positive dependent sum
Σ++ : (A : tp pos) (B : val A → tp pos) → tp pos
Σ++/decode : ∀ {A} {B : val A → tp pos} → val (Σ++ A B) ≡ Σ (val A) λ x → val (B x)
{-# REWRITE Σ++/decode #-}
-- agda sets
meta : Set → tp neg
meta/out : ∀ {A} → val (U (meta A)) ≡ A
{-# REWRITE meta/out #-}
bind/meta : ∀ A 𝕊 𝕋 e f (g : 𝕊 → 𝕋) → g (bind {A} (meta 𝕊) e f) ≡ bind {A} (meta 𝕋) e (λ a → g(f a))
tbind/meta : ∀ A 𝕊 e f (p : 𝕊 → □) → p (bind {A} (meta 𝕊) e f) ≡ cmp (tbind {A} e (λ a → meta (p (f a))))
bind/idem : ∀ A 𝕊 e (f : val A → val A → 𝕊) → bind {A} (meta 𝕊) e (λ a → (bind {A} (meta 𝕊) e (λ a' → f a a'))) ≡ bind {A} (meta 𝕊) e (λ a → f a a)
|
[STATEMENT]
lemma (in SecurityInvariant_preliminaries) sinvar_valid_remove_SOME_offending_flows:
assumes "set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP \<noteq> {}"
shows "sinvar \<lparr>nodes = nodesG, edges = edgesG - (SOME F. F \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP) \<rparr> nP"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. sinvar \<lparr>nodes = nodesG, edges = edgesG - (SOME F. F \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP)\<rparr> nP
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. sinvar \<lparr>nodes = nodesG, edges = edgesG - (SOME F. F \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP)\<rparr> nP
[PROOF STEP]
{
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. sinvar \<lparr>nodes = nodesG, edges = edgesG - (SOME F. F \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP)\<rparr> nP
[PROOF STEP]
fix f
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. sinvar \<lparr>nodes = nodesG, edges = edgesG - (SOME F. F \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP)\<rparr> nP
[PROOF STEP]
assume *: "f\<in>set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP"
[PROOF STATE]
proof (state)
this:
f \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP
goal (1 subgoal):
1. sinvar \<lparr>nodes = nodesG, edges = edgesG - (SOME F. F \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP)\<rparr> nP
[PROOF STEP]
from *
[PROOF STATE]
proof (chain)
picking this:
f \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP
[PROOF STEP]
have 1: "sinvar \<lparr>nodes = nodesG, edges = edgesG - f \<rparr> nP"
[PROOF STATE]
proof (prove)
using this:
f \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP
goal (1 subgoal):
1. sinvar \<lparr>nodes = nodesG, edges = edgesG - f\<rparr> nP
[PROOF STEP]
by (metis (opaque_lifting, mono_tags) SecurityInvariant_withOffendingFlows.valid_without_offending_flows delete_edges_simp2 graph.select_convs(1) graph.select_convs(2))
[PROOF STATE]
proof (state)
this:
sinvar \<lparr>nodes = nodesG, edges = edgesG - f\<rparr> nP
goal (1 subgoal):
1. sinvar \<lparr>nodes = nodesG, edges = edgesG - (SOME F. F \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP)\<rparr> nP
[PROOF STEP]
from *
[PROOF STATE]
proof (chain)
picking this:
f \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP
[PROOF STEP]
have 2: "edgesG - \<Union> (set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP) \<subseteq> edgesG - f"
[PROOF STATE]
proof (prove)
using this:
f \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP
goal (1 subgoal):
1. edgesG - \<Union> (set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP) \<subseteq> edgesG - f
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
edgesG - \<Union> (set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP) \<subseteq> edgesG - f
goal (1 subgoal):
1. sinvar \<lparr>nodes = nodesG, edges = edgesG - (SOME F. F \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP)\<rparr> nP
[PROOF STEP]
note 1 2
[PROOF STATE]
proof (state)
this:
sinvar \<lparr>nodes = nodesG, edges = edgesG - f\<rparr> nP
edgesG - \<Union> (set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP) \<subseteq> edgesG - f
goal (1 subgoal):
1. sinvar \<lparr>nodes = nodesG, edges = edgesG - (SOME F. F \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP)\<rparr> nP
[PROOF STEP]
}
[PROOF STATE]
proof (state)
this:
?f2 \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP \<Longrightarrow> sinvar \<lparr>nodes = nodesG, edges = edgesG - ?f2\<rparr> nP
?f2 \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP \<Longrightarrow> edgesG - \<Union> (set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP) \<subseteq> edgesG - ?f2
goal (1 subgoal):
1. sinvar \<lparr>nodes = nodesG, edges = edgesG - (SOME F. F \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP)\<rparr> nP
[PROOF STEP]
with assms
[PROOF STATE]
proof (chain)
picking this:
set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP \<noteq> {}
?f2 \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP \<Longrightarrow> sinvar \<lparr>nodes = nodesG, edges = edgesG - ?f2\<rparr> nP
?f2 \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP \<Longrightarrow> edgesG - \<Union> (set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP) \<subseteq> edgesG - ?f2
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP \<noteq> {}
?f2 \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP \<Longrightarrow> sinvar \<lparr>nodes = nodesG, edges = edgesG - ?f2\<rparr> nP
?f2 \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP \<Longrightarrow> edgesG - \<Union> (set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP) \<subseteq> edgesG - ?f2
goal (1 subgoal):
1. sinvar \<lparr>nodes = nodesG, edges = edgesG - (SOME F. F \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP)\<rparr> nP
[PROOF STEP]
by (simp add: some_in_eq)
[PROOF STATE]
proof (state)
this:
sinvar \<lparr>nodes = nodesG, edges = edgesG - (SOME F. F \<in> set_offending_flows \<lparr>nodes = nodesG, edges = edgesG\<rparr> nP)\<rparr> nP
goal:
No subgoals!
[PROOF STEP]
qed
|
test = forall _let_ → Set
|
lemma open_prod_elim: assumes "open S" and "x \<in> S" obtains A B where "open A" and "open B" and "x \<in> A \<times> B" and "A \<times> B \<subseteq> S"
|
SUBROUTINE DP_TERM ( datmin, datmax, res, logscl, iofset,
+ nbits, iret )
C************************************************************************
C* DP_TERM *
C* *
C* This subroutine computes the terms required by the data-packing *
C* subroutines. The scale factor, offset, and number of bits are *
C* computed from the minimum, maximum and resolution for each data *
C* item. These terms are computed for a single item in this subroutine.*
C* Therefore, this subroutine must be called for each data item to be *
C* packed. *
C* *
C* The resolution must be an integral power of 10. If not, the next *
C* smaller resolution will be used. For example: RES = .5 will use a *
C* resolution of .1 . LOGSCL is the base 10 logarithm of the value to *
C* be used in scaling data. NBITS must be less than 32. *
C* *
C* DP_TERM ( DATMIN, DATMAX, RES, LOGSCL, IOFSET, NBITS, IRET ) *
C* *
C* Input parameters: *
C* DATMIN REAL Minimum data value *
C* DATMAX REAL Maximum data value *
C* RES REAL Resolution to be retained *
C* *
C* Output parameters: *
C* LOGSCL INTEGER Log10 of scaling factor *
C* IOFSET INTEGER Data offset *
C* NBITS INTEGER Number of bits *
C* IRET INTEGER Return code *
C* 0 = normal return *
C* -5 = DATMAX less than DATMIN *
C* -6 = invalid resolution *
C** *
C* Log: *
C* G. Chatters/RDS 4/84 *
C* M. desJardins/GSFC 3/86 *
C* M. desJardins/GSFC 3/87 *
C* M. desJardins/GSFC 10/89 Allow packing of single value *
C* S. Jacobs/NCEP 5/01 Fixed error code: changed -2 to -5 *
C************************************************************************
C------------------------------------------------------------------------
rmax = 2. ** 31
logscl = 0
iofset = 0
nbits = 32
C
C* For invalid range, set return code, allow for storing full value.
C
IF ( datmax .lt. datmin ) THEN
iret = -5
C
C* Return error for "infinite" resolution ( res = 0 ) or
C* negative resolution.
C
ELSE IF ( res .le. 0. ) THEN
iret = -6
C
C* General case. Formula for packing is:
C* IPACK = NINT ( DATA / SCALE ) - IOFSET.
C* Where SCALE = 10.**LOGSCL.
C*
C* First compute log of scale factor, then take power of 10
C* to get scale factor for later internal computation. Log of
C* scale factor is log10 of resolution truncated to next
C* smaller integer value.
C
ELSE
logscl = INT ( ALOG10 ( res ) )
IF ( ALOG10 ( res ) .lt. 0.0 .and.
* ALOG10 ( res ) .ne. REAL ( INT ( ALOG10 ( res ) ) ) )
* logscl = logscl - 1
C
scale = 10.**logscl
C
C* Check to see that scale is not too small to do computations.
C* If it is, treat same as for RES = 0.0
C
IF ( ABS ( datmin / scale ) .gt. ( rmax ) .or.
* ABS ( datmax / scale ) .gt. ( rmax ) .or.
* ABS ( ( datmax - datmin ) / scale ) .gt. ( rmax)) THEN
iret = -6
C
C* The offset is the scaled value of DATMIN, which is then
C* truncated to next smaller integer. Thus, the smallest packed
C* data field will be zero. IF tests are necessary so that
C* truncation is done in right direction for negative values.
C
ELSE
iofset = INT ( datmin / scale )
IF ( datmin .lt. 0.0 .and.
* datmin / scale .NE. REAL ( INT ( datmin / scale ) ) )
* iofset = INT ( datmin / scale ) - 1
C
C* NBITS is the same as the number of bits required to store
C* DATMAX after it has scale and offset applied. We have to be
C* sure that this value is rounded up properly.
C
maxval = INT ( datmax / scale ) - iofset
IF ( datmax .gt. 0.0 .and.
* datmax / scale .NE. REAL ( INT ( datmax / scale ) ) )
* maxval = INT ( datmax / scale ) - iofset + 1
C
C* Add 1 so that the largest possible value ( all bits on ) can
C* be used as a missing data flag.
C
maxval = maxval + 1
C
C* Count number of bits required to store MAXVAL.
C
nbits = 0
DO WHILE ( maxval .NE. 0 )
maxval = ISHFT ( maxval, -1 )
nbits = nbits + 1
END DO
iret = 0
END IF
END IF
C*
RETURN
END
|
/-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
universe u v w
@[inline] def id {α : Sort u} (a : α) : α := a
/-
The kernel definitional equality test (t =?= s) has special support for idDelta applications.
It implements the following rules
1) (idDelta t) =?= t
2) t =?= (idDelta t)
3) (idDelta t) =?= s IF (unfoldOf t) =?= s
4) t =?= idDelta s IF t =?= (unfoldOf s)
This is mechanism for controlling the delta reduction (aka unfolding) used in the kernel.
We use idDelta applications to address performance problems when Type checking
theorems generated by the equation Compiler.
-/
@[inline] def idDelta {α : Sort u} (a : α) : α := a
/- `idRhs` is an auxiliary declaration used to implement "smart unfolding". It is used as a marker. -/
@[macroInline, reducible] def idRhs (α : Sort u) (a : α) : α := a
abbrev Function.comp {α : Sort u} {β : Sort v} {δ : Sort w} (f : β → δ) (g : α → β) : α → δ :=
fun x => f (g x)
abbrev Function.const {α : Sort u} (β : Sort v) (a : α) : β → α :=
fun x => a
@[reducible] def inferInstance {α : Type u} [i : α] : α := i
@[reducible] def inferInstanceAs (α : Type u) [i : α] : α := i
set_option bootstrap.inductiveCheckResultingUniverse false in
inductive PUnit : Sort u
| unit : PUnit
/-- An abbreviation for `PUnit.{0}`, its most common instantiation.
This Type should be preferred over `PUnit` where possible to avoid
unnecessary universe parameters. -/
abbrev Unit : Type := PUnit
@[matchPattern] abbrev Unit.unit : Unit := PUnit.unit
/-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/
unsafe axiom lcProof {α : Prop} : α
/-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/
unsafe axiom lcUnreachable {α : Sort u} : α
inductive True : Prop
| intro : True
inductive False : Prop
inductive Empty : Type
def Not (a : Prop) : Prop := a → False
@[macroInline] def False.elim {C : Sort u} (h : False) : C :=
False.rec (fun _ => C) h
@[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : Not a) : b :=
False.elim (h₂ h₁)
inductive Eq {α : Sort u} (a : α) : α → Prop
| refl {} : Eq a a
abbrev Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} (m : motive a) {b : α} (h : Eq a b) : motive b :=
Eq.rec (motive := fun α _ => motive α) m h
@[matchPattern] def rfl {α : Sort u} {a : α} : Eq a a := Eq.refl a
theorem Eq.subst {α : Sort u} {motive : α → Prop} {a b : α} (h₁ : Eq a b) (h₂ : motive a) : motive b :=
Eq.ndrec h₂ h₁
theorem Eq.symm {α : Sort u} {a b : α} (h : Eq a b) : Eq b a :=
h ▸ rfl
@[macroInline] def cast {α β : Sort u} (h : Eq α β) (a : α) : β :=
Eq.rec (motive := fun α _ => α) a h
theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : Eq a₁ a₂) : Eq (f a₁) (f a₂) :=
h ▸ rfl
/-
Initialize the Quotient Module, which effectively adds the following definitions:
constant Quot {α : Sort u} (r : α → α → Prop) : Sort u
constant Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r
constant Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) :
(∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β
constant Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} :
(∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q
-/
init_quot
inductive HEq {α : Sort u} (a : α) : {β : Sort u} → β → Prop
| refl {} : HEq a a
@[matchPattern] def HEq.rfl {α : Sort u} {a : α} : HEq a a :=
HEq.refl a
theorem eqOfHEq {α : Sort u} {a a' : α} (h : HEq a a') : Eq a a' :=
have : (α β : Sort u) → (a : α) → (b : β) → HEq a b → (h : Eq α β) → Eq (cast h a) b :=
fun α β a b h₁ =>
HEq.rec (motive := fun {β} (b : β) (h : HEq a b) => (h₂ : Eq α β) → Eq (cast h₂ a) b)
(fun (h₂ : Eq α α) => rfl)
h₁
this α α a a' h rfl
structure Prod (α : Type u) (β : Type v) :=
(fst : α) (snd : β)
attribute [unbox] Prod
/-- Similar to `Prod`, but `α` and `β` can be propositions.
We use this Type internally to automatically generate the brecOn recursor. -/
structure PProd (α : Sort u) (β : Sort v) :=
(fst : α) (snd : β)
/-- Similar to `Prod`, but `α` and `β` are in the same universe. -/
structure MProd (α β : Type u) :=
(fst : α) (snd : β)
structure And (a b : Prop) : Prop :=
intro :: (left : a) (right : b)
inductive Or (a b : Prop) : Prop
| inl (h : a) : Or a b
| inr (h : b) : Or a b
inductive Bool : Type
| false : Bool
| true : Bool
export Bool (false true)
/- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/
structure Subtype {α : Sort u} (p : α → Prop) :=
(val : α) (property : p val)
/-- Gadget for optional parameter support. -/
@[reducible] def optParam (α : Sort u) (default : α) : Sort u := α
/-- Gadget for marking output parameters in type classes. -/
@[reducible] def outParam (α : Sort u) : Sort u := α
/-- Auxiliary Declaration used to implement the notation (a : α) -/
@[reducible] def typedExpr (α : Sort u) (a : α) : α := a
/-- Auxiliary Declaration used to implement the named patterns `x@p` -/
@[reducible] def namedPattern {α : Sort u} (x a : α) : α := a
/- Auxiliary axiom used to implement `sorry`. -/
axiom sorryAx (α : Sort u) (synthetic := true) : α
theorem eqFalseOfNeTrue : {b : Bool} → Not (Eq b true) → Eq b false
| true, h => False.elim (h rfl)
| false, h => rfl
theorem eqTrueOfNeFalse : {b : Bool} → Not (Eq b false) → Eq b true
| true, h => rfl
| false, h => False.elim (h rfl)
theorem neFalseOfEqTrue : {b : Bool} → Eq b true → Not (Eq b false)
| true, _ => fun h => Bool.noConfusion h
| false, h => Bool.noConfusion h
theorem neTrueOfEqFalse : {b : Bool} → Eq b false → Not (Eq b true)
| true, h => Bool.noConfusion h
| false, _ => fun h => Bool.noConfusion h
class Inhabited (α : Sort u) :=
mk {} :: (default : α)
constant arbitrary (α : Sort u) [s : Inhabited α] : α :=
@Inhabited.default α s
instance (α : Sort u) {β : Sort v} [Inhabited β] : Inhabited (α → β) := {
default := fun _ => arbitrary β
}
instance (α : Sort u) {β : α → Sort v} [(a : α) → Inhabited (β a)] : Inhabited ((a : α) → β a) := {
default := fun a => arbitrary (β a)
}
/-- Universe lifting operation from Sort to Type -/
structure PLift (α : Sort u) : Type u :=
up :: (down : α)
/- Bijection between α and PLift α -/
theorem PLift.upDown {α : Sort u} : ∀ (b : PLift α), Eq (up (down b)) b
| up a => rfl
theorem PLift.downUp {α : Sort u} (a : α) : Eq (down (up a)) a :=
rfl
/- Pointed types -/
structure PointedType :=
(type : Type u)
(val : type)
instance : Inhabited PointedType.{u} := {
default := { type := PUnit.{u+1}, val := ⟨⟩ }
}
/-- Universe lifting operation -/
structure ULift.{r, s} (α : Type s) : Type (max s r) :=
up :: (down : α)
/- Bijection between α and ULift.{v} α -/
theorem ULift.upDown {α : Type u} : ∀ (b : ULift.{v} α), Eq (up (down b)) b
| up a => rfl
theorem ULift.downUp {α : Type u} (a : α) : Eq (down (up.{v} a)) a :=
rfl
class inductive Decidable (p : Prop)
| isFalse (h : Not p) : Decidable p
| isTrue (h : p) : Decidable p
@[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool :=
Decidable.casesOn (motive := fun _ => Bool) h (fun _ => false) (fun _ => true)
export Decidable (isTrue isFalse decide)
abbrev DecidablePred {α : Sort u} (r : α → Prop) :=
(a : α) → Decidable (r a)
abbrev DecidableRel {α : Sort u} (r : α → α → Prop) :=
(a b : α) → Decidable (r a b)
abbrev DecidableEq (α : Sort u) :=
(a b : α) → Decidable (Eq a b)
def decEq {α : Sort u} [s : DecidableEq α] (a b : α) : Decidable (Eq a b) :=
s a b
theorem decideEqTrue : {p : Prop} → [s : Decidable p] → p → Eq (decide p) true
| _, isTrue _, _ => rfl
| _, isFalse h₁, h₂ => absurd h₂ h₁
theorem decideEqTrue' : [s : Decidable p] → p → Eq (decide p) true
| isTrue _, _ => rfl
| isFalse h₁, h₂ => absurd h₂ h₁
theorem decideEqFalse : {p : Prop} → [s : Decidable p] → Not p → Eq (decide p) false
| _, isTrue h₁, h₂ => absurd h₁ h₂
| _, isFalse h, _ => rfl
theorem ofDecideEqTrue {p : Prop} [s : Decidable p] : Eq (decide p) true → p := fun h =>
match s with
| isTrue h₁ => h₁
| isFalse h₁ => absurd h (neTrueOfEqFalse (decideEqFalse h₁))
theorem ofDecideEqFalse {p : Prop} [s : Decidable p] : Eq (decide p) false → Not p := fun h =>
match s with
| isTrue h₁ => absurd h (neFalseOfEqTrue (decideEqTrue h₁))
| isFalse h₁ => h₁
@[inline] instance : DecidableEq Bool :=
fun a b => match a, b with
| false, false => isTrue rfl
| false, true => isFalse (fun h => Bool.noConfusion h)
| true, false => isFalse (fun h => Bool.noConfusion h)
| true, true => isTrue rfl
class BEq (α : Type u) := (beq : α → α → Bool)
open BEq (beq)
instance {α : Type u} [DecidableEq α] : BEq α :=
⟨fun a b => decide (Eq a b)⟩
-- We use "dependent" if-then-else to be able to communicate the if-then-else condition
-- to the branches
@[macroInline] def dite {α : Sort u} (c : Prop) [h : Decidable c] (t : c → α) (e : Not c → α) : α :=
Decidable.casesOn (motive := fun _ => α) h e t
|
module Idrlisp.Signature
import Idrlisp.Sexp
import Idrlisp.Pattern
%default total
public export
data Signature a
= Any String
| Num String
| Sym String
| Str String
| Bool String
| Nil
| (::) (Signature a) (Signature a)
| List (Signature a)
| Pat String
| Pure String a
| Or (Signature a) (Signature a)
namespace Args
public export
data ArgsSignature a
= Nil
| (::) (Signature a) (ArgsSignature a)
| Rest (Signature a)
export
Cast (Signature a) (Sexp b) where
cast (Any x) = Sym x
cast (Num x) = Sym x
cast (Sym x) = Sym x
cast (Str x) = Sym x
cast (Bool x) = Sym x
cast Nil = Nil
cast (x :: y) = cast x :: cast y
cast (List x) = [cast x, Sym "..."]
cast (Pat x) = Sym x
cast (Pure x _) = Sym x
cast (Or x y) = [Sym "or", cast x, cast y]
export
Cast (ArgsSignature a) (Sexp b) where
cast Nil = Nil
cast (x :: y) = cast x :: cast y
cast (Rest x) = [cast x, Sym "..."]
export
covering
Show (Signature a) where
show x = show (the (Sexp ()) (cast x))
export
covering
Show (ArgsSignature a) where
show x = show (the (Sexp ()) (cast x))
public export
interface Match a s | a where
SignatureType : a -> Type
match : (sig : a) -> s -> Maybe (SignatureType sig)
public export
Match () () where
SignatureType () = ()
match () () = Just ()
public export
Match a b => Match (Signature a) (Sexp b) where
SignatureType (Any _) = Sexp b
SignatureType (Num _) = Double
SignatureType (Sym _) = String
SignatureType (Str _) = String
SignatureType (Bool _) = Bool
SignatureType Nil = ()
SignatureType (a :: b) =
case b of
Nil => SignatureType a
b' => (SignatureType a, SignatureType b')
SignatureType (List a) = List (SignatureType a)
SignatureType (Pat _) = Pattern
SignatureType (Pure _ a) = SignatureType a
SignatureType (Or a b) = Either (SignatureType a) (SignatureType b)
match (Any _) x = Just x
match (Num _) (Num x) = Just x
match (Num _) _ = Nothing
match (Sym _) (Sym x) = Just x
match (Sym _) _ = Nothing
match (Str _) (Str x) = Just x
match (Str _) _ = Nothing
match (Bool _) (Bool x) = Just x
match (Bool _) _ = Nothing
match Nil [] = Just ()
match Nil _ = Nothing
match (car :: cdr) (x :: y) = do
x' <- match car x
y' <- match cdr y
Just $ case cdr of
Nil => x'
-- It seems that Idris type checker cannot specialize `SignatureType (car :: cdr)`.
_ => believe_me (x', y')
match (car :: cdr) _ = Nothing
match (List s) xs with (cast {to = SList b} xs)
| Proper xs' = traverse (match s) xs'
| Improper x = Nothing
match (Pat _) x =
case Pattern.build x of
Right p => Just p
Left _ => Nothing
match (Pure _ s) (Pure x) = match s x
match (Pure _ s) _ = Nothing
match (Or a b) x = (Left <$> match a x) <|> (Right <$> match b x)
public export
Match a b => Match (ArgsSignature a) (List (Sexp b)) where
SignatureType Nil = ()
SignatureType (x :: y) =
case y of
Nil => SignatureType x
y' => (SignatureType x, SignatureType y')
SignatureType (Rest x) = List (SignatureType x)
match Nil [] = Just ()
match Nil _ = Nothing
match (car :: cdr) (x :: y) = do
x' <- match car x
y' <- match cdr y
Just $ case cdr of
Nil => x'
-- Same as Match Signature, Idris type checker cannot specialize `SignatureType (car :: cdr)`.
_ => believe_me (x', y')
match (car :: cdr) _ = Nothing
match (Rest s) xs = traverse (match s) xs
|
[STATEMENT]
lemma PO_m3_step4_refines_m2_step4:
"{R23}
(m2_step4 Ra A B Na Kab), (m3_step4 Ra A B Na Kab)
{> R23}"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. {R23} m2_step4 Ra A B Na Kab, m3_step4 Ra A B Na Kab {> R23}
[PROOF STEP]
by (auto simp add: PO_rhoare_defs R23_def m2_defs m3_defs intro!: R23_intros)
(auto)
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ViewPatterns #-}
module Main where
import Control.Lens hiding (inside, transform)
import Control.Monad.Extra
import Control.Monad.ST
import Data.Array.Repa
import Data.Complex
import Data.Matrix (Matrix)
import Data.STRef
import GHC.Base (until)
import Graphics.Gloss.Interface.Pure.Game hiding (Vector, shift)
import Graphics.Gloss.Raster.Array
import Relude
import qualified Data.ByteString as B
import qualified Data.Matrix as Mtx
data World = World { _v :: Matrix Float
, _mtx :: Matrix Float
} deriving (Eq,Show)
makeLenses ''World
initialWorld :: World
initialWorld = World { _v = Mtx.fromLists [[-2],[-1]] -- FIXME no hardcode
, _mtx = Mtx.fromLists [[1/250,0],[0,1/250]]
}
type Vector a = Matrix a
data Settings = Settings { _windowSize :: (Int, Int)
, _offset :: (Int, Int)
, _pointSize :: (Int,Int)
, _threshold :: forall a. Num a => a
, _fps :: Int
, _iteration :: Int
}
makeLenses ''Settings
settings :: Settings
settings = Settings { _windowSize = (750,500)
, _offset = (250,250)
, _pointSize = (1,1)
, _threshold = 2
, _fps = 60
, _iteration = 100
}
window :: Display
window = InWindow "fractol" (settings^.windowSize) (settings^.offset)
toTup :: DIM2 -> (Int, Int)
toTup (Z :. y :. x) = (x,y)
toVec :: (Int, Int) -> Vector Float
toVec (!x, !y) = seq y $ seq x $ on f fromIntegral x y
where
f !x1 !x2 = Mtx.fromLists [[x1],[x2]]
{-# INLINE toVec #-}
transform :: World -> Vector Float -> Vector Float
transform !w !p = w^.mtx * p + w^.v
{-# INLINE transform #-}
mandel :: World -> Array D DIM2 Color
mandel !w = fromFunction (ix2 500 750) render
where
render (iter . transform w . toVec . toTup -> (len, n)) =
let diff = len - settings^.threshold
m = 2 * n
in if diff >= 0
then rgb' (0.9 * diff) (0.6 * diff) (0.1 * diff)
else black
toComplex :: Vector Float -> Complex Float
toComplex !v = let [!x,!y] = Mtx.toList v
in x :+ y
{-# INLINE toComplex #-}
iter :: Vector Float -> (Float,Int)
iter (toComplex -> !c) = let (!zn, !len, !n) = until condition endo start
in (len, n)
where
start = (0,0,0)
endo (!zn, !len, !n) = let new = zn * zn + c
in (new, magnitude new, succ n)
{-# INLINE endo #-}
condition (_, !len, !n) = len >= settings^.threshold
|| n > settings^.iteration
{-# INLINE condition #-}
{-# INLINE iter #-}
cast :: (Float, Float) -> (Int, Int)
cast (!x,!y) = on (,) floor x y
{-# INLINE cast #-}
shift :: Vector Float -> Vector Float
shift = (+ Mtx.fromLists [[375],[250]])
{-# INLINE shift #-}
eventHandler :: Event -> World -> World
eventHandler (EventKey (Char 'p') Up _ (shift . toVec . cast -> p)) w =
let truePoint = transform w p
in w & v -~ Mtx.scaleMatrix 0.1 truePoint
& mtx %~ (Mtx.scaleMatrix 1.1 (Mtx.identity 2) *)
eventHandler (EventKey (Char 'n') Up _ (shift . toVec . cast -> p)) w =
let truePoint = transform w p
in w & v +~ Mtx.scaleMatrix 0.1 truePoint
& mtx %~ (Mtx.scaleMatrix 0.9 (Mtx.identity 2) *)
eventHandler _ w = w
main :: IO ()
main = do
let fractol = playArray window (settings^.pointSize) (settings^.fps)
fractol initialWorld mandel eventHandler (const id)
|
[STATEMENT]
lemma uniformity_Abort:
"uniformity =
Filter.abstract_filter (\<lambda>u. Code.abort (STR ''uniformity is not executable'') (\<lambda>u. uniformity))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. uniformity = Filter.abstract_filter (\<lambda>u. Code.abort STR ''uniformity is not executable'' (\<lambda>u. uniformity))
[PROOF STEP]
by simp
|
lemma tendsto_compose_filtermap: "((g \<circ> f) \<longlongrightarrow> T) F \<longleftrightarrow> (g \<longlongrightarrow> T) (filtermap f F)"
|
export fit_statespace_dp
# Piecewise constant segmentation ==============================================
@inline function argmin_const(y,w,t1,t2)
# y'w/sum(w) weighted mean of y
s = 0.
dp = 0.
for t = t1:t2
dp += y[t]*w[t]
s += w[t]
end
dp/s
end
@inline function cost_const(y,w,t1,t2,argminfun)
# w'(y-dpamin)^2 weigted variance of y
dp = 0.
dpm = argminfun(y,w,t1,t2)
for t = t1:t2
dp += w[t]*(y[t]-dpm)^2
end
dp
end
# Piecewise linear segmentation ============================================
@inline function argmin_lin(input,w,t1,t2)
y = input[1]
A = input[2]
yminus = A[t1:t2,1] .- y[t1]
yreg = y[t1:t2] .- yminus
ones(t2-t1+1,1)\yreg # TODO: does not take care of w yet
end
# inuti costfun måste hela y användas, dvs simulation i stället för prediction. Annars hamnar alla knutpunkter på kurvan.
@inline function cost_lin(input,w,t1,t2,argminfun)
if t2 == t1
return Inf
end
y = input[1]
A = input[2]
n = size(y,1) ÷ length(w)
k = argminfun(input,w,t1,t2)
yminus = A[t1:t2,1] .- y[t1]
e = y[t1:t2] .- yminus .- k
return e⋅e
end
# Piecewise statespace segmentation ============================================
@inline function argmin_ss(input,w,t1,t2)
y = input[1]
A = input[2]
n = size(y,1) ÷ length(w)
ii = (t1-1)*n+1
ii2 = t2*n-1
A[ii:ii2,:]\y[ii:ii2] # TODO: does not take care of w yet
end
@inline function cost_ss(input,w,t1,t2,argminfun)
y = input[1]
A = input[2]
n = size(y,1) ÷ length(w)
ii = (t1-1)*n+1
ii2 = t2*n-1
k = argminfun(input,w,t1,t2)
e = y[ii:ii2]-A[ii:ii2,:]*k
return e⋅e
end
using Base.Threads
function seg_bellman(y,M,w, costfun=cost_const, argminfun=argmin_const; doplot=false)
doplot = @static isinteractive() && doplot
n = length(w)
@assert (M < n) "M must be smaller than the length of the data sequence"
B = zeros(Int,M-1,n) # back-pointer matrix
# initialize Bellman iteration
fi = zeros(n)
for jj = M:n
fi[jj] = costfun(y,w,jj,n,argminfun)
end
doplot && plot(fi, lab="fi init")
memorymat = fill(Inf,n,n)
# iterate Bellman iteration
fnext = Vector{Float64}(undef,n)
for jj = M-1:-1:1
for kk = jj:n-(M-jj)
opt = Inf
optll = 0
for ll = kk+1:n-(M-jj-1)
if memorymat[kk,ll-1] == Inf
memorymat[kk,ll-1] = costfun(y,w,kk,ll-1,argminfun)
end
cost = memorymat[kk,ll-1] + fi[ll]
if cost < opt
opt = cost
optll = ll
end
end
fnext[kk] = opt
B[jj,kk] = optll-1
end
fi .= fnext
fnext = Vector{Float64}(undef,n)
doplot && plot!(fi, lab="fi at $jj")
end
# last Bellman iterate
V = [(memorymat[1,jj] == Inf ? costfun(y,w,1,jj,argminfun) : memorymat[1,jj])+fi[jj+1] for jj = 1:n-M]
if isempty(V) || length(V) <= M
error("Failed to perform segmentation, try lowering M")
end
doplot && plot!(V, lab="V")
# backward pass
t = Vector{Int}(undef,M);
a = Vector{typeof(argminfun(y,w,1,2))}(undef,M+1);
_,t[1] = findmin(V[1:end-M])
a[1] = argminfun(y,w,1,t[1])
for jj = 2:M
t[jj] = B[jj-1,t[jj-1]]
a[jj] = argminfun(y,w,t[jj-1]+1,t[jj])
end
a[M+1] = argminfun(y,w,t[M]+1,n)
V,t,a
end
"""
model = fit_statespace_dp(x,u, M; extend=true)
Fit model using dynamic programming. `M` is the number of changepoints.
´x` and `u` should have time in the second dimension.
See Bagge Carlson et al. 2018 section IID
Usage example in function `benchmark_ss`
"""
function fit_statespace_dp(x,u, M; extend=true, kwargs...)
n,T = size(x)
m = size(u,1)
d = iddata(x[:,2:end],u, x[:,1:end-1])
input = matrices(SimpleLTVModel(d), d)
@show size.(input)
# input = matrices(x,u)
V,bps,a = seg_bellman(input,M, ones(T-1), cost_ss, argmin_ss, doplot=false)
At,Bt = segments2full(a,bps,n,m,T)
SimpleLTVModel(At, Bt,extend)
end
# Tests
# Dynamic programming ==========================================================
function benchmark_const(N, M=1, doplot=false)
doplot = @static isinteractive() && doplot
n = 3N
y = [0.1randn(N); 10 .+ 0.1randn(N); 20 .+ 0.1randn(N).+range(1, stop=10, length=N)]
V,t,a = @time seg_bellman(y,M, ones(length(y)))
if doplot
tplot = [1;t;n];
aplot = [a;a[end]];
plot(y)
plot!(tplot, aplot, l=:step);gui()
end
# yhat, x, a, b
end
function benchmark_lin(T_, M, doplot=false)
doplot = @static isinteractive() && doplot
# M = 1
# T_ = 400
x = sin.(range(0, stop=2π, length=T_))
u = ones(1,T_)
d = iddata(x',u, x')
input = matrices(SimpleLTVModel(d), d)
@time V,t,a = seg_bellman(input,M, ones(T_-1), cost_lin, argmin_lin, doplot=false)
# if doplot
# k = reduce(hcat, a)'
# @show size(a), size(k)
# At = reshape(k[:,1:n^2]',n,n,M+1)
# At = permutedims(At, [2,1,3])
# tplot = [1;t;T_]
# plot()
# for i = 1:M+1
# plot!(tplot[i:i+1],flatten(At)[i,:]'.*ones(2), c=[:blue :green :red :magenta], xlabel="Time index", ylabel="Model coefficients")
# end
# plot!([1,T_÷2-1], [0.95 0.1; 0 0.95][:]'.*ones(2), ylims=(-0.1,1), l=(:dash,:black, 1))
# plot!([T_÷2,T_], [0.5 0.05; 0 0.5][:]'.*ones(2), l=(:dash,:black, 1), grid=false)
# gui()
# end
V,t,a
end
function benchmark_ss(T_, M, doplot=false)
doplot = @static isinteractive() && doplot
# M = 1
# T_ = 400
x,xm,u,n,m = testdata(T_)
dn = iddata(xm,u,xm)
input = matrices(SimpleLTVModel(dn), dn)
@time V,t,a = seg_bellman(input,M, ones(T_-1), cost_ss, argmin_ss, doplot=false)
if doplot
k = reduce(hcat, a)'
At = reshape(k[:,1:n^2]',n,n,M+1)
Bt = reshape(k[:,n^2+1:end]',m,n,M+1)
At = permutedims(At, [2,1,3])
Bt = permutedims(Bt, [2,1,3])
tplot = [1;t;T_]
plot()
for i = 1:M+1
plot!(tplot[i:i+1],flatten(At)[i,:]'.*ones(2), c=[:blue :green :red :magenta], xlabel="Time index", ylabel="Model coefficients")
end
plot!([1,T_÷2-1], [0.95 0.1; 0 0.95][:]'.*ones(2), ylims=(-0.1,1), l=(:dash,:black, 1))
plot!([T_÷2,T_], [0.5 0.05; 0 0.5][:]'.*ones(2), l=(:dash,:black, 1), grid=false)
gui()
end
V,t,a
end
# T_vec = round(Int,logspace(2, 4,10))
# times = map(T_vec) do T
# println(T)
# benchmark_ss(T, 1)
# end
# plot(T_vec, times)
#
# M_vec = [2,4,8,16,32]
# times = map(M_vec) do M
# println(M)
# @elapsed benchmark_ss(110, M)
# end
# plot(M_vec, times)
|
/*
This file is part of the Dynarithmic TWAIN Library (DTWAIN).
Copyright (c) 2002-2020 Dynarithmic Software.
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.
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
DYNARITHMIC SOFTWARE. DYNARITHMIC SOFTWARE DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS.
*/
#include <boost/format.hpp>
#include "ctltwmgr.h"
#include "enumeratorfuncs.h"
#include "errorcheck.h"
#include "ctltr025.h"
#ifdef _MSC_VER
#pragma warning (disable:4702)
#endif
using namespace std;
using namespace dynarithmic;
DTWAIN_BOOL DLLENTRY_DEF DTWAIN_GetImageInfoString(DTWAIN_SOURCE Source,
LPTSTR XResolution,
LPTSTR YResolution,
LPLONG Width,
LPLONG Length,
LPLONG NumSamples,
LPDTWAIN_ARRAY BitsPerSample,
LPLONG BitsPerPixel,
LPLONG Planar,
LPLONG PixelType,
LPLONG Compression)
{
LOG_FUNC_ENTRY_PARAMS((Source, XResolution, YResolution, Width, Length, NumSamples, BitsPerSample, BitsPerPixel, Planar, PixelType, Compression))
DTWAIN_FLOAT tempX;
DTWAIN_FLOAT tempY;
DTWAIN_BOOL retVal = DTWAIN_GetImageInfo(Source, &tempX, &tempY, Width, Length, NumSamples, BitsPerSample, BitsPerPixel, Planar, PixelType, Compression);
if (retVal)
{
CTL_StringStreamType strm;
strm << BOOST_FORMAT(_T("%1%")) % tempX;
StringWrapper::SafeStrcpy(XResolution, strm.str().c_str());
strm.str(_T(""));
strm << BOOST_FORMAT(_T("%1%")) % tempY;
StringWrapper::SafeStrcpy(YResolution, strm.str().c_str());
}
LOG_FUNC_EXIT_PARAMS(retVal)
CATCH_BLOCK(false)
}
DTWAIN_BOOL DLLENTRY_DEF DTWAIN_GetImageInfo(DTWAIN_SOURCE Source,
LPDTWAIN_FLOAT XResolution,
LPDTWAIN_FLOAT YResolution,
LPLONG Width,
LPLONG Length,
LPLONG NumSamples,
LPDTWAIN_ARRAY BitsPerSample,
LPLONG BitsPerPixel,
LPLONG Planar,
LPLONG PixelType,
LPLONG Compression)
{
LOG_FUNC_ENTRY_PARAMS((Source, XResolution, YResolution, Width, Length, NumSamples, BitsPerSample,BitsPerPixel, Planar, PixelType, Compression))
CTL_TwainDLLHandle *pHandle = static_cast<CTL_TwainDLLHandle *>(GetDTWAINHandle_Internal());
CTL_ITwainSource *p = VerifySourceHandle(pHandle, Source);
if (!p)
LOG_FUNC_EXIT_PARAMS(false)
DTWAIN_Check_Error_Condition_0_Ex(pHandle, [&]{ return (!CTL_TwainAppMgr::IsSourceOpen(p)); },
DTWAIN_ERR_SOURCE_NOT_OPEN, false, FUNC_MACRO);
CTL_ImageInfoTriplet II(pHandle->m_Session, p);
if (!CTL_TwainAppMgr::GetImageInfo(p, &II))
LOG_FUNC_EXIT_PARAMS(false)
// Get the image information
TW_IMAGEINFO *pInfo = II.GetImageInfoBuffer();
if (XResolution)
*XResolution = (DTWAIN_FLOAT)CTL_CapabilityTriplet::Twain32ToFloat(pInfo->XResolution);
if (YResolution)
*YResolution = (DTWAIN_FLOAT)CTL_CapabilityTriplet::Twain32ToFloat(pInfo->YResolution);
if (Width)
*Width = pInfo->ImageWidth;
if (Length)
*Length = pInfo->ImageLength;
if (NumSamples)
*NumSamples = pInfo->SamplesPerPixel;
if (BitsPerPixel)
*BitsPerPixel = pInfo->BitsPerPixel;
if (BitsPerSample)
{
DTWAIN_ARRAY Array = DTWAIN_ArrayCreate(DTWAIN_ARRAYLONG, 8);
auto& vValues = EnumeratorVector<LONG>(Array);
TW_INT16* pStart = &pInfo->BitsPerSample[0];
TW_INT16* pEnd = &pInfo->BitsPerSample[8];
std::copy(pStart, pEnd, vValues.begin());
*BitsPerSample = Array;
}
if (Planar)
*Planar = pInfo->Planar;
if (PixelType)
*PixelType = pInfo->PixelType;
if (Compression)
*Compression = pInfo->Compression;
LOG_FUNC_EXIT_PARAMS(true)
CATCH_BLOCK(false)
}
|
= = = <unk> AML = = =
|
Formal statement is: lemma LIMSEQ_lessThan_iff_atMost: shows "(\<lambda>n. f {..<n}) \<longlonglongrightarrow> x \<longleftrightarrow> (\<lambda>n. f {..n}) \<longlonglongrightarrow> x" Informal statement is: $\lim_{n \to \infty} f(\{1, 2, \ldots, n\}) = x$ if and only if $\lim_{n \to \infty} f(\{1, 2, \ldots, n-1\}) = x$.
|
State Before: l m r : List Char
p : Char → Bool
⊢ ValidFor (l ++ List.takeWhile p m) (List.dropWhile p m) r
(Substring.dropWhile
{ str := { data := l ++ m ++ r }, startPos := { byteIdx := utf8Len l },
stopPos := { byteIdx := utf8Len l + utf8Len m } }
p) State After: l m r : List Char
p : Char → Bool
⊢ ValidFor (l ++ List.takeWhile p m) (List.dropWhile p m) r
{ str := { data := l ++ m ++ r }, startPos := { byteIdx := utf8Len l + utf8Len (List.takeWhile p m) },
stopPos := { byteIdx := utf8Len l + utf8Len m } } Tactic: simp only [Substring.dropWhile, takeWhileAux_of_valid] State Before: l m r : List Char
p : Char → Bool
⊢ ValidFor (l ++ List.takeWhile p m) (List.dropWhile p m) r
{ str := { data := l ++ m ++ r }, startPos := { byteIdx := utf8Len l + utf8Len (List.takeWhile p m) },
stopPos := { byteIdx := utf8Len l + utf8Len m } } State After: case refine'_3
l m r : List Char
p : Char → Bool
⊢ utf8Len l + utf8Len m = utf8Len l + utf8Len (List.takeWhile p m) + utf8Len (List.dropWhile p m) Tactic: refine' .of_eq .. <;> simp State Before: case refine'_3
l m r : List Char
p : Char → Bool
⊢ utf8Len l + utf8Len m = utf8Len l + utf8Len (List.takeWhile p m) + utf8Len (List.dropWhile p m) State After: no goals Tactic: rw [Nat.add_assoc, ← utf8Len_append (m.takeWhile p), List.takeWhile_append_dropWhile]
|
State Before: f g : CircleDeg1Lift
hf : Continuous ↑f
m : ℤ
⊢ τ f = ↑m ↔ ∃ x, ↑f x = x + ↑m State After: case mp
f g : CircleDeg1Lift
hf : Continuous ↑f
m : ℤ
⊢ τ f = ↑m → ∃ x, ↑f x = x + ↑m
case mpr
f g : CircleDeg1Lift
hf : Continuous ↑f
m : ℤ
⊢ (∃ x, ↑f x = x + ↑m) → τ f = ↑m Tactic: constructor State Before: case mp
f g : CircleDeg1Lift
hf : Continuous ↑f
m : ℤ
⊢ τ f = ↑m → ∃ x, ↑f x = x + ↑m State After: case mp
f g : CircleDeg1Lift
hf : Continuous ↑f
m : ℤ
h : τ f = ↑m
⊢ ∃ x, ↑f x = x + ↑m Tactic: intro h State Before: case mp
f g : CircleDeg1Lift
hf : Continuous ↑f
m : ℤ
h : τ f = ↑m
⊢ ∃ x, ↑f x = x + ↑m State After: case mp
f g : CircleDeg1Lift
hf : Continuous ↑f
m : ℤ
h : τ f = ↑m
⊢ ∃ x, ↑f x = x + τ f Tactic: simp only [← h] State Before: case mp
f g : CircleDeg1Lift
hf : Continuous ↑f
m : ℤ
h : τ f = ↑m
⊢ ∃ x, ↑f x = x + τ f State After: no goals Tactic: exact f.exists_eq_add_translationNumber hf State Before: case mpr
f g : CircleDeg1Lift
hf : Continuous ↑f
m : ℤ
⊢ (∃ x, ↑f x = x + ↑m) → τ f = ↑m State After: case mpr.intro
f g : CircleDeg1Lift
hf : Continuous ↑f
m : ℤ
x : ℝ
hx : ↑f x = x + ↑m
⊢ τ f = ↑m Tactic: rintro ⟨x, hx⟩ State Before: case mpr.intro
f g : CircleDeg1Lift
hf : Continuous ↑f
m : ℤ
x : ℝ
hx : ↑f x = x + ↑m
⊢ τ f = ↑m State After: no goals Tactic: exact f.translationNumber_of_eq_add_int hx
|
from ROAR.perception_module.detector import Detector
import logging
import open3d as o3d
import numpy as np
import cv2
import time
from typing import Optional
class PointCloudDetector(Detector):
def __init__(self, max_detectable_distance=0.05, depth_scaling_factor=1000, max_points_to_convert=10000, **kwargs):
"""
Args:
max_detectable_distance: maximum detectable distance in km
depth_scaling_factor: scaling depth back to world scale. 1000 m = 1 km
**kwargs:
"""
super().__init__(**kwargs)
self.max_detectable_distance = max_detectable_distance
self.depth_scaling_factor = depth_scaling_factor
self.max_points_to_convert = max_points_to_convert
self.logger = logging.getLogger("Point Cloud Detector")
self.pcd: o3d.geometry.PointCloud = o3d.geometry.PointCloud()
self.vis = o3d.visualization.Visualizer()
self.counter = 0
def run_step(self) -> Optional[np.ndarray]:
points_3d = self.calculate_world_cords() # (Nx3)
return points_3d
def calculate_world_cords(self):
depth_img = self.agent.front_depth_camera.data.copy()
coords = np.where(depth_img < self.max_detectable_distance)
indices_to_select = np.random.choice(np.shape(coords)[1],
size=min([self.max_points_to_convert, np.shape(coords)[1]]),
replace=False)
coords = (
coords[0][indices_to_select],
coords[1][indices_to_select]
)
raw_p2d = np.reshape(self._pix2xyz(depth_img=depth_img, i=coords[0], j=coords[1]), (3, np.shape(coords)[1])).T
cords_y_minus_z_x = np.linalg.inv(self.agent.front_depth_camera.intrinsics_matrix) @ raw_p2d.T
cords_xyz_1 = np.vstack([
cords_y_minus_z_x[2, :],
cords_y_minus_z_x[0, :],
-cords_y_minus_z_x[1, :],
np.ones((1, np.shape(cords_y_minus_z_x)[1]))
])
points: np.ndarray = self.agent.vehicle.transform.get_matrix() @ self.agent.front_depth_camera.transform.get_matrix() @ cords_xyz_1
points = points.T[:, :3]
return points
@staticmethod
def _pix2xyz(depth_img, i, j):
return [
depth_img[i, j] * j * 1000,
depth_img[i, j] * i * 1000,
depth_img[i, j] * 1000
]
|
Require Import HoTT.
(*Strangely, I cannot find any proofs of nat being associative*)
Local Open Scope nat_scope.
Definition plus_assoc : forall j k l : nat, (j + k) + l = j + (k + l).
intros j k l.
induction j.
- exact idpath.
- exact (ap S IHj).
Defined.
(*Cancellation in nat*)
Open Scope nat_scope.
(* Subtraction of natural numbers. *)
(* Is given by [m,n => -m + n] *)
(* This is the same as the already defined [minus], but the below lemma is much easier to prove *)
Fixpoint nat_minus (m n : nat) : nat :=
match m with
|0 => n (*-0 + m := m*)
|m.+1 => match n with
|0 => 0 (*-(m+1)+0 = 0*)
|n.+1 => nat_minus m n (*- m+1 + n+1= -m + n*)
end
end.
(* Just to show that this is the same as the old minus. *)
Lemma nat_minus_is_minus (m n : nat) : nat_minus m n = minus n m.
Proof.
revert n.
induction m.
- induction n; reflexivity.
- induction n.
+ reflexivity.
+ simpl. apply IHm.
Defined.
Definition nat_plus_minus (m n : nat) : nat_minus m (m + n) = n.
Proof.
induction m.
- reflexivity.
- exact IHm.
Defined.
Definition nat_plus_cancelL (l m n : nat) : l + m = l + n -> m = n.
Proof.
intro p.
refine ((nat_plus_minus l m)^ @ _ @ nat_plus_minus l n).
apply (ap (nat_minus l) p).
Defined.
(* Definition not_leq_is_gt (i j : nat) : not (i <= j) <~> i > j. *)
(* Proof. *)
(* unfold not. unfold leq. unfold gt. *)
(* simpl. *)
(* induction i. simpl. *)
(* Definition split_nat (i : nat) : *)
(* nat <~> {j : nat & j <= i} + {j : nat & j > i}. *)
(* Proof. *)
(* srapply @equiv_adjointify. *)
(* - intro k. induction k. *)
(* (* k = 0 *) *)
(* + apply inl. *)
(* exists 0. *)
(* apply leq0n. *)
(* (* k+1 *) *)
(* + *)
Close Scope nat_scope.
(* Comparing not_leq to gt *)
Section Inequalities.
Local Open Scope nat.
(* For two natural numbers, one is either less than or equal the other, or it is greater. *)
Definition leq_or_gt (i j : nat) : (i <= j) + (i > j).
Proof.
revert j. induction i; intro j.
(* 0 <= j *)
- exact (inl tt).
- destruct j.
(* 0 < i+1 *)
+ exact (inr tt).
(* (i < j+1) + (j.+1 < i + 1) <-> (i <= j) + (j < i) *)
+ apply IHi.
Defined.
Definition leq_succ (n : nat) : n <= n.+1.
Proof.
induction n.
- reflexivity.
- apply IHn.
Defined.
(* Lemma leq_refl_code (i j : nat) : i =n j -> i <= j. *)
(* Proof. *)
(* intro H. *)
(* destruct (path_nat H). apply leq_refl. *)
(* Qed. *)
Definition neq_succ (n : nat) : not (n =n n.+1).
Proof.
induction n.
- exact idmap.
- exact IHn.
Defined.
Definition leq0 {n : nat} : n <= 0 -> n =n 0.
Proof.
induction n; exact idmap.
Defined.
(* if both i<=j and j<=i, then they are equal *)
Definition leq_geq_to_eq (i j : nat) : (i <= j) -> (j <= i) -> i =n j.
Proof.
revert i.
induction j; intros i i_leq_j j_leq_i.
- exact (leq0 i_leq_j).
- destruct i.
+ intros. destruct j_leq_i.
+ simpl. intros.
apply (IHj _ i_leq_j j_leq_i).
Defined.
(* If i <= n, then i < n or i = n+1 *)
Definition lt_or_eq (i n : nat) : i <= n -> (i < n) + (i = n).
Proof.
intro i_leq_n.
destruct (leq_or_gt n i) as [n_leq_i | n_gt_i].
- apply inr. apply path_nat. exact (leq_geq_to_eq _ _ i_leq_n n_leq_i).
- exact (inl n_gt_i).
Defined.
Definition lt_or_eq_or_gt (i n : nat) :
(i < n) + (i = n) + (i > n).
Proof.
destruct (leq_or_gt i n) as [leq | gt].
- apply inl. apply (lt_or_eq i n leq).
- exact (inr gt).
Defined.
(* Definition leq_to_lt_plus_eq (i j : nat) : i <= j -> (i < j) + (i = j). *)
(* Proof. *)
(* intro i_leq_j. *)
(* destruct (dec (i = j)). *)
(* - exact (inr p). *)
(* - apply inl. *)
(* induction j. *)
(* + simpl. rewrite (path_nat (leq0 i i_leq_j)) in n. apply n. reflexivity. *)
(* + destruct i. exact tt. *)
(* srapply (@leq_transd i.+2 j j.+1). *)
(* * apply IHj. *)
(* admit. *)
(* simpl. *)
(* i. *)
(* + simpl. *)
(* destruct j. *)
(* apply inr. apply path_nat. apply (leq0 i (i_leq_j)). *)
(* destruct i. *)
(* - simpl. *)
(* apply inl. change (i < j.+1) with (i <= j). *)
(* apply (leq_transd *)
(* Definition nlt_n0 (n : nat) : ~(n < 0) := idmap. *)
Definition gt_to_notleq (i j : nat) : j > i -> ~(j <= i).
Proof.
intro i_lt_j.
intro j_leq_i.
apply (neq_succ i).
apply (leq_antisymd (leq_succ i)).
apply (leq_transd i_lt_j j_leq_i).
(* set (Si_leq_i := leq_transd i_lt_j j_leq_i). *)
(* set (Si_eq_i := leq_antisymd (leq_succ i) Si_leq_i). *)
(* apply (neq_succ i Si_eq_i). *)
(* induction i. *)
(* exact Si_eq_i. *)
Defined.
Definition not_i_lt_i (i : nat) : ~(i < i).
Proof.
unfold not.
induction i.
- exact idmap.
- exact IHi.
Defined.
(* Lemma notleq_to_gt (i j : nat) : ~(j <= i) -> j > i. *)
(* Proof. *)
(* intro j_nleq_i. *)
(* induction j. *)
(* - apply j_nleq_i. *)
(* apply leq0n. *)
(* - change (i < j.+1) with (i <= j). *)
(* destruct (dec (i =n j)). *)
(* (* i = j *) *)
(* + destruct (path_nat t). apply leq_refl. *)
(* + *)
(* induction i. *)
(* + exact tt. *)
(* + *)
(* induction i, j. *)
(* - apply j_nleq_i. exact tt. *)
(* - exact tt. *)
(* - simpl. simpl in IHi. simpl in j_nleq_i. apply IHi. exact j_nleq_i. *)
(* - change (i.+1 < j.+1) with (i < j). *)
(* change (j < i.+1) with (j <= i) in j_nleq_i. *)
(* change (i < j.+1) with (i <= j) in IHi. *)
(* destruct (dec (~ (j <= i))). *)
(* - set (f := j_nleq_i t). destruct f. *)
(* - *)
(* If i <= j, then j is the sum of i and some natural number *)
Definition leq_to_sum {i j : nat} : i <= j -> {k : nat | j = i + k}%nat.
Proof.
revert j. induction i; intro j.
- intro.
exists j. reflexivity.
- destruct j.
+ intros [].
+ simpl. change (i < j.+1) with (i <= j).
intro i_leq_j.
apply (functor_sigma (A := nat) idmap (fun _ => ap S)).
apply (IHi j i_leq_j).
(* exists (IHi j i_leq_j).1. *)
(* apply (ap S). *)
(* apply (IHi j i_leq_j).2. *)
Defined.
(* If j > i, then j is a successor *)
Definition gt_is_succ {i j : nat} : i < j -> {k : nat | j = k.+1}.
Proof.
intro i_lt_j.
destruct (leq_to_sum i_lt_j) as [k H].
exact (i+k; H)%nat.
Defined.
End Inequalities.
|
theory Category imports FreeLogic
abbrevs "modphism" = ":\<rightarrow>" and
"wedge" = "\<leftarrow>-()-\<rightarrow>"
begin
(*Begin: some useful parameter settings*)
declare [[ smt_solver = cvc4, smt_oracle = true, smt_timeout = 120]] declare [[ show_types ]]
sledgehammer_params [provers = cvc4 z3 spass e vampire remote_leo3]
nitpick_params [user_axioms, show_all, format = 2]
(*nitpick_params[user_axioms, show_all, format = 2, expect = genuine]*)
(*End: some useful parameter settings*)
section \<open>The basis of category theory\<close>
class category =
fixes domain:: "'a \<Rightarrow> 'a" ("dom _" [108] 109) and
codomain:: "'a\<Rightarrow> 'a" ("cod _" [110] 111) and
composition:: "'a \<Rightarrow> 'a \<Rightarrow> 'a" (infix "\<cdot>" 110)
assumes
S1: "E(dom x) \<^bold>\<rightarrow> E x" and
S2: "E(cod y) \<^bold>\<rightarrow> E y" and
S3: "E(x\<cdot>y) \<^bold>\<leftrightarrow> dom x \<simeq> cod y" and
S4: "x\<cdot>(y\<cdot>z) \<cong> (x\<cdot>y)\<cdot>z" and
S5: "x\<cdot>(dom x) \<cong> x" and
S6: "(cod y)\<cdot>y \<cong> y"
begin
definition arrow ("(_):(_)\<rightarrow>(_)" [120,120,120] 119) where
"x:a\<rightarrow>b \<equiv> dom x \<simeq> a \<and> cod x \<simeq> b"
definition wedge ("_\<leftarrow>_- (_) -_\<rightarrow>_" [120,0,0,0,120] 119) where
"a \<leftarrow>f- (x) -g\<rightarrow> b \<equiv> dom f \<simeq> x \<and> cod f \<simeq> a \<and> dom g \<simeq> x \<and> cod g \<simeq> b"
definition monic::"'a \<Rightarrow> bool" where
"monic m \<equiv> \<forall>f g. m\<cdot>f \<simeq> m\<cdot>g \<longrightarrow> f \<simeq> g"
definition epi::"'a \<Rightarrow> bool" where
"epi m \<equiv> \<forall>f g. f\<cdot>m \<simeq> g\<cdot>m \<longrightarrow> f \<simeq> g"
definition isomorphism::"'a \<Rightarrow> bool" where
"isomorphism f \<equiv> \<exists>g. f\<cdot>g \<cong> (dom g) \<and> g\<cdot>f \<cong> (dom f)"
definition isomorphic::"'a \<Rightarrow> 'a \<Rightarrow> bool" where
"isomorphic z y \<equiv> \<exists>f. dom f \<cong> z \<and> cod f \<cong> y \<and> isomorphism f"
definition initial::"'a \<Rightarrow> bool" where
"initial z \<equiv> \<^bold>\<forall>t. (\<exists>!f. dom f \<simeq> z \<and> cod f \<simeq> t)"
definition final::"'a \<Rightarrow> bool" where
"final z \<equiv> \<^bold>\<forall>t. (\<exists>!f. dom f \<simeq> t \<and> cod f \<simeq> z)"
\<comment>\<open>Checking equivalences of definitions\<close>
lemma StrongerInitial1: "(initial z) \<longrightarrow> (\<^bold>\<forall>t. (\<^bold>\<exists>!f. dom f \<simeq> z \<and> cod f \<simeq> t))"
by (metis (no_types) S1 initial_def)
lemma StrongerInitial2: "(\<^bold>\<forall>t. (\<^bold>\<exists>!f. dom f \<simeq> z \<and> cod f \<simeq> t)) \<longrightarrow> initial z"
by (smt S2 initial_def)
lemma WeakerInitial1: "(\<^bold>\<forall>t. (\<exists>!f. dom f \<cong> z \<and> cod f \<cong> t)) \<longrightarrow> initial z"
by (smt S5 category.S2 category.S3 category_axioms initial_def)
lemma WeakerInitial2: "initial z \<longrightarrow> (\<^bold>\<forall>t. (\<exists>!f. dom f \<cong> z \<and> cod f \<cong> t))"
by (smt initial_def)
(*The same as above would do for final*)
end
lemma (in category) InitialsAreIsomorphic: "initial z \<and> initial y \<longrightarrow> isomorphic z y" (*sledgehammer sledgehammer [remote_leo3]*)
by (smt S1 S3 S5 S6 category_axioms epi_def initial_def isomorphic_def isomorphism_def)
lemma (in category) InitialIsUnique: "\<forall>z. \<forall>f. initial z \<and> (dom f \<cong> z \<and> cod f \<cong> z) \<longrightarrow> z \<cong> f" (*sledgehammer sledgehammer [remote_leo3]*)
by (metis(no_types) S3 S5 S6 initial_def)
lemma (in category) FinalsAreIsomorphic: "final z \<and> final y \<longrightarrow> isomorphic z y" (*sledgehammer sledgehammer [remote_leo3]*)
by (smt S2 S3 S5 final_def isomorphic_def isomorphism_def)
lemma (in category) FinalIsUnique: "\<forall>z. \<forall>f. final z \<and> ( dom f \<cong> z \<and> cod f \<cong> z) \<longrightarrow> z \<cong> f" (*sledgehammer sledgehammer [remote_leo3]*)
by (metis(no_types) S3 S5 S6 final_def)
lemma (in category) TwoMonicsBetweenTypes: "(\<^bold>\<forall>(m::'a) (n::'a). monic m \<and> monic n \<and> dom m \<simeq> dom n \<and> cod m \<simeq> cod n \<longrightarrow> (m\<simeq>n))" nitpick oops
(*Relationship between isomorphisms and epic and monic maps*)
proposition (in category) "isomorphism m \<longrightarrow> monic m \<and> epi m" \<comment>\<open>cvc4 and Leo-III proves this\<close>
(*sledgehammer sledgehammer [remote_leo3]*)
by (smt S1 S3 S4 S5 S6 epi_def isomorphism_def monic_def)
proposition (in category) "monic m \<and> epi m \<longrightarrow> isomorphism m" nitpick oops
section \<open>Product\<close>
definition (in category) product::"'a \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> bool" where
"product a b c \<equiv> \<^bold>\<exists>p1 p2. p1:c\<rightarrow>a \<and> p2:c\<rightarrow>b \<and>
(\<^bold>\<forall>x f g. (a\<leftarrow>f-(x)-g\<rightarrow>b) \<longrightarrow> (\<^bold>\<exists>!h. h:x\<rightarrow>c \<and> f \<simeq> p1\<cdot>h \<and> g \<simeq> p2\<cdot>h))"
lemma (in category) "((product a b c) \<and> (product a b d)) \<longrightarrow> isomorphic c d"
unfolding isomorphic_def isomorphism_def product_def arrow_def wedge_def
(* sledgehammer sledgehammer [remote_leo3] *)
by (smt S3 S4 S5)
lemma (in category) "(product b a c) \<longrightarrow> (product a b c)"
unfolding product_def arrow_def wedge_def
(* sledgehammer sledgehammer [remote_leo3] *)
by smt
end
|
Top producers in the mortgage industry all understand a fundamental truth that helps them maintain their success over a long period of time. Not only do they understand this truth, they constantly act upon it and even shape their business around it.
To build a successful mortgage business, create jobs within your company because of your production, and provide a fantastic level of service, your business needs to have a predictable source of revenue.
The most predicatable and repeatable way to generate revenue month-after-month is by building a network of actively referring agents and partners.
But it’s also easier said than done. The race for partnerships in the mortgage industry can be intense, and it’s exceedingly difficult to provide tangible reasons why you are a better choice than your competitors.
Our mortgage automation platform comes chock-full of functionality designed to streamline important, but time-consuming, portions of origination and relationship management process. This includes specific features designed to give you unique differentiators to discuss when a possible partner inevitably asks, “so what makes you different?”.
For many of the same reasons that it’s important for borrowers to know where exactly their loan is in the funding process, it’s also critical to their Realtor® to have the same information.
First, they need to know when they can take the client “shopping”.
No agent worth their salt will want to spend hours looking at houses without any assurance that the client will be able to acquire financing.
Second, they need to know the terms by which they can build their shopping list.
Even though borrowers don’t usually think through the transaction in that order, agents do. They want to know what their limits are, both in terms of the purchase price as well as any restrictions imposed by the loan program the borrower qualifies for.
And the third and final reason that your agent partners crave information, is that their business depends on it. They need loans to close in order to pay the bills, same as you.
It sounds like a lot of work, right? In years past it would have been.
With Floify, you can provide your partners with the timely information that makes their life easier with just a few clicks of your mouse.
Floify’s partner portal is a one-stop-shop for your agents to get an instant take on all of the loans that they’ve been invited to follow along with.
Similar to what you would see on your Loan Pipeline, partners will get a top-level view of where everything is at upon login and can dial-down into a specific loan to get a bit more information and functionality. Unlike what you see when you go deeper into a loan flow, partners will never have exposure to borrower documentation.
But they can see how many documents are still owed by the borrower, how many docs they’ve submitted, and what milestones have been checked-off in the process. That kind of oversight provides tons of information to your partners and keeps them from calling/emailing to check-in on how things are going. That way you can focus on developing and expanding your referral relationships, instead of just keeping them afloat.
They also have the ability to interact with the loan flow to upload any documentation that they are in possession of and can even generate custom, property-specific pre-approval letters for the client.
How many phone calls from agents do you (or your team members) field over the course of a week, asking for a pre-approval letter formatted for a property? Do you think that’s a pleasant experience for anyone?
Not only is that a disruption to your day, IF you can even get to it immediately, but your agent partner also has to wait for you to load up your Word file, make the changes to your template, and email them the final product. And that’s just for a single letter!
If you have multiple referring agents, who could be showing a single client multiple properties, the minutes can really start to add up.
But if you’ve invited these partners to participate through Floify, and given them permission to make letters, they can simply log in to the Partner Portal and create their own in a blink.
For any client that they share with you.
For any property that they’re viewing.
On your custom letter template.
Bound by loan limits that you set.
By using and marketing these differentiators, you can provide your referring partners and agents with a more efficient way to conduct business and manage your partnership.
And that’s in addition to all of the value that you can add for their clients.
|
function c=comp_nonsepdgt_multi(f,g,a,M,lt)
%COMP_NONSEPDGT_MULTI Compute Non-separable Discrete Gabor transform
% Usage: c=comp_nonsepdgt_multi(f,g,a,M,lt);
%
% This is a computational subroutine, do not call it directly.
% AUTHOR : Nicki Holighaus and Peter L. Søndergaard
% TESTING: TEST_NONSEPDGT
% REFERENCE: REF_NONSEPDGT
% Assert correct input.
L=size(f,1);
W=size(f,2);
N=L/a;
% ----- algorithm starts here, split into sub-lattices ---------------
c=zeros(M,N,W,assert_classname(f,g));
mwin=comp_nonsepwin2multi(g,a,M,lt,L);
% simple algorithm: split into sublattices
for ii=0:lt(2)-1
c(:,ii+1:lt(2):end,:)=comp_dgt(f,mwin(:,ii+1),lt(2)*a,M,[0 1],0,0,0);
end;
% Phase factor correction
E = zeros(1,N,assert_classname(f,g));
for win=0:lt(2)-1
for n=0:N/lt(2)-1
E(win+n*lt(2)+1) = exp(-2*pi*i*a*n*rem(win*lt(1),lt(2))/M);
end;
end;
c=bsxfun(@times,c,E);
|
[STATEMENT]
lemma substitutes_appE:
assumes "substitutes (App A B) x M X"
shows "\<exists>A' B'. substitutes A x M A' \<and> substitutes B x M B' \<and> X = App A' B'"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<exists>A' B'. substitutes A x M A' \<and> substitutes B x M B' \<and> X = App A' B'
[PROOF STEP]
by(
cases rule: substitutes_appE'[where A=A and B=B and x=x and M=M and X=X],
metis assms,
metis unit_not_app,
metis var_not_app,
metis var_not_app,
metis trm_simp(2,3),
auto simp add: app_not_fn app_not_pair app_not_fst app_not_snd
)
|
Inductive listn : nat -> Set :=
| niln : listn 0
| consn : forall n : nat, nat -> listn n -> listn (S n).
Definition length1 (n : nat) (l : listn n) :=
match l with
| consn n _ (consn m _ _) => S (S m)
| consn n _ _ => 1
| _ => 0
end.
Type
(fun (n : nat) (l : listn n) =>
match n return nat with
| O => 0
| S n => match l return nat with
| niln => 1
| l' => length1 (S n) l'
end
end).
|
-- Next time: let's see how the graph theory theorem about the sum of degrees being even is coded in lean.
import combinatorics.simple_graph.connectivity
open_locale classical
universe u
variables {V : Type u} (G : simple_graph V)
#print simple_graph.walk -- prints the definition
#check nonempty -- prints the type of the object
-- simple_graph.walk u v is the type of all walks from u to v
-- prove that if u is adjacent to v then the set of walks from u to v is non-empty
def simple_graph.walks_of_len (G : simple_graph V) (u v : V) (n : ℕ) :=
{ x : G.walk u v // x.length = n }
theorem adjacent_to_walk {u v : V} (h : G.adj u v) : nonempty (G.walks_of_len u v 1) :=
begin
apply nonempty.intro,
split,
swap,
{ have p := @simple_graph.walk.nil _ _ v,
exact simple_graph.walk.cons h p },
simp only [simple_graph.walk.length_nil, simple_graph.walk.length_cons],
end
-- lemma len_of_cons_ge_one {}
theorem eq_of_len_zero {u v : V} (w : G.walks_of_len u v 0) : u = v :=
begin
cases w with w h,
induction w,
{ refl },
{ exfalso,
simp only [nat.succ_ne_zero, simple_graph.walk.length_cons] at *,
exact h, }
end
theorem exists_walk_of_len {u v : V} (n : ℕ) (w : G.walk u v) (h : w.length = n + 1) :
∃ (v' : V) (w' : G.walk u v'), (w'.length = n) ∧ (G.adj v' v) :=
begin
sorry,
end
theorem non_eq_of_len_one {u v : V} (w : G.walk u v) (h : w.length = 1) : G.adj u v :=
begin
end
theorem non_eq_of_len_one {u v : V} (w : G.walks_of_len u v 1) : u ≠ v :=
begin
cases w with w h,
sorry,
-- induction w,
-- {intro h,
-- contradiction,},
-- simp,
-- contradiction,
end
theorem adj_of_len_one {u v : V} (w : G.walks_of_len u v 1) : G.adj u v :=
begin
cases w with w h,
sorry,
end
|
#!/usr/bin/env python
"""Analyze logs and plot results."""
import argparse
from itertools import cycle
import os
import pickle
import matplotlib as mpl
mpl.use('Agg')
from matplotlib import pyplot as plt
import numpy as np
from tugs import utils
mpl.rc('xtick', labelsize=7)
mpl.rc('ytick', labelsize=7)
mpl.rc('font', size=7)
col_gen = cycle('bgrcmk')
def plot_report(repickle):
paths = {
# 'bunny/runs/': (2, 113),
# 'bunny/runs_slugs/': (2, 63),
# 'bunny_goals/runs/': (2, 32),
# 'bunny_goals/runs_slugs/': (2, 33),
# 'bunny_many_goals/runs/': (2, 49),
# 'bunny_many_goals/runs_slugs/': (2, 49),
# 'synt15/runs_slugs/': (2, 49),
# 'synt15/runs_slugs_browne/': (2, 41),
#
'synt15/runs/': (2, 60),
#
# 'synt15/runs_gr1x_linear_conj/': (2, 65),
# 'synt15/runs_gr1x_logging_debug/': (2, 80),
# 'synt15/runs_gr1x_logging_info/': (2, 105),
# 'synt15/runs_gr1x_logging_info_missing_bdd/': (2, 65),
# 'synt15/runs_gr1x_memoize/': (2, 65),
# 'synt15/runs_gr1x_one_manager/': (2, 65),
# 'bunny/runs/': (2, 97)
# 'cinderella/runs': (0, 10),
# 'cinderella/runs_slugs': (0, 8)
# 'jcss12/runs': (2, 22),
# 'jcss12/runs_gr1x_no_defer': (2, 25),
# 'jcss12/runs_slugs': (2, 16),
#
# 'genbuf/runs': (2, 90),
# 'genbuf/runs_slugs': (2, 63),
}
for path, (first, last) in paths.iteritems():
plot_vs_parameter(path, first, last, repickle=repickle)
def plot_comparison_report(ignore=False):
pairs = [
# new='bunny_many_goals/runs',
# slugs='bunny_many_goals/runs_slugs',
# numerator='slugs',
#
dict(
new='synt15/runs_gr1x_fdbk_no_tight',
memoize='synt15/runs',
numerator='memoize',
fname='comparison_memoize.pdf'),
dict(
new='synt15/runs_gr1x_logging_info',
one_manager='synt15/runs_gr1x_one_manager',
numerator='one_manager',
fname='comparison_one_manager.pdf'),
dict(
new='synt15/runs_gr1x_logging_info',
linear_conj='synt15/runs_gr1x_linear_conj',
numerator='linear_conj',
fname='comparison_linear_conj.pdf'),
dict(
new='synt15/runs_gr1x_logging_info',
no_defer='synt15/runs_gr1x_no_defer',
numerator='no_defer',
fname='comparison_no_defer.pdf'),
dict(
new='synt15/runs_gr1x_logging_info',
slugs='synt15/runs_slugs',
numerator='slugs',
fname='comparison_gr1x_slugs.pdf'),
dict(
new='synt15/runs_gr1x_logging_info',
no_defer_no_fdbk='synt15/runs_gr1x_no_defer_no_fdbk',
numerator='no_defer_no_fdbk',
fname='comparison_no_defer_no_fdbk.pdf'),
dict(
new='synt15/runs_gr1x_logging_info',
no_defer_no_fdbk_xz='synt15/runs_gr1x_no_defer_no_fdbk_xz',
numerator='no_defer_no_fdbk_xz',
fname='comparison_no_defer_no_fdbk_xz.pdf'),
dict(
no_defer_no_fdbk='synt15/runs_gr1x_no_defer_no_fdbk',
no_defer_no_fdbk_xz='synt15/runs_gr1x_no_defer_no_fdbk_xz',
numerator='no_defer_no_fdbk_xz',
fname='comparison_no_defer_no_fdbk_vs_xz.pdf'),
dict(
new='synt15/runs_gr1x_logging_info',
fdbk_no_tight='synt15/runs_gr1x_fdbk_no_tight',
numerator='fdbk_no_tight',
fname='comparison_fdbk_no_tight.pdf'),
dict(
tight='synt15/runs_gr1x_no_defer_no_fdbk_xz',
no_tight='synt15/runs_gr1x_fdbk_no_tight',
numerator='no_tight',
fname='comparison_fdbk_no_vs_tight.pdf'),
dict(
slugs='synt15/runs_slugs',
slugs_browne='synt15/runs_slugs_browne',
numerator='slugs_browne',
fname='comparison_slugs_browne.pdf'),
dict(
no_defer='jcss12/runs_gr1x_no_defer',
slugs='jcss12/runs_slugs_1',
numerator='slugs',
fname='comparison_no_defer_slugs.pdf'),
dict(
binary='jcss12/runs_gr1x_defer_binary',
slugs='jcss12/runs_slugs_1',
numerator='slugs',
fname='comparison_binary_slugs.pdf'),
dict(
fdbk_no_tight='jcss12/runs',
slugs='jcss12/runs_slugs_1',
numerator='slugs',
fname='comparison_fdbk_no_tight_slugs.pdf'),
dict(
defer_binary='jcss12/runs_gr1x_defer_binary',
fdbk_no_tight='jcss12/runs',
numerator='fdbk_no_tight',
fname='comparison_fdbk_no_tight.pdf'),
dict(
defer_binary='jcss12/runs_gr1x_defer_binary',
no_defer='jcss12/runs_gr1x_no_defer',
numerator='no_defer',
fname='comparison_no_defer.pdf'),
dict(
fdbk_no_tight='genbuf/runs',
slugs='genbuf/runs_slugs',
numerator='fdbk_no_tight',
fname='comparison_fdbk_no_tight_vs_slugs.pdf'),
# dict(
# new='cinderella/runs',
# slugs='cinderella/runs_slugs',
# numerator='slugs',
# fname='comparison_gr1x_slugs.pdf')
]
for p in pairs:
plot_comparison(p, ignore)
def plot_vs_parameter(path, first, last, repickle=False):
"""Plot time, ratios, BDD nodes over parameterized experiments.
- time
- winning set computation / total time
- reordering / total time
- total nodes
- peak nodes
"""
measurements = pickle_results(path, first, last, repickle)
# expand
n_masters = measurements['n_masters']
total_time = measurements['total_time']
reordering_time_0 = measurements['reordering_time_0']
reordering_time_1 = measurements['reordering_time_1']
win_time = measurements['win_time']
win_ratio = measurements['win_ratio']
win_dump_ratio = measurements['win_dump_ratio']
strategy_dump_ratio = measurements['strategy_dump_ratio']
upratio_0 = measurements['upratio_0']
upratio_1 = measurements['upratio_1']
total_nodes_0 = measurements['total_nodes_0']
total_nodes_1 = measurements['total_nodes_1']
peak_nodes_0 = measurements['peak_nodes_0']
peak_nodes_1 = measurements['peak_nodes_1']
transducer_nodes = measurements['transducer_nodes']
# plot
fig_fname = os.path.join(path, 'stats.pdf')
fsz = 20
tsz = 15
fig = plt.figure()
fig.set_size_inches(5, 10)
plt.clf()
plt.subplots_adjust(hspace=0.3)
#
# times
ax = plt.subplot(3, 1, 1)
plt.plot(n_masters, total_time, 'b-', label='Total time')
if len(win_time) == len(n_masters):
plt.plot(n_masters, win_time, 'r--',
label='Winning set fixpoint')
if len(reordering_time_1):
total_reordering_time = reordering_time_0 + reordering_time_1
else:
total_reordering_time = reordering_time_0
if len(total_reordering_time) == len(n_masters):
plt.plot(n_masters, total_reordering_time, 'g-o',
label='Total reordering time')
# annotate
ax.set_yscale('log')
ax.tick_params(labelsize=tsz)
plt.grid()
plt.xlabel('Parameter', fontsize=fsz)
plt.ylabel('Time (sec)', fontsize=fsz)
leg = plt.legend(loc='upper left', fancybox=True)
leg.get_frame().set_alpha(0.5)
#
# ratios
ax = plt.subplot(3, 1, 2)
if len(win_ratio) == len(n_masters):
plt.plot(n_masters, win_ratio, 'b-.', label='Win / total time')
if len(upratio_0) == len(n_masters):
plt.plot(n_masters, upratio_0, 'b-o',
label='Reordering ratio (1)', markevery=10)
if len(upratio_1) == len(n_masters):
plt.plot(n_masters, upratio_1, 'r--o',
label='Reordering ratio (2)', markevery=10)
if len(win_dump_ratio) == len(n_masters):
plt.plot(n_masters, win_dump_ratio, 'g-*',
label='Win set dump / total time')
if len(strategy_dump_ratio) == len(n_masters):
plt.plot(n_masters, strategy_dump_ratio, 'm--*',
label='Strategy dump / total time')
# annotate
# ax.set_yscale('log')
ax.tick_params(labelsize=tsz)
plt.grid()
ax.set_ylim([0, 1])
plt.xlabel('Parameter', fontsize=fsz)
plt.ylabel('Ratios', fontsize=fsz)
leg = plt.legend(loc='upper left', fancybox=True)
leg.get_frame().set_alpha(0.5)
#
# nodes
ax = plt.subplot(3, 1, 3)
if len(total_nodes_0) == len(n_masters):
plt.plot(n_masters, total_nodes_0, 'b-+',
label='Total (1)', markevery=10)
plt.plot(n_masters, peak_nodes_0, 'b-*',
label='Peak (1)', markevery=10)
if len(total_nodes_1) == len(n_masters):
plt.plot(n_masters, total_nodes_1, 'r--+',
label='Total (2)', markevery=10)
plt.plot(n_masters, peak_nodes_1, 'r--*',
label='Peak (2)', markevery=10)
if len(transducer_nodes) == len(n_masters):
plt.plot(n_masters, transducer_nodes, 'g--o',
label='Strategy', markevery=10)
# annotate
ax.set_yscale('log')
ax.tick_params(labelsize=tsz)
plt.grid()
plt.xlabel('Parameter', fontsize=fsz)
plt.ylabel('BDD Nodes', fontsize=fsz)
leg = plt.legend(loc='upper left', fancybox=True)
leg.get_frame().set_alpha(0.5)
# save
plt.savefig(fig_fname, bbox_inches='tight')
def plot_comparison(paths, ignore):
"""Plot time, ratios, BDD nodes over parameterized experiments.
- time
- winning set computation / total time
- reordering / total time
- total nodes
- peak nodes
"""
assert len(paths) >= 2, paths
# paths
data_paths = dict(paths)
if 'numerator' in data_paths:
data_paths.pop('numerator')
data_paths.pop('fname')
else:
paths['numerator'] = next(iter(paths))
# file up to date ?
path = next(data_paths.itervalues())
head, _ = os.path.split(path)
fig_fname = os.path.join(head, paths['fname'])
try:
fig_time = os.path.getmtime(fig_fname)
except OSError:
fig_time = 0
# load
measurements = dict()
fname = 'data.pickle'
older = True
for path in data_paths.itervalues():
path = os.path.join(path, fname)
t = os.path.getmtime(path)
if t > fig_time:
older = False
break
if older and not ignore:
print('skip "{f}"\n'.format(f=fig_fname))
return
for k, path in data_paths.iteritems():
pickle_fname = os.path.join(path, fname)
print('open "{f}"'.format(f=pickle_fname))
with open(pickle_fname, 'r') as f:
measurements[k] = pickle.load(f)
# plot
fig = plt.figure()
fig.set_size_inches(10, 5)
plt.clf()
plt.subplots_adjust(hspace=0.3, wspace=0.3)
# styles = ['b-', 'r--']
for k, d in measurements.iteritems():
if k == paths['numerator']:
style = 'b-'
else:
style = 'r--'
plot_single_experiment_vs_parameter(d, k, style)
# plot_total_time_ratio(measurements, paths, data_paths)
# save
print('save "{f}"\n'.format(f=fig_fname))
plt.savefig(fig_fname, bbox_inches='tight')
def plot_total_time_ratio(measurements, paths, data_paths):
assert len(measurements) == 2, measurements
ax = plt.subplot(5, 1, 5)
ax.set_yscale('log')
numerator = paths['numerator']
denominator = set(data_paths)
denominator.remove(numerator)
(denominator,) = denominator
param_num = measurements[numerator]['n_masters']
param_den = measurements[denominator]['n_masters']
time_num = measurements[numerator]['total_time']
time_den = measurements[denominator]['total_time']
common = set(param_num).intersection(param_den)
param = [k for k in param_num if k in common]
time_num = [v for k, v in zip(param_num, time_num)
if k in common]
time_den = [v for k, v in zip(param_den, time_den)
if k in common]
time_num = np.array(time_num)
time_den = np.array(time_den)
y = time_num / time_den
plt.plot(param, y, 'b-')
plt.plot([param[0], param[-1]], [1.0, 1.0], 'g--')
# annotate
fsz = 12
tsz = 12
ax.tick_params(labelsize=tsz)
plt.grid(True)
plt.xlabel('Parameter', fontsize=fsz)
title = 'Ratio of total time\n({a} / {b})'.format(
a=numerator, b=denominator)
plt.ylabel(title, fontsize=fsz)
def plot_single_experiment_vs_parameter(measurements, name, style):
fsz = 12
tsz = 12
# expand
n_masters = measurements['n_masters']
total_time = measurements['total_time']
reordering_time_0 = measurements['reordering_time_0']
reordering_time_1 = measurements['reordering_time_1']
total_nodes_0 = measurements['total_nodes_0']
total_nodes_1 = measurements['total_nodes_1']
peak_nodes_0 = measurements['peak_nodes_0']
peak_nodes_1 = measurements['peak_nodes_1']
#
# total time
ax = plt.subplot(2, 2, 1)
plt.plot(n_masters, total_time, style, label=name)
# annotate
ax.set_yscale('log')
ax.tick_params(labelsize=tsz)
plt.grid(True)
plt.xlabel('Parameter', fontsize=fsz)
plt.ylabel('Total time\n(sec)', fontsize=fsz)
leg = plt.legend(loc='best', fancybox=True)
leg.get_frame().set_alpha(0.5)
#
# reordering time
ax = plt.subplot(2, 2, 3)
if len(reordering_time_1):
total_reordering_time = reordering_time_0 + reordering_time_1
else:
total_reordering_time = reordering_time_0
if len(total_reordering_time) == len(n_masters):
plt.plot(n_masters, total_reordering_time, style,
label=name)
# annotate
ax.set_yscale('log')
ax.tick_params(labelsize=tsz)
plt.grid(True)
plt.xlabel('Parameter', fontsize=fsz)
plt.ylabel('Total reordering time\n(sec)', fontsize=fsz)
leg = plt.legend(loc='best', fancybox=True)
leg.get_frame().set_alpha(0.5)
#
# peak BDD nodes
ax = plt.subplot(2, 2, 2)
if len(total_nodes_0) == len(n_masters):
plt.plot(n_masters, peak_nodes_0, style + 'o',
label='{name} (1)'.format(name=name),
markevery=10)
if len(total_nodes_1) == len(n_masters):
plt.plot(n_masters, peak_nodes_1, style,
label='{name} (2)'.format(name=name),
markevery=10)
# annotate
ax.set_yscale('log')
ax.tick_params(labelsize=tsz)
plt.grid(True)
plt.xlabel('Parameter', fontsize=fsz)
plt.ylabel('Peak BDD Nodes', fontsize=fsz)
leg = plt.legend(loc='best', fancybox=True)
leg.get_frame().set_alpha(0.5)
#
# peak BDD nodes
ax = plt.subplot(2, 2, 4)
if len(total_nodes_0) == len(n_masters):
plt.plot(n_masters, total_nodes_0, style,
label='{name} (1)'.format(name=name),
markevery=10)
if len(total_nodes_1) == len(n_masters):
plt.plot(n_masters, total_nodes_1, style + 'o',
label='{name} (2)'.format(name=name),
markevery=10)
# annotate
ax.set_yscale('log')
ax.tick_params(labelsize=tsz)
plt.grid(True)
plt.xlabel('Parameter', fontsize=fsz)
plt.ylabel('Total BDD Nodes', fontsize=fsz)
leg = plt.legend(loc='best', fancybox=True)
leg.get_frame().set_alpha(0.5)
def pickle_results(path, first, last, repickle):
"""Dump to pickle file all measurements from a directory."""
fname = 'details_{i}.txt'.format(i='{i}')
log_fname = os.path.join(path, fname)
fname = 'data.pickle'
pickle_fname = os.path.join(path, fname)
try:
with open(pickle_fname, 'r') as f:
measurements = pickle.load(f)
except IOError:
measurements = None
if measurements and not repickle:
print('found pickled data')
return measurements
measurements = dict(
n_masters=list(),
total_time=list(),
reordering_time_0=list(),
reordering_time_1=list(),
win_time=list(),
win_ratio=list(),
win_dump_ratio=list(),
strategy_dump_ratio=list(),
upratio_0=list(),
upratio_1=list(),
total_nodes_0=list(),
total_nodes_1=list(),
peak_nodes_0=list(),
peak_nodes_1=list(),
transducer_nodes=list())
n = first
m = last + 1
for i in xrange(n, m):
fname = log_fname.format(i=i)
try:
data = utils.load_log_file(fname)
print('open "{fname}"'.format(fname=fname))
except:
print('Skip: missing log file "{f}"'.format(
f=fname))
continue
collect_measurements(data, measurements)
measurements['n_masters'].append(i)
# np arrays
for k, v in measurements.iteritems():
measurements[k] = np.array(v)
# dump
with open(pickle_fname, 'w') as f:
pickle.dump(measurements, f)
return measurements
def collect_measurements(data, measurements):
"""Collect measurements from `data`."""
# total time
t0 = data['parse_slugsin']['time'][0]
# realizable ? (slugs only, gr1x always makes strategy)
if 'make_transducer_end' in data:
t1 = data['make_transducer_end']['time'][0]
elif 'winning_set_end' in data:
print('Warning: unrealizable found')
t1 = data['winning_set_end']['time'][0]
else:
raise Exception('Winning set unfinished!')
t = t1 - t0
measurements['total_time'].append(t)
# winning set / total time
if 'winning_set_start' in data:
t0 = data['winning_set_start']['time'][0]
t1 = data['winning_set_end']['time'][0]
t_win = t1 - t0
r = t_win / t
measurements['win_ratio'].append(r)
measurements['win_time'].append(t_win)
# winning set dump time / total time
if 'dump_winning_set_start' in data:
t0 = data['dump_winning_set_start']['time'][0]
t1 = data['dump_winning_set_end']['time'][0]
t_dump_win = t1 - t0
r = t_dump_win / t
measurements['win_dump_ratio'].append(r)
# strategy dump time / total time
if 'dump_strategy_start' in data:
t0 = data['dump_strategy_start']['time'][0]
t1 = data['dump_strategy_end']['time'][0]
t_dump_strategy = t1 - t0
r = t_dump_strategy / t
measurements['strategy_dump_ratio'].append(r)
if 'transducer_nodes' in data:
x = data['transducer_nodes']['value'][-1]
measurements['transducer_nodes'].append(x)
# construction time
# realizable (slugs) ?
if 'make_transducer_start' in data:
t0 = data['make_transducer_start']['time'][0]
t1 = data['make_transducer_end']['time'][0]
t_make = t1 - t0
if 'reordering_time' in data:
# reordering BDD 0
rt = data['reordering_time']['value'][-1]
r = rt / t
measurements['upratio_0'].append(r)
measurements['reordering_time_0'].append(rt)
# total nodes 0
tn = data['total_nodes']['value'][-1]
measurements['total_nodes_0'].append(tn)
# peak nodes 0
p = data['peak_nodes']['value'][-1]
measurements['peak_nodes_0'].append(p)
else:
print('Warning: no BDD manager 0')
if 'b3_reordering_time' in data:
# reordering BDD 1
rt = data['b3_reordering_time']['value'][-1]
r = rt / t_make
measurements['upratio_1'].append(r)
measurements['reordering_time_1'].append(rt)
# total nodes 1
tn = data['b3_total_nodes']['value'][-1]
measurements['total_nodes_1'].append(tn)
# peak nodes 1
p = data['b3_peak_nodes']['value'][-1]
measurements['peak_nodes_1'].append(p)
else:
print('Warning: no BDD manager 1')
def plot_multiple_experiments_vs_time(args):
n = args.min
m = args.max + 1
for i in xrange(n, m):
log_fname = 'details_{i}_masters.txt'.format(i=i)
fig_fname = 'details_{i}.pdf'.format(i=i)
plot_single_experiment_vs_time(log_fname, fig_fname)
def plot_single_experiment_vs_time(details_file, fig_file):
"""Plot BDD node changes during an experiment.
For each BDD manager:
- total nodes
- peak nodes
- reordering / total time
"""
data = utils.load_log_file(details_file)
# total time interval
t_min = min(v['time'][0] for v in data.itervalues())
t_max = max(v['time'][-1] for v in data.itervalues())
# subplot arrangement
n = 3
n_markers = 3
fig = plt.figure()
fig.set_size_inches(5, 10)
plt.clf()
plt.subplots_adjust(hspace=0.3)
ax = plt.subplot(n, 1, 1)
# total nodes
t, total_nodes = utils.get_signal('total_nodes', data)
t = t - t_min
plt.plot(t, total_nodes, 'b-', label='Total nodes (1)')
# peak nodes
t, peak_nodes = utils.get_signal('peak_nodes', data)
t = t - t_min
plt.plot(t, peak_nodes, 'b--', label='Peak nodes (1)')
# total nodes (other BDD)
t, total_nodes = utils.get_signal('b3_total_nodes', data)
t = t - t_min
plt.plot(t, total_nodes, 'r-o', label='Total nodes (2)',
markevery=max(int(len(t) / n_markers), 1))
# peak nodes (other BDD)
t, peak_nodes = utils.get_signal('b3_peak_nodes', data)
t = t - t_min
plt.plot(t, peak_nodes, 'r--o', label='Peak nodes (2)',
markevery=max(int(len(t) / n_markers), 1))
# annotate
ax.set_yscale('log')
plt.grid()
plt.xlabel('Time (sec)')
plt.ylabel('BDD nodes')
plt.legend(loc='upper left')
# uptime ratio
ax = plt.subplot(n, 1, 2)
t, reordering_time = utils.get_signal('reordering_time', data)
t = t - t_min
y = reordering_time / t
plt.plot(t, y, label='BDD 1')
# uptime ratio (other BDD)
ax = plt.subplot(n, 1, 2)
t, reordering_time = utils.get_signal('b3_reordering_time', data)
t_min_other = t[0]
t_other = t - t_min_other
y = reordering_time / t_other
t = t - t_min
plt.plot(t, y, 'r--', label='BDD 2')
# annotate
ax.set_yscale('log')
plt.grid()
plt.xlabel('Time (sec)')
plt.ylabel('Reordering / total time')
plt.legend(loc='upper left')
# save
plt.savefig(fig_file, bbox_inches='tight')
if __name__ == '__main__':
p = argparse.ArgumentParser()
p.add_argument('--compare', action='store_true',
help='plot comparison of two directories')
p.add_argument('--repickle', action='store_true',
help='ignore older pickled data')
p.add_argument('--ignore', action='store_true',
help='ignore older comparison PDF files')
args = p.parse_args()
if args.compare:
plot_comparison_report(args.ignore)
else:
plot_report(args.repickle)
|
/*
* car_model_propagator.hpp
*
* Created on: Oct 30, 2018 22:52
* Description:
*
* Copyright (c) 2018 Ruixiang Du (rdu)
*/
#ifndef CAR_MODEL_PROPAGATOR_HPP
#define CAR_MODEL_PROPAGATOR_HPP
#include <cstdint>
#include <vector>
#include <boost/numeric/odeint.hpp>
#include "reachability/details/car_longitudinal_model.hpp"
namespace robotnav {
class CarModelPropagator {
public:
CarLongitudinalModel::state_type Propagate(CarLongitudinalModel::state_type init_state,
CarLongitudinalModel::control_type u, double t0,
double tf, double dt) {
double t = t0;
CarLongitudinalModel::state_type x = init_state;
while (t <= tf) {
// integrator_(CarLongitudinalModel(u), x, t, dt);
boost::numeric::odeint::integrate_const(
boost::numeric::odeint::runge_kutta4<
CarLongitudinalModel::state_type>(),
CarLongitudinalModel(u), x, t, t+dt, dt/10.0);
// add additional constraint to s, v: s >= s0, v >=0, v < v_max
if (x[0] < init_state[0]) x[0] = init_state[0];
if (x[1] < 0) x[1] = 0;
if (x[1] > CarLongitudinalModel::v_max)
x[1] = CarLongitudinalModel::v_max;
}
return x;
}
};
} // namespace robotnav
#endif /* CAR_MODEL_PROPAGATOR_HPP */
|
/-
Copyright (c) 2020 Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kyle Miller
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.zmod.basic
import Mathlib.data.equiv.mul_add
import Mathlib.tactic.group
import Mathlib.PostPort
universes u l u_1 u_2 u_3
namespace Mathlib
/-!
# Racks and Quandles
This file defines racks and quandles, algebraic structures for sets
that bijectively act on themselves with a self-distributivity
property. If `R` is a rack and `act : R → (R ≃ R)` is the self-action,
then the self-distributivity is, equivalently, that
```
act (act x y) = act x * act y * (act x)⁻¹
```
where multiplication is composition in `R ≃ R` as a group.
Quandles are racks such that `act x x = x` for all `x`.
One example of a quandle (not yet in mathlib) is the action of a Lie
algebra on itself, defined by `act x y = Ad (exp x) y`.
Quandles and racks were independently developed by multiple
mathematicians. David Joyce introduced quandles in his thesis
[Joyce1982] to define an algebraic invariant of knot and link
complements that is analogous to the fundamental group of the
exterior, and he showed that the quandle associated to an oriented
knot is invariant up to orientation-reversed mirror image. Racks were
used by Fenn and Rourke for framed codimension-2 knots and
links.[FennRourke1992]
The name "rack" came from wordplay by Conway and Wraith for the "wrack
and ruin" of forgetting everything but the conjugation operation for a
group.
## Main definitions
* `shelf` is a type with a self-distributive action
* `rack` is a shelf whose action for each element is invertible
* `quandle` is a rack whose action for an element fixes that element
* `quandle.conj` defines a quandle of a group acting on itself by conjugation.
* `shelf_hom` is homomorphisms of shelves, racks, and quandles.
* `rack.envel_group` gives the universal group the rack maps to as a conjugation quandle.
* `rack.opp` gives the rack with the action replaced by its inverse.
## Main statements
* `rack.envel_group` is left adjoint to `quandle.conj` (`to_envel_group.map`).
The universality statements are `to_envel_group.univ` and `to_envel_group.univ_uniq`.
## Notation
The following notation is localized in `quandles`:
* `x ◃ y` is `shelf.act x y`
* `x ◃⁻¹ y` is `rack.inv_act x y`
* `S →◃ S'` is `shelf_hom S S'`
Use `open_locale quandles` to use these.
## Todo
* If g is the Lie algebra of a Lie group G, then (x ◃ y) = Ad (exp x) x forms a quandle
* If X is a symmetric space, then each point has a corresponding involution that acts on X, forming a quandle.
* Alexander quandle with `a ◃ b = t * b + (1 - t) * b`, with `a` and `b` elements of a module over Z[t,t⁻¹].
* If G is a group, H a subgroup, and z in H, then there is a quandle `(G/H;z)` defined by
`yH ◃ xH = yzy⁻¹xH`. Every homogeneous quandle (i.e., a quandle Q whose automorphism group acts
transitively on Q as a set) is isomorphic to such a quandle.
There is a generalization to this arbitrary quandles in [Joyce's paper (Theorem 7.2)][Joyce1982].
## Tags
rack, quandle
-/
/--
A *shelf* is a structure with a self-distributive binary operation.
The binary operation is regarded as a left action of the type on itself.
-/
class shelf (α : Type u)
where
act : α → α → α
self_distrib : ∀ {x y z : α}, act x (act y z) = act (act x y) (act x z)
/--
The type of homomorphisms between shelves.
This is also the notion of rack and quandle homomorphisms.
-/
structure shelf_hom (S₁ : Type u_1) (S₂ : Type u_2) [shelf S₁] [shelf S₂]
where
to_fun : S₁ → S₂
map_act' : ∀ {x y : S₁}, to_fun (shelf.act x y) = shelf.act (to_fun x) (to_fun y)
/--
A *rack* is an automorphic set (a set with an action on itself by
bijections) that is self-distributive. It is a shelf such that each
element's action is invertible.
The notations `x ◃ y` and `x ◃⁻¹ y` denote the action and the
inverse action, respectively, and they are right associative.
-/
class rack (α : Type u)
extends shelf α
where
inv_act : α → α → α
left_inv : ∀ (x : α), function.left_inverse (inv_act x) (shelf.act x)
right_inv : ∀ (x : α), function.right_inverse (inv_act x) (shelf.act x)
namespace rack
theorem self_distrib {R : Type u_1} [rack R] {x : R} {y : R} {z : R} : shelf.act x (shelf.act y z) = shelf.act (shelf.act x y) (shelf.act x z) :=
shelf.self_distrib
/--
A rack acts on itself by equivalences.
-/
def act {R : Type u_1} [rack R] (x : R) : R ≃ R :=
equiv.mk (shelf.act x) (inv_act x) (left_inv x) (right_inv x)
@[simp] theorem act_apply {R : Type u_1} [rack R] (x : R) (y : R) : coe_fn (act x) y = shelf.act x y :=
rfl
@[simp] theorem act_symm_apply {R : Type u_1} [rack R] (x : R) (y : R) : coe_fn (equiv.symm (act x)) y = inv_act x y :=
rfl
@[simp] theorem inv_act_apply {R : Type u_1} [rack R] (x : R) (y : R) : coe_fn (act x⁻¹) y = inv_act x y :=
rfl
@[simp] theorem inv_act_act_eq {R : Type u_1} [rack R] (x : R) (y : R) : inv_act x (shelf.act x y) = y :=
left_inv x y
@[simp] theorem act_inv_act_eq {R : Type u_1} [rack R] (x : R) (y : R) : shelf.act x (inv_act x y) = y :=
right_inv x y
theorem left_cancel {R : Type u_1} [rack R] (x : R) {y : R} {y' : R} : shelf.act x y = shelf.act x y' ↔ y = y' :=
{ mp := equiv.injective (act x), mpr := fun (ᾰ : y = y') => Eq._oldrec (Eq.refl (shelf.act x y)) ᾰ }
theorem left_cancel_inv {R : Type u_1} [rack R] (x : R) {y : R} {y' : R} : inv_act x y = inv_act x y' ↔ y = y' :=
{ mp := equiv.injective (equiv.symm (act x)), mpr := fun (ᾰ : y = y') => Eq._oldrec (Eq.refl (inv_act x y)) ᾰ }
theorem self_distrib_inv {R : Type u_1} [rack R] {x : R} {y : R} {z : R} : inv_act x (inv_act y z) = inv_act (inv_act x y) (inv_act x z) := sorry
/--
The *adjoint action* of a rack on itself is `op'`, and the adjoint
action of `x ◃ y` is the conjugate of the action of `y` by the action
of `x`. It is another way to understand the self-distributivity axiom.
This is used in the natural rack homomorphism `to_conj` from `R` to
`conj (R ≃ R)` defined by `op'`.
-/
theorem ad_conj {R : Type u_1} [rack R] (x : R) (y : R) : act (shelf.act x y) = act x * act y * (act x⁻¹) := sorry
/--
The opposite rack, swapping the roles of `◃` and `◃⁻¹`.
-/
protected instance opposite_rack {R : Type u_1} [rack R] : rack (Rᵒᵖ) :=
mk (fun (x y : Rᵒᵖ) => opposite.op (shelf.act (opposite.unop x) (opposite.unop y))) sorry sorry
@[simp] theorem op_act_op_eq {R : Type u_1} [rack R] {x : R} {y : R} : shelf.act (opposite.op x) (opposite.op y) = opposite.op (inv_act x y) :=
rfl
@[simp] theorem op_inv_act_op_eq {R : Type u_1} [rack R] {x : R} {y : R} : inv_act (opposite.op x) (opposite.op y) = opposite.op (shelf.act x y) :=
rfl
@[simp] theorem self_act_act_eq {R : Type u_1} [rack R] {x : R} {y : R} : shelf.act (shelf.act x x) y = shelf.act x y := sorry
@[simp] theorem self_inv_act_inv_act_eq {R : Type u_1} [rack R] {x : R} {y : R} : inv_act (inv_act x x) y = inv_act x y := sorry
@[simp] theorem self_act_inv_act_eq {R : Type u_1} [rack R] {x : R} {y : R} : inv_act (shelf.act x x) y = inv_act x y := sorry
@[simp] theorem self_inv_act_act_eq {R : Type u_1} [rack R] {x : R} {y : R} : shelf.act (inv_act x x) y = shelf.act x y := sorry
theorem self_act_eq_iff_eq {R : Type u_1} [rack R] {x : R} {y : R} : shelf.act x x = shelf.act y y ↔ x = y := sorry
theorem self_inv_act_eq_iff_eq {R : Type u_1} [rack R] {x : R} {y : R} : inv_act x x = inv_act y y ↔ x = y := sorry
/--
The map `x ↦ x ◃ x` is a bijection. (This has applications for the
regular isotopy version of the Reidemeister I move for knot diagrams.)
-/
def self_apply_equiv (R : Type u_1) [rack R] : R ≃ R :=
equiv.mk (fun (x : R) => shelf.act x x) (fun (x : R) => inv_act x x) sorry sorry
/--
An involutory rack is one for which `rack.op R x` is an involution for every x.
-/
def is_involutory (R : Type u_1) [rack R] :=
∀ (x : R), function.involutive (shelf.act x)
theorem involutory_inv_act_eq_act {R : Type u_1} [rack R] (h : is_involutory R) (x : R) (y : R) : inv_act x y = shelf.act x y :=
eq.mpr (id (Eq._oldrec (Eq.refl (inv_act x y = shelf.act x y)) (Eq.symm (propext (left_cancel x)))))
(eq.mpr (id (Eq._oldrec (Eq.refl (shelf.act x (inv_act x y) = shelf.act x (shelf.act x y))) (right_inv x y)))
(Eq.symm (function.involutive.left_inverse (h x) y)))
/--
An abelian rack is one for which the mediality axiom holds.
-/
def is_abelian (R : Type u_1) [rack R] :=
∀ (x y z w : R), shelf.act (shelf.act x y) (shelf.act z w) = shelf.act (shelf.act x z) (shelf.act y w)
/--
Associative racks are uninteresting.
-/
theorem assoc_iff_id {R : Type u_1} [rack R] {x : R} {y : R} {z : R} : shelf.act x (shelf.act y z) = shelf.act (shelf.act x y) z ↔ shelf.act x z = z := sorry
end rack
namespace shelf_hom
protected instance has_coe_to_fun {S₁ : Type u_1} {S₂ : Type u_2} [shelf S₁] [shelf S₂] : has_coe_to_fun (shelf_hom S₁ S₂) :=
has_coe_to_fun.mk (fun (x : shelf_hom S₁ S₂) => S₁ → S₂) to_fun
@[simp] theorem to_fun_eq_coe {S₁ : Type u_1} {S₂ : Type u_2} [shelf S₁] [shelf S₂] (f : shelf_hom S₁ S₂) : to_fun f = ⇑f :=
rfl
@[simp] theorem map_act {S₁ : Type u_1} {S₂ : Type u_2} [shelf S₁] [shelf S₂] (f : shelf_hom S₁ S₂) {x : S₁} {y : S₁} : coe_fn f (shelf.act x y) = shelf.act (coe_fn f x) (coe_fn f y) :=
map_act' f
/-- The identity homomorphism -/
def id (S : Type u_1) [shelf S] : shelf_hom S S :=
mk id sorry
protected instance inhabited (S : Type u_1) [shelf S] : Inhabited (shelf_hom S S) :=
{ default := id S }
/-- The composition of shelf homomorphisms -/
def comp {S₁ : Type u_1} {S₂ : Type u_2} {S₃ : Type u_3} [shelf S₁] [shelf S₂] [shelf S₃] (g : shelf_hom S₂ S₃) (f : shelf_hom S₁ S₂) : shelf_hom S₁ S₃ :=
mk (to_fun g ∘ to_fun f) sorry
@[simp] theorem comp_apply {S₁ : Type u_1} {S₂ : Type u_2} {S₃ : Type u_3} [shelf S₁] [shelf S₂] [shelf S₃] (g : shelf_hom S₂ S₃) (f : shelf_hom S₁ S₂) (x : S₁) : coe_fn (comp g f) x = coe_fn g (coe_fn f x) :=
rfl
end shelf_hom
/--
A quandle is a rack such that each automorphism fixes its corresponding element.
-/
class quandle (α : Type u_1)
extends rack α
where
fix : ∀ {x : α}, shelf.act x x = x
namespace quandle
@[simp] theorem fix_inv {Q : Type u_1} [quandle Q] {x : Q} : rack.inv_act x x = x := sorry
protected instance opposite_quandle {Q : Type u_1} [quandle Q] : quandle (Qᵒᵖ) :=
mk sorry
/--
The conjugation quandle of a group. Each element of the group acts by
the corresponding inner automorphism.
-/
def conj (G : Type u_1) :=
G
protected instance conj.quandle (G : Type u_1) [group G] : quandle (conj G) :=
mk sorry
@[simp] theorem conj_act_eq_conj {G : Type u_1} [group G] (x : conj G) (y : conj G) : shelf.act x y = x * y * (x⁻¹) :=
rfl
theorem conj_swap {G : Type u_1} [group G] (x : conj G) (y : conj G) : shelf.act x y = y ↔ shelf.act y x = x := sorry
/--
`conj` is functorial
-/
def conj.map {G : Type u_1} {H : Type u_2} [group G] [group H] (f : G →* H) : shelf_hom (conj G) (conj H) :=
shelf_hom.mk ⇑f sorry
protected instance shelf_hom.has_lift {G : Type u_1} {H : Type u_2} [group G] [group H] : has_lift (G →* H) (shelf_hom (conj G) (conj H)) :=
has_lift.mk conj.map
/--
The dihedral quandle. This is the conjugation quandle of the dihedral group restrict to flips.
Used for Fox n-colorings of knots.
-/
def dihedral (n : ℕ) :=
zmod n
/--
The operation for the dihedral quandle. It does not need to be an equivalence
because it is an involution (see `dihedral_act.inv`).
-/
def dihedral_act (n : ℕ) (a : zmod n) : zmod n → zmod n :=
fun (b : zmod n) => bit0 1 * a - b
theorem dihedral_act.inv (n : ℕ) (a : zmod n) : function.involutive (dihedral_act n a) := sorry
protected instance dihedral.quandle (n : ℕ) : quandle (dihedral n) :=
mk sorry
end quandle
namespace rack
/--
This is the natural rack homomorphism to the conjugation quandle of the group `R ≃ R`
that acts on the rack.
-/
def to_conj (R : Type u_1) [rack R] : shelf_hom R (quandle.conj (R ≃ R)) :=
shelf_hom.mk act ad_conj
/-!
### Universal enveloping group of a rack
The universal enveloping group `envel_group R` of a rack `R` is the
universal group such that every rack homomorphism `R →◃ conj G` is
induced by a unique group homomorphism `envel_group R →* G`.
For quandles, Joyce called this group `AdConj R`.
The `envel_group` functor is left adjoint to the `conj` forgetful
functor, and the way we construct the enveloping group is via a
technique that should work for left adjoints of forgetful functors in
general. It involves thinking a little about 2-categories, but the
payoff is that the map `envel_group R →* G` has a nice description.
Let's think of a group as being a one-object category. The first step
is to define `pre_envel_group`, which gives formal expressions for all
the 1-morphisms and includes the unit element, elements of `R`,
multiplication, and inverses. To introduce relations, the second step
is to define `pre_envel_group_rel'`, which gives formal expressions
for all 2-morphisms between the 1-morphisms. The 2-morphisms include
associativity, multiplication by the unit, multiplication by inverses,
compatibility with multiplication and inverses (`congr_mul` and
`congr_inv`), the axioms for an equivalence relation, and,
importantly, the relationship between conjugation and the rack action
(see `rack.ad_conj`).
None of this forms a 2-category yet, for example due to lack of
associativity of `trans`. The `pre_envel_group_rel` relation is a
`Prop`-valued version of `pre_envel_group_rel'`, and making it
`Prop`-valued essentially introduces enough 3-isomorphisms so that
every pair of compatible 2-morphisms is isomorphic. Now, while
composition in `pre_envel_group` does not strictly satisfy the category
axioms, `pre_envel_group` and `pre_envel_group_rel'` do form a weak
2-category.
Since we just want a 1-category, the last step is to quotient
`pre_envel_group` by `pre_envel_group_rel'`, and the result is the
group `envel_group`.
For a homomorphism `f : R →◃ conj G`, how does
`envel_group.map f : envel_group R →* G` work? Let's think of `G` as
being a 2-category with one object, a 1-morphism per element of `G`,
and a single 2-morphism called `eq.refl` for each 1-morphism. We
define the map using a "higher `quotient.lift`" -- not only do we
evaluate elements of `pre_envel_group` as expressions in `G` (this is
`to_envel_group.map_aux`), but we evaluate elements of
`pre_envel_group'` as expressions of 2-morphisms of `G` (this is
`to_envel_group.map_aux.well_def`). That is to say,
`to_envel_group.map_aux.well_def` recursively evaluates formal
expressions of 2-morphisms as equality proofs in `G`. Now that all
morphisms are accounted for, the map descends to a homomorphism
`envel_group R →* G`.
Note: `Type`-valued relations are not common. The fact it is
`Type`-valued is what makes `to_envel_group.map_aux.well_def` have
well-founded recursion.
-/
/--
Free generators of the enveloping group.
-/
inductive pre_envel_group (R : Type u)
where
| unit : pre_envel_group R
| incl : R → pre_envel_group R
| mul : pre_envel_group R → pre_envel_group R → pre_envel_group R
| inv : pre_envel_group R → pre_envel_group R
protected instance pre_envel_group.inhabited (R : Type u) : Inhabited (pre_envel_group R) :=
{ default := pre_envel_group.unit }
/--
Relations for the enveloping group. This is a type-valued relation because
`to_envel_group.map_aux.well_def` inducts on it to show `to_envel_group.map`
is well-defined. The relation `pre_envel_group_rel` is the `Prop`-valued version,
which is used to define `envel_group` itself.
-/
inductive pre_envel_group_rel' (R : Type u) [rack R] : pre_envel_group R → pre_envel_group R → Type u
where
| refl : {a : pre_envel_group R} → pre_envel_group_rel' R a a
| symm : {a b : pre_envel_group R} → pre_envel_group_rel' R a b → pre_envel_group_rel' R b a
| trans : {a b c : pre_envel_group R} → pre_envel_group_rel' R a b → pre_envel_group_rel' R b c → pre_envel_group_rel' R a c
| congr_mul : {a b a' b' : pre_envel_group R} →
pre_envel_group_rel' R a a' →
pre_envel_group_rel' R b b' → pre_envel_group_rel' R (pre_envel_group.mul a b) (pre_envel_group.mul a' b')
| congr_inv : {a a' : pre_envel_group R} →
pre_envel_group_rel' R a a' → pre_envel_group_rel' R (pre_envel_group.inv a) (pre_envel_group.inv a')
| assoc : (a b c : pre_envel_group R) →
pre_envel_group_rel' R (pre_envel_group.mul (pre_envel_group.mul a b) c)
(pre_envel_group.mul a (pre_envel_group.mul b c))
| one_mul : (a : pre_envel_group R) → pre_envel_group_rel' R (pre_envel_group.mul pre_envel_group.unit a) a
| mul_one : (a : pre_envel_group R) → pre_envel_group_rel' R (pre_envel_group.mul a pre_envel_group.unit) a
| mul_left_inv : (a : pre_envel_group R) → pre_envel_group_rel' R (pre_envel_group.mul (pre_envel_group.inv a) a) pre_envel_group.unit
| act_incl : (x y : R) →
pre_envel_group_rel' R
(pre_envel_group.mul (pre_envel_group.mul (pre_envel_group.incl x) (pre_envel_group.incl y))
(pre_envel_group.inv (pre_envel_group.incl x)))
(pre_envel_group.incl (shelf.act x y))
protected instance pre_envel_group_rel'.inhabited (R : Type u) [rack R] : Inhabited (pre_envel_group_rel' R pre_envel_group.unit pre_envel_group.unit) :=
{ default := pre_envel_group_rel'.refl }
/--
The `pre_envel_group_rel` relation as a `Prop`. Used as the relation for `pre_envel_group.setoid`.
-/
inductive pre_envel_group_rel (R : Type u) [rack R] : pre_envel_group R → pre_envel_group R → Prop
where
| rel : ∀ {a b : pre_envel_group R}, pre_envel_group_rel' R a b → pre_envel_group_rel R a b
/--
A quick way to convert a `pre_envel_group_rel'` to a `pre_envel_group_rel`.
-/
theorem pre_envel_group_rel'.rel {R : Type u} [rack R] {a : pre_envel_group R} {b : pre_envel_group R} : pre_envel_group_rel' R a b → pre_envel_group_rel R a b :=
pre_envel_group_rel.rel
theorem pre_envel_group_rel.refl {R : Type u} [rack R] {a : pre_envel_group R} : pre_envel_group_rel R a a :=
pre_envel_group_rel.rel pre_envel_group_rel'.refl
theorem pre_envel_group_rel.symm {R : Type u} [rack R] {a : pre_envel_group R} {b : pre_envel_group R} : pre_envel_group_rel R a b → pre_envel_group_rel R b a := sorry
theorem pre_envel_group_rel.trans {R : Type u} [rack R] {a : pre_envel_group R} {b : pre_envel_group R} {c : pre_envel_group R} : pre_envel_group_rel R a b → pre_envel_group_rel R b c → pre_envel_group_rel R a c := sorry
protected instance pre_envel_group.setoid (R : Type u_1) [rack R] : setoid (pre_envel_group R) :=
setoid.mk (pre_envel_group_rel R) sorry
/--
The universal enveloping group for the rack R.
-/
def envel_group (R : Type u_1) [rack R] :=
quotient (pre_envel_group.setoid R)
-- Define the `group` instances in two steps so `inv` can be inferred correctly.
-- TODO: is there a non-invasive way of defining the instance directly?
protected instance envel_group.div_inv_monoid (R : Type u_1) [rack R] : div_inv_monoid (envel_group R) :=
div_inv_monoid.mk
(fun (a b : envel_group R) =>
quotient.lift_on₂ a b (fun (a b : pre_envel_group R) => quotient.mk (pre_envel_group.mul a b)) sorry)
sorry (quotient.mk pre_envel_group.unit) sorry sorry
(fun (a : envel_group R) =>
quotient.lift_on a (fun (a : pre_envel_group R) => quotient.mk (pre_envel_group.inv a)) sorry)
fun (a b : envel_group R) =>
quotient.lift_on₂ a (quotient.lift_on b (fun (a : pre_envel_group R) => quotient.mk (pre_envel_group.inv a)) sorry)
(fun (a b : pre_envel_group R) => quotient.mk (pre_envel_group.mul a b)) sorry
protected instance envel_group.group (R : Type u_1) [rack R] : group (envel_group R) :=
group.mk div_inv_monoid.mul sorry div_inv_monoid.one sorry sorry div_inv_monoid.inv div_inv_monoid.div sorry
protected instance envel_group.inhabited (R : Type u_1) [rack R] : Inhabited (envel_group R) :=
{ default := 1 }
/--
The canonical homomorphism from a rack to its enveloping group.
Satisfies universal properties given by `to_envel_group.map` and `to_envel_group.univ`.
-/
def to_envel_group (R : Type u_1) [rack R] : shelf_hom R (quandle.conj (envel_group R)) :=
shelf_hom.mk (fun (x : R) => quotient.mk (pre_envel_group.incl x)) sorry
/--
The preliminary definition of the induced map from the enveloping group.
See `to_envel_group.map`.
-/
def to_envel_group.map_aux {R : Type u_1} [rack R] {G : Type u_2} [group G] (f : shelf_hom R (quandle.conj G)) : pre_envel_group R → G :=
sorry
namespace to_envel_group.map_aux
/--
Show that `to_envel_group.map_aux` sends equivalent expressions to equal terms.
-/
theorem well_def {R : Type u_1} [rack R] {G : Type u_2} [group G] (f : shelf_hom R (quandle.conj G)) {a : pre_envel_group R} {b : pre_envel_group R} : pre_envel_group_rel' R a b → map_aux f a = map_aux f b := sorry
end to_envel_group.map_aux
/--
Given a map from a rack to a group, lift it to being a map from the enveloping group.
More precisely, the `envel_group` functor is left adjoint to `quandle.conj`.
-/
def to_envel_group.map {R : Type u_1} [rack R] {G : Type u_2} [group G] : shelf_hom R (quandle.conj G) ≃ (envel_group R →* G) :=
equiv.mk
(fun (f : shelf_hom R (quandle.conj G)) =>
monoid_hom.mk (fun (x : envel_group R) => quotient.lift_on x (to_envel_group.map_aux f) sorry) sorry sorry)
(fun (F : envel_group R →* G) => shelf_hom.comp (quandle.conj.map F) (to_envel_group R)) sorry sorry
/--
Given a homomorphism from a rack to a group, it factors through the enveloping group.
-/
theorem to_envel_group.univ (R : Type u_1) [rack R] (G : Type u_2) [group G] (f : shelf_hom R (quandle.conj G)) : shelf_hom.comp (quandle.conj.map (coe_fn to_envel_group.map f)) (to_envel_group R) = f :=
equiv.symm_apply_apply to_envel_group.map f
/--
The homomorphism `to_envel_group.map f` is the unique map that fits into the commutative
triangle in `to_envel_group.univ`.
-/
theorem to_envel_group.univ_uniq (R : Type u_1) [rack R] (G : Type u_2) [group G] (f : shelf_hom R (quandle.conj G)) (g : envel_group R →* G) (h : f = shelf_hom.comp (quandle.conj.map g) (to_envel_group R)) : g = coe_fn to_envel_group.map f :=
Eq.symm h ▸ Eq.symm (equiv.apply_symm_apply to_envel_group.map g)
/--
The induced group homomorphism from the enveloping group into bijections of the rack,
using `rack.to_conj`. Satisfies the property `envel_action_prop`.
This gives the rack `R` the structure of an augmented rack over `envel_group R`.
-/
def envel_action {R : Type u_1} [rack R] : envel_group R →* R ≃ R :=
coe_fn to_envel_group.map (to_conj R)
@[simp] theorem envel_action_prop {R : Type u_1} [rack R] (x : R) (y : R) : coe_fn (coe_fn envel_action (coe_fn (to_envel_group R) x)) y = shelf.act x y :=
rfl
|
% This is the testing demo of FFDNet for denoising noisy grayscale images corrupted by
% AWGN.
%
% To run the code, you should install Matconvnet first. Alternatively, you can use the
% function `vl_ffdnet_matlab` to perform denoising without Matconvnet.
%
% "FFDNet: Toward a Fast and Flexible Solution for CNN based Image Denoising"
% 2018/03/23
% If you have any question, please feel free to contact with me.
% Kai Zhang (e-mail: [email protected])
%clear; clc;
format compact;
global sigmas; % input noise level or input noise level map
addpath(fullfile('utilities'));
folderModel = 'models';
folderTest = 'H:\matlabH';
folderResult= 'results';
imageSets = {'BSD68','Set12'}; % testing datasets
setTestCur = imageSets{1}; % current testing dataset
showResult = 1;
useGPU = 1; % CPU or GPU. For single-threaded (ST) CPU computation, use "matlab -singleCompThread" to start matlab.
pauseTime = 0;
imageNoiseSigma = 25; % image noise level
inputNoiseSigma = 25; % input noise level
folderResultCur = fullfile(folderResult, [setTestCur,'_',num2str(imageNoiseSigma),'_',num2str(inputNoiseSigma)]);
if ~isdir(folderResultCur)
mkdir(folderResultCur)
end
load(fullfile('data','FFDNet_gray','FFDNet_gray-epoch-1.mat'));
net.layers = net.layers(1:end-1);
net = vl_simplenn_tidy(net);
% for i = 1:size(net.layers,2)
% net.layers{i}.precious = 1;
% end
if useGPU
net = vl_simplenn_move(net, 'gpu') ;
end
% read images
ext = {'*.jpg','*.png','*.bmp'};
filePaths = [];
for i = 1 : length(ext)
filePaths = cat(1,filePaths, dir(fullfile(folderTest,setTestCur,ext{i})));
end
% PSNR and SSIM
PSNRs = zeros(1,length(filePaths));
SSIMs = zeros(1,length(filePaths));
for i = 1:length(filePaths)
% read images
label = imread(fullfile(folderTest,setTestCur,filePaths(i).name));
[w,h,~]=size(label);
if size(label,3)==3
label = rgb2gray(label);
end
[~,nameCur,extCur] = fileparts(filePaths(i).name);
label = im2double(label);
% add noise
randn('seed',0);
noise = imageNoiseSigma/255.*randn(size(label));
input = single(label + noise);
if mod(w,2)==1
input = cat(1,input, input(end,:)) ;
end
if mod(h,2)==1
input = cat(2,input, input(:,end)) ;
end
% tic;
if useGPU
input = gpuArray(input);
end
% set noise level map
sigmas = inputNoiseSigma/255; % see "vl_simplenn.m".
% perform denoising
res = vl_simplenn(net,input,[],[],'conserveMemory',true,'mode','test'); % matconvnet default
% res = vl_ffdnet_concise(net, input); % concise version of vl_simplenn for testing FFDNet
% res = vl_ffdnet_matlab(net, input); % use this if you did not install matconvnet; very slow
% output = input - res(end).x; % for 'model_gray.mat'
output = res(end).x;
if mod(w,2)==1
output = output(1:end-1,:);
input = input(1:end-1,:);
end
if mod(h,2)==1
output = output(:,1:end-1);
input = input(:,1:end-1);
end
if useGPU
output = gather(output);
input = gather(input);
end
% toc;
% calculate PSNR, SSIM and save results
[PSNRCur, SSIMCur] = Cal_PSNRSSIM(im2uint8(label),im2uint8(output),0,0);
if showResult
imshow(cat(2,im2uint8(input),im2uint8(label),im2uint8(output)));
title([filePaths(i).name,' ',num2str(PSNRCur,'%2.2f'),'dB',' ',num2str(SSIMCur,'%2.4f')])
%imwrite(im2uint8(output), fullfile(folderResultCur, [nameCur, '_' num2str(imageNoiseSigma,'%02d'),'_' num2str(inputNoiseSigma,'%02d'),'_PSNR_',num2str(PSNRCur*100,'%4.0f'), extCur] ));
drawnow;
pause(pauseTime)
end
disp([filePaths(i).name,' ',num2str(PSNRCur,'%2.2f'),'dB',' ',num2str(SSIMCur,'%2.4f')])
PSNRs(i) = PSNRCur;
SSIMs(i) = SSIMCur;
end
disp([mean(PSNRs),mean(SSIMs)]);
|
import quapy as qp
import numpy as np
from sklearn.metrics import f1_score
def from_name(err_name):
"""Gets an error function from its name. E.g., `from_name("mae")` will return function :meth:`quapy.error.mae`
:param err_name: string, the error name
:return: a callable implementing the requested error
"""
assert err_name in ERROR_NAMES, f'unknown error {err_name}'
callable_error = globals()[err_name]
if err_name in QUANTIFICATION_ERROR_SMOOTH_NAMES:
eps = __check_eps()
def bound_callable_error(y_true, y_pred):
return callable_error(y_true, y_pred, eps)
return bound_callable_error
return callable_error
def f1e(y_true, y_pred):
"""F1 error: simply computes the error in terms of macro :math:`F_1`, i.e., :math:`1-F_1^M`,
where :math:`F_1` is the harmonic mean of precision and recall, defined as :math:`\\frac{2tp}{2tp+fp+fn}`,
with `tp`, `fp`, and `fn` standing for true positives, false positives, and false negatives, respectively.
`Macro` averaging means the :math:`F_1` is computed for each category independently, and then averaged.
:param y_true: array-like of true labels
:param y_pred: array-like of predicted labels
:return: :math:`1-F_1^M`
"""
return 1. - f1_score(y_true, y_pred, average='macro')
def acce(y_true, y_pred):
"""Computes the error in terms of 1-accuracy. The accuracy is computed as :math:`\\frac{tp+tn}{tp+fp+fn+tn}`, with
`tp`, `fp`, `fn`, and `tn` standing for true positives, false positives, false negatives, and true negatives,
respectively
:param y_true: array-like of true labels
:param y_pred: array-like of predicted labels
:return: 1-accuracy
"""
return 1. - (y_true == y_pred).mean()
def mae(prevs, prevs_hat):
"""Computes the mean absolute error (see :meth:`quapy.error.ae`) across the sample pairs.
:param prevs: array-like of shape `(n_samples, n_classes,)` with the true prevalence values
:param prevs_hat: array-like of shape `(n_samples, n_classes,)` with the predicted prevalence values
:return: mean absolute error
"""
return ae(prevs, prevs_hat).mean()
def ae(prevs, prevs_hat):
"""Computes the absolute error between the two prevalence vectors.
Absolute error between two prevalence vectors :math:`p` and :math:`\\hat{p}` is computed as
:math:`AE(p,\\hat{p})=\\frac{1}{|\\mathcal{Y}|}\\sum_{y\in \mathcal{Y}}|\\hat{p}(y)-p(y)|`,
where :math:`\\mathcal{Y}` are the classes of interest.
:param prevs: array-like of shape `(n_classes,)` with the true prevalence values
:param prevs_hat: array-like of shape `(n_classes,)` with the predicted prevalence values
:return: absolute error
"""
assert prevs.shape == prevs_hat.shape, f'wrong shape {prevs.shape} vs. {prevs_hat.shape}'
return abs(prevs_hat - prevs).mean(axis=-1)
def mse(prevs, prevs_hat):
"""Computes the mean squared error (see :meth:`quapy.error.se`) across the sample pairs.
:param prevs: array-like of shape `(n_samples, n_classes,)` with the true prevalence values
:param prevs_hat: array-like of shape `(n_samples, n_classes,)` with the predicted prevalence values
:return: mean squared error
"""
return se(prevs, prevs_hat).mean()
def se(p, p_hat):
"""Computes the squared error between the two prevalence vectors.
Squared error between two prevalence vectors :math:`p` and :math:`\\hat{p}` is computed as
:math:`SE(p,\\hat{p})=\\frac{1}{|\\mathcal{Y}|}\\sum_{y\in \mathcal{Y}}(\\hat{p}(y)-p(y))^2`, where
:math:`\\mathcal{Y}` are the classes of interest.
:param prevs: array-like of shape `(n_classes,)` with the true prevalence values
:param prevs_hat: array-like of shape `(n_classes,)` with the predicted prevalence values
:return: absolute error
"""
return ((p_hat-p)**2).mean(axis=-1)
def mkld(prevs, prevs_hat, eps=None):
"""Computes the mean Kullback-Leibler divergence (see :meth:`quapy.error.kld`) across the sample pairs.
The distributions are smoothed using the `eps` factor (see :meth:`quapy.error.smooth`).
:param prevs: array-like of shape `(n_samples, n_classes,)` with the true prevalence values
:param prevs_hat: array-like of shape `(n_samples, n_classes,)` with the predicted prevalence values
:param eps: smoothing factor. KLD is not defined in cases in which the distributions contain zeros; `eps`
is typically set to be :math:`\\frac{1}{2T}`, with :math:`T` the sample size. If `eps=None`, the sample size
will be taken from the environment variable `SAMPLE_SIZE` (which has thus to be set beforehand).
:return: mean Kullback-Leibler distribution
"""
return kld(prevs, prevs_hat, eps).mean()
def kld(p, p_hat, eps=None):
"""Computes the Kullback-Leibler divergence between the two prevalence distributions.
Kullback-Leibler divergence between two prevalence distributions :math:`p` and :math:`\\hat{p}` is computed as
:math:`KLD(p,\\hat{p})=D_{KL}(p||\\hat{p})=\\sum_{y\\in \\mathcal{Y}} p(y)\\log\\frac{p(y)}{\\hat{p}(y)}`, where
:math:`\\mathcal{Y}` are the classes of interest.
The distributions are smoothed using the `eps` factor (see :meth:`quapy.error.smooth`).
:param prevs: array-like of shape `(n_classes,)` with the true prevalence values
:param prevs_hat: array-like of shape `(n_classes,)` with the predicted prevalence values
:param eps: smoothing factor. KLD is not defined in cases in which the distributions contain zeros; `eps`
is typically set to be :math:`\\frac{1}{2T}`, with :math:`T` the sample size. If `eps=None`, the sample size
will be taken from the environment variable `SAMPLE_SIZE` (which has thus to be set beforehand).
:return: Kullback-Leibler divergence between the two distributions
"""
eps = __check_eps(eps)
sp = p+eps
sp_hat = p_hat + eps
return (sp*np.log(sp/sp_hat)).sum(axis=-1)
def mnkld(prevs, prevs_hat, eps=None):
"""Computes the mean Normalized Kullback-Leibler divergence (see :meth:`quapy.error.nkld`) across the sample pairs.
The distributions are smoothed using the `eps` factor (see :meth:`quapy.error.smooth`).
:param prevs: array-like of shape `(n_samples, n_classes,)` with the true prevalence values
:param prevs_hat: array-like of shape `(n_samples, n_classes,)` with the predicted prevalence values
:param eps: smoothing factor. NKLD is not defined in cases in which the distributions contain zeros; `eps`
is typically set to be :math:`\\frac{1}{2T}`, with :math:`T` the sample size. If `eps=None`, the sample size
will be taken from the environment variable `SAMPLE_SIZE` (which has thus to be set beforehand).
:return: mean Normalized Kullback-Leibler distribution
"""
return nkld(prevs, prevs_hat, eps).mean()
def nkld(p, p_hat, eps=None):
"""Computes the Normalized Kullback-Leibler divergence between the two prevalence distributions.
Normalized Kullback-Leibler divergence between two prevalence distributions :math:`p` and :math:`\\hat{p}`
is computed as :math:`NKLD(p,\\hat{p}) = 2\\frac{e^{KLD(p,\\hat{p})}}{e^{KLD(p,\\hat{p})}+1}-1`, where
:math:`\\mathcal{Y}` are the classes of interest.
The distributions are smoothed using the `eps` factor (see :meth:`quapy.error.smooth`).
:param prevs: array-like of shape `(n_classes,)` with the true prevalence values
:param prevs_hat: array-like of shape `(n_classes,)` with the predicted prevalence values
:param eps: smoothing factor. NKLD is not defined in cases in which the distributions contain zeros; `eps`
is typically set to be :math:`\\frac{1}{2T}`, with :math:`T` the sample size. If `eps=None`, the sample size
will be taken from the environment variable `SAMPLE_SIZE` (which has thus to be set beforehand).
:return: Normalized Kullback-Leibler divergence between the two distributions
"""
ekld = np.exp(kld(p, p_hat, eps))
return 2. * ekld / (1 + ekld) - 1.
def mrae(p, p_hat, eps=None):
"""Computes the mean relative absolute error (see :meth:`quapy.error.rae`) across the sample pairs.
The distributions are smoothed using the `eps` factor (see :meth:`quapy.error.smooth`).
:param prevs: array-like of shape `(n_samples, n_classes,)` with the true prevalence values
:param prevs_hat: array-like of shape `(n_samples, n_classes,)` with the predicted prevalence values
:param eps: smoothing factor. `mrae` is not defined in cases in which the true distribution contains zeros; `eps`
is typically set to be :math:`\\frac{1}{2T}`, with :math:`T` the sample size. If `eps=None`, the sample size
will be taken from the environment variable `SAMPLE_SIZE` (which has thus to be set beforehand).
:return: mean relative absolute error
"""
return rae(p, p_hat, eps).mean()
def rae(p, p_hat, eps=None):
"""Computes the absolute relative error between the two prevalence vectors.
Relative absolute error between two prevalence vectors :math:`p` and :math:`\\hat{p}` is computed as
:math:`RAE(p,\\hat{p})=\\frac{1}{|\\mathcal{Y}|}\\sum_{y\in \mathcal{Y}}\\frac{|\\hat{p}(y)-p(y)|}{p(y)}`,
where :math:`\\mathcal{Y}` are the classes of interest.
The distributions are smoothed using the `eps` factor (see :meth:`quapy.error.smooth`).
:param prevs: array-like of shape `(n_classes,)` with the true prevalence values
:param prevs_hat: array-like of shape `(n_classes,)` with the predicted prevalence values
:param eps: smoothing factor. `rae` is not defined in cases in which the true distribution contains zeros; `eps`
is typically set to be :math:`\\frac{1}{2T}`, with :math:`T` the sample size. If `eps=None`, the sample size
will be taken from the environment variable `SAMPLE_SIZE` (which has thus to be set beforehand).
:return: relative absolute error
"""
eps = __check_eps(eps)
p = smooth(p, eps)
p_hat = smooth(p_hat, eps)
return (abs(p-p_hat)/p).mean(axis=-1)
def smooth(prevs, eps):
""" Smooths a prevalence distribution with :math:`\epsilon` (`eps`) as:
:math:`\\underline{p}(y)=\\frac{\\epsilon+p(y)}{\\epsilon|\\mathcal{Y}|+\\displaystyle\\sum_{y\\in \\mathcal{Y}}p(y)}`
:param prevs: array-like of shape `(n_classes,)` with the true prevalence values
:param eps: smoothing factor
:return: array-like of shape `(n_classes,)` with the smoothed distribution
"""
n_classes = prevs.shape[-1]
return (prevs + eps) / (eps * n_classes + 1)
def __check_eps(eps=None):
if eps is None:
import quapy as qp
sample_size = qp.environ['SAMPLE_SIZE']
if sample_size is None:
raise ValueError('eps was not defined, and qp.environ["SAMPLE_SIZE"] was not set')
else:
eps = 1. / (2. * sample_size)
return eps
CLASSIFICATION_ERROR = {f1e, acce}
QUANTIFICATION_ERROR = {mae, mrae, mse, mkld, mnkld}
QUANTIFICATION_ERROR_SMOOTH = {kld, nkld, rae, mkld, mnkld, mrae}
CLASSIFICATION_ERROR_NAMES = {func.__name__ for func in CLASSIFICATION_ERROR}
QUANTIFICATION_ERROR_NAMES = {func.__name__ for func in QUANTIFICATION_ERROR}
QUANTIFICATION_ERROR_SMOOTH_NAMES = {func.__name__ for func in QUANTIFICATION_ERROR_SMOOTH}
ERROR_NAMES = CLASSIFICATION_ERROR_NAMES | QUANTIFICATION_ERROR_NAMES
f1_error = f1e
acc_error = acce
mean_absolute_error = mae
absolute_error = ae
mean_relative_absolute_error = mrae
relative_absolute_error = rae
|
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 sepcomp. Import SepComp.
Require Import arguments.
Require Import jstep.
Require Import pred_lemmas.
Require Import rc_semantics.
Require Import 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.
|
import data.real.basic
import data.polynomial.derivative
import linear_algebra.basic
import linear_algebra.finite_dimensional
-- On se place dans le R -espace vectoriel E = R[X] .
-- (a) Soit H un sous-espace vectoriel de dimension finie et f un endomorphisme de H. Montrer qu'il existe p ∈ N tel que
-- ∀k ≥ p, Ker f k+1 = Ker f k.
--
-- Soit F un sous-espace vectoriel de E stable par l'opérateur D de dérivation.
-- (b) On suppose que F est de dimension finie non nulle. Montrer que l'endomorphisme induit par D sur R n [X] est nilpotent pour tout n ∈ N .
-- Montrer qu'il existe m ∈ N tel que F = R m [X] .
-- (c) Montrer que si F est de dimension innie alors F = R[X] .
-- (d) Soit g ∈ L(E) tel que g^2 = kId + D avec k ∈ R . Quel est le signe de k ?
variable F: submodule real (polynomial real)
variable HF: forall p: polynomial real, p ∈ F.carrier -> polynomial.derivative p ∈ F.carrier
theorem b (_: finite_dimensional real F):
exists k >= 0, (linear_map.restrict polynomial.derivative HF)^ k = 0
:=
sorry
|
////////////////////////////////////////////////////////////////////////////////
// distribution::survival::response::right_truncated::meta_factory.hpp //
// //
// Copyright 2009 Erwann Rogard. Distributed under the Boost //
// Software License, Version 1.0. (See accompanying file //
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) //
////////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_RESPONSE_RIGHT_TRUNCATED_META_MAKE_RESPONSE_HPP_ER_2009
#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_RESPONSE_RIGHT_TRUNCATED_META_MAKE_RESPONSE_HPP_ER_2009
#include <boost/mpl/identity.hpp>
#include <boost/statistics/detail/distribution/survival/response/common/meta_factory.hpp>
#include <boost/statistics/detail/distribution/survival/response/types/right_truncated/event_factory.hpp>
namespace boost {
namespace statistics{
namespace detail{
namespace distribution{
namespace survival {
namespace response {
namespace meta{
template<typename T,typename B>
struct factory< event<T,B> > : boost::mpl::identity< event_factory<T,B> >{};
}// meta
}// response
}// survival
}// distribution
}// detail
}// statistics
}// boost
#endif
|
function psodemo(DemoMode)
% Runs the PSO on a few demonstration functions, which should be located
% in the <./testfcns> directory.
%
% For less intensive 3D graphics, run with input argument 'fast', viz.:
% >> psodemo('fast')
%
% S. Chen, Dec 2009.
% Available as part of "Another Particle Swarm Toolbox" at:
% http://www.mathworks.com/matlabcentral/fileexchange/25986
% Distributed under BSD license.
workingdir = pwd ;
testdir = ls('testf*') ;
if ~isempty(testdir), cd(testdir), end
[testfcn,testdir] = uigetfile('*.m','Load demo function for PSO') ;
if ~testfcn
cd(workingdir)
return
elseif isempty(regexp(testfcn,'\.m(?!.)','once'))
error('Test function must be m-file')
else
cd(testdir)
end
fitnessfcn = str2func(testfcn(1:regexp(testfcn,'\.m(?!.)')-1)) ;
cd(workingdir)
options = fitnessfcn('init') ;
if any(isfield(options,{'options','Aineq','Aeq','LB','nonlcon'}))
% Then the test function gave us a (partial) problem structure.
problem = options ;
else
% Aineq = [1 1] ; bineq = [1.2] ; % Test case for linear constraint
problem.options = options ;
problem.Aineq = [] ; problem.bineq = [] ;
problem.Aeq = [] ; problem.beq = [] ;
problem.LB = [] ; problem.UB = [] ;
problem.nonlcon = [] ;
end
problem.fitnessfcn = fitnessfcn ;
problem.nvars = 2 ;
if ~nargin
problem.options.DemoMode = 'pretty' ;
else
problem.options.DemoMode = DemoMode ;
end
problem.options.PlotFcns = {@psoplotbestf,@psoplotswarmsurf} ;
% problem.options.VelocityLimit = 0.2 ;
if isfield(problem.options,'PopulationType') && ...
~strcmp(problem.options.PopulationType,'bitstring')
problem.options.HybridFcn = @fmincon ;
end
% problem.options.Display = 'off' ;
if isfield(problem.options,'UseParallel') && ...
strcmp(problem.options.UseParallel,'always')
poolopen = false ;
if ~matlabpool('size')
matlabpool('open','AttachedFiles',{[pwd '\testfcns']}) ;
else
poolopen = true ;
pctRunOnAll addpath([pwd '\testfcns']) ;
end
end
pso(problem)
if isfield(problem.options,'UseParallel') && ...
strcmp(problem.options.UseParallel,'always') && ~poolopen
matlabpool('close');
end
|
" Being a good example " to their children .
|
{-# LANGUAGE ScopedTypeVariables, BangPatterns, RecordWildCards #-}
{-| Functions used internally by the SDR.Filter module. Most of these are
not actually used but exist for benchmarking purposes to determine the
fastest filter implementation.
-}
module SDR.FilterInternal where
import Control.Monad.Primitive
import Control.Monad
import Foreign.C.Types
import Foreign.Ptr
import Data.Coerce
import Data.Complex
import Foreign.Marshal.Array
import Foreign.Marshal.Alloc
import Foreign.Storable
import qualified Data.Vector.Generic as VG
import qualified Data.Vector.Generic.Mutable as VGM
import qualified Data.Vector.Storable as VS
import qualified Data.Vector.Storable.Mutable as VSM
import qualified Data.Vector.Fusion.Bundle as VFB
import SDR.VectorUtils
import SDR.Util
{-# INLINE filterHighLevel #-}
filterHighLevel :: (PrimMonad m, Functor m, Num a, Mult a b, VG.Vector v a, VG.Vector v b, VGM.MVector vm a) => v b -> Int -> v a -> vm (PrimState m) a -> m ()
filterHighLevel coeffs num inBuf outBuf = fill (VFB.generate num dotProd) outBuf
where
dotProd offset = VG.sum $ VG.zipWith mult (VG.unsafeDrop offset inBuf) coeffs
{-# INLINE filterImperative1 #-}
filterImperative1 :: (PrimMonad m, Functor m, Num a, Mult a b, VG.Vector v a, VG.Vector v b, VGM.MVector vm a) => v b -> Int -> v a -> vm (PrimState m) a -> m ()
filterImperative1 coeffs num inBuf outBuf = go 0
where
go offset
| offset < num = do
let res = dotProd offset
VGM.unsafeWrite outBuf offset res
go $ offset + 1
| otherwise = return ()
dotProd offset = VG.sum $ VG.zipWith mult (VG.unsafeDrop offset inBuf) coeffs
{-# INLINE filterImperative2 #-}
filterImperative2 :: (PrimMonad m, Functor m, Num a, Mult a b, VG.Vector v a, VG.Vector v b, VGM.MVector vm a) => v b -> Int -> v a -> vm (PrimState m) a -> m ()
filterImperative2 coeffs num inBuf outBuf = go 0
where
go offset
| offset < num = do
let res = dotProd (VG.unsafeDrop offset inBuf)
VGM.unsafeWrite outBuf offset res
go $ offset + 1
| otherwise = return ()
dotProd buf = go 0 0
where
go !accum j
| j < VG.length coeffs = go (VG.unsafeIndex buf j `mult` VG.unsafeIndex coeffs j + accum) (j + 1)
| otherwise = accum
type FilterCRR = CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
type FilterRR = VS.Vector Float -> Int -> VS.Vector Float -> VS.MVector RealWorld Float -> IO ()
type FilterRC = VS.Vector Float -> Int -> VS.Vector (Complex Float) -> VS.MVector RealWorld (Complex Float) -> IO ()
filterFFIR :: FilterCRR -> FilterRR
filterFFIR func coeffs num inBuf outBuf =
VS.unsafeWith (coerce coeffs) $ \cPtr ->
VS.unsafeWith (coerce inBuf) $ \iPtr ->
VSM.unsafeWith (coerce outBuf) $ \oPtr ->
func (fromIntegral num) (fromIntegral $ VG.length coeffs) cPtr iPtr oPtr
filterFFIC :: FilterCRR -> FilterRC
filterFFIC func coeffs num inBuf outBuf =
VS.unsafeWith (coerce coeffs) $ \cPtr ->
VS.unsafeWith (coerce inBuf) $ \iPtr ->
VSM.unsafeWith (coerce outBuf) $ \oPtr ->
func (fromIntegral num) (fromIntegral $ VG.length coeffs) cPtr iPtr oPtr
foreign import ccall unsafe "filterRR"
filterRR_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
filterCRR :: FilterRR
filterCRR = filterFFIR filterRR_c
foreign import ccall unsafe "filterRC"
filterRC_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
filterCRC :: FilterRC
filterCRC = filterFFIC filterRC_c
foreign import ccall unsafe "filterSSERR"
filterSSERR_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
filterCSSERR :: FilterRR
filterCSSERR = filterFFIR filterSSERR_c
foreign import ccall unsafe "filterSSESymmetricRR"
filterSSESymmetricRR_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
filterCSSESymmetricRR :: FilterRR
filterCSSESymmetricRR = filterFFIR filterSSESymmetricRR_c
foreign import ccall unsafe "filterSSERC"
filterSSERC_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
filterCSSERC :: FilterRC
filterCSSERC = filterFFIC filterSSERC_c
foreign import ccall unsafe "filterSSERC2"
filterSSERC2_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
filterCSSERC2 :: FilterRC
filterCSSERC2 = filterFFIC filterSSERC2_c
foreign import ccall unsafe "filterAVXRR"
filterAVXRR_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
filterCAVXRR :: FilterRR
filterCAVXRR = filterFFIR filterAVXRR_c
foreign import ccall unsafe "filterAVXSymmetricRR"
filterAVXSymmetricRR_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
filterCAVXSymmetricRR :: FilterRR
filterCAVXSymmetricRR = filterFFIR filterAVXSymmetricRR_c
foreign import ccall unsafe "filterAVXRC"
filterAVXRC_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
filterCAVXRC :: FilterRC
filterCAVXRC = filterFFIC filterAVXRC_c
foreign import ccall unsafe "filterAVXRC2"
filterAVXRC2_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
filterCAVXRC2 :: FilterRC
filterCAVXRC2 = filterFFIC filterAVXRC2_c
foreign import ccall unsafe "filterSSESymmetricRC"
filterSSESymmetricRC_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
filterCSSESymmetricRC :: FilterRC
filterCSSESymmetricRC = filterFFIC filterSSESymmetricRC_c
foreign import ccall unsafe "filterAVXSymmetricRC"
filterAVXSymmetricRC_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
filterCAVXSymmetricRC :: FilterRC
filterCAVXSymmetricRC = filterFFIC filterAVXSymmetricRC_c
-- Decimation
{-# INLINE decimateHighLevel #-}
decimateHighLevel :: (PrimMonad m, Functor m, Num a, Mult a b, VG.Vector v a, VG.Vector v b, VGM.MVector vm a) => Int -> v b -> Int -> v a -> vm (PrimState m) a -> m ()
decimateHighLevel factor coeffs num inBuf outBuf = fill x outBuf
where
x = VFB.map dotProd (VFB.iterateN num (+ factor) 0)
dotProd offset = VG.sum $ VG.zipWith mult (VG.unsafeDrop offset inBuf) coeffs
type DecimateCRR = CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
type DecimateRR = Int -> VS.Vector Float -> Int -> VS.Vector Float -> VS.MVector RealWorld Float -> IO ()
type DecimateRC = Int -> VS.Vector Float -> Int -> VS.Vector (Complex Float) -> VS.MVector RealWorld (Complex Float) -> IO ()
decimateFFIR :: DecimateCRR -> DecimateRR
decimateFFIR func factor coeffs num inBuf outBuf =
VS.unsafeWith (coerce coeffs) $ \cPtr ->
VS.unsafeWith (coerce inBuf) $ \iPtr ->
VSM.unsafeWith (coerce outBuf) $ \oPtr ->
func (fromIntegral num) (fromIntegral factor) (fromIntegral $ VG.length coeffs) cPtr iPtr oPtr
decimateFFIC :: DecimateCRR -> DecimateRC
decimateFFIC func factor coeffs num inBuf outBuf =
VS.unsafeWith (coerce coeffs) $ \cPtr ->
VS.unsafeWith (coerce inBuf) $ \iPtr ->
VSM.unsafeWith (coerce outBuf) $ \oPtr ->
func (fromIntegral num) (fromIntegral factor) (fromIntegral $ VG.length coeffs) cPtr iPtr oPtr
foreign import ccall unsafe "decimateRR"
decimateCRR_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
decimateCRR :: DecimateRR
decimateCRR = decimateFFIR decimateCRR_c
foreign import ccall unsafe "decimateRC"
decimateCRC_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
decimateCRC :: DecimateRC
decimateCRC = decimateFFIC decimateCRC_c
foreign import ccall unsafe "decimateSSERR"
decimateSSERR_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
decimateCSSERR :: DecimateRR
decimateCSSERR = decimateFFIR decimateSSERR_c
foreign import ccall unsafe "decimateSSERC"
decimateSSERC_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
decimateCSSERC :: DecimateRC
decimateCSSERC = decimateFFIC decimateSSERC_c
foreign import ccall unsafe "decimateSSERC2"
decimateSSERC2_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
decimateCSSERC2 :: DecimateRC
decimateCSSERC2 = decimateFFIC decimateSSERC2_c
foreign import ccall unsafe "decimateAVXRR"
decimateAVXRR_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
decimateCAVXRR :: DecimateRR
decimateCAVXRR = decimateFFIR decimateAVXRR_c
foreign import ccall unsafe "decimateAVXRC"
decimateAVXRC_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
decimateCAVXRC :: DecimateRC
decimateCAVXRC = decimateFFIC decimateAVXRC_c
foreign import ccall unsafe "decimateAVXRC2"
decimateAVXRC2_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
decimateCAVXRC2 :: DecimateRC
decimateCAVXRC2 = decimateFFIC decimateAVXRC2_c
foreign import ccall unsafe "decimateSSESymmetricRR"
decimateSSESymmetricRR_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
decimateCSSESymmetricRR :: DecimateRR
decimateCSSESymmetricRR = decimateFFIR decimateSSESymmetricRR_c
foreign import ccall unsafe "decimateAVXSymmetricRR"
decimateAVXSymmetricRR_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
decimateCAVXSymmetricRR :: DecimateRR
decimateCAVXSymmetricRR = decimateFFIR decimateAVXSymmetricRR_c
foreign import ccall unsafe "decimateSSESymmetricRC"
decimateSSESymmetricRC_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
decimateCSSESymmetricRC :: DecimateRC
decimateCSSESymmetricRC = decimateFFIC decimateSSESymmetricRC_c
foreign import ccall unsafe "decimateAVXSymmetricRC"
decimateAVXSymmetricRC_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
decimateCAVXSymmetricRC :: DecimateRC
decimateCAVXSymmetricRC = decimateFFIC decimateAVXSymmetricRC_c
-- Resampling
{-# INLINE resampleHighLevel #-}
resampleHighLevel :: (PrimMonad m, Num a, Mult a b, VG.Vector v a, VG.Vector v b, VGM.MVector vm a) => Int -> Int -> v b -> Int -> Int -> v a -> vm (PrimState m) a -> m Int
resampleHighLevel interpolation decimation coeffs filterOffset count inBuf outBuf = fill 0 filterOffset 0
where
fill i filterOffset inputOffset
| i < count = do
let dp = dotProd filterOffset inputOffset
VGM.unsafeWrite outBuf i dp
let (q, r) = divMod (decimation - filterOffset - 1) interpolation
inputOffset' = inputOffset + q + 1
filterOffset' = interpolation - 1 - r
filterOffset' `seq` inputOffset' `seq` fill (i + 1) filterOffset' inputOffset'
| otherwise = return filterOffset
dotProd filterOffset offset = VG.sum $ VG.zipWith mult (VG.unsafeDrop offset inBuf) (stride interpolation (VG.unsafeDrop filterOffset coeffs))
foreign import ccall unsafe "resampleRR"
resample_c :: CInt -> CInt -> CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
resampleCRR :: Int -> Int -> Int -> Int -> VS.Vector Float -> VS.Vector Float -> VS.MVector RealWorld Float -> IO ()
resampleCRR num interpolation decimation offset coeffs inBuf outBuf =
VS.unsafeWith (coerce coeffs) $ \cPtr ->
VS.unsafeWith (coerce inBuf) $ \iPtr ->
VSM.unsafeWith (coerce outBuf) $ \oPtr ->
resample_c (fromIntegral num) (fromIntegral $ VG.length coeffs) (fromIntegral interpolation) (fromIntegral decimation) (fromIntegral offset) cPtr iPtr oPtr
pad :: a -> Int -> [a] -> [a]
pad with num list = list ++ replicate (num - length list) with
strideList :: Int -> [a] -> [a]
strideList s xs = go 0 xs
where
go _ [] = []
go 0 (x:xs) = x : go (s-1) xs
go n (x:xs) = go (n - 1) xs
roundUp :: Int -> Int -> Int
roundUp num div = ((num + div - 1) `quot` div) * div
data Coeffs = Coeffs {
numCoeffs :: Int,
numGroups :: Int,
increments :: [Int],
groups :: [[Float]]
}
prepareCoeffs :: Int -> Int -> Int -> [Float] -> Coeffs
prepareCoeffs n interpolation decimation coeffs = Coeffs {..}
where
numCoeffs = maximum $ map (length . snd) dats
numGroups = length groups
increments = map fst dats
groups :: [[Float]]
groups = map (pad 0 (roundUp numCoeffs n)) $ map snd dats
dats :: [(Int, [Float])]
dats = func 0
where
func' 0 = []
func' x = func x
func :: Int -> [(Int, [Float])]
func offset = (increment, strideList interpolation $ drop offset coeffs) : func' offset'
where
(q, r) = divMod (decimation - offset - 1) interpolation
increment = q + 1
offset' = interpolation - 1 - r
resampleFFIR :: (Ptr CFloat -> Ptr CFloat -> IO CInt) -> VS.Vector Float -> VSM.MVector RealWorld Float -> IO Int
resampleFFIR func inBuf outBuf = liftM fromIntegral $
VS.unsafeWith (coerce inBuf) $ \iPtr ->
VSM.unsafeWith (coerce outBuf) $ \oPtr ->
func iPtr oPtr
resampleFFIC :: (Ptr CFloat -> Ptr CFloat -> IO CInt) -> VS.Vector (Complex Float) -> VSM.MVector RealWorld (Complex Float) -> IO Int
resampleFFIC func inBuf outBuf = liftM fromIntegral $
VS.unsafeWith (coerce inBuf) $ \iPtr ->
VSM.unsafeWith (coerce outBuf) $ \oPtr ->
func iPtr oPtr
type ResampleR = CInt -> CInt -> CInt -> CInt -> Ptr CInt -> Ptr (Ptr CFloat) -> Ptr CFloat -> Ptr CFloat -> IO CInt
mkResampler :: ResampleR -> Int -> Int -> Int -> [Float] -> IO (Int -> Int -> VS.Vector Float -> VS.MVector RealWorld Float -> IO Int)
mkResampler func n interpolation decimation coeffs = do
groupsP <- mapM newArray $ map (map realToFrac) groups
groupsPP <- newArray groupsP
incrementsP <- newArray $ map fromIntegral increments
return $ \offset num -> resampleFFIR $ func (fromIntegral num) (fromIntegral numCoeffs) (fromIntegral offset) (fromIntegral numGroups) incrementsP groupsPP
where
Coeffs {..} = prepareCoeffs n interpolation decimation coeffs
type ResampleRR = Int -> Int -> [Float] -> IO (Int -> Int -> VS.Vector Float -> VS.MVector RealWorld Float -> IO Int)
foreign import ccall unsafe "resample2RR"
resample2_c :: CInt -> CInt -> CInt -> CInt -> Ptr CInt -> Ptr (Ptr CFloat) -> Ptr CFloat -> Ptr CFloat -> IO CInt
resampleCRR2 :: ResampleRR
resampleCRR2 = mkResampler resample2_c 1
foreign import ccall unsafe "resampleSSERR"
resampleCSSERR_c :: CInt -> CInt -> CInt -> CInt -> Ptr CInt -> Ptr (Ptr CFloat) -> Ptr CFloat -> Ptr CFloat -> IO CInt
resampleCSSERR :: ResampleRR
resampleCSSERR = mkResampler resampleCSSERR_c 4
foreign import ccall unsafe "resampleAVXRR"
resampleAVXRR_c :: CInt -> CInt -> CInt -> CInt -> Ptr CInt -> Ptr (Ptr CFloat) -> Ptr CFloat -> Ptr CFloat -> IO CInt
resampleCAVXRR :: ResampleRR
resampleCAVXRR = mkResampler resampleAVXRR_c 8
type ResampleRC = Int -> Int -> [Float] -> IO (Int -> Int -> VS.Vector (Complex Float) -> VS.MVector RealWorld (Complex Float) -> IO Int)
mkResamplerC :: ResampleR -> Int -> Int -> Int -> [Float] -> IO (Int -> Int -> VS.Vector (Complex Float) -> VS.MVector RealWorld (Complex Float) -> IO Int)
mkResamplerC func n interpolation decimation coeffs = do
groupsP <- mapM newArray $ map (map realToFrac) groups
groupsPP <- newArray groupsP
incrementsP <- newArray $ map fromIntegral increments
return $ \offset num -> resampleFFIC $ func (fromIntegral num) (fromIntegral numCoeffs) (fromIntegral offset) (fromIntegral numGroups) incrementsP groupsPP
where
Coeffs {..} = prepareCoeffs n interpolation decimation coeffs
foreign import ccall unsafe "resample2RC"
resample2RC_c :: CInt -> CInt -> CInt -> CInt -> Ptr CInt -> Ptr (Ptr CFloat) -> Ptr CFloat -> Ptr CFloat -> IO CInt
resampleCRC :: ResampleRC
resampleCRC = mkResamplerC resample2RC_c 1
foreign import ccall unsafe "resampleSSERC"
resampleCSSERC_c :: CInt -> CInt -> CInt -> CInt -> Ptr CInt -> Ptr (Ptr CFloat) -> Ptr CFloat -> Ptr CFloat -> IO CInt
resampleCSSERC :: ResampleRC
resampleCSSERC = mkResamplerC resampleCSSERC_c 4
foreign import ccall unsafe "resampleAVXRC"
resampleAVXRC_c :: CInt -> CInt -> CInt -> CInt -> Ptr CInt -> Ptr (Ptr CFloat) -> Ptr CFloat -> Ptr CFloat -> IO CInt
resampleCAVXRC :: ResampleRC
resampleCAVXRC = mkResamplerC resampleAVXRC_c 8
{-
- Cross buffer
-}
{-# INLINE decimateCrossHighLevel #-}
decimateCrossHighLevel :: (PrimMonad m, Functor m, Num a, Mult a b, VG.Vector v a, VG.Vector v b, VGM.MVector vm a) => Int -> v b -> Int -> v a -> v a -> vm (PrimState m) a -> m ()
decimateCrossHighLevel factor coeffs num lastBuf nextBuf outBuf = fill x outBuf
where
x = VFB.map dotProd (VFB.iterateN num (+ factor) 0)
dotProd i = VG.sum $ VG.zipWith mult (VG.unsafeDrop i lastBuf VG.++ nextBuf) coeffs
{-# INLINE filterCrossHighLevel #-}
filterCrossHighLevel :: (PrimMonad m, Functor m, Num a, Mult a b, VG.Vector v a, VG.Vector v b, VGM.MVector vm a) => v b -> Int -> v a -> v a -> vm (PrimState m) a -> m ()
filterCrossHighLevel coeffs num lastBuf nextBuf outBuf = fill (VFB.generate num dotProd) outBuf
where
dotProd i = VG.sum $ VG.zipWith mult (VG.unsafeDrop i lastBuf VG.++ nextBuf) coeffs
{-# INLINE resampleCrossHighLevel #-}
resampleCrossHighLevel :: (PrimMonad m, Num a, Mult a b, VG.Vector v a, VG.Vector v b, VGM.MVector vm a) => Int -> Int -> v b -> Int -> Int -> v a -> v a -> vm (PrimState m) a -> m Int
resampleCrossHighLevel interpolation decimation coeffs filterOffset count lastBuf nextBuf outBuf = fill 0 filterOffset 0
where
fill i filterOffset inputOffset
| i < count = do
let dp = dotProd filterOffset inputOffset
VGM.unsafeWrite outBuf i dp
let (q, r) = divMod (decimation - filterOffset - 1) interpolation
inputOffset' = inputOffset + q + 1
filterOffset' = interpolation - 1 - r
filterOffset' `seq` inputOffset' `seq` fill (i + 1) filterOffset' inputOffset'
| otherwise = return filterOffset
dotProd filterOffset i = VG.sum $ VG.zipWith mult (VG.unsafeDrop i lastBuf VG.++ nextBuf) (stride interpolation (VG.unsafeDrop filterOffset coeffs))
foreign import ccall unsafe "dcBlocker"
c_dcBlocker :: CInt -> CFloat -> CFloat -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()
dcBlocker :: Int -> Float -> Float -> VS.Vector Float -> VS.MVector RealWorld Float -> IO (Float, Float)
dcBlocker num lastSample lastOutput inBuf outBuf =
alloca $ \fsp ->
alloca $ \fop ->
VS.unsafeWith (coerce inBuf) $ \iPtr ->
VSM.unsafeWith (coerce outBuf) $ \oPtr -> do
c_dcBlocker (fromIntegral num) (realToFrac lastSample) (realToFrac lastOutput) fsp fop iPtr oPtr
r1 <- peek fsp
r2 <- peek fop
return (realToFrac r1, realToFrac r2)
|
lemma forall_coeffs_conv: "(\<forall>n. P (coeff p n)) \<longleftrightarrow> (\<forall>c \<in> set (coeffs p). P c)" if "P 0"
|
{-# LANGUAGE GADTs, DataKinds, KindSignatures, ScopedTypeVariables, TypeApplications, TypeOperators, RankNTypes, FlexibleContexts #-}
import Numeric.LinearAlgebra.Static
import GHC.TypeLits
import Data.Proxy
import Data.Maybe (mapMaybe)
import Data.Monoid (getSum, Sum(..))
import Data.Coerce
import MLP.Types (Pattern(..))
import MLP.Network (Net(..), AllCon, ArrList(..), Weights(..), MLP(..), Learn(..), fromScalarR, netUpd)
import Data.Singletons
data EncPat where
EncPat :: forall i o. (KnownNat i, KnownNat o) => Pattern i o -> EncPat
data EncNet where
EncNet :: forall i hs o. (SingI (Topo (Net i hs o)), Learn (Net i hs o), AllCon KnownNat (i ': o ': hs), MLP (Net i hs o)) => Net i hs o -> EncNet
readMat :: IO (EncPat, EncNet)
readMat = do
i <- read <$> (putStr "inputs: " >> getLine)
o <- read <$> (putStr "outputs: " >> getLine)
let Just someNatI = someNatVal (ceiling i)
Just someNatO = someNatVal (ceiling o)
case someNatI of
SomeNat (_ :: Proxy i) ->
case someNatO of
SomeNat (_ :: Proxy o) ->
let n = EncNet . SLayer $ Weights (matrix @o @i [1..(i * o)] ) (vector @o [1..o])
p = EncPat $ Pattern (vector @i [1..i]) (vector @o [1..o])
in pure (p,n)
io :: forall i o hs. (KnownNat i, KnownNat o) => Net i hs o -> [Integer]
io _ = map fromIntegral . fromSing $ sing @'[i, o]
main :: IO ()
main = do
(EncPat (Pattern i o), EncNet n) <- readMat
let arrl = mkDeltas i o n
case netUpd 1.0 i arrl n of
SLayer l -> print l
_ -> print ""
|
# -*- coding: utf-8 -*-
# # Univariate Polynomial Regression
#
# This example demonstrates how to use manipulate a univariate regression model in an algebraically precise way. It builds on the example `pseudo_polynomial_regression.jl`.
# Let `m` be a statistical model like
# ```julia
# f(x) = βx
# X = rand(Normal(0,1), n)
# target[i] = f(X[i]) + rand(Normal(0,1), 1)
# min_{a,b} sum_i (f(X[i]) - target[i])^2
# ```
#
# So it is a linear least squares regression model. The parameter $\beta$ is the regression coefficients that are learned from data.
#
# Define the set of transformations $T$ as the free monoid generated by
#
# ```julia
# T_x = f(x)->x*f(x)
# T_1 = f(x)->f(x) + C
# ```
#
# Namely, the set of strings over the alphabet $\{T_x, T_1\}$
#
# The monoid generated by this set of transformations acts on `m` to create all polynomial univariate regressions.
#
# ```julia
# f(x) = sum(β_i*x^i)
# X = rand(Normal(0,1), n)
# target[i] = f(X[i]) + rand(Normal(0,1), 1)
# min_{β} sum_i (f_β(x[i]) - target[i])^2
# ```
#
# for all polynomials `f`. The ring of polynomials is well studied and we should be able to apply our knowledge of polynomial algebras to say something about the model transformations.
#
# We will replicate the feature selection process used in standard polynomial regression models using our model augmentation tools.
#
# Here is an example implementation of this theory.
# ## Example Model
#Our working example of a multivariate nonlinear regression model
expr = quote
module Regression
using Random
using LsqFit
using LinearAlgebra
function f(x, β)
# This .+ node is added so that we have something to grab onto
# in the metaprogramming. It is the ∀a .+(a) == a.
return .+(β[1].* x.^0)
end
# Generate the data for this example
function sample(g::Function, n)
x = randn(Float64, n)
target = g(x) .+ randn(Float64, n[1])./1600
return x, target
end
# Compute the regression statistics
function describe(fit)
if !fit.converged
error("Did not converge")
end
return (β = fit.param, r=norm(fit.resid,2), n=length(fit.resid))
end
#setup
# Random.seed!(42)
β = (1/2, 1/2)
n = (1000)
g(x) = β[1].*x.^3 + β[2].*x.^2
X, target = sample(g, n)
# x, y = X[:,1], X[:,2]
# @show size(X), size(target)
# loss(a) = sum((f.(a, x, y) .- target).^2)
# @show loss.([-1,-1/2,-1/4, 0, 1/4,1/3,1/2,2/3, 1])
a₀ = [1.5]
try
ŷ₀ = f(X, a₀)
catch except
@show except
error("Could not execute f on the initial data")
end
#solving
fit = curve_fit(f, X, target, a₀)#; autodiff=:forwarddiff)
result = describe(fit)
end
end
eval(expr.args[2])
Regression.fit.param
# ## Implementation Details
# The following code is the implementation details for representing the models as an `AbstractProblem` and representing the transformations as sequences of operations and applying the transformations onto the models.
#
# You can skip these if you are not interested in how this is implemented.
# +
using LinearAlgebra
import Base: show
using SemanticModels
using SemanticModels.ExprModels
import SemanticModels: model, AbstractModel
import SemanticModels.ExprModels: isexpr
import SemanticModels.ExprModels.Parsers: findfunc, findassign
import SemanticModels.ExprModels.Transformations: Pow
# -
ExprModels.Transformations.Pow
# +
""" Lsq
A program that solves min_β || f(X,β) - y ||_2
Example:
`f(X, β) = β[1].*X.^p .+ β[2].*X.^q`
See also [`(t::Pow)(m::Lsq)`](@ref)
"""
struct Lsq <: AbstractModel
expr
f
coefficient
p₀
end
function show(io::IO, m::Lsq)
write(io, "Lsq(\n f=$(repr(m.f)),\n coefficient=$(repr(m.coefficient)),\n p₀=$(repr(m.p₀))\n)")
end
function model(::Type{Lsq}, expr::Expr)
if expr.head == :block
return model(Lsq, expr.args[2])
end
objective = :l2norm
f = callsites(expr, :curve_fit)[end].args[2]
coeff = callsites(expr, f)[1].args[end]
p₀ = callsites(expr, :curve_fit)[end].args[end]
return Lsq(expr, f, coeff, p₀)
end
""" poly(m::Lsq)::Expr
find the part of the model that implements the polynomial model for regression.
"""
function poly(m::Lsq)
func = findfunc(m.expr, m.f)[1]
poly = func.args[2].args[end].args[1]
return poly
end
""" (t::Pow)(m::Lsq)
Example:
If `m` is a program implementing `f(X, β) = β[1]*X^p + β[2]*X^q`
a) and `t = Pow(2)` then `t(m)` is the model implementing
`f(X, β) = β[1]*X^p+2 + β[2]*X^q+q`.
"""
function (t::Pow)(m::Lsq)
p = poly(m)
for i in 2:length(p.args)
slot = p.args[i]
pow = callsites(slot, :(.^))
pow[end].args[3] += t.inc
end
return m
end
struct AddConst <: ExprModels.Transformations.Transformation end
""" (c::AddConst)(m::Lsq)
Example:
If `m` is a program implementing `f(X, β) = β[1]*X^p + β[2]*X^q`
a) and `c = AddConst()` then `c(m)` is the model implementing
`f(X, β) = β[1]*X^p + β[2]*X^0`.
"""
function (c::AddConst)(m::Lsq)
p = poly(m)
ix = map(t->t.args[2].args[2], p.args[2:end])
i = maximum(ix)+1
@show p
push!(p.args, :(β[$i].*x.^0))
assigns = findassign(m.expr, m.p₀)
@show assigns
b = assigns[end].args[2].args
push!(b, 1)
return m
end
# -
m = model(Lsq, deepcopy(expr))
# ## Model Augmentation with Group Actions
#
# Now we have all the machinery in place to build novel models from old models.
# Let's build an instance of the model object from the code snippet expr
m = model(Lsq, deepcopy(expr))
@show m
poly(m)
# Some *generator elements* will come in handy for building elements of the transformation group.
# $T_x,T_1$ are *generators* for our group of transformations $T = \langle T_x, T_1 \rangle$. Application of $T_1$ adds a constant to our polynomial while application of $T_x$ increments all the powers of the terms by 1. Any polynomial can be generated by these two operations.
@show Tₓ = Pow(1)
@show T₁ = AddConst()
Tₓ, T₁
# TODO: make these tests
m = model(Lsq, deepcopy(expr))
@show poly(Tₓ(m))
@show poly(T₁(m))
@show poly(Tₓ(m))
@show poly(Tₓ(m))
@show poly(T₁(m))
# Theorem: Any polynomial regression model can be produced by repeated application of $T_x,T_1$.
#
# Proof: Let $p(x) = \sum_i^d \beta_i x^i$ Starting from $q_0(x)= \beta[1] = \beta[1] x^0$,
#
# ```
# for i in 1:d
# if \beta_{d-i} != 0 then
# apply T_1
# end
# apply T_x
# end
# ```
#
# This algorithm is Horner's rule for evaluating $p(x)$ on the symbolic coeffients $\beta_i$
# ## Exploring the Orbits
#
# We use the Levenberg Marquardt algorithm for general least squares problems in data analysis. The goal is to fix a model class and find the best coefficients for that class. Our algebraic representation allows us to have a similar treatment of model class (in this case the exponents $i,j$ in our formula). We can sample from the orbits of the group when applied to the model and solve for the best coefficients in order to find the best model class.
#
# In this case we have reduced the code search space to a model search space to an algebraic formulation.
m = model(Lsq, deepcopy(expr))
results = []
for i in 1:5
p = poly(m)
M = eval(m.expr)
push!(results, (i=i, M.result..., p=deepcopy(p)))
T₁(Tₓ(m))
end
# It turns out that this method recovers the *true* model order $2,3$
for r in results
# \t$(map(x->string(x.args[3]), r.p.args[2:end]))
β̂ = map(βᵢ -> round(βᵢ, digits=4), r.β)
s = join(map(x->string(x.args[3].args[3]), r.p.args[2:end]),", ")
dof = length(r.p.args)-1
println("DoF: $(dof)\tPoly: x^{$s}")
println("Residual: $(round(r.r, digits=4))\tβ̂: $(β̂))")
ℓ1 = norm(β̂, 1)
println("ℓ₁ norm of β̂: $ℓ1")
println("--------------------------------------------------------\n\n")
end
# ## Appied Algebra
#
# We know that the data generating function is an odd polynomial and that any polynomial in $\langle T_x\dot T_x, T_1\rangle$ will be even. The following metamodel shows that no even polynomial fits our data well.
# +
m = model(Lsq, deepcopy(expr))
results = []
for i in 1:5
p = poly(m)
M = eval(m.expr)
push!(results, (i=i, M.result..., p=deepcopy(p)))
T₁(Tₓ(Tₓ(m)))
end
for r in results
# \t$(map(x->string(x.args[3]), r.p.args[2:end]))
β̂ = map(βᵢ -> round(βᵢ, digits=4), r.β)
s = join(map(x->string(x.args[3].args[3]), r.p.args[2:end]),", ")
dof = length(r.p.args)-1
println("DoF: $(dof)\tPoly: x^{$s}")
println("Residual: $(round(r.r, digits=4))\tβ̂: $(β̂))")
ℓ1 = norm(β̂, 1)
println("ℓ₁ norm of β̂: $ℓ1")
println("--------------------------------------------------------\n\n")
end
# -
# ## Conclusions
#
# We have seen how abstract algebra can be applied to the category of models to build a systematic treatment of model augmentation. This proves that the model transformations can be arranged into a simple algebraic structure that can act on a model to build new models. The structure of the transformations are easier to analyze than the changes to the models themselves.
|
# +--------------------------------------------------------+
# | Generate package documentation pages from inline |
# | documentation. Build, check and install package |
# +--------------------------------------------------------+
rm(list=ls(all=TRUE))
prjName <- "macrounchained"
pkgName <- "codeinfo"
pkgDir <- Sys.getenv( x = "rPackagesDir", unset = NA_character_ )
if( is.na( pkgDir ) ){
stop( "Variable 'rPackagesDir' not defined." )
}else{ pkgDir <- file.path( pkgDir, prjName ) }
buildDir <- file.path( pkgDir, pkgName, "_package_binaries" )
local_repos <- Sys.getenv( x = "rPackagesLocalRepos",
unset = NA_character_ )
if( is.na( local_repos ) ){
stop( "Variable 'rPackagesLocalRepos' not defined." )
}else{ local_repos <- file.path( local_repos, prjName ) }
setwd( pkgDir )
# Source some utility functions (prefix: pdu_)
source( file.path( pkgName, "pkg_dev_utilities.fun.r" ) )
pdu_detach( pkgName = pkgName )
# +--------------------------------------------------------+
# | Generate package documentation pages from inline |
# | documentation. |
# +--------------------------------------------------------+
# Change the description file:
pdu_pkgDescription(
pkgName = pkgName,
pkgDir = pkgDir,
pkgVersion = "0.1.3",
pkgDepends = NULL,
pkgImports = c( "utils", "tools" ),
pkgSuggests = NULL,
RVersion = "R (>= 3.1.0)" )
library( "roxygen2" )
roxygen2::roxygenize(
package.dir = file.path( pkgDir, pkgName ),
# unlink.target = TRUE,
roclets = c( "namespace", "rd" ) # "collate"
)
# pdu_pkgRemove( pkgName = pkgName )
# +--------------------------------------------------------+
# | Run R CMD build (build tar.gz source binary) |
# | Run R CMD check (check package) |
# | Run R CMD INSTALL (build Windows binary and install) |
# +--------------------------------------------------------+
# # Source some utility functions (prefix: pdu_)
# source( file.path( pkgName, "pkg_dev_utilities.fun.r" ) )
pdu_rcmdbuild( pkgName = pkgName, pkgDir = pkgDir,
buildDir = buildDir, gitRevison = TRUE,
noVignettes = FALSE, compactVignettes = "gs+qpdf",
md5 = TRUE )
pdu_rcmdinstall( pkgName = pkgName, pkgDir = pkgDir,
buildDir = buildDir, build = TRUE,
compactDocs = TRUE, byteCompile = TRUE )
pdu_rcmdcheck( pkgName = pkgName, pkgDir = pkgDir,
buildDir = buildDir, noExamples = FALSE,
noTests = FALSE, noVignettes = FALSE )
# Remove .Rcheck folder
pdu_rm_Rcheck( pkgName = pkgName, pkgDir = pkgDir,
buildDir = buildDir )
# Load and unload the package:
library( pkgName, character.only = TRUE )
pdu_detach( pkgName = pkgName )
# +--------------------------------------------------------+
# | Rebuild vignette (optional) |
# +--------------------------------------------------------+
# # Source some utility functions (prefix: pdu_)
# source( file.path( pkgName, "pkg_dev_utilities.fun.r" ) )
# pdu_build_vignette( RnwFile = "macroutils2_vignette.Rnw",
# pkgName = pkgName, pkgDir = pkgDir, buildDir = buildDir,
# pdf = TRUE, quiet = TRUE )
# +--------------------------------------------------------+
# | Build PDF-version of the manual (help pages) |
# +--------------------------------------------------------+
# # Source some utility functions (prefix: pdu_)
# source( file.path( pkgName, "pkg_dev_utilities.fun.r" ) )
pdu_rd2pdf( pkgName = pkgName, pkgDir = pkgDir,
buildDir = buildDir )
# +--------------------------------------------------------+
# | Copy source and zip binaries to local repos |
# +--------------------------------------------------------+
pdu_copy_to_repos( pkgName = pkgName, pkgDir = pkgDir,
buildDir = buildDir, local_repos = local_repos )
|
State Before: Ω : Type u_1
inst✝⁶ : MeasurableSpace Ω
R : Type ?u.126329
inst✝⁵ : SMul R ℝ≥0
inst✝⁴ : SMul R ℝ≥0∞
inst✝³ : IsScalarTower R ℝ≥0 ℝ≥0∞
inst✝² : IsScalarTower R ℝ≥0∞ ℝ≥0∞
inst✝¹ : TopologicalSpace Ω
inst✝ : OpensMeasurableSpace Ω
⊢ Continuous fun μ => mass μ State After: Ω : Type u_1
inst✝⁶ : MeasurableSpace Ω
R : Type ?u.126329
inst✝⁵ : SMul R ℝ≥0
inst✝⁴ : SMul R ℝ≥0∞
inst✝³ : IsScalarTower R ℝ≥0 ℝ≥0∞
inst✝² : IsScalarTower R ℝ≥0∞ ℝ≥0∞
inst✝¹ : TopologicalSpace Ω
inst✝ : OpensMeasurableSpace Ω
⊢ Continuous fun μ => testAgainstNN μ 1 Tactic: simp_rw [← testAgainstNN_one] State Before: Ω : Type u_1
inst✝⁶ : MeasurableSpace Ω
R : Type ?u.126329
inst✝⁵ : SMul R ℝ≥0
inst✝⁴ : SMul R ℝ≥0∞
inst✝³ : IsScalarTower R ℝ≥0 ℝ≥0∞
inst✝² : IsScalarTower R ℝ≥0∞ ℝ≥0∞
inst✝¹ : TopologicalSpace Ω
inst✝ : OpensMeasurableSpace Ω
⊢ Continuous fun μ => testAgainstNN μ 1 State After: no goals Tactic: exact continuous_testAgainstNN_eval 1
|
/**
*
* @file dsungesv.c
*
* PLASMA computational routines
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Emmanuel Agullo
* @date 2010-11-15
* @generated ds Tue Jan 7 11:45:09 2014
*
**/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <lapacke.h>
#include "common.h"
#define PLASMA_dlag2s(_descA, _descSB) \
plasma_parallel_call_4(plasma_pdlag2s, \
PLASMA_desc, (_descA), \
PLASMA_desc, (_descSB), \
PLASMA_sequence*, sequence, \
PLASMA_request*, request)
#define PLASMA_slag2d(_descSA, _descB) \
plasma_parallel_call_4(plasma_pslag2d, \
PLASMA_desc, (_descSA), \
PLASMA_desc, (_descB), \
PLASMA_sequence*, sequence, \
PLASMA_request*, request)
#define PLASMA_dlange(_norm, _descA, _result, _work) \
_result = 0; \
plasma_parallel_call_6(plasma_pdlange, \
PLASMA_enum, (_norm), \
PLASMA_desc, (_descA), \
double*, (_work), \
double*, &(_result), \
PLASMA_sequence*, sequence, \
PLASMA_request*, request);
#define PLASMA_dlacpy(_descA, _descB) \
plasma_parallel_call_5(plasma_pdlacpy, \
PLASMA_enum, PlasmaUpperLower, \
PLASMA_desc, (_descA), \
PLASMA_desc, (_descB), \
PLASMA_sequence*, sequence, \
PLASMA_request*, request)
#define PLASMA_dgeadd(_alpha, _descA, _descB) \
plasma_parallel_call_5(plasma_pdgeadd, \
double, (_alpha), \
PLASMA_desc, (_descA), \
PLASMA_desc, (_descB), \
PLASMA_sequence*, sequence, \
PLASMA_request*, request)
/***************************************************************************//**
*
* @ingroup double
*
* PLASMA_dsungesv - Solves overdetermined or underdetermined linear systems involving an M-by-N
* matrix A using the QR or the LQ factorization of A. It is assumed that A has full rank.
* The following options are provided:
*
* # trans = PlasmaNoTrans and M >= N: find the least squares solution of an overdetermined
* system, i.e., solve the least squares problem: minimize || B - A*X ||.
*
* # trans = PlasmaNoTrans and M < N: find the minimum norm solution of an underdetermined
* system A * X = B.
*
* Several right hand side vectors B and solution vectors X can be handled in a single call;
* they are stored as the columns of the M-by-NRHS right hand side matrix B and the N-by-NRHS
* solution matrix X.
*
* PLASMA_dsungesv first attempts to factorize the matrix in COMPLEX and use this
* factorization within an iterative refinement procedure to produce a
* solution with COMPLEX*16 normwise backward error quality (see below).
* If the approach fails the method switches to a COMPLEX*16
* factorization and solve.
*
* The iterative refinement is not going to be a winning strategy if
* the ratio COMPLEX performance over COMPLEX*16 performance is too
* small. A reasonable strategy should take the number of right-hand
* sides and the size of the matrix into account. This might be done
* with a call to ILAENV in the future. Up to now, we always try
* iterative refinement.
*
* The iterative refinement process is stopped if ITER > ITERMAX or
* for all the RHS we have: RNRM < N*XNRM*ANRM*EPS*BWDMAX
* where:
*
* - ITER is the number of the current iteration in the iterative refinement process
* - RNRM is the infinity-norm of the residual
* - XNRM is the infinity-norm of the solution
* - ANRM is the infinity-operator-norm of the matrix A
* - EPS is the machine epsilon returned by DLAMCH('Epsilon').
*
* Actually, in its current state (PLASMA 2.1.0), the test is slightly relaxed.
*
* The values ITERMAX and BWDMAX are fixed to 30 and 1.0D+00 respectively.
*
* We follow Bjorck's algorithm proposed in "Iterative Refinement of Linear
* Least Squares solutions I", BIT, 7:257-278, 1967.4
*
*******************************************************************************
*
* @param[in] trans
* Intended usage:
* = PlasmaNoTrans: the linear system involves A;
* = PlasmaTrans: the linear system involves A**H.
* Currently only PlasmaNoTrans is supported.
*
* @param[in] N
* The number of columns of the matrix A. N >= 0.
*
* @param[in] NRHS
* The number of right hand sides, i.e., the number of columns of the matrices B and X.
* NRHS >= 0.
*
* @param[in] A
* The M-by-N matrix A. This matrix is not modified.
*
* @param[in] LDA
* The leading dimension of the array A. LDA >= max(1,M).
*
* @param[in] B
* The M-by-NRHS matrix B of right hand side vectors, stored columnwise. Not modified.
*
* @param[in] LDB
* The leading dimension of the array B. LDB >= MAX(1,M,N).
*
* @param[out] X
* If return value = 0, the solution vectors, stored columnwise.
* if M >= N, rows 1 to N of B contain the least squares solution vectors; the residual
* sum of squares for the solution in each column is given by the sum of squares of the
* modulus of elements N+1 to M in that column;
* if M < N, rows 1 to N of B contain the minimum norm solution vectors;
*
* @param[in] LDX
* The leading dimension of the array B. LDB >= MAX(1,M,N).
*
* @param[out] ITER
* The number of the current iteration in the iterative refinement process
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval <0 if -i, the i-th argument had an illegal value
*
*******************************************************************************
*
* @sa PLASMA_dsungesv_Tile
* @sa PLASMA_dsungesv_Tile_Async
* @sa PLASMA_dsungesv
* @sa PLASMA_dgels
*
******************************************************************************/
int PLASMA_dsungesv(PLASMA_enum trans, int N, int NRHS,
double *A, int LDA,
double *B, int LDB,
double *X, int LDX, int *ITER)
{
int NB;
int status;
PLASMA_desc descA;
PLASMA_desc descB;
PLASMA_desc *descT;
PLASMA_desc descX;
plasma_context_t *plasma;
PLASMA_sequence *sequence = NULL;
PLASMA_request request = PLASMA_REQUEST_INITIALIZER;
plasma = plasma_context_self();
if (plasma == NULL) {
plasma_fatal_error("PLASMA_dsungesv", "PLASMA not initialized");
return PLASMA_ERR_NOT_INITIALIZED;
}
*ITER = 0;
/* Check input arguments */
if (trans != PlasmaNoTrans &&
trans != PlasmaTrans &&
trans != PlasmaTrans )
{
plasma_error("PLASMA_dsungesv", "illegal value of trans");
return -1;
}
if (trans != PlasmaNoTrans) {
plasma_error("PLASMA_dsungesv", "only PlasmaNoTrans supported");
return PLASMA_ERR_NOT_SUPPORTED;
}
if (N < 0) {
plasma_error("PLASMA_dsungesv", "illegal value of N");
return -2;
}
if (NRHS < 0) {
plasma_error("PLASMA_dsungesv", "illegal value of NRHS");
return -3;
}
if (LDA < max(1, N)) {
plasma_error("PLASMA_dsungesv", "illegal value of LDA");
return -5;
}
if (LDB < max(1, N)) {
plasma_error("PLASMA_dsungesv", "illegal value of LDB");
return -7;
}
if (LDX < max(1, N)) {
plasma_error("PLASMA_dsungesv", "illegal value of LDX");
return -9;
}
/* Quick return */
if ( N == 0 )
return PLASMA_SUCCESS;
/* Tune NB & IB depending on M, N & NRHS; Set NBNB */
status = plasma_tune(PLASMA_FUNC_DSGELS, N, N, NRHS);
if (status != PLASMA_SUCCESS) {
plasma_error("PLASMA_dsungesv", "plasma_tune() failed");
return status;
}
NB = PLASMA_NB;
plasma_sequence_create(plasma, &sequence);
/* DOUBLE PRECISION INITIALIZATION */
if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {
plasma_dooplap2tile( descA, A, NB, NB, LDA, N, 0, 0, N, N, sequence, &request,
plasma_desc_mat_free(&(descA)) );
plasma_dooplap2tile( descB, B, NB, NB, LDB, NRHS, 0, 0, N, NRHS, sequence, &request,
plasma_desc_mat_free(&(descA)); plasma_desc_mat_free(&(descB)) );
plasma_ddesc_alloc( descX, NB, NB, N, NRHS, 0, 0, N, NRHS, plasma_desc_mat_free(&(descA)); plasma_desc_mat_free(&(descB)); plasma_desc_mat_free(&(descX)) );
} else {
plasma_diplap2tile( descA, A, NB, NB, LDA, N, 0, 0, N, N,
sequence, &request);
plasma_diplap2tile( descB, B, NB, NB, LDB, NRHS, 0, 0, N, NRHS,
sequence, &request);
descX = plasma_desc_init(
PlasmaRealDouble, NB, NB, (NB*NB),
LDX, NRHS, 0, 0, N, NRHS);
descX.mat = X;
}
/* Allocate workspace */
PLASMA_Alloc_Workspace_dgels_Tile(N, N, &descT);
/* Call the native interface */
status = PLASMA_dsungesv_Tile_Async(PlasmaNoTrans, &descA, descT, &descB, &descX, ITER,
sequence, &request);
if (status == PLASMA_SUCCESS) {
if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {
plasma_dooptile2lap( descX, X, NB, NB, LDX, NRHS, sequence, &request);
plasma_dynamic_sync();
plasma_desc_mat_free(&descA);
plasma_desc_mat_free(&descB);
plasma_desc_mat_free(&descX);
} else {
plasma_diptile2lap( descA, A, NB, NB, LDA, N, sequence, &request);
plasma_diptile2lap( descB, B, NB, NB, LDB, NRHS, sequence, &request);
plasma_diptile2lap( descX, X, NB, NB, LDX, NRHS, sequence, &request);
plasma_dynamic_sync();
}
}
PLASMA_Dealloc_Handle_Tile(&descT);
plasma_sequence_destroy(plasma, sequence);
return status;
}
/***************************************************************************//**
*
* @ingroup double_Tile
*
* PLASMA_dsungesv_Tile - Solves symmetric linear system of equations using the tile QR
* or the tile LQ factorization and mixed-precision iterative refinement.
* Tile equivalent of PLASMA_dsungesv().
* Operates on matrices stored by tiles.
* All matrices are passed through descriptors.
* All dimensions are taken from the descriptors.
*
*******************************************************************************
*
* @param[in] trans
* Intended usage:
* = PlasmaNoTrans: the linear system involves A;
* = PlasmaTrans: the linear system involves A**H.
* Currently only PlasmaNoTrans is supported.
*
* @param[in,out] A
* - If the iterative refinement converged, A is not modified;
* - otherwise, it fell back to double precision solution, and
* on exit the M-by-N matrix A contains:
* if M >= N, A is overwritten by details of its QR factorization as returned by
* PLASMA_dgeqrf;
* if M < N, A is overwritten by details of its LQ factorization as returned by
* PLASMA_dgelqf.
*
* @param[out] T
* On exit:
* - if the iterative refinement converged, T is not modified;
* - otherwise, it fell back to double precision solution,
* and then T is an auxiliary factorization data.
*
* @param[in,out] B
* On entry, the M-by-NRHS matrix B of right hand side vectors, stored columnwise;
* @param[in] B
* The N-by-NRHS matrix of right hand side matrix B.
*
* @param[out] X
* If return value = 0, X is the solution vectors, stored columnwise:
* if M >= N, rows 1 to N of X contain the least squares solution vectors; the residual
* sum of squares for the solution in each column is given by the sum of squares of the
* modulus of elements N+1 to M in that column;
* if M < N, rows 1 to N of X contain the minimum norm solution vectors;
*
* @param[out] ITER
* The number of the current iteration in the iterative refinement process
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
*
*******************************************************************************
*
* @sa PLASMA_dsungesv
* @sa PLASMA_dsungesv_Tile_Async
* @sa PLASMA_dsungesv_Tile
* @sa PLASMA_dgels_Tile
*
******************************************************************************/
int PLASMA_dsungesv_Tile(PLASMA_enum trans, PLASMA_desc *A, PLASMA_desc *T,
PLASMA_desc *B, PLASMA_desc *X, int *ITER)
{
plasma_context_t *plasma;
PLASMA_sequence *sequence = NULL;
PLASMA_request request = PLASMA_REQUEST_INITIALIZER;
int status;
plasma = plasma_context_self();
if (plasma == NULL) {
plasma_fatal_error("PLASMA_dsungesv_Tile", "PLASMA not initialized");
return PLASMA_ERR_NOT_INITIALIZED;
}
plasma_sequence_create(plasma, &sequence);
status = PLASMA_dsungesv_Tile_Async(trans, A, T, B, X, ITER, sequence, &request);
if (status != PLASMA_SUCCESS)
return status;
plasma_dynamic_sync();
status = sequence->status;
plasma_sequence_destroy(plasma, sequence);
return status;
}
/***************************************************************************//**
*
* @ingroup double_Tile_Async
*
* PLASMA_dsungesv_Tile_Async - Solves symmetric linear system of equations using
* the tile QR or the tile LQ factorization and mixed-precision iterative refinement.
* Non-blocking equivalent of PLASMA_dsungesv_Tile().
* May return before the computation is finished.
* Allows for pipelining of operations at runtime.
*
*******************************************************************************
*
* @param[in] sequence
* Identifies the sequence of function calls that this call belongs to
* (for completion checks and exception handling purposes).
*
* @param[out] request
* Identifies this function call (for exception handling purposes).
*
*******************************************************************************
*
* @sa PLASMA_dsungesv
* @sa PLASMA_dsungesv_Tile
* @sa PLASMA_dsungesv_Tile_Async
* @sa PLASMA_dgels_Tile_Async
*
******************************************************************************/
int PLASMA_dsungesv_Tile_Async(PLASMA_enum trans, PLASMA_desc *A, PLASMA_desc *T,
PLASMA_desc *B, PLASMA_desc *X, int *ITER,
PLASMA_sequence *sequence, PLASMA_request *request)
{
int N, NB, IB;
PLASMA_desc descA;
PLASMA_desc descT;
PLASMA_desc descB;
PLASMA_desc descX;
PLASMA_desc descR, descSA, descST, descSX;
plasma_context_t *plasma;
double *work;
const int itermax = 30;
const double bwdmax = 1.0;
const double negone = -1.0;
const double one = 1.0;
int iiter;
double Anorm, cte, eps, Rnorm, Xnorm;
*ITER=0;
plasma = plasma_context_self();
if (plasma == NULL) {
plasma_fatal_error("PLASMA_dsungesv_Tile", "PLASMA not initialized");
return PLASMA_ERR_NOT_INITIALIZED;
}
if (sequence == NULL) {
plasma_fatal_error("PLASMA_dsungesv_Tile", "NULL sequence");
return PLASMA_ERR_UNALLOCATED;
}
if (request == NULL) {
plasma_fatal_error("PLASMA_dsungesv_Tile", "NULL request");
return PLASMA_ERR_UNALLOCATED;
}
/* Check sequence status */
if (sequence->status == PLASMA_SUCCESS)
request->status = PLASMA_SUCCESS;
else
return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);
/* Check descriptors for correctness */
if (plasma_desc_check(A) != PLASMA_SUCCESS) {
plasma_error("PLASMA_dsungesv_Tile", "invalid first descriptor");
return PLASMA_ERR_ILLEGAL_VALUE;
} else {
descA = *A;
}
if (plasma_desc_check(T) != PLASMA_SUCCESS) {
plasma_error("PLASMA_dsungesv_Tile", "invalid second descriptor");
return PLASMA_ERR_ILLEGAL_VALUE;
} else {
descT = *T;
}
if (plasma_desc_check(B) != PLASMA_SUCCESS) {
plasma_error("PLASMA_dsungesv_Tile", "invalid third descriptor");
return PLASMA_ERR_ILLEGAL_VALUE;
} else {
descB = *B;
}
if (plasma_desc_check(X) != PLASMA_SUCCESS) {
plasma_error("PLASMA_dsungesv_Tile", "invalid fourth descriptor");
return PLASMA_ERR_ILLEGAL_VALUE;
} else {
descX = *X;
}
/* Check input arguments */
if ( (descA.nb != descA.mb) || (descB.nb != descB.mb) || (descX.nb != descX.mb) ||
(descA.mb != descB.mb) || (descB.mb != descX.mb) ) {
plasma_error("PLASMA_dsungesv_Tile", "only square tiles of same size are supported");
return PLASMA_ERR_ILLEGAL_VALUE;
}
if (trans != PlasmaNoTrans) {
plasma_error("PLASMA_dsungesv_Tile", "only PlasmaNoTrans supported");
return PLASMA_ERR_NOT_SUPPORTED;
}
/* Set N, NRHS, NB */
N = descA.m;
NB = descA.nb;
IB = descT.mb;
work = (double *)plasma_shared_alloc(plasma, PLASMA_SIZE, PlasmaRealDouble);
if (work == NULL) {
plasma_error("PLASMA_dsungesv", "plasma_shared_alloc() failed");
plasma_shared_free(plasma, work);
return PLASMA_ERR_OUT_OF_RESOURCES;
}
plasma_ddesc_alloc( descR, NB, NB, descB.m, descB.n, 0, 0, descB.m, descB.n, plasma_shared_free( plasma, work ); plasma_desc_mat_free(&descR) );
plasma_sdesc_alloc( descSA, NB, NB, descA.m, descA.n, 0, 0, descA.m, descA.n, plasma_shared_free( plasma, work ); plasma_desc_mat_free(&descR); plasma_desc_mat_free(&descSA) );
plasma_sdesc_alloc( descST, IB, NB, descT.m, descT.n, 0, 0, descT.m, descT.n, plasma_shared_free( plasma, work ); plasma_desc_mat_free(&descR); plasma_desc_mat_free(&descSA); plasma_desc_mat_free(&descST) );
plasma_sdesc_alloc( descSX, NB, NB, descX.m, descX.n, 0, 0, descX.m, descX.n, plasma_shared_free( plasma, work ); plasma_desc_mat_free(&descR); plasma_desc_mat_free(&descSA); plasma_desc_mat_free(&descST); plasma_desc_mat_free(&descSX) );
/* Compute some constants */
PLASMA_dlange(PlasmaInfNorm, descA, Anorm, work);
eps = LAPACKE_dlamch_work('e');
/* Convert B from double precision to single precision and store
the result in SX. */
PLASMA_dlag2s(descB, descSX);
if (sequence->status != PLASMA_SUCCESS)
return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);
/* Convert A from double precision to single precision and store
the result in SA. */
PLASMA_dlag2s(descA, descSA);
if (sequence->status != PLASMA_SUCCESS)
return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);
/* Compute the QR factorization of SA */
plasma_parallel_call_4(plasma_psgeqrf,
PLASMA_desc, descSA,
PLASMA_desc, descST,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
/* Compute the solve in simple */
plasma_parallel_call_7(plasma_psormqr,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaTrans,
PLASMA_desc, descSA,
PLASMA_desc, descSX,
PLASMA_desc, descST,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_parallel_call_9(plasma_pstrsm,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaUpper,
PLASMA_enum, PlasmaNoTrans,
PLASMA_enum, PlasmaNonUnit,
float, 1.0,
PLASMA_desc, descSA,
PLASMA_desc, descSX,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
/* Convert SX back to double precision */
PLASMA_slag2d(descSX, descX);
/* Compute R = B - AX. */
PLASMA_dlacpy(descB, descR);
plasma_parallel_call_9(plasma_pdgemm,
PLASMA_enum, PlasmaNoTrans,
PLASMA_enum, PlasmaNoTrans,
double, negone,
PLASMA_desc, descA,
PLASMA_desc, descX,
double, one,
PLASMA_desc, descR,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
/* Check whether the NRHS normwise backward error satisfies the
stopping criterion. If yes return. Note that ITER=0 (already set). */
PLASMA_dlange(PlasmaInfNorm, descX, Xnorm, work);
PLASMA_dlange(PlasmaInfNorm, descR, Rnorm, work);
/* Wait for the end of Anorm, Xnorm and Bnorm computations */
plasma_dynamic_sync();
cte = Anorm*eps*((double) N)*bwdmax;
if (Rnorm < Xnorm * cte){
/* The NRHS normwise backward errors satisfy the
stopping criterion. We are good to exit. */
plasma_desc_mat_free(&descSA);
plasma_desc_mat_free(&descST);
plasma_desc_mat_free(&descSX);
plasma_desc_mat_free(&descR);
plasma_shared_free(plasma, work);
return PLASMA_SUCCESS;
}
/* Iterative refinement */
for (iiter = 0; iiter < itermax; iiter++){
/* Convert R from double precision to single precision
and store the result in SX. */
PLASMA_dlag2s(descR, descSX);
plasma_parallel_call_7(plasma_psormqr,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaTrans,
PLASMA_desc, descSA,
PLASMA_desc, descSX,
PLASMA_desc, descST,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_parallel_call_9(plasma_pstrsm,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaUpper,
PLASMA_enum, PlasmaNoTrans,
PLASMA_enum, PlasmaNonUnit,
float, (float)1.0,
PLASMA_desc, descSA,
PLASMA_desc, descSX,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
/* Convert SX back to double precision and update the current
iterate. */
PLASMA_slag2d(descSX, descR);
PLASMA_dgeadd(one, descR, descX);
/* Compute R = B - AX. */
PLASMA_dlacpy(descB,descR);
plasma_parallel_call_9(plasma_pdgemm,
PLASMA_enum, PlasmaNoTrans,
PLASMA_enum, PlasmaNoTrans,
double, negone,
PLASMA_desc, descA,
PLASMA_desc, descX,
double, one,
PLASMA_desc, descR,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
/* Check whether the NRHS normwise backward errors satisfy the
stopping criterion. If yes, set ITER=IITER>0 and return. */
PLASMA_dlange(PlasmaInfNorm, descX, Xnorm, work);
PLASMA_dlange(PlasmaInfNorm, descR, Rnorm, work);
/* Wait for the end of Xnorm and Bnorm computations */
plasma_dynamic_sync();
if (Rnorm < Xnorm * cte){
/* The NRHS normwise backward errors satisfy the
stopping criterion. We are good to exit. */
*ITER = iiter;
plasma_desc_mat_free(&descSA);
plasma_desc_mat_free(&descST);
plasma_desc_mat_free(&descSX);
plasma_desc_mat_free(&descR);
plasma_shared_free(plasma, work);
return PLASMA_SUCCESS;
}
}
/* We have performed ITER=itermax iterations and never satisified
the stopping criterion, set up the ITER flag accordingly and
follow up on double precision routine. */
*ITER = -itermax - 1;
plasma_desc_mat_free(&descSA);
plasma_desc_mat_free(&descST);
plasma_desc_mat_free(&descSX);
plasma_desc_mat_free(&descR);
plasma_shared_free(plasma, work);
/* Single-precision iterative refinement failed to converge to a
satisfactory solution, so we restart to double precision. */
PLASMA_dlacpy(descB, descX);
plasma_parallel_call_4(plasma_pdgeqrf,
PLASMA_desc, descA,
PLASMA_desc, descT,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_parallel_call_7(plasma_pdormqr,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaTrans,
PLASMA_desc, descA,
PLASMA_desc, descX,
PLASMA_desc, descT,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_parallel_call_9(plasma_pdtrsm,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaUpper,
PLASMA_enum, PlasmaNoTrans,
PLASMA_enum, PlasmaNonUnit,
double, (double)1.0,
PLASMA_desc, descA,
PLASMA_desc, descX,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
return PLASMA_SUCCESS;
}
|
#ifndef TOOLS_H
#define TOOLS_H
#include <iostream>
#include <string>
#include <vector>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <math.h>
using namespace std;
//required for TRACE / DEBUG
extern int indentLevel;
extern string BLANKLINE;
//how many blanks to indent
#define INDENTATION 2
#define INDENT BLANKLINE.substr(0,(indentLevel)*INDENTATION)
#define INDENT_INC BLANKLINE.substr(0,(indentLevel++)*INDENTATION)
#define INDENT_DEC BLANKLINE.substr(0,(--indentLevel)*INDENTATION)
#define MAX(x,y) ((x) > (y) ? (x) : (y))
#define ABS(x) ((x)>0 ? (x) : -(x))
#ifdef STDOUT
#define OUTPUT(x) cout << INDENT << (x) <<"\n";
#define OUTPUT1(x,arg1) cout << INDENT << (x) <<arg1<<"\n";
#define OUTPUT2(x,arg1,arg2) cout << INDENT << (x) <<arg1<<" / " <<arg2<<"\n";
#else
#define OUTPUT(x) ""
#define OUTPUT1(x,arg1) ""
#define OUTPUT2(x,arg1,arg2) ""
#endif //STDOUT
#ifdef TRACE
#define TRACE_IN(x) cout << INDENT_INC << "***TRACE_IN: "<< (x) <<"()\n";
#define TRACE_IN1(x,arg1) cout << INDENT_INC << "***TRACE_IN: "<< (x) <<"("<<arg1<<")\n";
#define TRACE_OUT(x,ok) cout << INDENT_DEC << "***TRACE_OUT: "<< (x) <<"() = " << ok << "\n";
#else
#define TRACE_IN(x) ""
#define TRACE_IN1(x,arg1) ""
#define TRACE_OUT(x,ok) ""
#endif //TRACE
#ifdef TRACEV
#define TRACEV_IN(x) cout << INDENT_INC << "***TRACE_IN: "<< (x) <<"()\n";
#define TRACEV_IN1(x,arg1) cout << INDENT_INC << "***TRACE_IN: "<< (x) <<"("<<arg1<<")\n";
#define TRACEV_OUT(x,ok) cout << INDENT_DEC << "***TRACE_OUT: "<< (x) <<"() = " << ok << "\n";
#else
#define TRACEV_IN(x) ""
#define TRACEV_IN1(x,arg1) ""
#define TRACEV_OUT(x,ok) ""
#endif //TRACEV
#ifdef DBUG
#define DEBUG(x) cout << INDENT << "***DEBUG: "<< (x) <<"\n";
#define DEBUG1(x,arg1) cout << INDENT << "***DEBUG: "<< (x) <<arg1<<"\n";
#define DEBUG2(x,arg1,arg2) cout << INDENT << "***DEBUG: "<< (x) <<arg1<<" / " <<arg2<<"\n";
#else
#define DEBUG(x) ""
#define DEBUG1(x,arg1) ""
#define DEBUG2(x,arg1,arg2) ""
#endif //DBUG
//verbose debug information
//mainly exact positions (quite big with dim=30)
#ifdef DBUGV
#define DEBUGV(x) cout << "***DEBUG: "<< (x) <<"\n";
#define DEBUGV1(x,arg1) cout << "***DEBUG: "<< (x) <<arg1<<"\n";
#define DEBUGV2(x,arg1,arg2) cout << "***DEBUG: "<< (x) <<arg1<<" / " <<arg2<<"\n";
#else
#define DEBUGV(x) ""
#define DEBUGV1(x,arg1) ""
#define DEBUGV2(x,arg1,arg2) ""
#endif //DBUGV
///Little helper function calculating the maximum height
/**of a regularly built pyramid of
*@param minDegree minimum degree*/
int getMaxHeight(int minDegree, int swarmsize);
//fix the seed for the global RNG
void fixSeed(unsigned seed);
///Free the RNG ressources
void freeRng();
///Return gaussian distributed double from [0;1)
double randDoubleGaussian(double sigma);
///Return double from [0;1)
double randDouble();
///Wrapper to GSL Function call
/**Returns double from range [min,max)*/
double randDoubleRange(double min, double max);
///Wrapper to GSL Function call
/**Returns int from range [min,max]*/
int randIntRange(int min, int max);
string printVec(const vector<double>&);
double euclideanDistance(const vector<double>& v1, const vector<double>& v2);
///Generate a reproducable sequence
/**The seed is passed and thus the sequence is repeatable*/
class SequenceGenerator {
public:
///Pass the seed
SequenceGenerator(unsigned seed_in);
///Destructor
~SequenceGenerator();
///Return exponentially distributed random variable, with mean mu
double nextDoubleExponential(double mu);
///Wrapper to GSL Function call
/**Returns double from range [min,max)*/
double nextDoubleRange(double min, double max);
///Wrapper to GSL Function call
/**Returns int from range [min,max]*/
int nextIntRange(int min, int max);
private:
///The random number generator
gsl_rng* randGen;
///The random seed defining the sequence
unsigned seed;
};
#endif //ifndef TOOLS_H
|
(* ***************************************************************** *)
(* *)
(* Released: 2021/05/31. *)
(* Due: 2021/06/04, 23:59:59, CST. *)
(* *)
(* 0. Read instructions carefully before start writing your answer. *)
(* *)
(* 1. You should not add any hypotheses in this assignment. *)
(* Necessary ones have been provided for you. *)
(* *)
(* 2. In order to check whether you have finished all tasks or not, *)
(* just see whether all "Admitted" has been replaced. *)
(* *)
(* 3. You should submit this file (Assignment10.v) on CANVAS. *)
(* *)
(* 4. Only valid Coq files are accepted. In other words, please *)
(* make sure that your file does not generate a Coq error. A *)
(* way to check that is: click "compile buffer" for this file *)
(* and see whether an "Assignment10.vo" file is generated. *)
(* *)
(* 5. Do not copy and paste others' answer. *)
(* *)
(* 6. Using any theorems and/or tactics provided by Coq's standard *)
(* library is allowed in this assignment, if not specified. *)
(* *)
(* 7. When you finish, answer the following question: *)
(* *)
(* Who did you discuss with when finishing this *)
(* assignment? Your answer to this question will *)
(* NOT affect your grade. *)
(* (* FILL IN YOUR ANSWER HERE AS COMMENT *) *)
(* *)
(* ***************************************************************** *)
Require Import Coq.Strings.String.
Require Import Coq.Lists.List.
Require Import Coq.ZArith.ZArith.
Require Import PL.RTClosure.
Require Import PL.Lambda.
(* ################################################################# *)
(** * Task 1: Progress And Preservation *)
Module Task1.
Import LambdaIB.
Local Open Scope Z.
Local Open Scope string.
(** In this task, you need to answer some basic questions about lambda
expressions with integers and booleans involved (references are not
involved). We have seen the definition of [do_it_three_times] and
[add_one] in class. *)
Definition do_it_three_times: tm :=
abs "f" (abs "x" (app "f" (app "f" (app "f" "x")))).
Definition add_one: tm :=
abs "x" (app (app Oplus "x") 1).
(** Please prove that the following expression is well-typed. Hint: you may use
[type_of_add_one] and [type_of_do_it_three_times] in this proof. *)
(* type_of_add_one: empty_context |- add_one \in (TInt ~> TInt) *)
(* type_of_do_it_three_times: forall T,
empty_context |- do_it_three_times \in ((T ~> T) ~> (T ~> T)) *)
(** **** Exercise: 2 stars, standard (power_3_3_well_typed) *)
Lemma power_3_3_well_typed:
empty_context |- app (app do_it_three_times do_it_three_times) add_one \in
(TInt ~> TInt).
Proof.
eapply T_app.
2: apply type_of_add_one.
eapply T_app.
+ apply type_of_do_it_three_times.
+ apply type_of_do_it_three_times.
Qed.
(** [] *)
(** Obviously, we can take at least one step to in the process of evaluating
this expression above. In other words, the following statement is true: *)
Definition step_statement: Prop :=
exists step_result: tm,
step (app (app do_it_three_times do_it_three_times) add_one) step_result.
(** On one hand, we can prove this statement above by providing a [step_result]
explicitly and prove the step relation. What is that step result? *)
(** **** Exercise: 1 star, standard (step_result) *)
Definition step_result: tm :=
app (abs "x" (app do_it_three_times
(app do_it_three_times (app do_it_three_times "x")))) add_one.
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *)
(** [] *)
(** On the other hand, we know that step result must exists since lambda
expression evaluation is type safe. Which type safety property proves this
existences lemma?
1. Progress. 2. Preservation. *)
(** **** Exercise: 1 star, standard *)
Definition my_choice1: Z := 1.
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *)
(** [] *)
(** Moreover, from type safety, we know that the [step_result] is also well
typed. In other words, *)
Definition step_result_type_statement: Prop :=
empty_context |- step_result \in (TInt ~> TInt).
(** Which type safety property proves this claim?
1. Progress. 2. Preservation. *)
(** **** Exercise: 1 star, standard *)
Definition my_choice2: Z := 2.
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *)
(** [] *)
End Task1.
(* ################################################################# *)
(** * Task 2: Let In Lambda Expressions *)
Module Task2.
Import LambdaIBR.
Local Open Scope Z.
Local Open Scope string.
(** We have seen how to encode "let" expression using normal lambda expressions.
Please describe the evaluation result of the following lambda expressions.
*)
Module Task2_Example.
Definition expression: tm := \let "x" \be (app Onot true) \in "x".
Definition eval_result: tm := false.
(** Remember, when we write [false] here, it actually means
- [con (bool_const (false))].
*)
End Task2_Example.
(** **** Exercise: 1 star, standard *)
Module Task2_1.
Definition expression: tm :=
\let "x" \be 1 \in
\let "y" \be ("x" + 1)%tm \in
\let "x" \be ("y" + 1)%tm \in
"x".
Definition eval_result: tm := 3.
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *)
(** [] *)
End Task2_1.
(** **** Exercise: 1 star, standard *)
Module Task2_2.
Definition expression: tm :=
\let "x" \be app (abs "x" "x") 1 \in
"x".
Definition eval_result: tm := 1.
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *)
(** [] *)
End Task2_2.
(** **** Exercise: 1 star, standard *)
Module Task2_3.
Definition expression: tm :=
\let "F" \be
(abs "f" (abs "x"
(\let "x" \be app "f" "x" \in
\let "x" \be app "f" "x" \in
\let "x" \be app "f" "x" \in
"x"))) \in
app (app (app "F" "F") (abs "x" ("x" + 1)%tm)) 0.
Definition eval_result: tm := 27.
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *)
(** [] *)
End Task2_3.
(** **** Exercise: 1 star, standard *)
Module Task2_4.
Definition expression: tm :=
\let "swap_arg" \be
(abs "f" (abs "x" (abs "y" (app (app "f" "y") "x")))) \in
app "swap_arg" (abs "x" (abs "y" ("x" - "y")%tm)).
Definition eval_result: tm :=
abs "x" (abs "y" (app (app
(abs "x" (abs "y" ("x" - "y")%tm)) "y") "x")).
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *)
(** [] *)
End Task2_4.
End Task2.
(* ################################################################# *)
(** * Lambda Expressions With References *)
Module Task3.
Import LambdaIBR.
Local Open Scope Z.
Local Open Scope string.
(** Please describe the evaluation results. *)
(** **** Exercise: 2 stars, standard *)
Module Task3_1.
Definition expression: tm :=
\let "get_and_add" \be
(abs "p"
(\let "x" \be (app Oread "p") \in
\let "y" \be ("x" + 1)%tm \in
\let "_" \be (app (app Owrite "p") "y") \in
"x")) \in
\let "p" \be app Oalloc 0 \in
\let "x" \be app "get_and_add" "p" \in
\let "x" \be app "get_and_add" "p" \in
\let "x" \be app "get_and_add" "p" \in
"x".
Definition eval_result: tm := 2.
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *)
(** [] *)
End Task3_1.
(** **** Exercise: 2 stars, standard *)
Module Task3_2.
Definition expression: tm :=
\let "func_add_one" \be
(abs "f" (abs "x" ((app "f" "x") + 1)%tm)) \in
\let "f" \be (abs "x" "x") \in
\let "p" \be (app Oalloc "f") \in
\let "f" \be (app "func_add_one" (app Oread "p")) \in
\let "p" \be (app Oalloc "f") \in
\let "f" \be (app "func_add_one" (app Oread "p")) \in
app "f" 0.
Definition eval_result: tm := 2.
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *)
(** [] *)
End Task3_2.
End Task3.
(* 2021-05-31 21:29 *)
|
Formal statement is: lemma complex_split_polar: "\<exists>r a. z = complex_of_real r * (cos a + \<i> * sin a)" Informal statement is: Every complex number can be written as $r(\cos a + i \sin a)$ for some real numbers $r$ and $a$.
|
module AllTests where
import Issue14
import LanguageConstructs
import Numbers
import Pragmas
import Sections
import Test
import Tuples
import Where
{-# FOREIGN AGDA2HS
import Issue14
import LanguageConstructs
import Numbers
import Pragmas
import Sections
import Test
import Tuples
import Where
#-}
|
[STATEMENT]
lemma pos_le_minus_divideC_eq [field_simps]:
"a \<le> - (b /\<^sub>C c) \<longleftrightarrow> c *\<^sub>C a \<le> - b" if "c > 0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (a \<le> - (b /\<^sub>C c)) = (c *\<^sub>C a \<le> - b)
[PROOF STEP]
using that
[PROOF STATE]
proof (prove)
using this:
0 < c
goal (1 subgoal):
1. (a \<le> - (b /\<^sub>C c)) = (c *\<^sub>C a \<le> - b)
[PROOF STEP]
by (metis local.ab_left_minus local.add.inverse_unique local.add.right_inverse local.add_minus_cancel local.le_minus_iff local.pos_divideC_le_eq local.scaleC_add_right local.scaleC_one local.scaleC_scaleC)
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Dh=hammingDist(B1, B2)
%
% Written by Rob Fergus
% Compute hamming distance between two sets of samples (B1, B2)
%
% Dh=hammingDist(B1, B2);
%
% Input
% B1, B2: compact bit vectors. Each datapoint is one row.
% size(B1) = [ndatapoints1, nwords]
% size(B2) = [ndatapoints2, nwords]
% It is faster if ndatapoints1 < ndatapoints2
%
% Output
% Dh = hamming distance.
% size(Dh) = [ndatapoints1, ndatapoints2]
%
% example query
% Dhamm = hammingDist(B2, B1);
% this will give the same result than:
% Dhamm = distMat(U2>0, U1>0).^2;
% the size of the distance matrix is:
% size(Dhamm) = [Ntest x Ntraining]
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% loop-up table:
bit_in_char = uint16([...
0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4 1 2 2 3 2 3 ...
3 4 2 3 3 4 3 4 4 5 1 2 2 3 2 3 3 4 2 3 3 4 ...
3 4 4 5 2 3 3 4 3 4 4 5 3 4 4 5 4 5 5 6 1 2 ...
2 3 2 3 3 4 2 3 3 4 3 4 4 5 2 3 3 4 3 4 4 5 ...
3 4 4 5 4 5 5 6 2 3 3 4 3 4 4 5 3 4 4 5 4 5 ...
5 6 3 4 4 5 4 5 5 6 4 5 5 6 5 6 6 7 1 2 2 3 ...
2 3 3 4 2 3 3 4 3 4 4 5 2 3 3 4 3 4 4 5 3 4 ...
4 5 4 5 5 6 2 3 3 4 3 4 4 5 3 4 4 5 4 5 5 6 ...
3 4 4 5 4 5 5 6 4 5 5 6 5 6 6 7 2 3 3 4 3 4 ...
4 5 3 4 4 5 4 5 5 6 3 4 4 5 4 5 5 6 4 5 5 6 ...
5 6 6 7 3 4 4 5 4 5 5 6 4 5 5 6 5 6 6 7 4 5 ...
5 6 5 6 6 7 5 6 6 7 6 7 7 8]);
n1 = size(B1,1);
[n2, nwords] = size(B2);
Dh = zeros([n1 n2], 'uint16');
for j = 1:n1
for n=1:nwords
y = bitxor(B1(j,n),B2(:,n));
Dh(j,:) = Dh(j,:) + bit_in_char(y+1);
end
end
|
[STATEMENT]
lemma p_eq_f:
assumes "k > 0" "k \<le> n"
shows "p k = f k"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. p k = f k
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
0 < k
k \<le> n
goal (1 subgoal):
1. p k = f k
[PROOF STEP]
proof (induction k rule: less_induct)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x. \<lbrakk>\<And>y. \<lbrakk>y < x; 0 < y; y \<le> n\<rbrakk> \<Longrightarrow> p y = f y; 0 < x; x \<le> n\<rbrakk> \<Longrightarrow> p x = f x
[PROOF STEP]
case (less k)
[PROOF STATE]
proof (state)
this:
\<lbrakk>?y < k; 0 < ?y; ?y \<le> n\<rbrakk> \<Longrightarrow> p ?y = f ?y
0 < k
k \<le> n
goal (1 subgoal):
1. \<And>x. \<lbrakk>\<And>y. \<lbrakk>y < x; 0 < y; y \<le> n\<rbrakk> \<Longrightarrow> p y = f y; 0 < x; x \<le> n\<rbrakk> \<Longrightarrow> p x = f x
[PROOF STEP]
thus "p k = f k"
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>?y < k; 0 < ?y; ?y \<le> n\<rbrakk> \<Longrightarrow> p ?y = f ?y
0 < k
k \<le> n
goal (1 subgoal):
1. p k = f k
[PROOF STEP]
using p_recurrence[of k] f_recurrence[of k] less
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>?y < k; 0 < ?y; ?y \<le> n\<rbrakk> \<Longrightarrow> p ?y = f ?y
0 < k
k \<le> n
0 < k \<Longrightarrow> p k = - of_nat k * (- 1) ^ k * e k - (\<Sum>i = 1..<k. (- 1) ^ i * e i * p (k - i))
\<lbrakk>0 < k; k \<le> n\<rbrakk> \<Longrightarrow> f k = - of_nat k * (- 1) ^ k * e' k - (\<Sum>i = 1..<k. (- 1) ^ i * e' i * f (k - i))
\<lbrakk>?y < k; 0 < ?y; ?y \<le> n\<rbrakk> \<Longrightarrow> p ?y = f ?y
0 < k
k \<le> n
goal (1 subgoal):
1. p k = f k
[PROOF STEP]
by (simp add: e'_eq_e)
[PROOF STATE]
proof (state)
this:
p k = f k
goal:
No subgoals!
[PROOF STEP]
qed
|
import Base.show, Base.summary
export show, summary
using AbstractTrees: AbstractTrees
using .TreePrint
"""
const MAXDEPTH = Ref(3)
Controls depth of tree printing globally for Convex.jl
"""
const MAXDEPTH = Ref(3)
"""
const MAXWIDTH = Ref(15)
Controls width of tree printing globally for Convex.jl
"""
const MAXWIDTH= Ref(15)
"""
show_id(io::IO, x::Union{AbstractExpr, Constraint}; digits = 3)
Print a truncated version of the objects `id_hash` field.
## Example
```julia-repl
julia> x = Variable();
julia> Convex.show_id(stdout, x)
id: 163…906
```
"""
show_id(io::IO, x::Union{AbstractExpr, Constraint}; digits = 3) = print(io, show_id(x; digits=digits))
function show_id(x::Union{AbstractExpr, Constraint}; digits = 3)
hash_str = string(x.id_hash)
return "id: " * first(hash_str, digits) * "…" * last(hash_str, digits)
end
"""
Base.summary(io::IO, x::Variable)
Prints a one-line summary of a variable `x` to `io`.
## Examples
```julia-repl
julia> x = ComplexVariable(3,2);
julia> summary(stdout, x)
3×2 complex variable (id: 732…737)
```
"""
function Base.summary(io::IO, x::Variable)
sgn = summary(sign(x))
cst = vexity(x) == ConstVexity() ? " (fixed)" : ""
cst = cst * " (" * sprint(show_id, x) * ")"
if size(x) == (1,1)
print(io, "$(sgn) variable$(cst)")
elseif size(x,2) == 1
print(io, "$(size(x,1))-element $(sgn) variable$(cst)")
else
print(io, "$(size(x,1))×$(size(x,2)) $(sgn) variable$(cst)")
end
end
Base.summary(io::IO, ::AffineVexity) = print(io, "affine")
Base.summary(io::IO, ::ConvexVexity) = print(io, "convex")
Base.summary(io::IO, ::ConcaveVexity) = print(io, "concave")
Base.summary(io::IO, ::ConstVexity) = print(io, "constant")
Base.summary(io::IO, ::Positive) = print(io, "positive")
Base.summary(io::IO, ::Negative) = print(io, "negative")
Base.summary(io::IO, ::NoSign) = print(io, "real")
Base.summary(io::IO, ::ComplexSign) = print(io, "complex")
function Base.summary(io::IO, c::Constraint)
print(io, "$(c.head) constraint (")
summary(io, vexity(c))
print(io, ")")
end
function Base.summary(io::IO, e::AbstractExpr)
print(io, "$(e.head) (")
summary(io, vexity(e))
print(io, "; ")
summary(io, sign(e))
print(io, ")")
end
# A Constant is simply a wrapper around a native Julia constant
# Hence, we simply display its value
show(io::IO, x::Constant) = print(io, x.value)
# A variable, for example, Variable(3, 4), will be displayed as:
# julia> Variable(3,4)
# Variable
# size: (3, 4)
# sign: real
# vexity: affine
# id: 758…633
# here, the `id` will change from run to run.
function show(io::IO, x::Variable)
print(io, "Variable")
print(io, "\nsize: $(size(x))")
print(io, "\nsign: ")
summary(io, sign(x))
print(io, "\nvexity: ")
summary(io, vexity(x))
println(io)
show_id(io, x)
if x.value !== nothing
print(io, "\nvalue: $(x.value)")
end
end
"""
print_tree_rstrip(io::IO, x)
Prints the results of `TreePrint.print_tree(io, x)`
without the final newline. Used for `show` methods which
invoke `print_tree`.
"""
function print_tree_rstrip(io::IO, x)
str = sprint(TreePrint.print_tree, x, MAXDEPTH[], MAXWIDTH[])
print(io, rstrip(str))
end
# This object is used to work around the fact that
# Convex overloads booleans for AbstractExpr's
# in order to generate constraints. This is problematic
# for `AbstractTrees.print_tree` which wants to compare
# the root of the tree to itself at some point.
# By wrapping all tree roots in structs, this comparison
# occurs on the level of the `struct`, and `==` falls
# back to object equality (`===`), which is what we
# want in this case.
#
# The same construct is used below for other tree roots.
struct ConstraintRoot
constraint::Constraint
end
TreePrint.print_tree(io::IO, c::Constraint, args...; kwargs...) = TreePrint.print_tree(io, ConstraintRoot(c), args...; kwargs...)
AbstractTrees.children(c::ConstraintRoot) = AbstractTrees.children(c.constraint)
AbstractTrees.printnode(io::IO, c::ConstraintRoot) = AbstractTrees.printnode(io, c.constraint)
show(io::IO, c::Constraint) = print_tree_rstrip(io, c)
struct ExprRoot
expr::AbstractExpr
end
TreePrint.print_tree(io::IO, e::AbstractExpr, args...; kwargs...) = TreePrint.print_tree(io, ExprRoot(e), args...; kwargs...)
AbstractTrees.children(e::ExprRoot) = AbstractTrees.children(e.expr)
AbstractTrees.printnode(io::IO, e::ExprRoot) = AbstractTrees.printnode(io, e.expr)
show(io::IO, e::AbstractExpr) = print_tree_rstrip(io, e)
struct ProblemObjectiveRoot
head::Symbol
objective::AbstractExpr
end
AbstractTrees.children(p::ProblemObjectiveRoot) = (p.objective,)
AbstractTrees.printnode(io::IO, p::ProblemObjectiveRoot) = print(io, string(p.head))
struct ProblemConstraintsRoot
constraints::Vector{Constraint}
end
AbstractTrees.children(p::ProblemConstraintsRoot) = p.constraints
AbstractTrees.printnode(io::IO, p::ProblemConstraintsRoot) = print(io, "subject to")
function TreePrint.print_tree(io::IO, p::Problem, args...; kwargs...)
TreePrint.print_tree(io, ProblemObjectiveRoot(p.head, p.objective), args...; kwargs...)
if !(isempty(p.constraints))
TreePrint.print_tree(io, ProblemConstraintsRoot(p.constraints), args...; kwargs...)
end
end
function show(io::IO, p::Problem)
TreePrint.print_tree(io, p, MAXDEPTH[], MAXWIDTH[])
print(io, "\ncurrent status: $(p.status)")
if p.status == "solved"
print(io, " with optimal value of $(round(p.optval, digits=4))")
end
end
|
Formal statement is: lemma diameter_compact_attained: assumes "compact S" and "S \<noteq> {}" shows "\<exists>x\<in>S. \<exists>y\<in>S. dist x y = diameter S" Informal statement is: If $S$ is a nonempty compact set, then there exist $x, y \in S$ such that $d(x, y) = \text{diameter}(S)$.
|
/*
* PARTICLE SWARM OPTIMIZATION
* ===========================
*
* Author: Gabriel E Leventhal, 2011-12-02
*
* adapted from
* Author: Tomas V. Arredondo
* SimPSOLib: A simple yet flexible PSO implementation in C++.
*
*/
#ifndef __PSO_SWARM__
#define __PSO_SWARM__
#include <iostream>
#include <iomanip>
#include <sstream>
#include <vector>
#include <ctime>
#include <queue>
using namespace std;
#include "GSLRng.h"
#include <gsl/gsl_math.h>
#include "Particle.h"
#include "Point.h"
#include "Parameters.h"
#include "Network.h"
#ifdef USE_MPI
#include "mpi.h"
#endif
namespace PSO {
class Swarm {
public:
Swarm() {}
Swarm(int size, int np, Parameters* pars)
: swarmSize(size), numParams(np), numEvals(0), curIt(0),
numInform(3),
phiPi(np,2.5), phiPf(np,0.5), phiGi(np,0.5),phiGf(np,2.5),
omegai(np,0.721), omegaf(np,0.721), p(pars),
bestVal(-INFINITY), bestParticle(-1),
mpi_type(0), mpi_rank(0), mpi_ntasks(1)
{
bestPos = Point(np,0.0);
setInformants(numInform);
}
virtual ~Swarm() { destroy(); }
inline void setMPI(int type) { mpi_type = (type >= 0) ? type : 0; }
inline void setVars(const Point& pp, const Point& pg, const Point& o) {
phiPi = pp; phiGi = pg; omegai = o;
phiPf = pp; phiGf = pg; omegaf = o;
phiP = pp; phiG = pg; omega = o;
}
inline void setInformants(int K) {
numInform = (K > swarmSize-1) ? swarmSize-1 : K;
links.resize(swarmSize);
init_network();
}
double maximum_swarm_radius() const;
double search_space_diameter() const;
// get everything ready to go
void begin(int argc, char* argv[]);
// finish up stuff
void end();
void initialize(int type = 0);
void display(ostream* out = &cout, string prefix = "");
virtual void evaluate(int vflag = 0, ostream* out = NULL, ostream* hist = NULL);
virtual double evaluateParticle(int j);
void updateVelocity(int j, bool bestVals = true);
void updateVelocity(bool bestVals = true);
void updatePosition(int j);
void updatePosition();
void randomizeInf(int maxTries = 1000);
void randomPosition(int j);
virtual void run(int numIt, int slowdown = 0, int vflag = 0,
ostream* out = NULL, ostream* hist = NULL);
inline bool is_master() const { return (mpi_rank == 0); }
inline void seed_rng(unsigned long seed) { rng.set(seed); }
inline const Particle& at(size_t i) const { return *swarm[i]; }
inline Particle best() const { return *swarm[bestParticle]; }
inline double fitness(int i) const { return swarm.at(i)->fitness(); }
inline int size() const { return swarmSize; }
inline int nextIt() { return ++curIt; }
inline void setIt(int i) { curIt = i; }
double mean(int i) const;
double var(int i) const;
Point mean() const;
Point var() const;
#ifdef USE_MPI
virtual void evaluate_slave();
void run_mpi(int numInt, int vflag = 0, ostream* out = NULL, ostream* hist = NULL);
virtual void run_master(int numInt, int vflag, ostream* out, ostream* hist);
inline void evaluate_master(int vflag = 0) { run_master(-1,vflag,NULL,NULL); }
#endif
protected:
void create();
void destroy();
void init_network();
int find_best();
int swarmSize; /* swarm size */
vector<Particle*> swarm; /* swarm */
int numParams; /* number of parameters */
int numEvals; /* current number of function evaluations */
int curIt; /* current swarm iteration */
int numInform; /* number of informants */
Network links; /* information network */
Point phiP;
Point phiG;
Point omega;
Point phiPi; /* phiP initial */
Point phiPf; /* phiP final */
Point phiGi; /* phiG initial */
Point phiGf; /* phiG final */
Point omegai; /* omega initial */
Point omegaf; /* omega final */
Parameters* p;
double bestVal; /* current best value */
Point bestPos; /* current best position */
int bestParticle;
myGSL::Rng rng;
int mpi_type;
int mpi_rank;
int mpi_ntasks;
};
}
#endif // __PSO_SWARM__
|
/-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import set_theory.cardinal.basic
import topology.metric_space.closeds
import topology.metric_space.completion
import topology.metric_space.gromov_hausdorff_realized
import topology.metric_space.kuratowski
/-!
# Gromov-Hausdorff distance
This file defines the Gromov-Hausdorff distance on the space of nonempty compact metric spaces
up to isometry.
We introduce the space of all nonempty compact metric spaces, up to isometry,
called `GH_space`, and endow it with a metric space structure. The distance,
known as the Gromov-Hausdorff distance, is defined as follows: given two
nonempty compact spaces `X` and `Y`, their distance is the minimum Hausdorff distance
between all possible isometric embeddings of `X` and `Y` in all metric spaces.
To define properly the Gromov-Hausdorff space, we consider the non-empty
compact subsets of `ℓ^∞(ℝ)` up to isometry, which is a well-defined type,
and define the distance as the infimum of the Hausdorff distance over all
embeddings in `ℓ^∞(ℝ)`. We prove that this coincides with the previous description,
as all separable metric spaces embed isometrically into `ℓ^∞(ℝ)`, through an
embedding called the Kuratowski embedding.
To prove that we have a distance, we should show that if spaces can be coupled
to be arbitrarily close, then they are isometric. More generally, the Gromov-Hausdorff
distance is realized, i.e., there is a coupling for which the Hausdorff distance
is exactly the Gromov-Hausdorff distance. This follows from a compactness
argument, essentially following from Arzela-Ascoli.
## Main results
We prove the most important properties of the Gromov-Hausdorff space: it is a polish space,
i.e., it is complete and second countable. We also prove the Gromov compactness criterion.
-/
noncomputable theory
open_locale classical topology ennreal
local notation `ℓ_infty_ℝ`:= lp (λ n : ℕ, ℝ) ∞
universes u v w
open classical set function topological_space filter metric quotient
open bounded_continuous_function nat int Kuratowski_embedding
open sum (inl inr)
local attribute [instance] metric_space_sum
namespace Gromov_Hausdorff
section GH_space
/- In this section, we define the Gromov-Hausdorff space, denoted `GH_space` as the quotient
of nonempty compact subsets of `ℓ^∞(ℝ)` by identifying isometric sets.
Using the Kuratwoski embedding, we get a canonical map `to_GH_space` mapping any nonempty
compact type to `GH_space`. -/
/-- Equivalence relation identifying two nonempty compact sets which are isometric -/
private def isometry_rel : nonempty_compacts ℓ_infty_ℝ → nonempty_compacts ℓ_infty_ℝ → Prop :=
λ x y, nonempty (x ≃ᵢ y)
/-- This is indeed an equivalence relation -/
private lemma is_equivalence_isometry_rel : equivalence isometry_rel :=
⟨λ x, ⟨isometry_equiv.refl _⟩, λ x y ⟨e⟩, ⟨e.symm⟩, λ x y z ⟨e⟩ ⟨f⟩, ⟨e.trans f⟩⟩
/-- setoid instance identifying two isometric nonempty compact subspaces of ℓ^∞(ℝ) -/
instance isometry_rel.setoid : setoid (nonempty_compacts ℓ_infty_ℝ) :=
setoid.mk isometry_rel is_equivalence_isometry_rel
/-- The Gromov-Hausdorff space -/
definition GH_space : Type := quotient (isometry_rel.setoid)
/-- Map any nonempty compact type to `GH_space` -/
definition to_GH_space (X : Type u) [metric_space X] [compact_space X] [nonempty X] : GH_space :=
⟦nonempty_compacts.Kuratowski_embedding X⟧
instance : inhabited GH_space := ⟨quot.mk _ ⟨⟨{0}, is_compact_singleton⟩, singleton_nonempty _⟩⟩
/-- A metric space representative of any abstract point in `GH_space` -/
@[nolint has_nonempty_instance]
def GH_space.rep (p : GH_space) : Type := (quotient.out p : nonempty_compacts ℓ_infty_ℝ)
lemma eq_to_GH_space_iff {X : Type u} [metric_space X] [compact_space X] [nonempty X]
{p : nonempty_compacts ℓ_infty_ℝ} :
⟦p⟧ = to_GH_space X ↔ ∃ Ψ : X → ℓ_infty_ℝ, isometry Ψ ∧ range Ψ = p :=
begin
simp only [to_GH_space, quotient.eq],
refine ⟨λ h, _, _⟩,
{ rcases setoid.symm h with ⟨e⟩,
have f := (Kuratowski_embedding.isometry X).isometry_equiv_on_range.trans e,
use [λ x, f x, isometry_subtype_coe.comp f.isometry],
rw [range_comp, f.range_eq_univ, set.image_univ, subtype.range_coe],
refl },
{ rintros ⟨Ψ, ⟨isomΨ, rangeΨ⟩⟩,
have f := ((Kuratowski_embedding.isometry X).isometry_equiv_on_range.symm.trans
isomΨ.isometry_equiv_on_range).symm,
have E : (range Ψ ≃ᵢ nonempty_compacts.Kuratowski_embedding X) =
(p ≃ᵢ range (Kuratowski_embedding X)),
by { dunfold nonempty_compacts.Kuratowski_embedding, rw [rangeΨ]; refl },
exact ⟨cast E f⟩ }
end
lemma eq_to_GH_space {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space p :=
eq_to_GH_space_iff.2 ⟨λ x, x, isometry_subtype_coe, subtype.range_coe⟩
section
local attribute [reducible] GH_space.rep
instance rep_GH_space_metric_space {p : GH_space} : metric_space p.rep := by apply_instance
instance rep_GH_space_compact_space {p : GH_space} : compact_space p.rep := by apply_instance
instance rep_GH_space_nonempty {p : GH_space} : nonempty p.rep := by apply_instance
end
lemma GH_space.to_GH_space_rep (p : GH_space) : to_GH_space p.rep = p :=
begin
change to_GH_space (quot.out p : nonempty_compacts ℓ_infty_ℝ) = p,
rw ← eq_to_GH_space,
exact quot.out_eq p
end
/-- Two nonempty compact spaces have the same image in `GH_space` if and only if they are
isometric. -/
/-- Distance on `GH_space`: the distance between two nonempty compact spaces is the infimum
Hausdorff distance between isometric copies of the two spaces in a metric space. For the definition,
we only consider embeddings in `ℓ^∞(ℝ)`, but we will prove below that it works for all spaces. -/
instance : has_dist (GH_space) :=
{ dist := λ x y, Inf $
(λ p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ,
Hausdorff_dist (p.1 : set ℓ_infty_ℝ) p.2) '' ({a | ⟦a⟧ = x} ×ˢ {b | ⟦b⟧ = y}) }
/-- The Gromov-Hausdorff distance between two nonempty compact metric spaces, equal by definition to
the distance of the equivalence classes of these spaces in the Gromov-Hausdorff space. -/
def GH_dist (X : Type u) (Y : Type v) [metric_space X] [nonempty X] [compact_space X]
[metric_space Y] [nonempty Y] [compact_space Y] : ℝ := dist (to_GH_space X) (to_GH_space Y)
lemma dist_GH_dist (p q : GH_space) : dist p q = GH_dist p.rep (q.rep) :=
by rw [GH_dist, p.to_GH_space_rep, q.to_GH_space_rep]
/-- The Gromov-Hausdorff distance between two spaces is bounded by the Hausdorff distance
of isometric copies of the spaces, in any metric space. -/
theorem GH_dist_le_Hausdorff_dist {X : Type u} [metric_space X] [compact_space X] [nonempty X]
{Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y]
{γ : Type w} [metric_space γ] {Φ : X → γ} {Ψ : Y → γ} (ha : isometry Φ) (hb : isometry Ψ) :
GH_dist X Y ≤ Hausdorff_dist (range Φ) (range Ψ) :=
begin
/- For the proof, we want to embed `γ` in `ℓ^∞(ℝ)`, to say that the Hausdorff distance is realized
in `ℓ^∞(ℝ)` and therefore bounded below by the Gromov-Hausdorff-distance. However, `γ` is not
separable in general. We restrict to the union of the images of `X` and `Y` in `γ`, which is
separable and therefore embeddable in `ℓ^∞(ℝ)`. -/
rcases exists_mem_of_nonempty X with ⟨xX, _⟩,
let s : set γ := (range Φ) ∪ (range Ψ),
let Φ' : X → subtype s := λ y, ⟨Φ y, mem_union_left _ (mem_range_self _)⟩,
let Ψ' : Y → subtype s := λ y, ⟨Ψ y, mem_union_right _ (mem_range_self _)⟩,
have IΦ' : isometry Φ' := λ x y, ha x y,
have IΨ' : isometry Ψ' := λ x y, hb x y,
have : is_compact s, from (is_compact_range ha.continuous).union (is_compact_range hb.continuous),
letI : metric_space (subtype s) := by apply_instance,
haveI : compact_space (subtype s) := ⟨is_compact_iff_is_compact_univ.1 ‹is_compact s›⟩,
haveI : nonempty (subtype s) := ⟨Φ' xX⟩,
have ΦΦ' : Φ = subtype.val ∘ Φ', by { funext, refl },
have ΨΨ' : Ψ = subtype.val ∘ Ψ', by { funext, refl },
have : Hausdorff_dist (range Φ) (range Ψ) = Hausdorff_dist (range Φ') (range Ψ'),
{ rw [ΦΦ', ΨΨ', range_comp, range_comp],
exact Hausdorff_dist_image (isometry_subtype_coe) },
rw this,
-- Embed `s` in `ℓ^∞(ℝ)` through its Kuratowski embedding
let F := Kuratowski_embedding (subtype s),
have : Hausdorff_dist (F '' (range Φ')) (F '' (range Ψ')) =
Hausdorff_dist (range Φ') (range Ψ') := Hausdorff_dist_image (Kuratowski_embedding.isometry _),
rw ← this,
-- Let `A` and `B` be the images of `X` and `Y` under this embedding. They are in `ℓ^∞(ℝ)`, and
-- their Hausdorff distance is the same as in the original space.
let A : nonempty_compacts ℓ_infty_ℝ := ⟨⟨F '' (range Φ'), (is_compact_range IΦ'.continuous).image
(Kuratowski_embedding.isometry _).continuous⟩, (range_nonempty _).image _⟩,
let B : nonempty_compacts ℓ_infty_ℝ := ⟨⟨F '' (range Ψ'), (is_compact_range IΨ'.continuous).image
(Kuratowski_embedding.isometry _).continuous⟩, (range_nonempty _).image _⟩,
have AX : ⟦A⟧ = to_GH_space X,
{ rw eq_to_GH_space_iff,
exact ⟨λ x, F (Φ' x), (Kuratowski_embedding.isometry _).comp IΦ', range_comp _ _⟩ },
have BY : ⟦B⟧ = to_GH_space Y,
{ rw eq_to_GH_space_iff,
exact ⟨λ x, F (Ψ' x), (Kuratowski_embedding.isometry _).comp IΨ', range_comp _ _⟩ },
refine cInf_le ⟨0, _⟩ _,
{ simp only [lower_bounds, mem_image, mem_prod, mem_set_of_eq, prod.exists, and_imp,
forall_exists_index],
assume t _ _ _ _ ht,
rw ← ht,
exact Hausdorff_dist_nonneg },
apply (mem_image _ _ _).2,
existsi (⟨A, B⟩ : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
simp [AX, BY],
end
/-- The optimal coupling constructed above realizes exactly the Gromov-Hausdorff distance,
essentially by design. -/
lemma Hausdorff_dist_optimal {X : Type u} [metric_space X] [compact_space X] [nonempty X]
{Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] :
Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) = GH_dist X Y :=
begin
inhabit X, inhabit Y,
/- we only need to check the inequality `≤`, as the other one follows from the previous lemma.
As the Gromov-Hausdorff distance is an infimum, we need to check that the Hausdorff distance
in the optimal coupling is smaller than the Hausdorff distance of any coupling.
First, we check this for couplings which already have small Hausdorff distance: in this
case, the induced "distance" on `X ⊕ Y` belongs to the candidates family introduced in the
definition of the optimal coupling, and the conclusion follows from the optimality
of the optimal coupling within this family.
-/
have A : ∀ p q : nonempty_compacts ℓ_infty_ℝ, ⟦p⟧ = to_GH_space X → ⟦q⟧ = to_GH_space Y →
Hausdorff_dist (p : set ℓ_infty_ℝ) q < diam (univ : set X) + 1 + diam (univ : set Y) →
Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤
Hausdorff_dist (p : set ℓ_infty_ℝ) q,
{ assume p q hp hq bound,
rcases eq_to_GH_space_iff.1 hp with ⟨Φ, ⟨Φisom, Φrange⟩⟩,
rcases eq_to_GH_space_iff.1 hq with ⟨Ψ, ⟨Ψisom, Ψrange⟩⟩,
have I : diam (range Φ ∪ range Ψ) ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y),
{ rcases exists_mem_of_nonempty X with ⟨xX, _⟩,
have : ∃ y ∈ range Ψ, dist (Φ xX) y < diam (univ : set X) + 1 + diam (univ : set Y),
{ rw Ψrange,
have : Φ xX ∈ ↑p := Φrange.subst (mem_range_self _),
exact exists_dist_lt_of_Hausdorff_dist_lt this bound
(Hausdorff_edist_ne_top_of_nonempty_of_bounded p.nonempty q.nonempty
p.is_compact.bounded q.is_compact.bounded) },
rcases this with ⟨y, hy, dy⟩,
rcases mem_range.1 hy with ⟨z, hzy⟩,
rw ← hzy at dy,
have DΦ : diam (range Φ) = diam (univ : set X) := Φisom.diam_range,
have DΨ : diam (range Ψ) = diam (univ : set Y) := Ψisom.diam_range,
calc
diam (range Φ ∪ range Ψ) ≤ diam (range Φ) + dist (Φ xX) (Ψ z) + diam (range Ψ) :
diam_union (mem_range_self _) (mem_range_self _)
... ≤ diam (univ : set X) + (diam (univ : set X) + 1 + diam (univ : set Y)) +
diam (univ : set Y) :
by { rw [DΦ, DΨ], apply add_le_add (add_le_add le_rfl (le_of_lt dy)) le_rfl }
... = 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : by ring },
let f : X ⊕ Y → ℓ_infty_ℝ := λ x, match x with | inl y := Φ y | inr z := Ψ z end,
let F : (X ⊕ Y) × (X ⊕ Y) → ℝ := λ p, dist (f p.1) (f p.2),
-- check that the induced "distance" is a candidate
have Fgood : F ∈ candidates X Y,
{ simp only [candidates, forall_const, and_true, add_comm, eq_self_iff_true, dist_eq_zero,
and_self, set.mem_set_of_eq],
repeat {split},
{ exact λ x y, calc
F (inl x, inl y) = dist (Φ x) (Φ y) : rfl
... = dist x y : Φisom.dist_eq x y },
{ exact λ x y, calc
F (inr x, inr y) = dist (Ψ x) (Ψ y) : rfl
... = dist x y : Ψisom.dist_eq x y },
{ exact λ x y, dist_comm _ _ },
{ exact λ x y z, dist_triangle _ _ _ },
{ exact λ x y, calc
F (x, y) ≤ diam (range Φ ∪ range Ψ) :
begin
have A : ∀ z : X ⊕ Y, f z ∈ range Φ ∪ range Ψ,
{ assume z,
cases z,
{ apply mem_union_left, apply mem_range_self },
{ apply mem_union_right, apply mem_range_self } },
refine dist_le_diam_of_mem _ (A _) (A _),
rw [Φrange, Ψrange],
exact (p ⊔ q).is_compact.bounded,
end
... ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : I } },
let Fb := candidates_b_of_candidates F Fgood,
have : Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤ HD Fb :=
Hausdorff_dist_optimal_le_HD _ _ (candidates_b_of_candidates_mem F Fgood),
refine le_trans this (le_of_forall_le_of_dense (λ r hr, _)),
have I1 : ∀ x : X, (⨅ y, Fb (inl x, inr y)) ≤ r,
{ assume x,
have : f (inl x) ∈ ↑p := Φrange.subst (mem_range_self _),
rcases exists_dist_lt_of_Hausdorff_dist_lt this hr
(Hausdorff_edist_ne_top_of_nonempty_of_bounded p.nonempty q.nonempty
p.is_compact.bounded q.is_compact.bounded)
with ⟨z, zq, hz⟩,
have : z ∈ range Ψ, by rwa [← Ψrange] at zq,
rcases mem_range.1 this with ⟨y, hy⟩,
calc (⨅ y, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) :
cinfi_le (by simpa only [add_zero] using HD_below_aux1 0) y
... = dist (Φ x) (Ψ y) : rfl
... = dist (f (inl x)) z : by rw hy
... ≤ r : le_of_lt hz },
have I2 : ∀ y : Y, (⨅ x, Fb (inl x, inr y)) ≤ r,
{ assume y,
have : f (inr y) ∈ ↑q := Ψrange.subst (mem_range_self _),
rcases exists_dist_lt_of_Hausdorff_dist_lt' this hr
(Hausdorff_edist_ne_top_of_nonempty_of_bounded p.nonempty q.nonempty
p.is_compact.bounded q.is_compact.bounded)
with ⟨z, zq, hz⟩,
have : z ∈ range Φ, by rwa [← Φrange] at zq,
rcases mem_range.1 this with ⟨x, hx⟩,
calc (⨅ x, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) :
cinfi_le (by simpa only [add_zero] using HD_below_aux2 0) x
... = dist (Φ x) (Ψ y) : rfl
... = dist z (f (inr y)) : by rw hx
... ≤ r : le_of_lt hz },
simp only [HD, csupr_le I1, csupr_le I2, max_le_iff, and_self] },
/- Get the same inequality for any coupling. If the coupling is quite good, the desired
inequality has been proved above. If it is bad, then the inequality is obvious. -/
have B : ∀ p q : nonempty_compacts ℓ_infty_ℝ, ⟦p⟧ = to_GH_space X → ⟦q⟧ = to_GH_space Y →
Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤
Hausdorff_dist (p : set ℓ_infty_ℝ) q,
{ assume p q hp hq,
by_cases h :
Hausdorff_dist (p : set ℓ_infty_ℝ) q < diam (univ : set X) + 1 + diam (univ : set Y),
{ exact A p q hp hq h },
{ calc Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y))
≤ HD (candidates_b_dist X Y) :
Hausdorff_dist_optimal_le_HD _ _ (candidates_b_dist_mem_candidates_b)
... ≤ diam (univ : set X) + 1 + diam (univ : set Y) : HD_candidates_b_dist_le
... ≤ Hausdorff_dist (p : set ℓ_infty_ℝ) q : not_lt.1 h } },
refine le_antisymm _ _,
{ apply le_cInf,
{ refine (set.nonempty.prod _ _).image _; exact ⟨_, rfl⟩ },
{ rintro b ⟨⟨p, q⟩, ⟨hp, hq⟩, rfl⟩,
exact B p q hp hq } },
{ exact GH_dist_le_Hausdorff_dist (isometry_optimal_GH_injl X Y) (isometry_optimal_GH_injr X Y) }
end
/-- The Gromov-Hausdorff distance can also be realized by a coupling in `ℓ^∞(ℝ)`, by embedding
the optimal coupling through its Kuratowski embedding. -/
theorem GH_dist_eq_Hausdorff_dist (X : Type u) [metric_space X] [compact_space X] [nonempty X]
(Y : Type v) [metric_space Y] [compact_space Y] [nonempty Y] :
∃ Φ : X → ℓ_infty_ℝ, ∃ Ψ : Y → ℓ_infty_ℝ, isometry Φ ∧ isometry Ψ ∧
GH_dist X Y = Hausdorff_dist (range Φ) (range Ψ) :=
begin
let F := Kuratowski_embedding (optimal_GH_coupling X Y),
let Φ := F ∘ optimal_GH_injl X Y,
let Ψ := F ∘ optimal_GH_injr X Y,
refine ⟨Φ, Ψ, _, _, _⟩,
{ exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injl X Y) },
{ exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injr X Y) },
{ rw [← image_univ, ← image_univ, image_comp F, image_univ, image_comp F (optimal_GH_injr X Y),
image_univ, ← Hausdorff_dist_optimal],
exact (Hausdorff_dist_image (Kuratowski_embedding.isometry _)).symm },
end
/-- The Gromov-Hausdorff distance defines a genuine distance on the Gromov-Hausdorff space. -/
instance : metric_space GH_space :=
{ dist := dist,
dist_self := λ x, begin
rcases exists_rep x with ⟨y, hy⟩,
refine le_antisymm _ _,
{ apply cInf_le,
{ exact ⟨0, by { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } ⟩},
{ simp only [mem_image, mem_prod, mem_set_of_eq, prod.exists],
existsi [y, y],
simpa only [and_self, Hausdorff_dist_self_zero, eq_self_iff_true, and_true]} },
{ apply le_cInf,
{ exact (nonempty.prod ⟨y, hy⟩ ⟨y, hy⟩).image _ },
{ rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } },
end,
dist_comm := λ x y, begin
have A : (λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
Hausdorff_dist (p.1 : set ℓ_infty_ℝ) p.2) ''
({a | ⟦a⟧ = x} ×ˢ {b | ⟦b⟧ = y})
= ((λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
Hausdorff_dist (p.1 : set ℓ_infty_ℝ) p.2) ∘ prod.swap) ''
({a | ⟦a⟧ = x} ×ˢ {b | ⟦b⟧ = y}),
{ congr, funext, simp only [comp_app, prod.fst_swap, prod.snd_swap], rw Hausdorff_dist_comm },
simp only [dist, A, image_comp, image_swap_prod],
end,
eq_of_dist_eq_zero := λ x y hxy, begin
/- To show that two spaces at zero distance are isometric, we argue that the distance
is realized by some coupling. In this coupling, the two spaces are at zero Hausdorff distance,
i.e., they coincide. Therefore, the original spaces are isometric. -/
rcases GH_dist_eq_Hausdorff_dist x.rep y.rep with ⟨Φ, Ψ, Φisom, Ψisom, DΦΨ⟩,
rw [← dist_GH_dist, hxy] at DΦΨ,
have : range Φ = range Ψ,
{ have hΦ : is_compact (range Φ) := is_compact_range Φisom.continuous,
have hΨ : is_compact (range Ψ) := is_compact_range Ψisom.continuous,
apply (is_closed.Hausdorff_dist_zero_iff_eq _ _ _).1 (DΦΨ.symm),
{ exact hΦ.is_closed },
{ exact hΨ.is_closed },
{ exact Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _)
(range_nonempty _) hΦ.bounded hΨ.bounded } },
have T : ((range Ψ) ≃ᵢ y.rep) = ((range Φ) ≃ᵢ y.rep), by rw this,
have eΨ := cast T Ψisom.isometry_equiv_on_range.symm,
have e := Φisom.isometry_equiv_on_range.trans eΨ,
rw [← x.to_GH_space_rep, ← y.to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometry_equiv],
exact ⟨e⟩
end,
dist_triangle := λ x y z, begin
/- To show the triangular inequality between `X`, `Y` and `Z`, realize an optimal coupling
between `X` and `Y` in a space `γ1`, and an optimal coupling between `Y` and `Z` in a space
`γ2`. Then, glue these metric spaces along `Y`. We get a new space `γ` in which `X` and `Y` are
optimally coupled, as well as `Y` and `Z`. Apply the triangle inequality for the Hausdorff
distance in `γ` to conclude. -/
let X := x.rep,
let Y := y.rep,
let Z := z.rep,
let γ1 := optimal_GH_coupling X Y,
let γ2 := optimal_GH_coupling Y Z,
let Φ : Y → γ1 := optimal_GH_injr X Y,
have hΦ : isometry Φ := isometry_optimal_GH_injr X Y,
let Ψ : Y → γ2 := optimal_GH_injl Y Z,
have hΨ : isometry Ψ := isometry_optimal_GH_injl Y Z,
let γ := glue_space hΦ hΨ,
have Comm : (to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y) =
(to_glue_r hΦ hΨ) ∘ (optimal_GH_injl Y Z) := to_glue_commute hΦ hΨ,
calc dist x z = dist (to_GH_space X) (to_GH_space Z) :
by rw [x.to_GH_space_rep, z.to_GH_space_rep]
... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y)))
(range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) :
GH_dist_le_Hausdorff_dist
((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injl X Y))
((to_glue_r_isometry hΦ hΨ).comp (isometry_optimal_GH_injr Y Z))
... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y)))
(range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y)))
+ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y)))
(range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) :
begin
refine Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded
(range_nonempty _) (range_nonempty _) _ _),
{ exact (is_compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp
(isometry_optimal_GH_injl X Y)))).bounded },
{ exact (is_compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp
(isometry_optimal_GH_injr X Y)))).bounded }
end
... = Hausdorff_dist ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injl X Y)))
((to_glue_l hΦ hΨ) '' (range (optimal_GH_injr X Y)))
+ Hausdorff_dist ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injl Y Z)))
((to_glue_r hΦ hΨ) '' (range (optimal_GH_injr Y Z))) :
by simp only [← range_comp, Comm, eq_self_iff_true, add_right_inj]
... = Hausdorff_dist (range (optimal_GH_injl X Y))
(range (optimal_GH_injr X Y))
+ Hausdorff_dist (range (optimal_GH_injl Y Z))
(range (optimal_GH_injr Y Z)) :
by rw [Hausdorff_dist_image (to_glue_l_isometry hΦ hΨ),
Hausdorff_dist_image (to_glue_r_isometry hΦ hΨ)]
... = dist (to_GH_space X) (to_GH_space Y) + dist (to_GH_space Y) (to_GH_space Z) :
by rw [Hausdorff_dist_optimal, Hausdorff_dist_optimal, GH_dist, GH_dist]
... = dist x y + dist y z:
by rw [x.to_GH_space_rep, y.to_GH_space_rep, z.to_GH_space_rep]
end }
end GH_space --section
end Gromov_Hausdorff
/-- In particular, nonempty compacts of a metric space map to `GH_space`. We register this
in the topological_space namespace to take advantage of the notation `p.to_GH_space`. -/
definition topological_space.nonempty_compacts.to_GH_space {X : Type u} [metric_space X]
(p : nonempty_compacts X) : Gromov_Hausdorff.GH_space := Gromov_Hausdorff.to_GH_space p
open topological_space
namespace Gromov_Hausdorff
section nonempty_compacts
variables {X : Type u} [metric_space X]
theorem GH_dist_le_nonempty_compacts_dist (p q : nonempty_compacts X) :
dist p.to_GH_space q.to_GH_space ≤ dist p q :=
begin
have ha : isometry (coe : p → X) := isometry_subtype_coe,
have hb : isometry (coe : q → X) := isometry_subtype_coe,
have A : dist p q = Hausdorff_dist (p : set X) q := rfl,
have I : ↑p = range (coe : p → X) := subtype.range_coe_subtype.symm,
have J : ↑q = range (coe : q → X) := subtype.range_coe_subtype.symm,
rw [A, I, J],
exact GH_dist_le_Hausdorff_dist ha hb
end
lemma to_GH_space_lipschitz :
lipschitz_with 1 (nonempty_compacts.to_GH_space : nonempty_compacts X → GH_space) :=
lipschitz_with.mk_one GH_dist_le_nonempty_compacts_dist
lemma to_GH_space_continuous :
continuous (nonempty_compacts.to_GH_space : nonempty_compacts X → GH_space) :=
to_GH_space_lipschitz.continuous
end nonempty_compacts
section
/- In this section, we show that if two metric spaces are isometric up to `ε₂`, then their
Gromov-Hausdorff distance is bounded by `ε₂ / 2`. More generally, if there are subsets which are
`ε₁`-dense and `ε₃`-dense in two spaces, and isometric up to `ε₂`, then the Gromov-Hausdorff
distance between the spaces is bounded by `ε₁ + ε₂/2 + ε₃`. For this, we construct a suitable
coupling between the two spaces, by gluing them (approximately) along the two matching subsets. -/
variables {X : Type u} [metric_space X] [compact_space X] [nonempty X]
{Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y]
-- we want to ignore these instances in the following theorem
local attribute [instance, priority 10] sum.topological_space sum.uniform_space
/-- If there are subsets which are `ε₁`-dense and `ε₃`-dense in two spaces, and
isometric up to `ε₂`, then the Gromov-Hausdorff distance between the spaces is bounded by
`ε₁ + ε₂/2 + ε₃`. -/
theorem GH_dist_le_of_approx_subsets {s : set X} (Φ : s → Y) {ε₁ ε₂ ε₃ : ℝ}
(hs : ∀ x : X, ∃ y ∈ s, dist x y ≤ ε₁) (hs' : ∀ x : Y, ∃ y : s, dist x (Φ y) ≤ ε₃)
(H : ∀ x y : s, |dist x y - dist (Φ x) (Φ y)| ≤ ε₂) :
GH_dist X Y ≤ ε₁ + ε₂ / 2 + ε₃ :=
begin
refine le_of_forall_pos_le_add (λ δ δ0, _),
rcases exists_mem_of_nonempty X with ⟨xX, _⟩,
rcases hs xX with ⟨xs, hxs, Dxs⟩,
have sne : s.nonempty := ⟨xs, hxs⟩,
letI : nonempty s := sne.to_subtype,
have : 0 ≤ ε₂ := le_trans (abs_nonneg _) (H ⟨xs, hxs⟩ ⟨xs, hxs⟩),
have : ∀ p q : s, |dist p q - dist (Φ p) (Φ q)| ≤ 2 * (ε₂/2 + δ) := λ p q, calc
|dist p q - dist (Φ p) (Φ q)| ≤ ε₂ : H p q
... ≤ 2 * (ε₂/2 + δ) : by linarith,
-- glue `X` and `Y` along the almost matching subsets
letI : metric_space (X ⊕ Y) :=
glue_metric_approx (λ x:s, (x:X)) (λ x, Φ x) (ε₂/2 + δ) (by linarith) this,
let Fl := @sum.inl X Y,
let Fr := @sum.inr X Y,
have Il : isometry Fl := isometry.of_dist_eq (λ x y, rfl),
have Ir : isometry Fr := isometry.of_dist_eq (λ x y, rfl),
/- The proof goes as follows : the `GH_dist` is bounded by the Hausdorff distance of the images
in the coupling, which is bounded (using the triangular inequality) by the sum of the Hausdorff
distances of `X` and `s` (in the coupling or, equivalently in the original space), of `s` and
`Φ s`, and of `Φ s` and `Y` (in the coupling or, equivalently, in the original space). The first
term is bounded by `ε₁`, by `ε₁`-density. The third one is bounded by `ε₃`. And the middle one is
bounded by `ε₂/2` as in the coupling the points `x` and `Φ x` are at distance `ε₂/2` by
construction of the coupling (in fact `ε₂/2 + δ` where `δ` is an arbitrarily small positive
constant where positivity is used to ensure that the coupling is really a metric space and not a
premetric space on `X ⊕ Y`). -/
have : GH_dist X Y ≤ Hausdorff_dist (range Fl) (range Fr) :=
GH_dist_le_Hausdorff_dist Il Ir,
have : Hausdorff_dist (range Fl) (range Fr) ≤ Hausdorff_dist (range Fl) (Fl '' s)
+ Hausdorff_dist (Fl '' s) (range Fr),
{ have B : bounded (range Fl) := (is_compact_range Il.continuous).bounded,
exact Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded
(range_nonempty _) (sne.image _) B (B.mono (image_subset_range _ _))) },
have : Hausdorff_dist (Fl '' s) (range Fr) ≤ Hausdorff_dist (Fl '' s) (Fr '' (range Φ))
+ Hausdorff_dist (Fr '' (range Φ)) (range Fr),
{ have B : bounded (range Fr) := (is_compact_range Ir.continuous).bounded,
exact Hausdorff_dist_triangle' (Hausdorff_edist_ne_top_of_nonempty_of_bounded
((range_nonempty _).image _) (range_nonempty _)
(bounded.mono (image_subset_range _ _) B) B) },
have : Hausdorff_dist (range Fl) (Fl '' s) ≤ ε₁,
{ rw [← image_univ, Hausdorff_dist_image Il],
have : 0 ≤ ε₁ := le_trans dist_nonneg Dxs,
refine Hausdorff_dist_le_of_mem_dist this (λ x hx, hs x)
(λ x hx, ⟨x, mem_univ _, by simpa only [dist_self]⟩) },
have : Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) ≤ ε₂/2 + δ,
{ refine Hausdorff_dist_le_of_mem_dist (by linarith) _ _,
{ assume x' hx',
rcases (set.mem_image _ _ _).1 hx' with ⟨x, ⟨x_in_s, xx'⟩⟩,
rw ← xx',
use [Fr (Φ ⟨x, x_in_s⟩), mem_image_of_mem Fr (mem_range_self _)],
exact le_of_eq (glue_dist_glued_points (λ x:s, (x:X)) Φ (ε₂/2 + δ) ⟨x, x_in_s⟩) },
{ assume x' hx',
rcases (set.mem_image _ _ _).1 hx' with ⟨y, ⟨y_in_s', yx'⟩⟩,
rcases mem_range.1 y_in_s' with ⟨x, xy⟩,
use [Fl x, mem_image_of_mem _ x.2],
rw [← yx', ← xy, dist_comm],
exact le_of_eq (glue_dist_glued_points (@subtype.val X s) Φ (ε₂/2 + δ) x) } },
have : Hausdorff_dist (Fr '' (range Φ)) (range Fr) ≤ ε₃,
{ rw [← @image_univ _ _ Fr, Hausdorff_dist_image Ir],
rcases exists_mem_of_nonempty Y with ⟨xY, _⟩,
rcases hs' xY with ⟨xs', Dxs'⟩,
have : 0 ≤ ε₃ := le_trans dist_nonneg Dxs',
refine Hausdorff_dist_le_of_mem_dist this (λ x hx, ⟨x, mem_univ _, by simpa only [dist_self]⟩)
(λ x _, _),
rcases hs' x with ⟨y, Dy⟩,
exact ⟨Φ y, mem_range_self _, Dy⟩ },
linarith
end
end --section
/-- The Gromov-Hausdorff space is second countable. -/
instance : second_countable_topology GH_space :=
begin
refine second_countable_of_countable_discretization (λ δ δpos, _),
let ε := (2/5) * δ,
have εpos : 0 < ε := mul_pos (by norm_num) δpos,
have : ∀ p:GH_space, ∃ s : set p.rep, s.finite ∧ (univ ⊆ (⋃x∈s, ball x ε)) :=
λ p, by simpa only [subset_univ, exists_true_left]
using finite_cover_balls_of_compact is_compact_univ εpos,
-- for each `p`, `s p` is a finite `ε`-dense subset of `p` (or rather the metric space
-- `p.rep` representing `p`)
choose s hs using this,
have : ∀ p:GH_space, ∀ t:set p.rep, t.finite → ∃ n:ℕ, ∃ e:equiv t (fin n), true,
{ assume p t ht,
letI : fintype t := finite.fintype ht,
exact ⟨fintype.card t, fintype.equiv_fin t, trivial⟩ },
choose N e hne using this,
-- cardinality of the nice finite subset `s p` of `p.rep`, called `N p`
let N := λ p:GH_space, N p (s p) (hs p).1,
-- equiv from `s p`, a nice finite subset of `p.rep`, to `fin (N p)`, called `E p`
let E := λ p:GH_space, e p (s p) (hs p).1,
-- A function `F` associating to `p : GH_space` the data of all distances between points
-- in the `ε`-dense set `s p`.
let F : GH_space → Σn:ℕ, (fin n → fin n → ℤ) :=
λp, ⟨N p, λa b, ⌊ε⁻¹ * dist ((E p).symm a) ((E p).symm b)⌋⟩,
refine ⟨Σ n, fin n → fin n → ℤ, by apply_instance, F, λp q hpq, _⟩,
/- As the target space of F is countable, it suffices to show that two points
`p` and `q` with `F p = F q` are at distance `≤ δ`.
For this, we construct a map `Φ` from `s p ⊆ p.rep` (representing `p`)
to `q.rep` (representing `q`) which is almost an isometry on `s p`, and
with image `s q`. For this, we compose the identification of `s p` with `fin (N p)`
and the inverse of the identification of `s q` with `fin (N q)`. Together with
the fact that `N p = N q`, this constructs `Ψ` between `s p` and `s q`, and then
composing with the canonical inclusion we get `Φ`. -/
have Npq : N p = N q := (sigma.mk.inj_iff.1 hpq).1,
let Ψ : s p → s q := λ x, (E q).symm (fin.cast Npq ((E p) x)),
let Φ : s p → q.rep := λ x, Ψ x,
-- Use the almost isometry `Φ` to show that `p.rep` and `q.rep`
-- are within controlled Gromov-Hausdorff distance.
have main : GH_dist p.rep q.rep ≤ ε + ε/2 + ε,
{ refine GH_dist_le_of_approx_subsets Φ _ _ _,
show ∀ x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε,
{ -- by construction, `s p` is `ε`-dense
assume x,
have : x ∈ ⋃y∈(s p), ball y ε := (hs p).2 (mem_univ _),
rcases mem_Union₂.1 this with ⟨y, ys, hy⟩,
exact ⟨y, ys, le_of_lt hy⟩ },
show ∀ x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε,
{ -- by construction, `s q` is `ε`-dense, and it is the range of `Φ`
assume x,
have : x ∈ ⋃y∈(s q), ball y ε := (hs q).2 (mem_univ _),
rcases mem_Union₂.1 this with ⟨y, ys, hy⟩,
let i : ℕ := E q ⟨y, ys⟩,
let hi := ((E q) ⟨y, ys⟩).is_lt,
have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk],
have hiq : i < N q := hi,
have hip : i < N p, { rwa Npq.symm at hiq },
let z := (E p).symm ⟨i, hip⟩,
use z,
have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩,
have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl,
have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩,
{ rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ },
have : Φ z = y,
{ simp only [Φ, Ψ], rw [C1, C2, C3], refl },
rw this,
exact le_of_lt hy },
show ∀ x y : s p, |dist x y - dist (Φ x) (Φ y)| ≤ ε,
{ /- the distance between `x` and `y` is encoded in `F p`, and the distance between
`Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`.
As `F p = F q`, the distances are almost equal. -/
assume x y,
have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl,
rw this,
-- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)`
let i : ℕ := E p x,
have hip : i < N p := ((E p) x).2,
have hiq : i < N q, by rwa Npq at hip,
have i' : i = ((E q) (Ψ x)), by { simp only [equiv.apply_symm_apply, fin.coe_cast] },
-- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)`
let j : ℕ := E p y,
have hjp : j < N p := ((E p) y).2,
have hjq : j < N q, by rwa Npq at hjp,
have j' : j = ((E q) (Ψ y)).1,
{ simp only [equiv.apply_symm_apply, fin.val_eq_coe, fin.coe_cast] },
-- Express `dist x y` in terms of `F p`
have : (F p).2 ((E p) x) ((E p) y) = floor (ε⁻¹ * dist x y),
by simp only [F, (E p).symm_apply_apply],
have Ap : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = floor (ε⁻¹ * dist x y),
by { rw ← this, congr; apply fin.ext_iff.2; refl },
-- Express `dist (Φ x) (Φ y)` in terms of `F q`
have : (F q).2 ((E q) (Ψ x)) ((E q) (Ψ y)) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
by simp only [F, (E q).symm_apply_apply],
have Aq : (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩ = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
by { rw ← this, congr; apply fin.ext_iff.2; [exact i', exact j'] },
-- use the equality between `F p` and `F q` to deduce that the distances have equal
-- integer parts
have : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩,
{ -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works
-- with a constant, so replace `F q` (and everything that depends on it) by a constant `f`
-- then `subst`
revert hiq hjq,
change N q with (F q).1,
generalize_hyp : F q = f at hpq ⊢,
subst hpq,
intros,
refl },
rw [Ap, Aq] at this,
-- deduce that the distances coincide up to `ε`, by a straightforward computation
-- that should be automated
have I := calc
|ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)| =
|ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))| : (abs_mul _ _).symm
... = |(ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))| : by { congr, ring }
... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this),
calc
|dist x y - dist (Ψ x) (Ψ y)| = (ε * ε⁻¹) * |dist x y - dist (Ψ x) (Ψ y)| :
by rw [mul_inv_cancel (ne_of_gt εpos), one_mul]
... = ε * (|ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)|) :
by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc]
... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos)
... = ε : mul_one _ } },
calc dist p q = GH_dist p.rep (q.rep) : dist_GH_dist p q
... ≤ ε + ε/2 + ε : main
... = δ : by { simp only [ε], ring }
end
/-- Compactness criterion: a closed set of compact metric spaces is compact if the spaces have
a uniformly bounded diameter, and for all `ε` the number of balls of radius `ε` required
to cover the spaces is uniformly bounded. This is an equivalence, but we only prove the
interesting direction that these conditions imply compactness. -/
lemma totally_bounded {t : set GH_space} {C : ℝ} {u : ℕ → ℝ} {K : ℕ → ℕ}
(ulim : tendsto u at_top (𝓝 0))
(hdiam : ∀ p ∈ t, diam (univ : set (GH_space.rep p)) ≤ C)
(hcov : ∀ p ∈ t, ∀ n:ℕ, ∃ s : set (GH_space.rep p),
cardinal.mk s ≤ K n ∧ univ ⊆ ⋃x∈s, ball x (u n)) :
totally_bounded t :=
begin
/- Let `δ>0`, and `ε = δ/5`. For each `p`, we construct a finite subset `s p` of `p`, which
is `ε`-dense and has cardinality at most `K n`. Encoding the mutual distances of points in `s p`,
up to `ε`, we will get a map `F` associating to `p` finitely many data, and making it possible to
reconstruct `p` up to `ε`. This is enough to prove total boundedness. -/
refine metric.totally_bounded_of_finite_discretization (λ δ δpos, _),
let ε := (1/5) * δ,
have εpos : 0 < ε := mul_pos (by norm_num) δpos,
-- choose `n` for which `u n < ε`
rcases metric.tendsto_at_top.1 ulim ε εpos with ⟨n, hn⟩,
have u_le_ε : u n ≤ ε,
{ have := hn n le_rfl,
simp only [real.dist_eq, add_zero, sub_eq_add_neg, neg_zero] at this,
exact le_of_lt (lt_of_le_of_lt (le_abs_self _) this) },
-- construct a finite subset `s p` of `p` which is `ε`-dense and has cardinal `≤ K n`
have : ∀ p:GH_space, ∃ s : set p.rep, ∃ N ≤ K n, ∃ E : equiv s (fin N),
p ∈ t → univ ⊆ ⋃x∈s, ball x (u n),
{ assume p,
by_cases hp : p ∉ t,
{ have : nonempty (equiv (∅ : set p.rep) (fin 0)),
{ rw ← fintype.card_eq, simp only [empty_card', fintype.card_fin] },
use [∅, 0, bot_le, choice (this)] },
{ rcases hcov _ (set.not_not_mem.1 hp) n with ⟨s, ⟨scard, scover⟩⟩,
rcases cardinal.lt_aleph_0.1 (lt_of_le_of_lt scard (cardinal.nat_lt_aleph_0 _)) with ⟨N, hN⟩,
rw [hN, cardinal.nat_cast_le] at scard,
have : cardinal.mk s = cardinal.mk (fin N), by rw [hN, cardinal.mk_fin],
cases quotient.exact this with E,
use [s, N, scard, E],
simp only [scover, implies_true_iff] } },
choose s N hN E hs using this,
-- Define a function `F` taking values in a finite type and associating to `p` enough data
-- to reconstruct it up to `ε`, namely the (discretized) distances between elements of `s p`.
let M := ⌊ε⁻¹ * max C 0⌋₊,
let F : GH_space → (Σk:fin ((K n).succ), (fin k → fin k → fin (M.succ))) :=
λ p, ⟨⟨N p, lt_of_le_of_lt (hN p) (nat.lt_succ_self _)⟩,
λ a b, ⟨min M ⌊ε⁻¹ * dist ((E p).symm a) ((E p).symm b)⌋₊,
( min_le_left _ _).trans_lt (nat.lt_succ_self _) ⟩ ⟩,
refine ⟨_, _, (λ p, F p), _⟩, apply_instance,
-- It remains to show that if `F p = F q`, then `p` and `q` are `ε`-close
rintros ⟨p, pt⟩ ⟨q, qt⟩ hpq,
have Npq : N p = N q := fin.ext_iff.1 (sigma.mk.inj_iff.1 hpq).1,
let Ψ : s p → s q := λ x, (E q).symm (fin.cast Npq ((E p) x)),
let Φ : s p → q.rep := λ x, Ψ x,
have main : GH_dist p.rep (q.rep) ≤ ε + ε/2 + ε,
{ -- to prove the main inequality, argue that `s p` is `ε`-dense in `p`, and `s q` is `ε`-dense
-- in `q`, and `s p` and `s q` are almost isometric. Then closeness follows
-- from `GH_dist_le_of_approx_subsets`
refine GH_dist_le_of_approx_subsets Φ _ _ _,
show ∀ x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε,
{ -- by construction, `s p` is `ε`-dense
assume x,
have : x ∈ ⋃y∈(s p), ball y (u n) := (hs p pt) (mem_univ _),
rcases mem_Union₂.1 this with ⟨y, ys, hy⟩,
exact ⟨y, ys, le_trans (le_of_lt hy) u_le_ε⟩ },
show ∀ x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε,
{ -- by construction, `s q` is `ε`-dense, and it is the range of `Φ`
assume x,
have : x ∈ ⋃y∈(s q), ball y (u n) := (hs q qt) (mem_univ _),
rcases mem_Union₂.1 this with ⟨y, ys, hy⟩,
let i : ℕ := E q ⟨y, ys⟩,
let hi := ((E q) ⟨y, ys⟩).2,
have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk],
have hiq : i < N q := hi,
have hip : i < N p, { rwa Npq.symm at hiq },
let z := (E p).symm ⟨i, hip⟩,
use z,
have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩,
have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl,
have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩,
by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ },
have : Φ z = y :=
by { simp only [Φ, Ψ], rw [C1, C2, C3], refl },
rw this,
exact le_trans (le_of_lt hy) u_le_ε },
show ∀ x y : s p, |dist x y - dist (Φ x) (Φ y)| ≤ ε,
{ /- the distance between `x` and `y` is encoded in `F p`, and the distance between
`Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`.
As `F p = F q`, the distances are almost equal. -/
assume x y,
have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl,
rw this,
-- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)`
let i : ℕ := E p x,
have hip : i < N p := ((E p) x).2,
have hiq : i < N q, by rwa Npq at hip,
have i' : i = ((E q) (Ψ x)), by { simp only [equiv.apply_symm_apply, fin.coe_cast] },
-- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)`
let j : ℕ := E p y,
have hjp : j < N p := ((E p) y).2,
have hjq : j < N q, by rwa Npq at hjp,
have j' : j = ((E q) (Ψ y)), by { simp only [equiv.apply_symm_apply, fin.coe_cast] },
-- Express `dist x y` in terms of `F p`
have Ap : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ⌊ε⁻¹ * dist x y⌋₊ := calc
((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F p).2 ((E p) x) ((E p) y)).1 :
by { congr; apply fin.ext_iff.2; refl }
... = min M ⌊ε⁻¹ * dist x y⌋₊ :
by simp only [F, (E p).symm_apply_apply]
... = ⌊ε⁻¹ * dist x y⌋₊ :
begin
refine min_eq_right (nat.floor_mono _),
refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) ((inv_pos.2 εpos).le),
change dist (x : p.rep) y ≤ C,
refine le_trans (dist_le_diam_of_mem is_compact_univ.bounded (mem_univ _) (mem_univ _)) _,
exact hdiam p pt
end,
-- Express `dist (Φ x) (Φ y)` in terms of `F q`
have Aq : ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋₊ := calc
((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ((F q).2 ((E q) (Ψ x)) ((E q) (Ψ y))).1 :
by { congr; apply fin.ext_iff.2; [exact i', exact j'] }
... = min M ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋₊ :
by simp only [F, (E q).symm_apply_apply]
... = ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋₊ :
begin
refine min_eq_right (nat.floor_mono _),
refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) ((inv_pos.2 εpos).le),
change dist (Ψ x : q.rep) (Ψ y) ≤ C,
refine le_trans (dist_le_diam_of_mem is_compact_univ.bounded (mem_univ _) (mem_univ _)) _,
exact hdiam q qt
end,
-- use the equality between `F p` and `F q` to deduce that the distances have equal
-- integer parts
have : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1,
{ -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works
-- with a constant, so replace `F q` (and everything that depends on it) by a constant `f`
-- then `subst`
revert hiq hjq,
change N q with (F q).1,
generalize_hyp : F q = f at hpq ⊢,
subst hpq,
intros,
refl },
have : ⌊ε⁻¹ * dist x y⌋ = ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋,
{ rw [Ap, Aq] at this,
have D : 0 ≤ ⌊ε⁻¹ * dist x y⌋ :=
floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg),
have D' : 0 ≤ ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋ :=
floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg),
rw [← int.to_nat_of_nonneg D, ← int.to_nat_of_nonneg D', int.floor_to_nat,int.floor_to_nat,
this] },
-- deduce that the distances coincide up to `ε`, by a straightforward computation
-- that should be automated
have I := calc
|ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)| =
|ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))| : (abs_mul _ _).symm
... = |(ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))| : by { congr, ring }
... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this),
calc
|dist x y - dist (Ψ x) (Ψ y)| = (ε * ε⁻¹) * |dist x y - dist (Ψ x) (Ψ y)| :
by rw [mul_inv_cancel (ne_of_gt εpos), one_mul]
... = ε * (|ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)|) :
by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc]
... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos)
... = ε : mul_one _ } },
calc dist p q = GH_dist p.rep (q.rep) : dist_GH_dist p q
... ≤ ε + ε/2 + ε : main
... = δ/2 : by { simp only [ε, one_div], ring }
... < δ : half_lt_self δpos
end
section complete
/- We will show that a sequence `u n` of compact metric spaces satisfying
`dist (u n) (u (n+1)) < 1/2^n` converges, which implies completeness of the Gromov-Hausdorff space.
We need to exhibit the limiting compact metric space. For this, start from
a sequence `X n` of representatives of `u n`, and glue in an optimal way `X n` to `X (n+1)`
for all `n`, in a common metric space. Formally, this is done as follows.
Start from `Y 0 = X 0`. Then, glue `X 0` to `X 1` in an optimal way, yielding a space
`Y 1` (with an embedding of `X 1`). Then, consider an optimal gluing of `X 1` and `X 2`, and
glue it to `Y 1` along their common subspace `X 1`. This gives a new space `Y 2`, with an
embedding of `X 2`. Go on, to obtain a sequence of spaces `Y n`. Let `Z0` be the inductive
limit of the `Y n`, and finally let `Z` be the completion of `Z0`.
The images `X2 n` of `X n` in `Z` are at Hausdorff distance `< 1/2^n` by construction, hence they
form a Cauchy sequence for the Hausdorff distance. By completeness (of `Z`, and therefore of its
set of nonempty compact subsets), they converge to a limit `L`. This is the nonempty
compact metric space we are looking for. -/
variables (X : ℕ → Type) [∀ n, metric_space (X n)] [∀ n, compact_space (X n)] [∀ n, nonempty (X n)]
/-- Auxiliary structure used to glue metric spaces below, recording an isometric embedding
of a type `A` in another metric space. -/
structure aux_gluing_struct (A : Type) [metric_space A] : Type 1 :=
(space : Type)
(metric : metric_space space)
(embed : A → space)
(isom : isometry embed)
local attribute [instance] aux_gluing_struct.metric
instance (A : Type) [metric_space A] : inhabited (aux_gluing_struct A) :=
⟨{ space := A,
metric := by apply_instance,
embed := id,
isom := λ x y, rfl }⟩
/-- Auxiliary sequence of metric spaces, containing copies of `X 0`, ..., `X n`, where each
`X i` is glued to `X (i+1)` in an optimal way. The space at step `n+1` is obtained from the space
at step `n` by adding `X (n+1)`, glued in an optimal way to the `X n` already sitting there. -/
def aux_gluing (n : ℕ) : aux_gluing_struct (X n) :=
nat.rec_on n default $ λ n Y,
{ space := glue_space Y.isom (isometry_optimal_GH_injl (X n) (X (n+1))),
metric := by apply_instance,
embed := (to_glue_r Y.isom (isometry_optimal_GH_injl (X n) (X (n+1))))
∘ (optimal_GH_injr (X n) (X (n+1))),
isom := (to_glue_r_isometry _ _).comp (isometry_optimal_GH_injr (X n) (X (n+1))) }
/-- The Gromov-Hausdorff space is complete. -/
instance : complete_space GH_space :=
begin
have : ∀ (n : ℕ), 0 < ((1:ℝ) / 2) ^ n, by { apply pow_pos, norm_num },
-- start from a sequence of nonempty compact metric spaces within distance `1/2^n` of each other
refine metric.complete_of_convergent_controlled_sequences (λ n, (1/2)^n) this (λ u hu, _),
-- `X n` is a representative of `u n`
let X := λ n, (u n).rep,
-- glue them together successively in an optimal way, getting a sequence of metric spaces `Y n`
let Y := aux_gluing X,
-- this equality is true by definition but Lean unfolds some defs in the wrong order
have E : ∀ n : ℕ,
glue_space (Y n).isom (isometry_optimal_GH_injl (X n) (X (n + 1))) = (Y (n + 1)).space :=
λ n, by { dsimp only [Y, aux_gluing], refl },
let c := λ n, cast (E n),
have ic : ∀ n, isometry (c n) := λ n x y, by { dsimp only [Y, aux_gluing], exact rfl },
-- there is a canonical embedding of `Y n` in `Y (n+1)`, by construction
let f : Π n, (Y n).space → (Y (n + 1)).space :=
λ n, c n ∘ to_glue_l (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)),
have I : ∀ n, isometry (f n) := λ n, (ic n).comp (to_glue_l_isometry _ _),
-- consider the inductive limit `Z0` of the `Y n`, and then its completion `Z`
let Z0 := metric.inductive_limit I,
let Z := uniform_space.completion Z0,
let Φ := to_inductive_limit I,
let coeZ := (coe : Z0 → Z),
-- let `X2 n` be the image of `X n` in the space `Z`
let X2 := λ n, range (coeZ ∘ (Φ n) ∘ (Y n).embed),
have isom : ∀ n, isometry (coeZ ∘ (Φ n) ∘ (Y n).embed),
{ assume n,
refine uniform_space.completion.coe_isometry.comp _,
exact (to_inductive_limit_isometry _ _).comp (Y n).isom },
-- The Hausdorff distance of `X2 n` and `X2 (n+1)` is by construction the distance between
-- `u n` and `u (n+1)`, therefore bounded by `1/2^n`
have D2 : ∀ n, Hausdorff_dist (X2 n) (X2 n.succ) < (1/2)^n,
{ assume n,
have X2n : X2 n = range ((coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))))
∘ (optimal_GH_injl (X n) (X n.succ))),
{ change X2 n = range (coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))
∘ (optimal_GH_injl (X n) (X n.succ))),
simp only [X2, Φ],
rw [← to_inductive_limit_commute I],
simp only [f],
rw ← to_glue_commute },
rw range_comp at X2n,
have X2nsucc : X2 n.succ = range ((coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))))
∘ (optimal_GH_injr (X n) (X n.succ))), by refl,
rw range_comp at X2nsucc,
rw [X2n, X2nsucc, Hausdorff_dist_image, Hausdorff_dist_optimal, ← dist_GH_dist],
{ exact hu n n n.succ (le_refl n) (le_succ n) },
{ apply uniform_space.completion.coe_isometry.comp _,
exact (to_inductive_limit_isometry _ _).comp ((ic n).comp (to_glue_r_isometry _ _)) } },
-- consider `X2 n` as a member `X3 n` of the type of nonempty compact subsets of `Z`, which
-- is a metric space
let X3 : ℕ → nonempty_compacts Z := λ n,
⟨⟨X2 n, is_compact_range (isom n).continuous⟩, range_nonempty _⟩,
-- `X3 n` is a Cauchy sequence by construction, as the successive distances are
-- bounded by `(1/2)^n`
have : cauchy_seq X3,
{ refine cauchy_seq_of_le_geometric (1/2) 1 (by norm_num) (λ n, _),
rw one_mul,
exact le_of_lt (D2 n) },
-- therefore, it converges to a limit `L`
rcases cauchy_seq_tendsto_of_complete this with ⟨L, hL⟩,
-- the images of `X3 n` in the Gromov-Hausdorff space converge to the image of `L`
have M : tendsto (λ n, (X3 n).to_GH_space) at_top (𝓝 L.to_GH_space) :=
tendsto.comp (to_GH_space_continuous.tendsto _) hL,
-- By construction, the image of `X3 n` in the Gromov-Hausdorff space is `u n`.
have : ∀ n, (X3 n).to_GH_space = u n,
{ assume n,
rw [nonempty_compacts.to_GH_space, ← (u n).to_GH_space_rep,
to_GH_space_eq_to_GH_space_iff_isometry_equiv],
constructor,
convert (isom n).isometry_equiv_on_range.symm, },
-- Finally, we have proved the convergence of `u n`
exact ⟨L.to_GH_space, by simpa only [this] using M⟩
end
end complete--section
end Gromov_Hausdorff --namespace
|
(* Title: JinjaThreads/J/SmallTypeSafe.thy
Author: Tobias Nipkow, Andreas Lochbihler
*)
section \<open>Type Safety Proof\<close>
theory TypeSafe
imports
Progress
DefAssPreservation
begin
subsection\<open>Basic preservation lemmas\<close>
text\<open>First two easy preservation lemmas.\<close>
theorem (in J_conf_read)
shows red_preserves_hconf:
"\<lbrakk> extTA,P,t \<turnstile> \<langle>e,s\<rangle> -ta\<rightarrow> \<langle>e',s'\<rangle>; P,E,hp s \<turnstile> e : T; hconf (hp s) \<rbrakk> \<Longrightarrow> hconf (hp s')"
and reds_preserves_hconf:
"\<lbrakk> extTA,P,t \<turnstile> \<langle>es,s\<rangle> [-ta\<rightarrow>] \<langle>es',s'\<rangle>; P,E,hp s \<turnstile> es [:] Ts; hconf (hp s) \<rbrakk> \<Longrightarrow> hconf (hp s')"
proof (induct arbitrary: T E and Ts E rule: red_reds.inducts)
case RedNew thus ?case
by(auto intro: hconf_heap_ops_mono)
next
case RedNewFail thus ?case
by(auto intro: hconf_heap_ops_mono)
next
case RedNewArray thus ?case
by(auto intro: hconf_heap_ops_mono)
next
case RedNewArrayFail thus ?case
by(auto intro: hconf_heap_ops_mono)
next
case (RedAAss h a U n i v U' h' l)
from \<open>sint i < int n\<close> \<open>0 <=s i\<close>
have "nat (sint i) < n"
by (simp add: word_sle_eq nat_less_iff)
thus ?case using RedAAss
by(fastforce elim: hconf_heap_write_mono intro: addr_loc_type.intros simp add: conf_def)
next
case RedFAss thus ?case
by(fastforce elim: hconf_heap_write_mono intro: addr_loc_type.intros simp add: conf_def)
next
case RedCASSucceed thus ?case
by(fastforce elim: hconf_heap_write_mono intro: addr_loc_type.intros simp add: conf_def)
next
case (RedCallExternal s a U M Ts T' D vs ta va h' ta' e' s')
hence "P,hp s \<turnstile> a\<bullet>M(vs) : T"
by(fastforce simp add: external_WT'_iff dest: sees_method_fun)
with RedCallExternal show ?case by(auto dest: external_call_hconf)
qed auto
theorem (in J_heap) red_preserves_lconf:
"\<lbrakk> extTA,P,t \<turnstile> \<langle>e,s\<rangle> -ta\<rightarrow> \<langle>e',s'\<rangle>; P,E,hp s \<turnstile> e:T; P,hp s \<turnstile> lcl s (:\<le>) E \<rbrakk> \<Longrightarrow> P,hp s' \<turnstile> lcl s' (:\<le>) E"
and reds_preserves_lconf:
"\<lbrakk> extTA,P,t \<turnstile> \<langle>es,s\<rangle> [-ta\<rightarrow>] \<langle>es',s'\<rangle>; P,E,hp s \<turnstile> es[:]Ts; P,hp s \<turnstile> lcl s (:\<le>) E \<rbrakk> \<Longrightarrow> P,hp s' \<turnstile> lcl s' (:\<le>) E"
proof(induct arbitrary: T E and Ts E rule:red_reds.inducts)
case RedNew thus ?case
by(fastforce intro:lconf_hext hext_heap_ops simp del: fun_upd_apply)
next
case RedNewFail thus ?case
by(auto intro:lconf_hext hext_heap_ops simp del: fun_upd_apply)
next
case RedNewArray thus ?case
by(fastforce intro:lconf_hext hext_heap_ops simp del: fun_upd_apply)
next
case RedNewArrayFail thus ?case
by(fastforce intro:lconf_hext hext_heap_ops simp del: fun_upd_apply)
next
case RedLAss thus ?case
by(fastforce elim: lconf_upd simp add: conf_def simp del: fun_upd_apply )
next
case RedAAss thus ?case
by(fastforce intro:lconf_hext hext_heap_ops simp del: fun_upd_apply)
next
case RedFAss thus ?case
by(fastforce intro:lconf_hext hext_heap_ops simp del: fun_upd_apply)
next
case RedCASSucceed thus ?case
by(fastforce intro:lconf_hext hext_heap_ops simp del: fun_upd_apply)
next
case (BlockRed e h x V vo ta e' h' x' T T' E)
note red = \<open>extTA,P,t \<turnstile> \<langle>e,(h, x(V := vo))\<rangle> -ta\<rightarrow> \<langle>e',(h', x')\<rangle>\<close>
note IH = \<open>\<And>T E. \<lbrakk>P,E,hp (h, x(V := vo)) \<turnstile> e : T;
P,hp (h, x(V := vo)) \<turnstile> lcl (h, x(V := vo)) (:\<le>) E\<rbrakk>
\<Longrightarrow> P,hp (h', x') \<turnstile> lcl (h', x') (:\<le>) E\<close>
note wt = \<open>P,E,hp (h, x) \<turnstile> {V:T=vo; e} : T'\<close>
note lconf = \<open>P,hp (h, x) \<turnstile> lcl (h, x) (:\<le>) E\<close>
from lconf_hext[OF lconf[simplified] red_hext_incr[OF red, simplified]]
have "P,h' \<turnstile> x (:\<le>) E" .
moreover from wt have "P,E(V\<mapsto>T),h \<turnstile> e : T'" by(cases vo, auto)
moreover from lconf wt have "P,h \<turnstile> x(V := vo) (:\<le>) E(V \<mapsto> T)"
by(cases vo)(simp add: lconf_def,auto intro: lconf_upd2 simp add: conf_def)
ultimately have "P,h' \<turnstile> x' (:\<le>) E(V\<mapsto>T)"
by(auto intro: IH[simplified])
with \<open>P,h' \<turnstile> x (:\<le>) E\<close> show ?case
by(auto simp add: lconf_def split: if_split_asm)
next
case (RedCallExternal s a U M Ts T' D vs ta va h' ta' e' s')
from \<open>P,t \<turnstile> \<langle>a\<bullet>M(vs),hp s\<rangle> -ta\<rightarrow>ext \<langle>va,h'\<rangle>\<close> have "hp s \<unlhd> h'" by(rule red_external_hext)
with \<open>s' = (h', lcl s)\<close> \<open>P,hp s \<turnstile> lcl s (:\<le>) E\<close> show ?case by(auto intro: lconf_hext)
qed auto
text\<open>Combining conformance of heap and local variables:\<close>
definition (in J_heap_conf_base) sconf :: "env \<Rightarrow> ('addr, 'heap) Jstate \<Rightarrow> bool" ("_ \<turnstile> _ \<surd>" [51,51]50)
where "E \<turnstile> s \<surd> \<equiv> let (h,l) = s in hconf h \<and> P,h \<turnstile> l (:\<le>) E \<and> preallocated h"
context J_conf_read begin
lemma red_preserves_sconf:
"\<lbrakk> extTA,P,t \<turnstile> \<langle>e,s\<rangle> -tas\<rightarrow> \<langle>e',s'\<rangle>; P,E,hp s \<turnstile> e : T; E \<turnstile> s \<surd> \<rbrakk> \<Longrightarrow> E \<turnstile> s' \<surd>"
apply(auto dest: red_preserves_hconf red_preserves_lconf simp add:sconf_def)
apply(fastforce dest: red_hext_incr intro: preallocated_hext)
done
lemma reds_preserves_sconf:
"\<lbrakk> extTA,P,t \<turnstile> \<langle>es,s\<rangle> [-ta\<rightarrow>] \<langle>es',s'\<rangle>; P,E,hp s \<turnstile> es [:] Ts; E \<turnstile> s \<surd> \<rbrakk> \<Longrightarrow> E \<turnstile> s' \<surd>"
apply(auto dest: reds_preserves_hconf reds_preserves_lconf simp add: sconf_def)
apply(fastforce dest: reds_hext_incr intro: preallocated_hext)
done
end
lemma (in J_heap_base) wt_external_call:
"\<lbrakk> conf_extRet P h va T; P,E,h \<turnstile> e : T \<rbrakk> \<Longrightarrow> \<exists>T'. P,E,h \<turnstile> extRet2J e va : T' \<and> P \<turnstile> T' \<le> T"
by(cases va)(auto simp add: conf_def)
subsection "Subject reduction"
theorem (in J_conf_read) assumes wf: "wf_J_prog P"
shows subject_reduction:
"\<lbrakk> extTA,P,t \<turnstile> \<langle>e,s\<rangle> -ta\<rightarrow> \<langle>e',s'\<rangle>; E \<turnstile> s \<surd>; P,E,hp s \<turnstile> e:T; P,hp s \<turnstile> t \<surd>t \<rbrakk>
\<Longrightarrow> \<exists>T'. P,E,hp s' \<turnstile> e':T' \<and> P \<turnstile> T' \<le> T"
and subjects_reduction:
"\<lbrakk> extTA,P,t \<turnstile> \<langle>es,s\<rangle> [-ta\<rightarrow>] \<langle>es',s'\<rangle>; E \<turnstile> s \<surd>; P,E,hp s \<turnstile> es[:]Ts; P,hp s \<turnstile> t \<surd>t \<rbrakk>
\<Longrightarrow> \<exists>Ts'. P,E,hp s' \<turnstile> es'[:]Ts' \<and> P \<turnstile> Ts' [\<le>] Ts"
proof (induct arbitrary: T E and Ts E rule:red_reds.inducts)
case RedNew
thus ?case by(auto dest: allocate_SomeD)
next
case RedNewFail thus ?case unfolding sconf_def
by(fastforce intro:typeof_OutOfMemory preallocated_heap_ops simp add: xcpt_subcls_Throwable[OF _ wf])
next
case NewArrayRed
thus ?case by fastforce
next
case RedNewArray
thus ?case by(auto dest: allocate_SomeD)
next
case RedNewArrayNegative thus ?case unfolding sconf_def
by(fastforce intro: preallocated_heap_ops simp add: xcpt_subcls_Throwable[OF _ wf])
next
case RedNewArrayFail thus ?case unfolding sconf_def
by(fastforce intro:typeof_OutOfMemory preallocated_heap_ops simp add: xcpt_subcls_Throwable[OF _ wf])
next
case (CastRed e s ta e' s' C T E)
have esse: "extTA,P,t \<turnstile> \<langle>e,s\<rangle> -ta\<rightarrow> \<langle>e',s'\<rangle>"
and IH: "\<And>T E. \<lbrakk>E \<turnstile> s \<surd>; P,E,hp s \<turnstile> e : T; P,hp s \<turnstile> t \<surd>t\<rbrakk> \<Longrightarrow> \<exists>T'. P,E,hp s' \<turnstile> e' : T' \<and> P \<turnstile> T' \<le> T"
and hconf: "E \<turnstile> s \<surd>"
and wtc: "P,E,hp s \<turnstile> Cast C e : T" by fact+
thus ?case
proof(clarsimp)
fix T'
assume wte: "P,E,hp s \<turnstile> e : T'" "is_type P C"
from wte and hconf and IH and \<open>P,hp s \<turnstile> t \<surd>t\<close> have "\<exists>U. P,E,hp s' \<turnstile> e' : U \<and> P \<turnstile> U \<le> T'" by simp
then obtain U where wtee: "P,E,hp s' \<turnstile> e' : U" and UsTT: "P \<turnstile> U \<le> T'" by blast
from wtee \<open>is_type P C\<close> have "P,E,hp s' \<turnstile> Cast C e' : C" by(rule WTrtCast)
thus "\<exists>T'. P,E,hp s' \<turnstile> Cast C e' : T' \<and> P \<turnstile> T' \<le> C" by blast
qed
next
case RedCast thus ?case
by(clarsimp simp add: is_refT_def)
next
case RedCastFail thus ?case unfolding sconf_def
by(fastforce simp add: xcpt_subcls_Throwable[OF _ wf])
next
case (InstanceOfRed e s ta e' s' U T E)
have IH: "\<And>T E. \<lbrakk>E \<turnstile> s \<surd>; P,E,hp s \<turnstile> e : T; P,hp s \<turnstile> t \<surd>t\<rbrakk> \<Longrightarrow> \<exists>T'. P,E,hp s' \<turnstile> e' : T' \<and> P \<turnstile> T' \<le> T"
and hconf: "E \<turnstile> s \<surd>"
and wtc: "P,E,hp s \<turnstile> e instanceof U : T"
and tconf: "P,hp s \<turnstile> t \<surd>t" by fact+
from wtc obtain T' where "P,E,hp s \<turnstile> e : T'" by auto
from IH[OF hconf this tconf] obtain T'' where "P,E,hp s' \<turnstile> e' : T''" by auto
with wtc show ?case by auto
next
case RedInstanceOf thus ?case
by(clarsimp)
next
case (BinOpRed1 e\<^sub>1 s ta e\<^sub>1' s' bop e\<^sub>2 T E)
have red: "extTA,P,t \<turnstile> \<langle>e\<^sub>1, s\<rangle> -ta\<rightarrow> \<langle>e\<^sub>1', s'\<rangle>"
and IH: "\<And>T E. \<lbrakk>E \<turnstile> s \<surd>; P,E,hp s \<turnstile> e\<^sub>1:T; P,hp s \<turnstile> t \<surd>t\<rbrakk>
\<Longrightarrow> \<exists>U. P,E,hp s' \<turnstile> e\<^sub>1' : U \<and> P \<turnstile> U \<le> T"
and conf: "E \<turnstile> s \<surd>" and wt: "P,E,hp s \<turnstile> e\<^sub>1 \<guillemotleft>bop\<guillemotright> e\<^sub>2 : T"
and tconf: "P,hp s \<turnstile> t \<surd>t" by fact+
from wt obtain T1 T2 where wt1: "P,E,hp s \<turnstile> e\<^sub>1 : T1"
and wt2: "P,E,hp s \<turnstile> e\<^sub>2 : T2" and wtbop: "P \<turnstile> T1\<guillemotleft>bop\<guillemotright>T2 : T" by auto
from IH[OF conf wt1 tconf] obtain T1' where wt1': "P,E,hp s' \<turnstile> e\<^sub>1' : T1'"
and sub: "P \<turnstile> T1' \<le> T1" by blast
from WTrt_binop_widen_mono[OF wtbop sub widen_refl]
obtain T' where wtbop': "P \<turnstile> T1'\<guillemotleft>bop\<guillemotright>T2 : T'" and sub': "P \<turnstile> T' \<le> T" by blast
from wt1' WTrt_hext_mono[OF wt2 red_hext_incr[OF red]] wtbop'
have "P,E,hp s' \<turnstile> e\<^sub>1' \<guillemotleft>bop\<guillemotright> e\<^sub>2 : T'" by(rule WTrtBinOp)
with sub' show ?case by blast
next
case (BinOpRed2 e\<^sub>2 s ta e\<^sub>2' s' v\<^sub>1 bop T E)
have red: "extTA,P,t \<turnstile> \<langle>e\<^sub>2,s\<rangle> -ta\<rightarrow> \<langle>e\<^sub>2',s'\<rangle>" by fact
have IH: "\<And>E T. \<lbrakk>E \<turnstile> s \<surd>; P,E,hp s \<turnstile> e\<^sub>2:T; P,hp s \<turnstile> t \<surd>t\<rbrakk>
\<Longrightarrow> \<exists>U. P,E,hp s' \<turnstile> e\<^sub>2' : U \<and> P \<turnstile> U \<le> T"
and tconf: "P,hp s \<turnstile> t \<surd>t" by fact+
have conf: "E \<turnstile> s \<surd>" and wt: "P,E,hp s \<turnstile> (Val v\<^sub>1) \<guillemotleft>bop\<guillemotright> e\<^sub>2 : T" by fact+
from wt obtain T1 T2 where wt1: "P,E,hp s \<turnstile> Val v\<^sub>1 : T1"
and wt2: "P,E,hp s \<turnstile> e\<^sub>2 : T2" and wtbop: "P \<turnstile> T1\<guillemotleft>bop\<guillemotright>T2 : T" by auto
from IH[OF conf wt2 tconf] obtain T2' where wt2': "P,E,hp s' \<turnstile> e\<^sub>2' : T2'"
and sub: "P \<turnstile> T2' \<le> T2" by blast
from WTrt_binop_widen_mono[OF wtbop widen_refl sub]
obtain T' where wtbop': "P \<turnstile> T1\<guillemotleft>bop\<guillemotright>T2' : T'" and sub': "P \<turnstile> T' \<le> T" by blast
from WTrt_hext_mono[OF wt1 red_hext_incr[OF red]] wt2' wtbop'
have "P,E,hp s' \<turnstile> Val v\<^sub>1 \<guillemotleft>bop\<guillemotright> e\<^sub>2' : T'" by(rule WTrtBinOp)
with sub' show ?case by blast
next
case (RedBinOp bop v1 v2 v s)
from \<open>E \<turnstile> s \<surd>\<close> have preh: "preallocated (hp s)" by(cases s)(simp add: sconf_def)
from \<open>P,E,hp s \<turnstile> Val v1 \<guillemotleft>bop\<guillemotright> Val v2 : T\<close> obtain T1 T2
where "typeof\<^bsub>hp s\<^esub> v1 = \<lfloor>T1\<rfloor>" "typeof\<^bsub>hp s\<^esub> v2 = \<lfloor>T2\<rfloor>" "P \<turnstile> T1\<guillemotleft>bop\<guillemotright>T2 : T" by auto
with wf preh have "P,hp s \<turnstile> v :\<le> T" using \<open>binop bop v1 v2 = \<lfloor>Inl v\<rfloor>\<close>
by(rule binop_type)
thus ?case by(auto simp add: conf_def)
next
case (RedBinOpFail bop v1 v2 a s)
from \<open>E \<turnstile> s \<surd>\<close> have preh: "preallocated (hp s)" by(cases s)(simp add: sconf_def)
from \<open>P,E,hp s \<turnstile> Val v1 \<guillemotleft>bop\<guillemotright> Val v2 : T\<close> obtain T1 T2
where "typeof\<^bsub>hp s\<^esub> v1 = \<lfloor>T1\<rfloor>" "typeof\<^bsub>hp s\<^esub> v2 = \<lfloor>T2\<rfloor>" "P \<turnstile> T1\<guillemotleft>bop\<guillemotright>T2 : T" by auto
with wf preh have "P,hp s \<turnstile> Addr a :\<le> Class Throwable" using \<open>binop bop v1 v2 = \<lfloor>Inr a\<rfloor>\<close>
by(rule binop_type)
thus ?case by(auto simp add: conf_def)
next
case RedVar thus ?case by (fastforce simp:sconf_def lconf_def conf_def)
next
case LAssRed thus ?case by(blast intro:widen_trans)
next
case RedLAss thus ?case by fastforce
next
case (AAccRed1 a s ta a' s' i T E)
have IH: "\<And>E T. \<lbrakk>E \<turnstile> s \<surd>; P,E,hp s \<turnstile> a : T; P,hp s \<turnstile> t \<surd>t\<rbrakk> \<Longrightarrow> \<exists>T'. P,E,hp s' \<turnstile> a' : T' \<and> P \<turnstile> T' \<le> T"
and assa: "extTA,P,t \<turnstile> \<langle>a,s\<rangle> -ta\<rightarrow> \<langle>a',s'\<rangle>"
and wt: "P,E,hp s \<turnstile> a\<lfloor>i\<rceil> : T"
and hconf: "E \<turnstile> s \<surd>"
and tconf: "P,hp s \<turnstile> t \<surd>t" by fact+
from wt have wti: "P,E,hp s \<turnstile> i : Integer" by auto
from wti red_hext_incr[OF assa] have wti': "P,E,hp s' \<turnstile> i : Integer" by - (rule WTrt_hext_mono)
{ assume wta: "P,E,hp s \<turnstile> a : T\<lfloor>\<rceil>"
from IH[OF hconf wta tconf]
obtain U where wta': "P,E,hp s' \<turnstile> a' : U" and UsubT: "P \<turnstile> U \<le> T\<lfloor>\<rceil>" by fastforce
with wta' wti' have ?case by(cases U, auto simp add: widen_Array) }
moreover
{ assume wta: "P,E,hp s \<turnstile> a : NT"
from IH[OF hconf wta tconf] have "P,E,hp s' \<turnstile> a' : NT" by fastforce
from this wti' have ?case
by(fastforce intro:WTrtAAccNT) }
ultimately show ?case using wt by auto
next
case (AAccRed2 i s ta i' s' a T E)
have IH: "\<And>E T. \<lbrakk>E \<turnstile> s \<surd>; P,E,hp s \<turnstile> i : T; P,hp s \<turnstile> t \<surd>t\<rbrakk> \<Longrightarrow> \<exists>T'. P,E,hp s' \<turnstile> i' : T' \<and> P \<turnstile> T' \<le> T"
and issi: "extTA,P,t \<turnstile> \<langle>i,s\<rangle> -ta\<rightarrow> \<langle>i',s'\<rangle>"
and wt: "P,E,hp s \<turnstile> Val a\<lfloor>i\<rceil> : T"
and sconf: "E \<turnstile> s \<surd>"
and tconf: "P,hp s \<turnstile> t \<surd>t" by fact+
from wt have wti: "P,E,hp s \<turnstile> i : Integer" by auto
from wti IH sconf tconf have wti': "P,E,hp s' \<turnstile> i' : Integer" by blast
from wt show ?case
proof (rule WTrt_elim_cases)
assume wta: "P,E,hp s \<turnstile> Val a : T\<lfloor>\<rceil>"
from wta red_hext_incr[OF issi] have wta': "P,E,hp s' \<turnstile> Val a : T\<lfloor>\<rceil>" by (rule WTrt_hext_mono)
from wta' wti' show ?case by(fastforce)
next
assume wta: "P,E,hp s \<turnstile> Val a : NT"
from wta red_hext_incr[OF issi] have wta': "P,E,hp s' \<turnstile> Val a : NT" by (rule WTrt_hext_mono)
from wta' wti' show ?case
by(fastforce elim:WTrtAAccNT)
qed
next
case RedAAccNull thus ?case unfolding sconf_def
by(fastforce simp add: xcpt_subcls_Throwable[OF _ wf])
next
case RedAAccBounds thus ?case unfolding sconf_def
by(fastforce simp add: xcpt_subcls_Throwable[OF _ wf])
next
case (RedAAcc h a T n i v l T' E)
from \<open>E \<turnstile> (h, l) \<surd>\<close> have "hconf h" by(clarsimp simp add: sconf_def)
from \<open>0 <=s i\<close> \<open>sint i < int n\<close>
have "nat (sint i) < n"
by (simp add: word_sle_eq nat_less_iff)
with \<open>typeof_addr h a = \<lfloor>Array_type T n\<rfloor>\<close> have "P,h \<turnstile> a@ACell (nat (sint i)) : T"
by(auto intro: addr_loc_type.intros)
from heap_read_conf[OF \<open>heap_read h a (ACell (nat (sint i))) v\<close> this] \<open>hconf h\<close>
have "P,h \<turnstile> v :\<le> T" by simp
thus ?case using RedAAcc by(auto simp add: conf_def)
next
case (AAssRed1 a s ta a' s' i e T E)
have IH: "\<And>E T. \<lbrakk>E \<turnstile> s \<surd>; P,E,hp s \<turnstile> a : T; P,hp s \<turnstile> t \<surd>t\<rbrakk> \<Longrightarrow> \<exists>T'. P,E,hp s' \<turnstile> a' : T' \<and> P \<turnstile> T' \<le> T"
and assa: "extTA,P,t \<turnstile> \<langle>a,s\<rangle> -ta\<rightarrow> \<langle>a',s'\<rangle>"
and wt: "P,E,hp s \<turnstile> a\<lfloor>i\<rceil> := e : T"
and sconf: "E \<turnstile> s \<surd>"
and tconf: "P,hp s \<turnstile> t \<surd>t" by fact+
from wt have void: "T = Void" by blast
from wt have wti: "P,E,hp s \<turnstile> i : Integer" by auto
from wti red_hext_incr[OF assa] have wti': "P,E,hp s' \<turnstile> i : Integer" by - (rule WTrt_hext_mono)
{ assume wta: "P,E,hp s \<turnstile> a : NT"
from IH[OF sconf wta tconf] have wta': "P,E,hp s' \<turnstile> a' : NT" by fastforce
from wt wta obtain V where wte: "P,E,hp s \<turnstile> e : V" by(auto)
from wte red_hext_incr[OF assa] have wte': "P,E,hp s' \<turnstile> e : V" by - (rule WTrt_hext_mono)
from wta' wti' wte' void have ?case
by(fastforce elim: WTrtAAssNT) }
moreover
{ fix U
assume wta: "P,E,hp s \<turnstile> a : U\<lfloor>\<rceil>"
from IH[OF sconf wta tconf]
obtain U' where wta': "P,E,hp s' \<turnstile> a' : U'" and UsubT: "P \<turnstile> U' \<le> U\<lfloor>\<rceil>" by fastforce
with wta' have ?case
proof(cases U')
case NT
assume UNT: "U' = NT"
from UNT wt wta obtain V where wte: "P,E,hp s \<turnstile> e : V" by(auto)
from wte red_hext_incr[OF assa] have wte': "P,E,hp s' \<turnstile> e : V" by - (rule WTrt_hext_mono)
from wta' UNT wti' wte' void show ?thesis
by(fastforce elim: WTrtAAssNT)
next
case (Array A)
have UA: "U' = A\<lfloor>\<rceil>" by fact
with UA UsubT wt wta obtain V where wte: "P,E,hp s \<turnstile> e : V" by auto
from wte red_hext_incr[OF assa] have wte': "P,E,hp s' \<turnstile> e : V" by - (rule WTrt_hext_mono)
with wta' wte' UA wti' void show ?thesis by (fast elim:WTrtAAss)
qed(simp_all add: widen_Array) }
ultimately show ?case using wt by blast
next
case (AAssRed2 i s ta i' s' a e T E)
have IH: "\<And>E T. \<lbrakk>E \<turnstile> s \<surd>; P,E,hp s \<turnstile> i : T; P,hp s \<turnstile> t \<surd>t \<rbrakk> \<Longrightarrow> \<exists>T'. P,E,hp s' \<turnstile> i' : T' \<and> P \<turnstile> T' \<le> T"
and issi: "extTA,P,t \<turnstile> \<langle>i,s\<rangle> -ta\<rightarrow> \<langle>i',s'\<rangle>"
and wt: "P,E,hp s \<turnstile> Val a\<lfloor>i\<rceil> := e : T"
and sconf: "E \<turnstile> s \<surd>" and tconf: "P,hp s \<turnstile> t \<surd>t" by fact+
from wt have void: "T = Void" by blast
from wt have wti: "P,E,hp s \<turnstile> i : Integer" by auto
from IH[OF sconf wti tconf] have wti': "P,E,hp s' \<turnstile> i' : Integer" by fastforce
from wt show ?case
proof(rule WTrt_elim_cases)
fix U T'
assume wta: "P,E,hp s \<turnstile> Val a : U\<lfloor>\<rceil>"
and wte: "P,E,hp s \<turnstile> e : T'"
from wte red_hext_incr[OF issi] have wte': "P,E,hp s' \<turnstile> e : T'" by - (rule WTrt_hext_mono)
from wta red_hext_incr[OF issi] have wta': "P,E,hp s' \<turnstile> Val a : U\<lfloor>\<rceil>" by - (rule WTrt_hext_mono)
from wta' wti' wte' void show ?case by (fastforce elim:WTrtAAss)
next
fix T'
assume wta: "P,E,hp s \<turnstile> Val a : NT"
and wte: "P,E,hp s \<turnstile> e : T'"
from wte red_hext_incr[OF issi] have wte': "P,E,hp s' \<turnstile> e : T'" by - (rule WTrt_hext_mono)
from wta red_hext_incr[OF issi] have wta': "P,E,hp s' \<turnstile> Val a : NT" by - (rule WTrt_hext_mono)
from wta' wti' wte' void show ?case by (fastforce elim:WTrtAAss)
qed
next
case (AAssRed3 e s ta e' s' a i T E)
have IH: "\<And>E T. \<lbrakk>E \<turnstile> s \<surd>; P,E,hp s \<turnstile> e : T; P,hp s \<turnstile> t \<surd>t\<rbrakk> \<Longrightarrow> \<exists>T'. P,E,hp s' \<turnstile> e' : T' \<and> P \<turnstile> T' \<le> T"
and issi: "extTA,P,t \<turnstile> \<langle>e,s\<rangle> -ta\<rightarrow> \<langle>e',s'\<rangle>"
and wt: "P,E,hp s \<turnstile> Val a\<lfloor>Val i\<rceil> := e : T"
and sconf: "E \<turnstile> s \<surd>" and tconf: "P,hp s \<turnstile> t \<surd>t" by fact+
from wt have void: "T = Void" by blast
from wt have wti: "P,E,hp s \<turnstile> Val i : Integer" by auto
from wti red_hext_incr[OF issi] have wti': "P,E,hp s' \<turnstile> Val i : Integer" by - (rule WTrt_hext_mono)
from wt show ?case
proof(rule WTrt_elim_cases)
fix U T'
assume wta: "P,E,hp s \<turnstile> Val a : U\<lfloor>\<rceil>"
and wte: "P,E,hp s \<turnstile> e : T'"
from wta red_hext_incr[OF issi] have wta': "P,E,hp s' \<turnstile> Val a : U\<lfloor>\<rceil>" by - (rule WTrt_hext_mono)
from IH[OF sconf wte tconf]
obtain V where wte': "P,E,hp s' \<turnstile> e' : V" by fastforce
from wta' wti' wte' void show ?case by (fastforce elim:WTrtAAss)
next
fix T'
assume wta: "P,E,hp s \<turnstile> Val a : NT"
and wte: "P,E,hp s \<turnstile> e : T'"
from wta red_hext_incr[OF issi] have wta': "P,E,hp s' \<turnstile> Val a : NT" by - (rule WTrt_hext_mono)
from IH[OF sconf wte tconf]
obtain V where wte': "P,E,hp s' \<turnstile> e' : V" by fastforce
from wta' wti' wte' void show ?case by (fastforce elim:WTrtAAss)
qed
next
case RedAAssNull thus ?case unfolding sconf_def
by(fastforce simp add: xcpt_subcls_Throwable[OF _ wf])
next
case RedAAssBounds thus ?case unfolding sconf_def
by(fastforce simp add: xcpt_subcls_Throwable[OF _ wf])
next
case RedAAssStore thus ?case unfolding sconf_def
by(fastforce simp add: xcpt_subcls_Throwable[OF _ wf])
next
case RedAAss thus ?case
by(auto simp del:fun_upd_apply)
next
case (ALengthRed a s ta a' s' T E)
note IH = \<open>\<And>T'. \<lbrakk>E \<turnstile> s \<surd>; P,E,hp s \<turnstile> a : T'; P,hp s \<turnstile> t \<surd>t\<rbrakk>
\<Longrightarrow> \<exists>T''. P,E,hp s' \<turnstile> a' : T'' \<and> P \<turnstile> T'' \<le> T'\<close>
from \<open>P,E,hp s \<turnstile> a\<bullet>length : T\<close>
show ?case
proof(rule WTrt_elim_cases)
fix T'
assume [simp]: "T = Integer"
and wta: "P,E,hp s \<turnstile> a : T'\<lfloor>\<rceil>"
from wta \<open>E \<turnstile> s \<surd>\<close> IH \<open>P,hp s \<turnstile> t \<surd>t\<close>
obtain T'' where wta': "P,E,hp s' \<turnstile> a' : T''"
and sub: "P \<turnstile> T'' \<le> T'\<lfloor>\<rceil>" by blast
from sub have "P,E,hp s' \<turnstile> a'\<bullet>length : Integer"
unfolding widen_Array
proof(rule disjE)
assume "T'' = NT"
with wta' show ?thesis by(auto)
next
assume "\<exists>V. T'' = V\<lfloor>\<rceil> \<and> P \<turnstile> V \<le> T'"
then obtain V where "T'' = V\<lfloor>\<rceil>" "P \<turnstile> V \<le> T'" by blast
with wta' show ?thesis by -(rule WTrtALength, simp)
qed
thus ?thesis by(simp)
next
assume "P,E,hp s \<turnstile> a : NT"
with \<open>E \<turnstile> s \<surd>\<close> IH \<open>P,hp s \<turnstile> t \<surd>t\<close>
obtain T'' where wta': "P,E,hp s' \<turnstile> a' : T''"
and sub: "P \<turnstile> T'' \<le> NT" by blast
from sub have "T'' = NT" by auto
with wta' show ?thesis by(auto)
qed
next
case (RedALength h a T n l T' E)
from \<open>P,E,hp (h, l) \<turnstile> addr a\<bullet>length : T'\<close> \<open>typeof_addr h a = \<lfloor>Array_type T n\<rfloor>\<close>
have [simp]: "T' = Integer" by(auto)
thus ?case by(auto)
next
case RedALengthNull thus ?case unfolding sconf_def
by(fastforce simp add: xcpt_subcls_Throwable[OF _ wf])
next
case (FAccRed e s ta e' s' F D T E)
have IH: "\<And>E T. \<lbrakk>E \<turnstile> s \<surd>; P,E,hp s \<turnstile> e : T; P,hp s \<turnstile> t \<surd>t\<rbrakk>
\<Longrightarrow> \<exists>U. P,E,hp s' \<turnstile> e' : U \<and> P \<turnstile> U \<le> T"
and conf: "E \<turnstile> s \<surd>" and wt: "P,E,hp s \<turnstile> e\<bullet>F{D} : T"
and tconf: "P,hp s \<turnstile> t \<surd>t" by fact+
\<comment> \<open>Now distinguish the two cases how wt can have arisen.\<close>
{ fix T' C fm
assume wte: "P,E,hp s \<turnstile> e : T'"
and icto: "class_type_of' T' = \<lfloor>C\<rfloor>"
and has: "P \<turnstile> C has F:T (fm) in D"
from IH[OF conf wte tconf]
obtain U where wte': "P,E,hp s' \<turnstile> e' : U" and UsubC: "P \<turnstile> U \<le> T'" by auto
\<comment> \<open>Now distinguish what @{term U} can be.\<close>
with UsubC have ?case
proof(cases "U = NT")
case True
thus ?thesis using wte' by(blast intro:WTrtFAccNT widen_refl)
next
case False
with icto UsubC obtain C' where icto': "class_type_of' U = \<lfloor>C'\<rfloor>"
and C'subC: "P \<turnstile> C' \<preceq>\<^sup>* C"
by(rule widen_is_class_type_of)
from has_field_mono[OF has C'subC] wte' icto'
show ?thesis by(auto intro!:WTrtFAcc)
qed }
moreover
{ assume "P,E,hp s \<turnstile> e : NT"
hence "P,E,hp s' \<turnstile> e' : NT" using IH[OF conf _ tconf] by fastforce
hence ?case by(fastforce intro:WTrtFAccNT widen_refl) }
ultimately show ?case using wt by blast
next
case RedFAcc thus ?case unfolding sconf_def
by(fastforce dest: heap_read_conf intro: addr_loc_type.intros simp add: conf_def)
next
case RedFAccNull thus ?case unfolding sconf_def
by(fastforce simp add: xcpt_subcls_Throwable[OF _ wf])
next
case (FAssRed1 e s ta e' s' F D e\<^sub>2)
have red: "extTA,P,t \<turnstile> \<langle>e,s\<rangle> -ta\<rightarrow> \<langle>e',s'\<rangle>"
and IH: "\<And>E T. \<lbrakk>E \<turnstile> s \<surd>; P,E,hp s \<turnstile> e : T; P,hp s \<turnstile> t \<surd>t\<rbrakk>
\<Longrightarrow> \<exists>U. P,E,hp s' \<turnstile> e' : U \<and> P \<turnstile> U \<le> T"
and conf: "E \<turnstile> s \<surd>" and wt: "P,E,hp s \<turnstile> e\<bullet>F{D}:=e\<^sub>2 : T"
and tconf: "P,hp s \<turnstile> t \<surd>t" by fact+
from wt have void: "T = Void" by blast
\<comment> \<open>We distinguish if @{term e} has type @{term NT} or a Class type\<close>
{ assume "P,E,hp s \<turnstile> e : NT"
hence "P,E,hp s' \<turnstile> e' : NT" using IH[OF conf _ tconf] by fastforce
moreover obtain T\<^sub>2 where "P,E,hp s \<turnstile> e\<^sub>2 : T\<^sub>2" using wt by auto
from this red_hext_incr[OF red] have "P,E,hp s' \<turnstile> e\<^sub>2 : T\<^sub>2"
by(rule WTrt_hext_mono)
ultimately have ?case using void by(blast intro!:WTrtFAssNT)
}
moreover
{ fix T' C TF T\<^sub>2 fm
assume wt\<^sub>1: "P,E,hp s \<turnstile> e : T'" and icto: "class_type_of' T' = \<lfloor>C\<rfloor>" and wt\<^sub>2: "P,E,hp s \<turnstile> e\<^sub>2 : T\<^sub>2"
and has: "P \<turnstile> C has F:TF (fm) in D" and sub: "P \<turnstile> T\<^sub>2 \<le> TF"
obtain U where wt\<^sub>1': "P,E,hp s' \<turnstile> e' : U" and UsubC: "P \<turnstile> U \<le> T'"
using IH[OF conf wt\<^sub>1 tconf] by blast
have wt\<^sub>2': "P,E,hp s' \<turnstile> e\<^sub>2 : T\<^sub>2"
by(rule WTrt_hext_mono[OF wt\<^sub>2 red_hext_incr[OF red]])
\<comment> \<open>Is @{term U} the null type or a class type?\<close>
have ?case
proof(cases "U = NT")
case True
with wt\<^sub>1' wt\<^sub>2' void show ?thesis by(blast intro!:WTrtFAssNT)
next
case False
with icto UsubC obtain C' where icto': "class_type_of' U = \<lfloor>C'\<rfloor>"
and "subclass": "P \<turnstile> C' \<preceq>\<^sup>* C" by(rule widen_is_class_type_of)
have "P \<turnstile> C' has F:TF (fm) in D" by(rule has_field_mono[OF has "subclass"])
with wt\<^sub>1' show ?thesis using wt\<^sub>2' sub void icto' by(blast intro:WTrtFAss)
qed }
ultimately show ?case using wt by blast
next
case (FAssRed2 e\<^sub>2 s ta e\<^sub>2' s' v F D T E)
have red: "extTA,P,t \<turnstile> \<langle>e\<^sub>2,s\<rangle> -ta\<rightarrow> \<langle>e\<^sub>2',s'\<rangle>"
and IH: "\<And>E T. \<lbrakk>E \<turnstile> s \<surd>; P,E,hp s \<turnstile> e\<^sub>2 : T; P,hp s \<turnstile> t \<surd>t\<rbrakk>
\<Longrightarrow> \<exists>U. P,E,hp s' \<turnstile> e\<^sub>2' : U \<and> P \<turnstile> U \<le> T"
and conf: "E \<turnstile> s \<surd>" and wt: "P,E,hp s \<turnstile> Val v\<bullet>F{D}:=e\<^sub>2 : T"
and tconf: "P,hp s \<turnstile> t \<surd>t" by fact+
from wt have [simp]: "T = Void" by auto
from wt show ?case
proof (rule WTrt_elim_cases)
fix U C TF T\<^sub>2 fm
assume wt\<^sub>1: "P,E,hp s \<turnstile> Val v : U"
and icto: "class_type_of' U = \<lfloor>C\<rfloor>"
and has: "P \<turnstile> C has F:TF (fm) in D"
and wt\<^sub>2: "P,E,hp s \<turnstile> e\<^sub>2 : T\<^sub>2" and TsubTF: "P \<turnstile> T\<^sub>2 \<le> TF"
have wt\<^sub>1': "P,E,hp s' \<turnstile> Val v : U"
by(rule WTrt_hext_mono[OF wt\<^sub>1 red_hext_incr[OF red]])
obtain T\<^sub>2' where wt\<^sub>2': "P,E,hp s' \<turnstile> e\<^sub>2' : T\<^sub>2'" and T'subT: "P \<turnstile> T\<^sub>2' \<le> T\<^sub>2"
using IH[OF conf wt\<^sub>2 tconf] by blast
have "P,E,hp s' \<turnstile> Val v\<bullet>F{D}:=e\<^sub>2' : Void"
by(rule WTrtFAss[OF wt\<^sub>1' icto has wt\<^sub>2' widen_trans[OF T'subT TsubTF]])
thus ?case by auto
next
fix T\<^sub>2 assume null: "P,E,hp s \<turnstile> Val v : NT" and wt\<^sub>2: "P,E,hp s \<turnstile> e\<^sub>2 : T\<^sub>2"
from null have "v = Null" by simp
moreover
obtain T\<^sub>2' where "P,E,hp s' \<turnstile> e\<^sub>2' : T\<^sub>2' \<and> P \<turnstile> T\<^sub>2' \<le> T\<^sub>2"
using IH[OF conf wt\<^sub>2 tconf] by blast
ultimately show ?thesis by(fastforce intro:WTrtFAssNT)
qed
next
case RedFAss thus ?case by(auto simp del:fun_upd_apply)
next
case RedFAssNull thus ?case unfolding sconf_def
by(fastforce simp add: xcpt_subcls_Throwable[OF _ wf])
next
case (CASRed1 e s ta e' s' D F e2 e3)
from CASRed1.prems(2) consider (NT) T2 T3 where
"P,E,hp s \<turnstile> e : NT" "T = Boolean" "P,E,hp s \<turnstile> e2 : T2" "P,E,hp s \<turnstile> e3 : T3"
| (RefT) U T' C fm T2 T3 where
"P,E,hp s \<turnstile> e : U" "T = Boolean" "class_type_of' U = \<lfloor>C\<rfloor>" "P \<turnstile> C has F:T' (fm) in D"
"P,E,hp s \<turnstile> e2 : T2" "P \<turnstile> T2 \<le> T'" "P,E,hp s \<turnstile> e3 : T3" "P \<turnstile> T3 \<le> T'" "volatile fm" by fastforce
thus ?case
proof cases
case NT
have "P,E,hp s' \<turnstile> e' : NT" using CASRed1.hyps(2)[OF CASRed1.prems(1) NT(1) CASRed1.prems(3)] by auto
moreover from NT CASRed1.hyps(1)[THEN red_hext_incr]
have "P,E,hp s' \<turnstile> e2 : T2" "P,E,hp s' \<turnstile> e3 : T3" by(auto intro: WTrt_hext_mono)
ultimately show ?thesis using NT by(auto intro: WTrtCASNT)
next
case RefT
from CASRed1.hyps(2)[OF CASRed1.prems(1) RefT(1) CASRed1.prems(3)]
obtain U' where wt1: "P,E,hp s' \<turnstile> e' : U'" "P \<turnstile> U' \<le> U" by blast
from RefT CASRed1.hyps(1)[THEN red_hext_incr]
have wt2: "P,E,hp s' \<turnstile> e2 : T2" and wt3: "P,E,hp s' \<turnstile> e3 : T3" by(auto intro: WTrt_hext_mono)
show ?thesis
proof(cases "U' = NT")
case True
with RefT wt1 wt2 wt3 show ?thesis by(auto intro: WTrtCASNT)
next
case False
with RefT(3) wt1 obtain C' where icto': "class_type_of' U' = \<lfloor>C'\<rfloor>"
and "subclass": "P \<turnstile> C' \<preceq>\<^sup>* C" by(blast intro: widen_is_class_type_of)
have "P \<turnstile> C' has F:T' (fm) in D" by(rule has_field_mono[OF RefT(4) "subclass"])
with RefT wt1 wt2 wt3 icto' show ?thesis by(auto intro!: WTrtCAS)
qed
qed
next
case (CASRed2 e s ta e' s' v D F e3)
consider (Null) "v = Null" | (Val) U C T' fm T2 T3 where
"class_type_of' U = \<lfloor>C\<rfloor>" "P \<turnstile> C has F:T' (fm) in D" "volatile fm"
"P,E,hp s \<turnstile> e : T2" "P \<turnstile> T2 \<le> T'" "P,E,hp s \<turnstile> e3 : T3" "P \<turnstile> T3 \<le> T'" "T = Boolean"
"typeof\<^bsub>hp s\<^esub> v = \<lfloor>U\<rfloor>" using CASRed2.prems(2) by auto
then show ?case
proof cases
case Null
then show ?thesis using CASRed2
by(force dest: red_hext_incr intro: WTrt_hext_mono WTrtCASNT)
next
case Val
from CASRed2.hyps(1) have hext: "hp s \<unlhd> hp s'" by(auto dest: red_hext_incr)
with Val(9) have "typeof\<^bsub>hp s'\<^esub> v = \<lfloor>U\<rfloor>" by(rule type_of_hext_type_of)
moreover from CASRed2.hyps(2)[OF CASRed2.prems(1) Val(4) CASRed2.prems(3)] Val(5)
obtain T2' where "P,E,hp s' \<turnstile> e' : T2'" "P \<turnstile> T2' \<le> T'" by(auto intro: widen_trans)
moreover from Val(6) hext have "P,E,hp s' \<turnstile> e3 : T3" by(rule WTrt_hext_mono)
ultimately show ?thesis using Val by(auto intro: WTrtCAS)
qed
next
case (CASRed3 e s ta e' s' v D F v')
consider (Null) "v = Null" | (Val) U C T' fm T2 T3 where
"T = Boolean" "class_type_of' U = \<lfloor>C\<rfloor>" "P \<turnstile> C has F:T' (fm) in D" "volatile fm"
"P \<turnstile> T2 \<le> T'" "P,E,hp s \<turnstile> e : T3" "P \<turnstile> T3 \<le> T'"
"typeof\<^bsub>hp s\<^esub> v = \<lfloor>U\<rfloor>" "typeof\<^bsub>hp s\<^esub> v' = \<lfloor>T2\<rfloor>"
using CASRed3.prems(2) by auto
then show ?case
proof cases
case Null
then show ?thesis using CASRed3
by(force dest: red_hext_incr intro: type_of_hext_type_of WTrtCASNT)
next
case Val
from CASRed3.hyps(1) have hext: "hp s \<unlhd> hp s'" by(auto dest: red_hext_incr)
with Val(8,9) have "typeof\<^bsub>hp s'\<^esub> v = \<lfloor>U\<rfloor>" "typeof\<^bsub>hp s'\<^esub> v' = \<lfloor>T2\<rfloor>"
by(blast intro: type_of_hext_type_of)+
moreover from CASRed3.hyps(2)[OF CASRed3.prems(1) Val(6) CASRed3.prems(3)] Val(7)
obtain T3' where "P,E,hp s' \<turnstile> e' : T3'" "P \<turnstile> T3' \<le> T'" by(auto intro: widen_trans)
ultimately show ?thesis using Val by(auto intro: WTrtCAS)
qed
next
case CASNull thus ?case unfolding sconf_def
by(fastforce simp add: xcpt_subcls_Throwable[OF _ wf])
next
case (CallObj e s ta e' s' M es T E)
have red: "extTA,P,t \<turnstile> \<langle>e,s\<rangle> -ta\<rightarrow> \<langle>e',s'\<rangle>"
and IH: "\<And>E T. \<lbrakk>E \<turnstile> s \<surd>; P,E,hp s \<turnstile> e : T; P,hp s \<turnstile> t \<surd>t\<rbrakk>
\<Longrightarrow> \<exists>U. P,E,hp s' \<turnstile> e' : U \<and> P \<turnstile> U \<le> T"
and conf: "E \<turnstile> s \<surd>" and wt: "P,E,hp s \<turnstile> e\<bullet>M(es) : T"
and tconf: "P,hp s \<turnstile> t \<surd>t" by fact+
\<comment> \<open>We distinguish if @{term e} has type @{term NT} or a Class type\<close>
from wt show ?case
proof(rule WTrt_elim_cases)
fix T' C Ts meth D Us
assume wte: "P,E,hp s \<turnstile> e : T'" and icto: "class_type_of' T' = \<lfloor>C\<rfloor>"
and "method": "P \<turnstile> C sees M:Ts\<rightarrow>T = meth in D"
and wtes: "P,E,hp s \<turnstile> es [:] Us" and subs: "P \<turnstile> Us [\<le>] Ts"
obtain U where wte': "P,E,hp s' \<turnstile> e' : U" and UsubC: "P \<turnstile> U \<le> T'"
using IH[OF conf wte tconf] by blast
show ?thesis
proof(cases "U = NT")
case True
moreover have "P,E,hp s' \<turnstile> es [:] Us"
by(rule WTrts_hext_mono[OF wtes red_hext_incr[OF red]])
ultimately show ?thesis using wte' by(blast intro!:WTrtCallNT)
next
case False
with icto UsubC obtain C'
where icto': "class_type_of' U = \<lfloor>C'\<rfloor>" and "subclass": "P \<turnstile> C' \<preceq>\<^sup>* C"
by(rule widen_is_class_type_of)
obtain Ts' T' meth' D'
where method': "P \<turnstile> C' sees M:Ts'\<rightarrow>T' = meth' in D'"
and subs': "P \<turnstile> Ts [\<le>] Ts'" and sub': "P \<turnstile> T' \<le> T"
using Call_lemma[OF "method" "subclass" wf] by fast
have wtes': "P,E,hp s' \<turnstile> es [:] Us"
by(rule WTrts_hext_mono[OF wtes red_hext_incr[OF red]])
show ?thesis using wtes' wte' icto' subs method' subs' sub' by(blast intro:widens_trans)
qed
next
fix Ts
assume "P,E,hp s \<turnstile> e:NT"
hence "P,E,hp s' \<turnstile> e' : NT" using IH[OF conf _ tconf] by fastforce
moreover
fix Ts assume wtes: "P,E,hp s \<turnstile> es [:] Ts"
have "P,E,hp s' \<turnstile> es [:] Ts"
by(rule WTrts_hext_mono[OF wtes red_hext_incr[OF red]])
ultimately show ?thesis by(blast intro!:WTrtCallNT)
qed
next
case (CallParams es s ta es' s' v M T E)
have reds: "extTA,P,t \<turnstile> \<langle>es,s\<rangle> [-ta\<rightarrow>] \<langle>es',s'\<rangle>"
and IH: "\<And>Ts E. \<lbrakk>E \<turnstile> s \<surd>; P,E,hp s \<turnstile> es [:] Ts; P,hp s \<turnstile> t \<surd>t\<rbrakk>
\<Longrightarrow> \<exists>Ts'. P,E,hp s' \<turnstile> es' [:] Ts' \<and> P \<turnstile> Ts' [\<le>] Ts"
and conf: "E \<turnstile> s \<surd>" and wt: "P,E,hp s \<turnstile> Val v\<bullet>M(es) : T"
and tconf: "P,hp s \<turnstile> t \<surd>t" by fact+
from wt show ?case
proof (rule WTrt_elim_cases)
fix U C Ts meth D Us
assume wte: "P,E,hp s \<turnstile> Val v : U" and icto: "class_type_of' U = \<lfloor>C\<rfloor>"
and "P \<turnstile> C sees M:Ts\<rightarrow>T = meth in D"
and wtes: "P,E,hp s \<turnstile> es [:] Us" and "P \<turnstile> Us [\<le>] Ts"
moreover have "P,E,hp s' \<turnstile> Val v : U"
by(rule WTrt_hext_mono[OF wte reds_hext_incr[OF reds]])
moreover obtain Us' where "P,E,hp s' \<turnstile> es' [:] Us'" "P \<turnstile> Us' [\<le>] Us"
using IH[OF conf wtes tconf] by blast
ultimately show ?thesis by(fastforce intro:WTrtCall widens_trans)
next
fix Us
assume null: "P,E,hp s \<turnstile> Val v : NT" and wtes: "P,E,hp s \<turnstile> es [:] Us"
from null have "v = Null" by simp
moreover
obtain Us' where "P,E,hp s' \<turnstile> es' [:] Us' \<and> P \<turnstile> Us' [\<le>] Us"
using IH[OF conf wtes tconf] by blast
ultimately show ?thesis by(fastforce intro:WTrtCallNT)
qed
next
case (RedCall s a U M Ts T pns body D vs T' E)
have hp: "typeof_addr (hp s) a = \<lfloor>U\<rfloor>"
and "method": "P \<turnstile> class_type_of U sees M: Ts\<rightarrow>T = \<lfloor>(pns,body)\<rfloor> in D"
and wt: "P,E,hp s \<turnstile> addr a\<bullet>M(map Val vs) : T'" by fact+
obtain Ts' where wtes: "P,E,hp s \<turnstile> map Val vs [:] Ts'"
and subs: "P \<turnstile> Ts' [\<le>] Ts" and T'isT: "T' = T"
using wt "method" hp wf by(auto 4 3 dest: sees_method_fun)
from wtes subs have length_vs: "length vs = length Ts"
by(auto simp add: WTrts_conv_list_all2 dest!: list_all2_lengthD)
have UsubD: "P \<turnstile> ty_of_htype U \<le> Class (class_type_of U)"
by(cases U)(simp_all add: widen_array_object)
from sees_wf_mdecl[OF wf "method"] obtain T''
where wtabody: "P,[this#pns [\<mapsto>] Class D#Ts] \<turnstile> body :: T''"
and T''subT: "P \<turnstile> T'' \<le> T" and length_pns: "length pns = length Ts"
by(fastforce simp:wf_mdecl_def simp del:map_upds_twist)
from wtabody have "P,Map.empty(this#pns [\<mapsto>] Class D#Ts),hp s \<turnstile> body : T''"
by(rule WT_implies_WTrt)
hence "P,E(this#pns [\<mapsto>] Class D#Ts),hp s \<turnstile> body : T''"
by(rule WTrt_env_mono) simp
hence "P,E,hp s \<turnstile> blocks (this#pns) (Class D#Ts) (Addr a#vs) body : T''"
using wtes subs hp sees_method_decl_above[OF "method"] length_vs length_pns UsubD
by(auto simp add:wt_blocks rel_list_all2_Cons2 intro: widen_trans)
with T''subT T'isT show ?case by blast
next
case (RedCallExternal s a U M Ts T' D vs ta va h' ta' e' s')
from \<open>P,t \<turnstile> \<langle>a\<bullet>M(vs),hp s\<rangle> -ta\<rightarrow>ext \<langle>va,h'\<rangle>\<close> have "hp s \<unlhd> h'" by(rule red_external_hext)
with \<open>P,E,hp s \<turnstile> addr a\<bullet>M(map Val vs) : T\<close>
have "P,E,h' \<turnstile> addr a\<bullet>M(map Val vs) : T" by(rule WTrt_hext_mono)
moreover from \<open>typeof_addr (hp s) a = \<lfloor>U\<rfloor>\<close> \<open>P \<turnstile> class_type_of U sees M: Ts\<rightarrow>T' = Native in D\<close> \<open>P,E,hp s \<turnstile> addr a\<bullet>M(map Val vs) : T\<close>
have "P,hp s \<turnstile> a\<bullet>M(vs) : T'"
by(fastforce simp add: external_WT'_iff dest: sees_method_fun)
ultimately show ?case using RedCallExternal
by(auto 4 3 intro: red_external_conf_extRet[OF wf] intro!: wt_external_call simp add: sconf_def dest: sees_method_fun[where C="class_type_of U"])
next
case RedCallNull thus ?case unfolding sconf_def
by(fastforce simp add: xcpt_subcls_Throwable[OF _ wf])
next
case (BlockRed e h x V vo ta e' h' x' T T' E)
note IH = \<open>\<And>T E. \<lbrakk>E \<turnstile> (h, x(V := vo)) \<surd>; P,E,hp (h, x(V := vo)) \<turnstile> e : T; P,hp (h, x(V := vo)) \<turnstile> t \<surd>t\<rbrakk>
\<Longrightarrow> \<exists>T'. P,E,hp (h', x') \<turnstile> e' : T' \<and> P \<turnstile> T' \<le> T\<close>[simplified]
from \<open>P,E,hp (h, x) \<turnstile> {V:T=vo; e} : T'\<close> have "P,E(V\<mapsto>T),h \<turnstile> e : T'" by(cases vo, auto)
moreover from \<open>E \<turnstile> (h, x) \<surd>\<close> \<open>P,E,hp (h, x) \<turnstile> {V:T=vo; e} : T'\<close>
have "(E(V \<mapsto> T)) \<turnstile> (h, x(V := vo)) \<surd>"
by(cases vo)(simp add: lconf_def sconf_def,auto simp add: sconf_def conf_def intro: lconf_upd2)
ultimately obtain T'' where wt': "P,E(V\<mapsto>T),h' \<turnstile> e' : T''" "P \<turnstile> T'' \<le> T'" using \<open>P,hp (h, x) \<turnstile> t \<surd>t\<close>
by(auto dest: IH)
{ fix v
assume vo: "x' V = \<lfloor>v\<rfloor>"
from \<open>(E(V \<mapsto> T)) \<turnstile> (h, x(V := vo)) \<surd>\<close> \<open>extTA,P,t \<turnstile> \<langle>e,(h, x(V := vo))\<rangle> -ta\<rightarrow> \<langle>e',(h', x')\<rangle>\<close> \<open>P,E(V\<mapsto>T),h \<turnstile> e : T'\<close>
have "P,h' \<turnstile> x' (:\<le>) (E(V \<mapsto> T))" by(auto simp add: sconf_def dest: red_preserves_lconf)
with vo have "\<exists>T'. typeof\<^bsub>h'\<^esub> v = \<lfloor>T'\<rfloor> \<and> P \<turnstile> T' \<le> T" by(fastforce simp add: sconf_def lconf_def conf_def)
then obtain T' where "typeof\<^bsub>h'\<^esub> v = \<lfloor>T'\<rfloor>" "P \<turnstile> T' \<le> T" by blast
hence ?case using wt' vo by(auto) }
moreover
{ assume "x' V = None" with wt' have ?case by(auto) }
ultimately show ?case by blast
next
case RedBlock thus ?case by auto
next
case (SynchronizedRed1 o' s ta o'' s' e T E)
have red: "extTA,P,t \<turnstile> \<langle>o',s\<rangle> -ta\<rightarrow> \<langle>o'',s'\<rangle>" by fact
have IH: "\<And>T E. \<lbrakk>E \<turnstile> s \<surd>; P,E,hp s \<turnstile> o' : T; P,hp s \<turnstile> t \<surd>t\<rbrakk> \<Longrightarrow> \<exists>T'. P,E,hp s' \<turnstile> o'' : T' \<and> P \<turnstile> T' \<le> T" by fact
have conf: "E \<turnstile> s \<surd>" by fact
have wt: "P,E,hp s \<turnstile> sync(o') e : T" by fact+
thus ?case
proof(rule WTrt_elim_cases)
fix To
assume wto: "P,E,hp s \<turnstile> o' : To"
and refT: "is_refT To"
and wte: "P,E,hp s \<turnstile> e : T"
from IH[OF conf wto \<open>P,hp s \<turnstile> t \<surd>t\<close>] obtain To' where "P,E,hp s' \<turnstile> o'' : To'" and sub: "P \<turnstile> To' \<le> To" by auto
moreover have "P,E,hp s' \<turnstile> e : T"
by(rule WTrt_hext_mono[OF wte red_hext_incr[OF red]])
moreover have "is_refT To'" using refT sub by(auto intro: widen_refT)
ultimately show ?thesis by(auto)
qed
next
case SynchronizedNull thus ?case unfolding sconf_def
by(fastforce simp add: xcpt_subcls_Throwable[OF _ wf])
next
case LockSynchronized thus ?case by(auto)
next
case (SynchronizedRed2 e s ta e' s' a T E)
have red: "extTA,P,t \<turnstile> \<langle>e,s\<rangle> -ta\<rightarrow> \<langle>e',s'\<rangle>" by fact
have IH: "\<And>T E. \<lbrakk>E \<turnstile> s \<surd>; P,E,hp s \<turnstile> e : T; P,hp s \<turnstile> t \<surd>t\<rbrakk> \<Longrightarrow> \<exists>T'. P,E,hp s' \<turnstile> e' : T' \<and> P \<turnstile> T' \<le> T" by fact
have conf: "E \<turnstile> s \<surd>" by fact
have wt: "P,E,hp s \<turnstile> insync(a) e : T" by fact
thus ?case
proof(rule WTrt_elim_cases)
fix Ta
assume "P,E,hp s \<turnstile> e : T"
and hpa: "typeof_addr (hp s) a = \<lfloor>Ta\<rfloor>"
from \<open>P,E,hp s \<turnstile> e : T\<close> conf \<open>P,hp s \<turnstile> t \<surd>t\<close> obtain T'
where "P,E,hp s' \<turnstile> e' : T'" "P \<turnstile> T' \<le> T" by(blast dest: IH)
moreover from red have hext: "hp s \<unlhd> hp s'" by(auto dest: red_hext_incr)
with hpa have "P,E,hp s' \<turnstile> addr a : ty_of_htype Ta"
by(auto intro: typeof_addr_hext_mono)
ultimately show ?thesis by auto
qed
next
case UnlockSynchronized thus ?case by(auto)
next
case SeqRed thus ?case
apply(auto)
apply(drule WTrt_hext_mono[OF _ red_hext_incr], assumption)
by auto
next
case (CondRed b s ta b' s' e1 e2 T E)
have red: "extTA,P,t \<turnstile> \<langle>b,s\<rangle> -ta\<rightarrow> \<langle>b',s'\<rangle>" by fact
have IH: "\<And>T E. \<lbrakk>E \<turnstile> s \<surd>; P,E,hp s \<turnstile> b : T; P,hp s \<turnstile> t \<surd>t\<rbrakk> \<Longrightarrow> \<exists>T'. P,E,hp s' \<turnstile> b' : T' \<and> P \<turnstile> T' \<le> T" by fact
have conf: "E \<turnstile> s \<surd>" by fact
have wt: "P,E,hp s \<turnstile> if (b) e1 else e2 : T" by fact
thus ?case
proof(rule WTrt_elim_cases)
fix T1 T2
assume wtb: "P,E,hp s \<turnstile> b : Boolean"
and wte1: "P,E,hp s \<turnstile> e1 : T1"
and wte2: "P,E,hp s \<turnstile> e2 : T2"
and lub: "P \<turnstile> lub(T1, T2) = T"
from IH[OF conf wtb \<open>P,hp s \<turnstile> t \<surd>t\<close>] have "P,E,hp s' \<turnstile> b' : Boolean" by(auto)
moreover have "P,E,hp s' \<turnstile> e1 : T1"
by(rule WTrt_hext_mono[OF wte1 red_hext_incr[OF red]])
moreover have "P,E,hp s' \<turnstile> e2 : T2"
by(rule WTrt_hext_mono[OF wte2 red_hext_incr[OF red]])
ultimately show ?thesis using lub by auto
qed
next
case (ThrowRed e s ta e' s' T E)
have IH: "\<And>T E. \<lbrakk>E \<turnstile> s \<surd>; P,E,hp s \<turnstile> e : T; P,hp s \<turnstile> t \<surd>t\<rbrakk> \<Longrightarrow> \<exists>T'. P,E,hp s' \<turnstile> e' : T' \<and> P \<turnstile> T' \<le> T" by fact
have conf: "E \<turnstile> s \<surd>" by fact
have wt: "P,E,hp s \<turnstile> throw e : T" by fact
then obtain T'
where wte: "P,E,hp s \<turnstile> e : T'"
and nobject: "P \<turnstile> T' \<le> Class Throwable" by auto
from IH[OF conf wte \<open>P,hp s \<turnstile> t \<surd>t\<close>] obtain T''
where wte': "P,E,hp s' \<turnstile> e' : T''"
and PT'T'': "P \<turnstile> T'' \<le> T'" by blast
from nobject PT'T'' have "P \<turnstile> T'' \<le> Class Throwable"
by(auto simp add: widen_Class)(erule notE, rule rtranclp_trans)
hence "P,E,hp s' \<turnstile> throw e' : T" using wte' PT'T''
by -(erule WTrtThrow)
thus ?case by(auto)
next
case RedThrowNull thus ?case unfolding sconf_def
by(fastforce simp add: xcpt_subcls_Throwable[OF _ wf])
next
case (TryRed e s ta e' s' C V e2 T E)
have red: "extTA,P,t \<turnstile> \<langle>e,s\<rangle> -ta\<rightarrow> \<langle>e',s'\<rangle>" by fact
have IH: "\<And>T E. \<lbrakk>E \<turnstile> s \<surd>; P,E,hp s \<turnstile> e : T; P,hp s \<turnstile> t \<surd>t\<rbrakk> \<Longrightarrow> \<exists>T'. P,E,hp s' \<turnstile> e' : T' \<and> P \<turnstile> T' \<le> T" by fact
have conf: "E \<turnstile> s \<surd>" by fact
have wt: "P,E,hp s \<turnstile> try e catch(C V) e2 : T" by fact
thus ?case
proof(rule WTrt_elim_cases)
fix T1
assume wte: "P,E,hp s \<turnstile> e : T1"
and wte2: "P,E(V \<mapsto> Class C),hp s \<turnstile> e2 : T"
and sub: "P \<turnstile> T1 \<le> T"
from IH[OF conf wte \<open>P,hp s \<turnstile> t \<surd>t\<close>] obtain T1' where "P,E,hp s' \<turnstile> e' : T1'" and "P \<turnstile> T1' \<le> T1" by(auto)
moreover have "P,E(V \<mapsto> Class C),hp s' \<turnstile> e2 : T"
by(rule WTrt_hext_mono[OF wte2 red_hext_incr[OF red]])
ultimately show ?thesis using sub by(auto elim: widen_trans)
qed
next
case RedTryFail thus ?case unfolding sconf_def
by(fastforce simp add: xcpt_subcls_Throwable[OF _ wf])
next
case RedSeq thus ?case by auto
next
case RedCondT thus ?case by(auto dest: is_lub_upper)
next
case RedCondF thus ?case by(auto dest: is_lub_upper)
next
case RedWhile thus ?case by(fastforce)
next
case RedTry thus ?case by auto
next
case RedTryCatch thus ?case by(fastforce)
next
case (ListRed1 e s ta e' s' es Ts E)
note IH = \<open>\<And>T E. \<lbrakk>E \<turnstile> s \<surd>; P,E,hp s \<turnstile> e : T; P,hp s \<turnstile> t \<surd>t\<rbrakk> \<Longrightarrow> \<exists>T'. P,E,hp s' \<turnstile> e' : T' \<and> P \<turnstile> T' \<le> T\<close>
from \<open>P,E,hp s \<turnstile> e # es [:] Ts\<close> obtain T Ts' where "Ts = T # Ts'" "P,E,hp s \<turnstile> e : T" "P,E,hp s \<turnstile> es [:] Ts'" by auto
with IH[of E T] \<open>E \<turnstile> s \<surd>\<close> WTrts_hext_mono[OF \<open>P,E,hp s \<turnstile> es [:] Ts'\<close> red_hext_incr[OF \<open>extTA,P,t \<turnstile> \<langle>e,s\<rangle> -ta\<rightarrow> \<langle>e',s'\<rangle>\<close>]]
show ?case using \<open>P,hp s \<turnstile> t \<surd>t\<close> by(auto simp add: list_all2_Cons2 intro: widens_refl)
next
case ListRed2 thus ?case
by(fastforce dest: hext_typeof_mono[OF reds_hext_incr])
qed(fastforce)+
end
|
import group_theory.group_action.basic
variables (R M S : Type*)
/-- Some arbitrary type depending on `has_smul R M` -/
@[irreducible, nolint has_nonempty_instance unused_arguments]
def foo [has_smul R M] : Type* := ℕ
variables [has_smul R M] [has_smul S R] [has_smul S M]
/-- This instance is incompatible with `has_smul.comp.is_scalar_tower`.
However, all its parameters are (instance) implicits or irreducible defs, so it
should not be dangerous. -/
@[nolint unused_arguments]
instance foo.has_smul [is_scalar_tower S R M] : has_smul S (foo R M) :=
⟨λ _ _, by { unfold foo, exact 37 }⟩
-- If there is no `is_scalar_tower S R M` parameter, this should fail quickly,
-- not loop forever.
example : has_smul S (foo R M) :=
begin
tactic.success_if_fail_with_msg tactic.interactive.apply_instance
"tactic.mk_instance failed to generate instance for
has_smul S (foo R M)",
unfold foo,
exact ⟨λ _ _, 37⟩
end
/-
local attribute [instance] has_smul.comp.is_scalar_tower
-- When `has_smul.comp.is_scalar_tower` is an instance, this recurses indefinitely.
example : has_smul S (foo R M) :=
begin
tactic.success_if_fail_with_msg tactic.interactive.apply_instance
"maximum class-instance resolution depth has been reached (the limit can be increased by setting option 'class.instance_max_depth') (the class-instance resolution trace can be visualized by setting option 'trace.class_instances')",
unfold foo,
exact ⟨λ _ _, 37⟩
end
-/
|
//=======================================================================
// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee,
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <iostream>
#include <boost/graph/edge_list.hpp>
#include <boost/graph/bellman_ford_shortest_paths.hpp>
int
main()
{
using namespace boost;
// ID numbers for the routers (vertices).
enum
{ A, B, C, D, E, F, G, H, n_vertices };
const int n_edges = 11;
typedef std::pair < int, int >Edge;
// The list of connections between routers stored in an array.
Edge edges[] = {
Edge(A, B), Edge(A, C),
Edge(B, D), Edge(B, E), Edge(C, E), Edge(C, F), Edge(D, H),
Edge(D, E), Edge(E, H), Edge(F, G), Edge(G, H)
};
// Specify the graph type and declare a graph object
typedef edge_list < Edge*, Edge, std::ptrdiff_t, std::random_access_iterator_tag> Graph;
Graph g(edges, edges + n_edges);
// The transmission delay values for each edge.
float delay[] =
{5.0, 1.0, 1.3, 3.0, 10.0, 2.0, 6.3, 0.4, 1.3, 1.2, 0.5};
// Declare some storage for some "external" vertex properties.
char name[] = "ABCDEFGH";
int parent[n_vertices];
for (int i = 0; i < n_vertices; ++i)
parent[i] = i;
float distance[n_vertices];
std::fill(distance, distance + n_vertices, (std::numeric_limits < float >::max)());
// Specify A as the source vertex
distance[A] = 0;
bool r = bellman_ford_shortest_paths(g, int (n_vertices),
weight_map(make_iterator_property_map
(&delay[0],
get(edge_index, g),
delay[0])).
distance_map(&distance[0]).
predecessor_map(&parent[0]));
if (r)
for (int i = 0; i < n_vertices; ++i)
std::cout << name[i] << ": " << distance[i]
<< " " << name[parent[i]] << std::endl;
else
std::cout << "negative cycle" << std::endl;
return EXIT_SUCCESS;
}
|
(* Title: HOL/Analysis/Norm_Arith.thy
Author: Amine Chaieb, University of Cambridge
*)
section \<open>Linear Decision Procedure for Normed Spaces\<close>
theory Norm_Arith
imports "HOL-Library.Sum_of_Squares"
begin
(* FIXME: move elsewhere *)
lemma sum_sqs_eq:
fixes x::"'a::idom" shows "x * x + y * y = x * (y * 2) \<Longrightarrow> y = x"
by algebra
lemma norm_cmul_rule_thm:
fixes x :: "'a::real_normed_vector"
shows "b \<ge> norm x \<Longrightarrow> \<bar>c\<bar> * b \<ge> norm (scaleR c x)"
unfolding norm_scaleR
apply (erule mult_left_mono)
apply simp
done
(* FIXME: Move all these theorems into the ML code using lemma antiquotation *)
lemma norm_add_rule_thm:
fixes x1 x2 :: "'a::real_normed_vector"
shows "norm x1 \<le> b1 \<Longrightarrow> norm x2 \<le> b2 \<Longrightarrow> norm (x1 + x2) \<le> b1 + b2"
by (rule order_trans [OF norm_triangle_ineq add_mono])
lemma ge_iff_diff_ge_0:
fixes a :: "'a::linordered_ring"
shows "a \<ge> b \<equiv> a - b \<ge> 0"
by (simp add: field_simps)
lemma pth_1:
fixes x :: "'a::real_normed_vector"
shows "x \<equiv> scaleR 1 x" by simp
lemma pth_2:
fixes x :: "'a::real_normed_vector"
shows "x - y \<equiv> x + -y"
by (atomize (full)) simp
lemma pth_3:
fixes x :: "'a::real_normed_vector"
shows "- x \<equiv> scaleR (-1) x"
by simp
lemma pth_4:
fixes x :: "'a::real_normed_vector"
shows "scaleR 0 x \<equiv> 0"
and "scaleR c 0 = (0::'a)"
by simp_all
lemma pth_5:
fixes x :: "'a::real_normed_vector"
shows "scaleR c (scaleR d x) \<equiv> scaleR (c * d) x"
by simp
lemma pth_6:
fixes x :: "'a::real_normed_vector"
shows "scaleR c (x + y) \<equiv> scaleR c x + scaleR c y"
by (simp add: scaleR_right_distrib)
lemma pth_7:
fixes x :: "'a::real_normed_vector"
shows "0 + x \<equiv> x"
and "x + 0 \<equiv> x"
by simp_all
lemma pth_8:
fixes x :: "'a::real_normed_vector"
shows "scaleR c x + scaleR d x \<equiv> scaleR (c + d) x"
by (simp add: scaleR_left_distrib)
lemma pth_9:
fixes x :: "'a::real_normed_vector"
shows "(scaleR c x + z) + scaleR d x \<equiv> scaleR (c + d) x + z"
and "scaleR c x + (scaleR d x + z) \<equiv> scaleR (c + d) x + z"
and "(scaleR c x + w) + (scaleR d x + z) \<equiv> scaleR (c + d) x + (w + z)"
by (simp_all add: algebra_simps)
lemma pth_a:
fixes x :: "'a::real_normed_vector"
shows "scaleR 0 x + y \<equiv> y"
by simp
lemma pth_b:
fixes x :: "'a::real_normed_vector"
shows "scaleR c x + scaleR d y \<equiv> scaleR c x + scaleR d y"
and "(scaleR c x + z) + scaleR d y \<equiv> scaleR c x + (z + scaleR d y)"
and "scaleR c x + (scaleR d y + z) \<equiv> scaleR c x + (scaleR d y + z)"
and "(scaleR c x + w) + (scaleR d y + z) \<equiv> scaleR c x + (w + (scaleR d y + z))"
by (simp_all add: algebra_simps)
lemma pth_c:
fixes x :: "'a::real_normed_vector"
shows "scaleR c x + scaleR d y \<equiv> scaleR d y + scaleR c x"
and "(scaleR c x + z) + scaleR d y \<equiv> scaleR d y + (scaleR c x + z)"
and "scaleR c x + (scaleR d y + z) \<equiv> scaleR d y + (scaleR c x + z)"
and "(scaleR c x + w) + (scaleR d y + z) \<equiv> scaleR d y + ((scaleR c x + w) + z)"
by (simp_all add: algebra_simps)
lemma pth_d:
fixes x :: "'a::real_normed_vector"
shows "x + 0 \<equiv> x"
by simp
lemma norm_imp_pos_and_ge:
fixes x :: "'a::real_normed_vector"
shows "norm x \<equiv> n \<Longrightarrow> norm x \<ge> 0 \<and> n \<ge> norm x"
by atomize auto
lemma real_eq_0_iff_le_ge_0:
fixes x :: real
shows "x = 0 \<equiv> x \<ge> 0 \<and> - x \<ge> 0"
by arith
lemma norm_pths:
fixes x :: "'a::real_normed_vector"
shows "x = y \<longleftrightarrow> norm (x - y) \<le> 0"
and "x \<noteq> y \<longleftrightarrow> \<not> (norm (x - y) \<le> 0)"
using norm_ge_zero[of "x - y"] by auto
lemmas arithmetic_simps =
arith_simps
add_numeral_special
add_neg_numeral_special
mult_1_left
mult_1_right
ML_file \<open>normarith.ML\<close>
method_setup\<^marker>\<open>tag important\<close> norm = \<open>
Scan.succeed (SIMPLE_METHOD' o NormArith.norm_arith_tac)
\<close> "prove simple linear statements about vector norms"
text \<open>Hence more metric properties.\<close>
text\<^marker>\<open>tag important\<close> \<open>%whitespace\<close>
proposition dist_triangle_add:
fixes x y x' y' :: "'a::real_normed_vector"
shows "dist (x + y) (x' + y') \<le> dist x x' + dist y y'"
by norm
lemma dist_triangle_add_half:
fixes x x' y y' :: "'a::real_normed_vector"
shows "dist x x' < e / 2 \<Longrightarrow> dist y y' < e / 2 \<Longrightarrow> dist(x + y) (x' + y') < e"
by norm
end
|
<a href="https://colab.research.google.com/github/ricardoprins/intro-quantum/blob/main/Parte%201%20-%20Intro.ipynb" target="_parent"></a>
# Intro a Computação Quântica e Portas Lógicas Quânticas
Esta palestra é introdutória ao tema de Computação Quântica (originalmente dada para membros do grupo de pesquisa QPower), portanto considera um público com noções consideráveis de matemática, física e programação (você deve saber pelo menos multiplicar matrizes para entender o que vai acontecer aqui). Por essa razão, a abordagem aqui será mais _hands on_, e a linguagem utilizada será o Python.
A discussão não cobrirá o tema de _quantum annealing_, sendo limitada somente a portas lógicas quânticas.
It will just cover gate quantum computation model - there will be no annealing discussed here.
Desse modo, ao cobrir apenas conceitos gerais e portas lógicas quânticas, será mais fácil de estabelecer a distinção e a relação entre a computação clássica e a computação quântica. A palestra utilizará usando Qiskit (pronuncia-se _quískit_), uma biblioteca em _Python_ para computação quântica.
Ainda, para os que não possuem um sólido conhecimento em Python, os auxílios visuais utilizados aqui servirão de suporte para a compreensão dos conceitos abordados.
Meu email: [email protected]
```
# Instalação do Qiskit
!pip install qiskit
```
Collecting qiskit
Downloading qiskit-0.29.1.tar.gz (12 kB)
Collecting qiskit-terra==0.18.2
Downloading qiskit_terra-0.18.2-cp37-cp37m-manylinux2010_x86_64.whl (6.1 MB)
[K |████████████████████████████████| 6.1 MB 2.0 MB/s
[?25hCollecting qiskit-aer==0.8.2
Downloading qiskit_aer-0.8.2-cp37-cp37m-manylinux2010_x86_64.whl (18.0 MB)
[K |████████████████████████████████| 18.0 MB 130 kB/s
[?25hCollecting qiskit-ibmq-provider==0.16.0
Downloading qiskit_ibmq_provider-0.16.0-py3-none-any.whl (235 kB)
[K |████████████████████████████████| 235 kB 46.1 MB/s
[?25hCollecting qiskit-ignis==0.6.0
Downloading qiskit_ignis-0.6.0-py3-none-any.whl (207 kB)
[K |████████████████████████████████| 207 kB 56.7 MB/s
[?25hCollecting qiskit-aqua==0.9.5
Downloading qiskit_aqua-0.9.5-py3-none-any.whl (2.1 MB)
[K |████████████████████████████████| 2.1 MB 44.3 MB/s
[?25hRequirement already satisfied: scipy>=1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.8.2->qiskit) (1.4.1)
Collecting pybind11>=2.6
Downloading pybind11-2.7.1-py2.py3-none-any.whl (200 kB)
[K |████████████████████████████████| 200 kB 72.2 MB/s
[?25hRequirement already satisfied: numpy>=1.16.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.8.2->qiskit) (1.19.5)
Collecting docplex>=2.21.207
Downloading docplex-2.21.207.tar.gz (635 kB)
[K |████████████████████████████████| 635 kB 71.7 MB/s
[?25hRequirement already satisfied: h5py<3.3.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (3.1.0)
Collecting yfinance>=0.1.62
Downloading yfinance-0.1.63.tar.gz (26 kB)
Requirement already satisfied: fastdtw<=0.3.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (0.3.4)
Collecting retworkx>=0.8.0
Downloading retworkx-0.10.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.4 MB)
[K |████████████████████████████████| 1.4 MB 38.5 MB/s
[?25hRequirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (5.4.8)
Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (1.7.1)
Collecting quandl
Downloading Quandl-3.6.1-py2.py3-none-any.whl (26 kB)
Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (1.1.5)
Collecting dlx<=1.0.4
Downloading dlx-1.0.4.tar.gz (5.5 kB)
Requirement already satisfied: scikit-learn>=0.20.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (0.22.2.post1)
Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (57.4.0)
Collecting websocket-client>=1.0.1
Downloading websocket_client-1.2.1-py2.py3-none-any.whl (52 kB)
[K |████████████████████████████████| 52 kB 1.8 MB/s
[?25hRequirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.16.0->qiskit) (2.23.0)
Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.16.0->qiskit) (2.8.2)
Collecting requests-ntlm>=1.1.0
Downloading requests_ntlm-1.1.0-py2.py3-none-any.whl (5.7 kB)
Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.16.0->qiskit) (1.24.3)
Collecting python-constraint>=1.4
Downloading python-constraint-1.4.0.tar.bz2 (18 kB)
Collecting fastjsonschema>=2.10
Downloading fastjsonschema-2.15.1-py3-none-any.whl (21 kB)
Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.18.2->qiskit) (0.3.4)
Collecting tweedledum<2.0,>=1.1
Downloading tweedledum-1.1.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (943 kB)
[K |████████████████████████████████| 943 kB 64.1 MB/s
[?25hCollecting ply>=3.10
Downloading ply-3.11-py2.py3-none-any.whl (49 kB)
[K |████████████████████████████████| 49 kB 6.3 MB/s
[?25hCollecting symengine>0.7
Downloading symengine-0.8.1-cp37-cp37m-manylinux2010_x86_64.whl (38.2 MB)
[K |████████████████████████████████| 38.2 MB 20 kB/s
[?25hRequirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.18.2->qiskit) (2.6.0)
Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from docplex>=2.21.207->qiskit-aqua==0.9.5->qiskit) (1.15.0)
Requirement already satisfied: cached-property in /usr/local/lib/python3.7/dist-packages (from h5py<3.3.0->qiskit-aqua==0.9.5->qiskit) (1.5.2)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.16.0->qiskit) (3.0.4)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.16.0->qiskit) (2021.5.30)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.16.0->qiskit) (2.10)
Collecting ntlm-auth>=1.0.2
Downloading ntlm_auth-1.5.0-py2.py3-none-any.whl (29 kB)
Collecting cryptography>=1.3
Downloading cryptography-3.4.8-cp36-abi3-manylinux_2_24_x86_64.whl (3.0 MB)
[K |████████████████████████████████| 3.0 MB 47.7 MB/s
[?25hRequirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.16.0->qiskit) (1.14.6)
Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.16.0->qiskit) (2.20)
Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.9.5->qiskit) (1.0.1)
Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-aqua==0.9.5->qiskit) (1.2.1)
Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance>=0.1.62->qiskit-aqua==0.9.5->qiskit) (0.0.9)
Collecting lxml>=4.5.1
Downloading lxml-4.6.3-cp37-cp37m-manylinux2014_x86_64.whl (6.3 MB)
[K |████████████████████████████████| 6.3 MB 25.2 MB/s
[?25hRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->qiskit-aqua==0.9.5->qiskit) (2018.9)
Requirement already satisfied: more-itertools in /usr/local/lib/python3.7/dist-packages (from quandl->qiskit-aqua==0.9.5->qiskit) (8.8.0)
Collecting inflection>=0.3.1
Downloading inflection-0.5.1-py2.py3-none-any.whl (9.5 kB)
Building wheels for collected packages: qiskit, dlx, docplex, python-constraint, yfinance
Building wheel for qiskit (setup.py) ... [?25l[?25hdone
Created wheel for qiskit: filename=qiskit-0.29.1-py3-none-any.whl size=11239 sha256=560b5df8dfb9db7b4a4f8cea4f3f7d0ff3796317657794ea9c91cb4007caa70a
Stored in directory: /root/.cache/pip/wheels/7a/b8/82/921a13d73dac0322d4eea1eceb7a5419ac8f92cc0f54197456
Building wheel for dlx (setup.py) ... [?25l[?25hdone
Created wheel for dlx: filename=dlx-1.0.4-py3-none-any.whl size=5719 sha256=94dc04f74b2ab61418e81f123073e727556408c8e6da66a49aa290f09198c786
Stored in directory: /root/.cache/pip/wheels/78/55/c8/dc61e772445a566b7608a476d151e9dcaf4e092b01b0c4bc3c
Building wheel for docplex (setup.py) ... [?25l[?25hdone
Created wheel for docplex: filename=docplex-2.21.207-py3-none-any.whl size=700544 sha256=f42221fcd76fd5186d44ac5a38efc670fdafd65e07b5b31370ef9f73424e4adb
Stored in directory: /root/.cache/pip/wheels/d8/4e/62/e43a45757e70549e6aa4712ccfcf67440a203c278ecb68de49
Building wheel for python-constraint (setup.py) ... [?25l[?25hdone
Created wheel for python-constraint: filename=python_constraint-1.4.0-py2.py3-none-any.whl size=24081 sha256=17eadd2a02707d47c4d742c41d8b219f865371e0df1c63dc19c87177750c7cdf
Stored in directory: /root/.cache/pip/wheels/07/27/db/1222c80eb1e431f3d2199c12569cb1cac60f562a451fe30479
Building wheel for yfinance (setup.py) ... [?25l[?25hdone
Created wheel for yfinance: filename=yfinance-0.1.63-py2.py3-none-any.whl size=23918 sha256=a7617ea60aa76ec188e8e7d9322fe5a2c3784613bebe9961c1ac913c688afff0
Stored in directory: /root/.cache/pip/wheels/fe/87/8b/7ec24486e001d3926537f5f7801f57a74d181be25b11157983
Successfully built qiskit dlx docplex python-constraint yfinance
Installing collected packages: tweedledum, symengine, retworkx, python-constraint, ply, fastjsonschema, qiskit-terra, ntlm-auth, lxml, inflection, cryptography, yfinance, websocket-client, requests-ntlm, quandl, qiskit-ignis, pybind11, docplex, dlx, qiskit-ibmq-provider, qiskit-aqua, qiskit-aer, qiskit
Attempting uninstall: lxml
Found existing installation: lxml 4.2.6
Uninstalling lxml-4.2.6:
Successfully uninstalled lxml-4.2.6
Successfully installed cryptography-3.4.8 dlx-1.0.4 docplex-2.21.207 fastjsonschema-2.15.1 inflection-0.5.1 lxml-4.6.3 ntlm-auth-1.5.0 ply-3.11 pybind11-2.7.1 python-constraint-1.4.0 qiskit-0.29.1 qiskit-aer-0.8.2 qiskit-aqua-0.9.5 qiskit-ibmq-provider-0.16.0 qiskit-ignis-0.6.0 qiskit-terra-0.18.2 quandl-3.6.1 requests-ntlm-1.1.0 retworkx-0.10.2 symengine-0.8.1 tweedledum-1.1.1 websocket-client-1.2.1 yfinance-0.1.63
```
# Inicializações iniciais
import numpy as np
import matplotlib.pyplot as plt
from math import sqrt, pi
from qiskit import *
from qiskit.extensions import Initialize
```
## Computação e Informação
Toda a teoria por trás de computadores está relacionada à Teoria da Informação. Ambos os campos caminham juntos, unidos e interrelacionados em seu progresso.
Desse modo, ao falarmos de computação clássica e computação quântica, é preciso começar de um ponto fundamental: ambas tratam de maneiras distintas de *processamento* de informação. Assim, é preciso definir o conceito de _processar_:
$$\text{Entrada } \Longrightarrow \text{ Saída}$$
Quando nós manipulamos qualquer quantidade de informação, e posteriormente a processamos, obtendo informação como resultado desta operação, estamos falando em _processamento_ de informação, ou ainda em _computação_ de informação. Para simplificar, não serão considerados transmissores, receptores e possíveis fontes de ruído: a ideia aqui é somente a de entender o sentido básico de computar ou processar informação em geral.
Essa informação nos ajuda a entender as diferenças fundamentais entre a computação clássica e a computação quântica.
A primeira distinção é na unidade fundamental de informação. Sem perda de generalidade, podemos evitar uma discussão profunda em Teoria de Informação [(clique aqui para saber mais)](http://people.math.harvard.edu/~ctm/home/text/others/shannon/entropy/entropy.pdf), e falar apenas nas unidades fundamentais: _bits_ e _qubits_.
## Bits e Qubits
Um _bit_ é a unidade fundamental de informação da computação clássica. Ela representa uma entidade capaz de armazenar duas posições *estáveis*, como um relé (interruptor). Ligado ou desligado, 0 ou 1, corrente ou ausência de corrente.
Vamos recorrer aqui a uma notação vetorial:
$$1 = \begin{pmatrix} 0\\1 \end{pmatrix}\space e\space\space 0 = \begin{pmatrix} 1\\0 \end{pmatrix} $$
```
zero = np.matrix('1;0')
um = np.matrix('0;1')
```
### Quatro operações básicas com bits
Com _bits_, há quatro operações básicas possíveis:
$$\text{Identidade:}\space\space {f}(x) = x$$<br>
$$\text{Negação:}\space\space {f}(x) = \neg x$$<br>
$$\text{Constante-0:}\space\space {f}(x) = 0$$<br>
$$\text{Constante-1:}\space\space {f}(x) = 1$$<br>
Usando notação matricial:
```
# Identidade:
identidade = np.matrix('1 0; 0 1')
print('A matriz identidade:')
print(identidade,'\n')
# Zero multiplicado pela matriz identidade retorna zero,
result = identidade @ zero
print(result, '\n')
# e ainda: um, multiplicado pela matriz identidade retorna um, como esperado.
result = identidade @ um
print(result)
```
A matriz identidade:
[[1 0]
[0 1]]
[[1]
[0]]
[[0]
[1]]
```
# Negação:
neg = np.matrix('0 1; 1 0')
print('A matriz negação:')
print(neg, '\n')
# Zero multiplicado pela matriz negação retorna um,
result = neg @ zero
print(result, '\n')
# e um multiplicado pela matriz negação retorna zero, como esperado.
result = neg @ um
print(result)
```
A matriz negação:
[[0 1]
[1 0]]
[[0]
[1]]
[[1]
[0]]
```
# Constante-0:
c_zero = np.matrix('1 1; 0 0')
print('A matriz Constante-0')
print(c_zero, '\n')
# Multiplicando zero pela matriz Constante-0 retornará zero,
result = c_zero @ zero
print(result, '\n')
# e multiplicando um pela matriz Constante-0 retornará zero, como esperado.
result = c_zero @ um
print(result)
```
A matriz Constante-0
[[1 1]
[0 0]]
[[1]
[0]]
[[1]
[0]]
```
# Constante-1:
c_um = np.matrix('0 0; 1 1')
print('A matriz Constante-1:')
print(c_um, '\n')
# Multiplicando zero pela matriz Constante-1 retornará um,
result = c_um @ zero
print(result, '\n')
# e multiplicando um pela matriz Constante-1 retornará um, como esperado.
result = c_um @ um
print(result)
```
A matriz Constante-1:
[[0 0]
[1 1]]
[[0]
[1]]
[[0]
[1]]
### Operações reversíveis com bits
Para nosso propósito aqui, é conveniente definir _operações reversíveis_ como **quaisquer processos** (cf. a definição supracitada de processamento) **que permitam que a entrada seja identificada ao se conhecer a saída e da operação utilizada.**
Nas operações acima, quais são reversíveis e quais não são?
É possível na computação clássica ocorrer operações não-reversíveis, e isso não é um problema.
### Produto Kronecker
Para a compreensão plena dos próximos conceitos, é necessário explicar uma operação que nem sempre é ensinada nas aulas de Álgebra Linear: o produto Kronecker. [(para maiores explicações, clique aqui)](https://www.grc.nasa.gov/www/k-12/Numbers/Math/documents/Tensors_TM2002211716.pdf).
Também é conveniente estudar sobre produtos tensoriais, para maior compreensão, uma vez que produtos Kronecker são um caso particular de produtos tensoriais.
Esses exemplos são satisfatórios para o fim de explicar a operação:<br><br>
$$\begin{pmatrix} x_{0} \\ x_{1} \end{pmatrix} \otimes \begin{pmatrix} y_{0} \\ y_{1} \end{pmatrix} = \begin{pmatrix} x_{0}y_{0} \\ x_{0}y_{1} \\ x_{1}y_{0} \\ x_{1}y_{1} \end{pmatrix} $$
Outro exemplo:<br><br>
$$\begin{pmatrix} x_{0} \\ x_{1} \end{pmatrix} \otimes \begin{pmatrix} y_{0} \\ y_{1} \end{pmatrix} \otimes \begin{pmatrix} z_{0} \\ z_{1} \end{pmatrix} = \begin{pmatrix} x_{0}y_{0}z_{0} \\ x_{0}y_{0}z_{1} \\ x_{0}y_{1}z_{0} \\ x_{0}y_{1}z_{1} \\ x_{1}y_{0}z_{0} \\ x_{1}y_{0}z_{1} \\ x_{1}y_{1}z_{0} \\ x_{1}y_{1}z_{1} \end{pmatrix} $$
### A representação de múltiplos bits
Para representar os estados possíveis de múltiplos bits, utiliza-se o produto Kronecker de vetores de um bit. Novamente é preciso enfatizar que essa é uma explicação simplificada, porém útil o suficiente para a compreensão das operações com múltiplos bits, e suficientemente satisfatória para mostrar o poder da computação quântica.
A representação tensorial de múltiplos bits é chamada de _estado produto_. Essa representação é utilíssima, pois permite a fatoração do _estado produto_ em seus respectivos estados individuais.
Vamos usar como exemplo os estados produto para dois bits:
$$\text{Temos quatro estados possíveis para dois bits:}$$
$$00, 01, 10\space ou\space 11$$:
$$\begin{pmatrix} 1 \\ 0 \end{pmatrix} \otimes \begin{pmatrix} 1 \\ 0 \end{pmatrix} = \begin{pmatrix} 1 \\ 0 \\ 0 \\ 0 \end{pmatrix} \space\space\text{0 com 0,}$$
$$\begin{pmatrix} 1 \\ 0 \end{pmatrix} \otimes \begin{pmatrix} 0 \\ 1 \end{pmatrix} = \begin{pmatrix} 0 \\ 1 \\ 0 \\ 0 \end{pmatrix} \space\space\text{0 com 1,}$$
$$\begin{pmatrix} 0 \\ 1 \end{pmatrix} \otimes \begin{pmatrix} 1 \\ 0 \end{pmatrix} = \begin{pmatrix} 0 \\ 0 \\ 1 \\ 0 \end{pmatrix} \space\space\text{1 com 0,}$$
$$\begin{pmatrix} 0 \\ 1 \end{pmatrix} \otimes \begin{pmatrix} 0 \\ 1 \end{pmatrix} = \begin{pmatrix} 0 \\ 0 \\ 0 \\ 1 \end{pmatrix} \space\space\text{e 1 com 1}$$
```
# usando NumPy:
zero_zero = np.kron(zero, zero)
zero_um = np.kron(zero, um)
um_zero = np.kron(um, zero)
um_um = np.kron(um, um)
print(zero_zero,'\n\n', zero_um,'\n\n', um_zero,'\n\n', um_um)
```
[[1]
[0]
[0]
[0]]
[[0]
[1]
[0]
[0]]
[[0]
[0]
[1]
[0]]
[[0]
[0]
[0]
[1]]
Assim, como se pode observar, há quatro _estados produto_ possíveis para um par de bits.
Conclui-se, portanto, que o número de _estados produto_ possíveis em _n_ bits é igual a $ 2^{n}$.
### CNOT: Uma operação com múltiplos bits
Um dos blocos fundamentais para a computação reversível é a operação CNOT.
A operação CNOT funciona em pares de _bits_; um é designado como _bit controle_ e o outro como _bit alvo_.
O mecanismo de funcionamento dessa _porta_ (daqui em diante, essas operações serão chamadas de _portas_) é o seguinte:
- Se o bit controle for 1, o bit alvo é invertido
- Se o bit controle for 0, o bit alvo segue inalterado
- O bit controle nunca é alterado
- O bit mais significativo (aquele à esquerda) é o bit controle, e o outro, o bit alvo
Exemplo:
```
cnot = np.matrix('1 0 0 0; 0 1 0 0; 0 0 0 1; 0 0 1 0')
print(cnot)
```
[[1 0 0 0]
[0 1 0 0]
[0 0 0 1]
[0 0 1 0]]
```
# CNOT on 00:
result = cnot @ zero_zero
print('Como o bit controle é zero, o bit alvo segue sem alteração,\n')
print(result, '\n')
# CNOT on 01
result = cnot @ zero_um
print('o que da mesma maneira acontece aqui.\n')
print(result)
```
Como o bit controle é zero, o bit alvo segue sem alteração,
[[1]
[0]
[0]
[0]]
o que da mesma maneira acontece aqui.
[[0]
[1]
[0]
[0]]
```
# CNOT on 10:
result = cnot @ um_zero
print('No entanto, ele é invertido neste exemplo,\n')
print(result, '\n')
# CNOT on 11
result = cnot @ um_um
print('tal como no seguinte:\n')
print(result)
```
No entanto, ele é invertido neste exemplo,
[[0]
[0]
[0]
[1]]
tal como no seguinte:
[[0]
[0]
[1]
[0]]
### _Qubits_ - as unidades fundamentais de informação quântica
O primeiro ponto a ser mencionado aqui é que todas as operações com _qubits_ DEVEM ser reversíveis (e o são).
Disso decorre que elas são seu próprio inverso - ao aplicar a mesma operação duas vezes em sequência, o valor inicial necessariamente será obtido.
Para os fins deste treinamento, a afirmação acima será tratada de forma axiomática, bem como a seguinte: a mecânica quântica é, além de reversível, unitária. A demonstração disso decorre da equação de Schröddinger.
A única exceção aqui é para as operações/portas de medição, uma vez que estas não são, de fato, operações ou portas.
Ainda que todas as operações acima feitas tenham considerado _bits_, todas elas são *igualmente válidas para _qubits_*. É possível afirmar que os _bits_ vistos em sua forma vetorial são casos particulares de vetores _qubits_.
**Definição:**<br><br>
Um qubit pode ser representado por um vetor $\begin{pmatrix} a \\ b \end{pmatrix} : \space a,b \in \mathbb{C}\space\space, \lVert a\rVert^{2} + \lVert b\rVert^{2} = 1$
Exemplos: $\begin{pmatrix} -1 \\ 0 \end{pmatrix}, \begin{pmatrix} \frac12 \\ \frac{\sqrt3}{2} \end{pmatrix}, \begin{pmatrix} \frac{1}{\sqrt2} \\ \frac{1}{\sqrt2} \end{pmatrix}, \begin{pmatrix} \frac{1}{\sqrt2} \\ \frac{-1}{\sqrt2} \end{pmatrix}$
Analogamente aos _bits_, é plausível buscar uma interpretação prática para o comportamento de um _qubit_: ele, tal como seu par da computação clássica, pode representar 0 ou 1 (um par de possibilidades, presença de corrente ou ausência, etc) ou ambos os valores possíveis ao mesmo tempo!
### Superposição quântica - uma explicação matemática
Agora é o momento de encarar as definições físicas mais complicadas relacionadas aos qubits.
Vamos, por um momento, deixar de lado o fato de que um qubit pode assumir ao mesmo tempo os valores 0 e 1, e considerar apenas as questões matemáticas decorrentes dessa característica.
Algo importante também verificável na mecânica quântica é que no momento em que se mede um qubit, ele instantaneamente entrará em colapso para um dos valores, seja 0 ou 1.
Com isso, de maneira igualmente axiomática, afirma-se que a probabilidade que um qubit $\begin{pmatrix} a \\ b \end{pmatrix}$ tem de _colapsar_ para um valor 0 é $\lVert a\rVert^{2}$ e para 1, $\lVert b\rVert^{2}$.
Esse axioma facilita a compreensão do comportamento de um sistema com múltiplos qubits.
### Múltiplos qubits
A representação de um sistema com mais de um qubit é análoga à que foi feita para bits clássicos - utiliza-se o produto Kronecker das matrizes de qubits individuais.
```
## Exemplo com NumPy:
# Partindo do qubit (1/sqrt(2), 1/sqrt(2)):
qubit = np.array([[1/sqrt(2)],[1/sqrt(2)]])
# O estado produto desse qubit é o produto Kronecker dele consigo mesmo:
product_state = np.kron(qubit, qubit)
print(product_state)
# Note que o vetor resultante para o estado produto também é unitário.
```
[[0.5]
[0.5]
[0.5]
[0.5]]
É possível observar no estado produto acima, que o sistema possui uma probabilidade de
$\lVert\frac12\rVert^{2}= \frac14 $ (vamos chamar de amplitude) de colapsar nos estados 00, 01, 10 ou 11 após a medição.
## Portas Quânticas (ou ainda, operações com qubits)
Todas as operações descritas acima são aplicáveis a qubits, com a seguinte ressalva: elas devem ser reversíveis.
### Hadamard
_Desse ponto em diante, iniciaremos o uso da biblioteca Qiskit para visualizar também a notação circuito._
A porta Hadamard (H-gate) leva um qubit 0 ou 1 para um estado de superposição _exactly equal_:
$$ H = \begin{pmatrix} \frac1{\sqrt2} \ \frac1{\sqrt2} \\ \frac1{\sqrt2} \ \frac{-1}{\sqrt2} \end{pmatrix}$$
```
hadamard = np.array([[1/sqrt(2),1/sqrt(2)],[1/sqrt(2),-1/sqrt(2)]])
# Applying Hadamard to qubit 0,
result = hadamard @ zero
print(result, '\n')
# and to qubit 1:
result = hadamard @ um
print(result)
```
[[0.70710678]
[0.70710678]]
[[ 0.70710678]
[-0.70710678]]
O resultado acima mostra vetores qubit em superposição, com a mesma probabilidade de colapsarem em ambos estados 0 ou 1.
**Pergunta**
O que acontece se aplicarmos a H-gate a um desses qubits resultantes da superposição acima?
### A notação circuito
Uma das notações utilizadas para representar uma sequência de operações com qubits é a notação circuito.
Uma das vantagens da biblioteca Qiskit é a de permitir a visualização das sucessivas operações utilizando essa operação, conforme exemplo abaixo:
```
def challengeTwo(qc, qubit):
qc.x(qubit)
qc.h(qubit)
qc.x(qubit)
qc.h(qubit)
qc.x(qubit)
return qc
quantum_circuit = QuantumCircuit(1)
initial_state = [1,0]
initializer = Initialize(initial_state)
initializer.label = "init"
challengeTwo(quantum_circuit, 0)
quantum_circuit.draw()
```
<pre style="word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: "Courier New",Courier,monospace"> ┌───┐┌───┐┌───┐┌───┐┌───┐
q_0: ┤ X ├┤ H ├┤ X ├┤ H ├┤ X ├
└───┘└───┘└───┘└───┘└───┘</pre>
O circuito acima exibe uma sequência de operações realizadas com um qubit em um circuito (duh!), de onde deriva-se o nome _notação circuito_.
Para este caso, partindo de um qubit 0, as operações a seguir são realizadas:
1. Uma porta negação (chamada de Pauli-X)
2. Uma porta Hadamard
3. Outra Pauli-X
4. Outra Hadamard
5. Mais uma Pauli-X
**Pergunta** Você consegue determinar o resultado da medição do qubit após essas cinco operações?
### Pauli
Para os que possuem familiaridade com álgebra linear, as matrizes Pauli não serão novidade: um conjunto de três matrizes 2x2 que são hermitianas e unitárias.
Começaremos pela Pauli X - carinhosamente chamada de "porta X"
####Pauli X ou porta NOT
$$ X = \begin{pmatrix} 0 \ 1 \\ 1 \ 0 \end{pmatrix}$$
Essa é análoga à matriz negação que utilizamos para operações com bits. Observemos seu comportamento com qubits:
```
from qiskit.visualization import plot_bloch_multivector
# Vamos desenhar um circuito com um qubit inicializado no estado 0
# e aplicar uma porta X a ele:
qc = QuantumCircuit(1)
qc.x(0)
# A representação abaixo é chamada de Esfera de Bloch, e é usada
# para representar qubits e seus estados. Como podemos ver abaixo,
# esse é o estado em que o qubit "repousa"
# após sua passagem pelo circuito.
def displayBloch():
backend = Aer.get_backend('statevector_simulator')
output = execute(qc, backend).result().get_statevector()
return plot_bloch_multivector(output)
displayBloch()
```
Como esperado, o estado resultante é 1:
uma rotação de $\pi$ radianos sobre o eixo _x_ da esfera.
Você também verá essa porta sendo chamada de porta _NOT_.
#### Pauli Y
Análoga à porta X, esta rotaciona um qubit
$\pi$ radianos sobre o eixo _y_ da esfera:
$$ Y = \begin{pmatrix} 0 \ -i \\ i \ 0 \end{pmatrix}$$
```
# Inicializaremos um qubit no estado 1,
qc = QuantumCircuit(1)
initial_state = [0,1]
qc.initialize(initial_state,0)
qc.draw()
```
<pre style="word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: "Courier New",Courier,monospace"> ┌─────────────────┐
q_0: ┤ Initialize(0,1) ├
└─────────────────┘</pre>
```
# essa é sua exibição na esfera de Bloch
displayBloch()
```
```
# e, a rotação resultante da Y-gate:
qc.y(0)
displayBloch()
```
#### Pauli Z
Rotação de $\pi$ radianos sobre o eixo _z_:
$$ Z = \begin{pmatrix} 1 \ 0 \\ 0 \ {-1} \end{pmatrix}$$
```
# Inicializamos um qubit cujo ângulo em relação ao eixo z
# possa ser facilmente observável.
initial_state = [sqrt(3)/2,1/2]
qc.initialize(initial_state,0)
displayBloch()
```
```
# aplicamos a Z-gate sobre esse qubit, verificando a rotação
qc.z(0)
displayBloch()
```
### $R_\phi$ (ou $R_z$)
A porta $R_\phi$ é uma porta parametrizada que executa uma rotação de $\phi$ graus sobre o eixo Z:
_Disso pode-se deduzir que a porta Pauli-Z é um caso particular da porta $R_\phi$ com $\phi=\pi$._
$$ R_\phi = \begin{pmatrix} 1 \ 0 \\ 0 \ e^{i\phi} \end{pmatrix} , com \space\space \phi \in \mathbb R $$
### Identidade
A porta I (Identidade) faz exatamente o que seu nome indica: nada.
No entanto, há algumas aplicações práticas para seu uso, as quais fogem ao escopo desta palestra.
### T
A porta T é outro caso particular da porta $R_\phi$, com $\phi = \frac{\pi}{4}$:
$$ T = \begin{pmatrix} 1 \ 0 \\ 0 \ e^{i\frac{\pi}{4}} \end{pmatrix} \text{e } T\dagger = \begin{pmatrix} 1 \ 0 \\ 0 \ e^{-i\frac{\pi}{4}} \end{pmatrix}$$
### S
A porta S é ainda outro caso particular da porta $R_\phi$, com $\phi = \frac{\pi}{2}$:
$$ S = \begin{pmatrix} 1 \ 0 \\ 0 \ e^{i\frac{\pi}{2}} \end{pmatrix} \text{and } S\dagger = \begin{pmatrix} 1 \ 0 \\ 0 \ e^{-i\frac{\pi}{2}} \end{pmatrix}$$
É conveniente notar que aplicar duas portas S é o mesmo que aplicar uma porta Z, por razões óbvias.
### $U_3$
Todas as portas acima podem ser consideradas como casos particulares da porta $U_3$.
Devido a sua evidente complexidade de exibição, dificilmente ela é utilizada em diagramas.
Uma observação importante: a escolha de rotações nas portas acima sobre o eixo z é apenas uma convenção computacional para facilitar a vida dos programadores e evitar que estes sejam institucionalizados em manicômios.
$$ U_3(\theta,\phi,\lambda) = \begin{pmatrix} \cos(\frac\theta2) \ -e^{i\lambda}\sin(\frac\theta2) \\ e^{i\phi}\sin(\frac\theta2) \ e^{i\phi+i\theta}\cos(\frac\theta2) \end{pmatrix}$$
# OBRIGADO A TODOS!
|
/-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
! This file was ported from Lean 3 source module data.rat.cast
! leanprover-community/mathlib commit acebd8d49928f6ed8920e502a6c90674e75bd441
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathlib.Data.Rat.Order
import Mathlib.Data.Rat.Lemmas
import Mathlib.Data.Int.CharZero
import Mathlib.Algebra.GroupWithZero.Power
import Mathlib.Algebra.Field.Opposite
import Mathlib.Algebra.Order.Field.Basic
/-!
# Casts for Rational Numbers
## Summary
We define the canonical injection from ℚ into an arbitrary division ring and prove various
casting lemmas showing the well-behavedness of this injection.
## Notations
- `/.` is infix notation for `rat.mk`.
## Tags
rat, rationals, field, ℚ, numerator, denominator, num, denom, cast, coercion, casting
-/
variable {F ι α β : Type _}
namespace Rat
open Rat
section WithDivRing
variable [DivisionRing α]
@[simp, norm_cast]
theorem cast_coe_int (n : ℤ) : ((n : ℚ) : α) = n :=
(cast_def _).trans <| show (n / (1 : ℕ) : α) = n by rw [Nat.cast_one, div_one]
#align rat.cast_coe_int Rat.cast_coe_int
@[simp, norm_cast]
@[simp, norm_cast]
theorem cast_zero : ((0 : ℚ) : α) = 0 :=
(cast_coe_int _).trans Int.cast_zero
#align rat.cast_zero Rat.cast_zero
@[simp, norm_cast]
theorem cast_one : ((1 : ℚ) : α) = 1 :=
(cast_coe_int _).trans Int.cast_one
#align rat.cast_one Rat.cast_one
theorem cast_commute (r : ℚ) (a : α) : Commute (↑r) a := by
simpa only [cast_def] using (r.1.cast_commute a).div_left (r.2.cast_commute a)
#align rat.cast_commute Rat.cast_commute
theorem cast_comm (r : ℚ) (a : α) : (r : α) * a = a * r :=
(cast_commute r a).eq
#align rat.cast_comm Rat.cast_comm
theorem commute_cast (a : α) (r : ℚ) : Commute a r :=
(r.cast_commute a).symm
#align rat.commute_cast Rat.commute_cast
@[norm_cast]
theorem cast_mk_of_ne_zero (a b : ℤ) (b0 : (b : α) ≠ 0) : (a /. b : α) = a / b := by
have b0' : b ≠ 0 := by
refine' mt _ b0
simp (config := { contextual := true })
cases' e : a /. b with n d h c
have d0 : (d : α) ≠ 0 := by
intro d0
have dd := den_dvd a b
cases' show (d : ℤ) ∣ b by rwa [e] at dd with k ke
have : (b : α) = (d : α) * (k : α) := by rw [ke, Int.cast_mul, Int.cast_ofNat]
rw [d0, zero_mul] at this
contradiction
rw [num_den'] at e
have := congr_arg ((↑) : ℤ → α)
((divInt_eq_iff b0' <| ne_of_gt <| Int.coe_nat_pos.2 h.bot_lt).1 e)
rw [Int.cast_mul, Int.cast_mul, Int.cast_ofNat] at this
-- Porting note: was `symm`
apply Eq.symm
rw [cast_def, div_eq_mul_inv, eq_div_iff_mul_eq d0, mul_assoc, (d.commute_cast _).eq, ← mul_assoc,
this, mul_assoc, mul_inv_cancel b0, mul_one]
#align rat.cast_mk_of_ne_zero Rat.cast_mk_of_ne_zero
@[norm_cast]
theorem cast_add_of_ne_zero :
∀ {m n : ℚ}, (m.den : α) ≠ 0 → (n.den : α) ≠ 0 → ((m + n : ℚ) : α) = m + n
| ⟨n₁, d₁, h₁, c₁⟩, ⟨n₂, d₂, h₂, c₂⟩ => fun (d₁0 : (d₁ : α) ≠ 0) (d₂0 : (d₂ : α) ≠ 0) =>
by
have d₁0' : (d₁ : ℤ) ≠ 0 :=
Int.coe_nat_ne_zero.2 fun e => by rw [e] at d₁0 ; exact d₁0 Nat.cast_zero
have d₂0' : (d₂ : ℤ) ≠ 0 :=
Int.coe_nat_ne_zero.2 fun e => by rw [e] at d₂0 ; exact d₂0 Nat.cast_zero
rw [num_den', num_den', add_def'' d₁0' d₂0']
suffices (n₁ * (d₂ * ((d₂ : α)⁻¹ * (d₁ : α)⁻¹)) + n₂ * (d₁ * (d₂ : α)⁻¹) * (d₁ : α)⁻¹ : α)
= n₁ * (d₁ : α)⁻¹ + n₂ * (d₂ : α)⁻¹
by
rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero]
· simpa [division_def, left_distrib, right_distrib, mul_inv_rev, d₁0, d₂0, mul_assoc]
all_goals simp [d₁0, d₂0]
rw [← mul_assoc (d₂ : α), mul_inv_cancel d₂0, one_mul, (Nat.cast_commute _ _).eq]
simp [d₁0, mul_assoc]
#align rat.cast_add_of_ne_zero Rat.cast_add_of_ne_zero
@[simp, norm_cast]
theorem cast_neg : ∀ n, ((-n : ℚ) : α) = -n
| ⟨n, d, h, c⟩ => by
simpa only [cast_def] using
show (↑(-n) / d : α) = -(n / d) by
rw [div_eq_mul_inv, div_eq_mul_inv, Int.cast_neg, neg_mul_eq_neg_mul]
#align rat.cast_neg Rat.cast_neg
@[norm_cast]
theorem cast_sub_of_ne_zero {m n : ℚ} (m0 : (m.den : α) ≠ 0) (n0 : (n.den : α) ≠ 0) :
((m - n : ℚ) : α) = m - n := by
have : ((-n).den : α) ≠ 0 := by cases n ; exact n0
simp [sub_eq_add_neg, cast_add_of_ne_zero m0 this]
#align rat.cast_sub_of_ne_zero Rat.cast_sub_of_ne_zero
@[norm_cast]
theorem cast_mul_of_ne_zero :
∀ {m n : ℚ}, (m.den : α) ≠ 0 → (n.den : α) ≠ 0 → ((m * n : ℚ) : α) = m * n
| ⟨n₁, d₁, h₁, c₁⟩, ⟨n₂, d₂, h₂, c₂⟩ => fun (d₁0 : (d₁ : α) ≠ 0) (d₂0 : (d₂ : α) ≠ 0) =>
by
have d₁0' : (d₁ : ℤ) ≠ 0 :=
Int.coe_nat_ne_zero.2 fun e => by rw [e] at d₁0 ; exact d₁0 Nat.cast_zero
have d₂0' : (d₂ : ℤ) ≠ 0 :=
Int.coe_nat_ne_zero.2 fun e => by rw [e] at d₂0 ; exact d₂0 Nat.cast_zero
rw [num_den', num_den', mul_def' d₁0' d₂0']
suffices (n₁ * (n₂ * (d₂ : α)⁻¹ * (d₁ : α)⁻¹) : α) = n₁ * ((d₁ : α)⁻¹ * (n₂ * (d₂ : α)⁻¹))
by
rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero]
· simpa [division_def, mul_inv_rev, d₁0, d₂0, mul_assoc]
all_goals simp [d₁0, d₂0]
rw [(d₁.commute_cast (_ : α)).inv_right₀.eq]
#align rat.cast_mul_of_ne_zero Rat.cast_mul_of_ne_zero
-- Porting note: rewrote proof
@[simp]
theorem cast_inv_nat (n : ℕ) : ((n⁻¹ : ℚ) : α) = (n : α)⁻¹ := by
cases' n with n
· simp
rw [cast_def, inv_coe_nat_num, inv_coe_nat_den, if_neg n.succ_ne_zero,
Int.sign_eq_one_of_pos (Nat.cast_pos.mpr n.succ_pos), Int.cast_one, one_div]
#align rat.cast_inv_nat Rat.cast_inv_nat
-- Porting note: proof got a lot easier - is this still the intended statement?
@[simp]
theorem cast_inv_int (n : ℤ) : ((n⁻¹ : ℚ) : α) = (n : α)⁻¹ := by
cases' n with n n
· simp [ofInt_eq_cast, cast_inv_nat]
· simp only [ofInt_eq_cast, Int.cast_negSucc, ← Nat.cast_succ, cast_neg, inv_neg, cast_inv_nat]
#align rat.cast_inv_int Rat.cast_inv_int
@[norm_cast]
theorem cast_inv_of_ne_zero :
∀ {n : ℚ}, (n.num : α) ≠ 0 → (n.den : α) ≠ 0 → ((n⁻¹ : ℚ) : α) = (n : α)⁻¹
| ⟨n, d, h, c⟩ => fun (n0 : (n : α) ≠ 0) (d0 : (d : α) ≠ 0) =>
by
have _ : (n : ℤ) ≠ 0 := fun e => by rw [e] at n0 ; exact n0 Int.cast_zero
have _ : (d : ℤ) ≠ 0 :=
Int.coe_nat_ne_zero.2 fun e => by rw [e] at d0 ; exact d0 Nat.cast_zero
rw [num_den', inv_def']
rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, inv_div] <;> simp [n0, d0]
#align rat.cast_inv_of_ne_zero Rat.cast_inv_of_ne_zero
@[norm_cast]
theorem cast_div_of_ne_zero {m n : ℚ} (md : (m.den : α) ≠ 0) (nn : (n.num : α) ≠ 0)
(nd : (n.den : α) ≠ 0) : ((m / n : ℚ) : α) = m / n := by
have : (n⁻¹.den : ℤ) ∣ n.num := by
conv in n⁻¹.den => rw [← @num_den n, inv_def']
apply den_dvd
have : (n⁻¹.den : α) = 0 → (n.num : α) = 0 := fun h =>
by
let ⟨k, e⟩ := this
have := congr_arg ((↑) : ℤ → α) e ; rwa [Int.cast_mul, Int.cast_ofNat, h, zero_mul] at this
rw [division_def, cast_mul_of_ne_zero md (mt this nn), cast_inv_of_ne_zero nn nd, division_def]
#align rat.cast_div_of_ne_zero Rat.cast_div_of_ne_zero
@[simp, norm_cast]
theorem cast_inj [CharZero α] : ∀ {m n : ℚ}, (m : α) = n ↔ m = n
| ⟨n₁, d₁, d₁0, c₁⟩, ⟨n₂, d₂, d₂0, c₂⟩ =>
by
refine' ⟨fun h => _, congr_arg _⟩
have d₁a : (d₁ : α) ≠ 0 := Nat.cast_ne_zero.2 d₁0
have d₂a : (d₂ : α) ≠ 0 := Nat.cast_ne_zero.2 d₂0
rw [num_den', num_den'] at h⊢
rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero] at h <;> simp [d₁0, d₂0] at h⊢
rwa [eq_div_iff_mul_eq d₂a, division_def, mul_assoc, (d₁.cast_commute (d₂ : α)).inv_left₀.eq, ←
mul_assoc, ← division_def, eq_comm, eq_div_iff_mul_eq d₁a, eq_comm, ← Int.cast_ofNat d₁, ←
Int.cast_mul, ← Int.cast_ofNat d₂, ← Int.cast_mul, Int.cast_inj, ← mkRat_eq_iff d₁0 d₂0] at h
#align rat.cast_inj Rat.cast_inj
theorem cast_injective [CharZero α] : Function.Injective ((↑) : ℚ → α)
| _, _ => cast_inj.1
#align rat.cast_injective Rat.cast_injective
@[simp]
theorem cast_eq_zero [CharZero α] {n : ℚ} : (n : α) = 0 ↔ n = 0 := by rw [← cast_zero, cast_inj]
#align rat.cast_eq_zero Rat.cast_eq_zero
theorem cast_ne_zero [CharZero α] {n : ℚ} : (n : α) ≠ 0 ↔ n ≠ 0 :=
not_congr cast_eq_zero
#align rat.cast_ne_zero Rat.cast_ne_zero
@[simp, norm_cast]
theorem cast_add [CharZero α] (m n) : ((m + n : ℚ) : α) = m + n :=
cast_add_of_ne_zero (Nat.cast_ne_zero.2 <| ne_of_gt m.pos) (Nat.cast_ne_zero.2 <| ne_of_gt n.pos)
#align rat.cast_add Rat.cast_add
@[simp, norm_cast]
theorem cast_sub [CharZero α] (m n) : ((m - n : ℚ) : α) = m - n :=
cast_sub_of_ne_zero (Nat.cast_ne_zero.2 <| ne_of_gt m.pos) (Nat.cast_ne_zero.2 <| ne_of_gt n.pos)
#align rat.cast_sub Rat.cast_sub
@[simp, norm_cast]
theorem cast_mul [CharZero α] (m n) : ((m * n : ℚ) : α) = m * n :=
cast_mul_of_ne_zero (Nat.cast_ne_zero.2 <| ne_of_gt m.pos) (Nat.cast_ne_zero.2 <| ne_of_gt n.pos)
#align rat.cast_mul Rat.cast_mul
section
set_option linter.deprecated false
@[simp, norm_cast]
theorem cast_bit0 [CharZero α] (n : ℚ) : ((bit0 n : ℚ) : α) = (bit0 n : α) :=
cast_add _ _
#align rat.cast_bit0 Rat.cast_bit0
@[simp, norm_cast]
theorem cast_bit1 [CharZero α] (n : ℚ) : ((bit1 n : ℚ) : α) = (bit1 n : α) := by
rw [bit1, cast_add, cast_one, cast_bit0] ; rfl
#align rat.cast_bit1 Rat.cast_bit1
end
variable (α)
variable [CharZero α]
/-- Coercion `ℚ → α` as a `RingHom`. -/
def castHom : ℚ →+* α where
toFun := (↑)
map_one' := cast_one
map_mul' := cast_mul
map_zero' := cast_zero
map_add' := cast_add
#align rat.cast_hom Rat.castHom
variable {α}
@[simp]
theorem coe_cast_hom : ⇑(castHom α) = ((↑) : ℚ → α) :=
rfl
#align rat.coe_cast_hom Rat.coe_cast_hom
@[simp, norm_cast]
theorem cast_inv (n) : ((n⁻¹ : ℚ) : α) = (n : α)⁻¹ :=
map_inv₀ (castHom α) _
#align rat.cast_inv Rat.cast_inv
@[simp, norm_cast]
theorem cast_div (m n) : ((m / n : ℚ) : α) = m / n :=
map_div₀ (castHom α) _ _
#align rat.cast_div Rat.cast_div
@[simp, norm_cast]
theorem cast_zpow (q : ℚ) (n : ℤ) : ((q ^ n : ℚ) : α) = (q : α) ^ n :=
map_zpow₀ (castHom α) q n
#align rat.cast_zpow Rat.cast_zpow
@[norm_cast]
theorem cast_mk (a b : ℤ) : (a /. b : α) = a / b := by
simp only [divInt_eq_div, cast_div, cast_coe_int]
#align rat.cast_mk Rat.cast_mk
@[simp, norm_cast]
theorem cast_pow (q) (k : ℕ) : ((q : ℚ) ^ k : α) = (q : α) ^ k :=
(castHom α).map_pow q k
#align rat.cast_pow Rat.cast_pow
end WithDivRing
section LinearOrderedField
variable {K : Type _} [LinearOrderedField K]
theorem cast_pos_of_pos {r : ℚ} (hr : 0 < r) : (0 : K) < r := by
rw [Rat.cast_def]
exact div_pos (Int.cast_pos.2 <| num_pos_iff_pos.2 hr) (Nat.cast_pos.2 r.pos)
#align rat.cast_pos_of_pos Rat.cast_pos_of_pos
@[mono]
theorem cast_strictMono : StrictMono ((↑) : ℚ → K) := fun m n => by
simpa only [sub_pos, cast_sub] using @cast_pos_of_pos K _ (n - m)
#align rat.cast_strict_mono Rat.cast_strictMono
@[mono]
theorem cast_mono : Monotone ((↑) : ℚ → K) :=
cast_strictMono.monotone
#align rat.cast_mono Rat.cast_mono
/-- Coercion from `ℚ` as an order embedding. -/
@[simps!]
def castOrderEmbedding : ℚ ↪o K :=
OrderEmbedding.ofStrictMono (↑) cast_strictMono
#align rat.cast_order_embedding Rat.castOrderEmbedding
#align rat.cast_order_embedding_apply Rat.castOrderEmbedding_apply
@[simp, norm_cast]
theorem cast_le {m n : ℚ} : (m : K) ≤ n ↔ m ≤ n :=
castOrderEmbedding.le_iff_le
#align rat.cast_le Rat.cast_le
@[simp, norm_cast]
theorem cast_lt {m n : ℚ} : (m : K) < n ↔ m < n :=
cast_strictMono.lt_iff_lt
#align rat.cast_lt Rat.cast_lt
@[simp]
theorem cast_nonneg {n : ℚ} : 0 ≤ (n : K) ↔ 0 ≤ n := by
norm_cast
#align rat.cast_nonneg Rat.cast_nonneg
@[simp]
theorem cast_nonpos {n : ℚ} : (n : K) ≤ 0 ↔ n ≤ 0 := by
norm_cast
#align rat.cast_nonpos Rat.cast_nonpos
@[simp]
theorem cast_pos {n : ℚ} : (0 : K) < n ↔ 0 < n := by
norm_cast
#align rat.cast_pos Rat.cast_pos
@[simp]
theorem cast_lt_zero {n : ℚ} : (n : K) < 0 ↔ n < 0 := by
norm_cast
#align rat.cast_lt_zero Rat.cast_lt_zero
@[simp, norm_cast]
theorem cast_min {a b : ℚ} : (↑(min a b) : K) = min (a : K) (b : K) :=
(@cast_mono K _).map_min
#align rat.cast_min Rat.cast_min
@[simp, norm_cast]
theorem cast_max {a b : ℚ} : (↑(max a b) : K) = max (a : K) (b : K) :=
(@cast_mono K _).map_max
#align rat.cast_max Rat.cast_max
@[simp, norm_cast]
theorem cast_abs {q : ℚ} : ((|q| : ℚ) : K) = |(q : K)| := by simp [abs_eq_max_neg]
#align rat.cast_abs Rat.cast_abs
open Set
@[simp]
theorem preimage_cast_Icc (a b : ℚ) : (↑) ⁻¹' Icc (a : K) b = Icc a b := by
ext x
simp
#align rat.preimage_cast_Icc Rat.preimage_cast_Icc
@[simp]
theorem preimage_cast_Ico (a b : ℚ) : (↑) ⁻¹' Ico (a : K) b = Ico a b := by
ext x
simp
#align rat.preimage_cast_Ico Rat.preimage_cast_Ico
@[simp]
theorem preimage_cast_Ioc (a b : ℚ) : (↑) ⁻¹' Ioc (a : K) b = Ioc a b := by
ext x
simp
#align rat.preimage_cast_Ioc Rat.preimage_cast_Ioc
@[simp]
theorem preimage_cast_Ioo (a b : ℚ) : (↑) ⁻¹' Ioo (a : K) b = Ioo a b := by
ext x
simp
#align rat.preimage_cast_Ioo Rat.preimage_cast_Ioo
@[simp]
theorem preimage_cast_Ici (a : ℚ) : (↑) ⁻¹' Ici (a : K) = Ici a := by
ext x
simp
#align rat.preimage_cast_Ici Rat.preimage_cast_Ici
@[simp]
theorem preimage_cast_Iic (a : ℚ) : (↑) ⁻¹' Iic (a : K) = Iic a := by
ext x
simp
#align rat.preimage_cast_Iic Rat.preimage_cast_Iic
@[simp]
theorem preimage_cast_Ioi (a : ℚ) : (↑) ⁻¹' Ioi (a : K) = Ioi a := by
ext x
simp
#align rat.preimage_cast_Ioi Rat.preimage_cast_Ioi
@[simp]
theorem preimage_cast_Iio (a : ℚ) : (↑) ⁻¹' Iio (a : K) = Iio a := by
ext x
simp
#align rat.preimage_cast_Iio Rat.preimage_cast_Iio
end LinearOrderedField
-- Porting note: statement made more explicit
@[norm_cast]
theorem cast_id (n : ℚ) : Rat.cast n = n := rfl
#align rat.cast_id Rat.cast_id
@[simp]
theorem cast_eq_id : ((↑) : ℚ → ℚ) = id :=
funext fun _ => rfl
#align rat.cast_eq_id Rat.cast_eq_id
@[simp]
theorem cast_hom_rat : castHom ℚ = RingHom.id ℚ :=
RingHom.ext cast_id
#align rat.cast_hom_rat Rat.cast_hom_rat
end Rat
open Rat
@[simp]
theorem map_ratCast [DivisionRing α] [DivisionRing β] [RingHomClass F α β] (f : F) (q : ℚ) :
f q = q := by rw [cast_def, map_div₀, map_intCast, map_natCast, cast_def]
#align map_rat_cast map_ratCast
@[simp]
theorem eq_ratCast {k} [DivisionRing k] [RingHomClass F ℚ k] (f : F) (r : ℚ) : f r = r := by
rw [← map_ratCast f, Rat.cast_id]
#align eq_rat_cast eq_ratCast
namespace MonoidWithZeroHom
variable {M₀ : Type _} [MonoidWithZero M₀] [MonoidWithZeroHomClass F ℚ M₀] {f g : F}
/-- If `f` and `g` agree on the integers then they are equal `φ`. -/
theorem ext_rat' (h : ∀ m : ℤ, f m = g m) : f = g :=
(FunLike.ext f g) fun r => by
rw [← r.num_div_den, div_eq_mul_inv, map_mul, map_mul, h, ← Int.cast_ofNat,
eq_on_inv₀ f g]
apply h
#align monoid_with_zero_hom.ext_rat' MonoidWithZeroHom.ext_rat'
/-- If `f` and `g` agree on the integers then they are equal `φ`.
See note [partially-applied ext lemmas] for why `comp` is used here. -/
@[ext]
theorem ext_rat {f g : ℚ →*₀ M₀}
(h : f.comp (Int.castRingHom ℚ : ℤ →*₀ ℚ) = g.comp (Int.castRingHom ℚ)) : f = g :=
ext_rat' <| FunLike.congr_fun h
#align monoid_with_zero_hom.ext_rat MonoidWithZeroHom.ext_rat
/-- Positive integer values of a morphism `φ` and its value on `-1` completely determine `φ`. -/
theorem ext_rat_on_pnat (same_on_neg_one : f (-1) = g (-1))
(same_on_pnat : ∀ n : ℕ, 0 < n → f n = g n) : f = g :=
ext_rat' <|
FunLike.congr_fun <|
show
(f : ℚ →*₀ M₀).comp (Int.castRingHom ℚ : ℤ →*₀ ℚ) =
(g : ℚ →*₀ M₀).comp (Int.castRingHom ℚ : ℤ →*₀ ℚ)
from ext_int' (by simpa) (by simpa)
#align monoid_with_zero_hom.ext_rat_on_pnat MonoidWithZeroHom.ext_rat_on_pnat
end MonoidWithZeroHom
/-- Any two ring homomorphisms from `ℚ` to a semiring are equal. If the codomain is a division ring,
then this lemma follows from `eq_ratCast`. -/
theorem RingHom.ext_rat {R : Type _} [Semiring R] [RingHomClass F ℚ R] (f g : F) : f = g :=
MonoidWithZeroHom.ext_rat' <|
RingHom.congr_fun <|
((f : ℚ →+* R).comp (Int.castRingHom ℚ)).ext_int ((g : ℚ →+* R).comp (Int.castRingHom ℚ))
#align ring_hom.ext_rat RingHom.ext_rat
instance Rat.subsingleton_ringHom {R : Type _} [Semiring R] : Subsingleton (ℚ →+* R) :=
⟨RingHom.ext_rat⟩
#align rat.subsingleton_ring_hom Rat.subsingleton_ringHom
section SMul
namespace Rat
variable {K : Type _} [DivisionRing K]
instance (priority := 100) distribSMul : DistribSMul ℚ K where
smul := (· • ·)
smul_zero a := by rw [smul_def, mul_zero]
smul_add a x y := by rw [smul_def, smul_def, smul_def, mul_add]
#align rat.distrib_smul Rat.distribSMul
instance isScalarTower_right : IsScalarTower ℚ K K :=
⟨fun a x y => by simp only [smul_def, smul_eq_mul, mul_assoc]⟩
#align rat.is_scalar_tower_right Rat.isScalarTower_right
end Rat
end SMul
|
<!-- dom:TITLE: Single-particle properties and nuclear data -->
# Single-particle properties and nuclear data
<!-- dom:AUTHOR: Morten Hjorth-Jensen at [National Superconducting Cyclotron Laboratory](http://www.nscl.msu.edu/) and [Department of Physics and Astronomy](https://www.pa.msu.edu/), [Michigan State University](http://www.msu.edu/), East Lansing, MI 48824, USA -->
<!-- Author: -->
**Morten Hjorth-Jensen**, [National Superconducting Cyclotron Laboratory](http://www.nscl.msu.edu/) and [Department of Physics and Astronomy](https://www.pa.msu.edu/), [Michigan State University](http://www.msu.edu/), East Lansing, MI 48824, USA
Date: **Jul 4, 2017**
Copyright 2013-2017, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
<!-- !split -->
## Stability of matter
To understand why matter is stable, and thereby shed light on the limits of
nuclear stability, is one of the
overarching aims and intellectual challenges
of basic research in nuclear physics. To relate the stability of matter
to the underlying fundamental forces and particles of nature as manifested in nuclear matter, is central
to present and planned rare isotope facilities.
Important properties of nuclear systems which can reveal information about these topics
are for example masses, and thereby binding energies, and density distributions of nuclei.
These are quantities which convey important information on
the shell structure of nuclei, with their
pertinent magic numbers and shell closures or the eventual disappearence of the latter
away from the valley of stability.
<!-- !split -->
## Drip lines
Neutron-rich nuclei are particularly interesting for the above endeavour. As a particular chain
of isotopes becomes more and more neutron rich, one reaches finally the limit of stability, the so-called
dripline, where one additional neutron makes the next isotopes unstable with respect
to the previous ones. The appearence or not of magic numbers and shell structures,
the formation of neutron skins and halos
can thence be probed via investigations of quantities like the binding energy
or the charge radii and neutron rms radii of neutron-rich nuclei.
These quantities have in turn important
consequences for theoretical models of nuclear structure and their application in astrophysics.
<!-- !split -->
## More on [Neutron-rich nuclei](http://iopscience.iop.org/1402-4896/2013/T152)
Neutron radius of ${}^{208}\mbox{Pb}$, recently extracted from the PREX
experiment at Jefferson Laboratory can be used to constrain the equation of state of
neutron matter. A related quantity to the
neutron rms radius $r_n^{\mathrm{rms}}=\langle r^2\rangle_n^{1/2}$ is the neutron skin
$r_{\mathrm{skin}}=r_n^{\mathrm{rms}}-r_p^{\mathrm{rms}}$,
where $r_p^{\mathrm{rms}}$ is the corresponding proton rms radius.
There are several properties which relate the thickness of the neutron skin to quantities in nuclei and
nuclear matter, such as the symmetry energy at the saturation point for nuclear matter, the slope
of the equation of state for neutron matter
or the low-energy electric dipole strength due to the pigmy dipole resonance.
<!-- !split -->
## Motivation
Having access to precise measurements of masses, radii, and
electromagnetic moments for a wide range of nuclei allows to study
trends with varying neutron excess. A quantitative description of
various experimental data with quantified uncertainty still remains a
major challenge for nuclear structure theory. Global theoretical
studies of isotopic chains, such as the Ca chain shown in the figure below here, make it possible to test systematic
properties of effective interactions between nucleons. Such calculations also
provide critical tests of limitations of many-body methods. As one
approaches the particle emission thresholds, it becomes increasingly
important to describe correctly the coupling to the continuum of
decays and scattering channels. While the
full treatment of antisymmetrization and short-range correlations has
become routine in first principle approaches (to be defined later) to nuclear bound states, the
many-body problem becomes more difficult when long-range correlations
and continuum effects are considered.
<!-- !split -->
## FRIB limits
<!-- dom:FIGURE: [figslides/careach.png, width=500 frac=0.6] Expected experimental information on the calcium isotopes that can be obtained at FRIB. The limits for detailed spectroscopic information are around $A\sim 60$. -->
<!-- begin figure -->
<p>Expected experimental information on the calcium isotopes that can be obtained at FRIB. The limits for detailed spectroscopic information are around $A\sim 60$.</p>
<!-- end figure -->
<!-- !split -->
## Motivation and aims
The aim of the first part of this course is to present some of the
experimental data which can be used to extract information about
correlations in nuclear systems. In particular, we will start with a
theoretical analysis of a quantity called the separation energy for
neutrons or protons. This quantity, to be discussed below, is defined
as the difference between two binding energies (masses) of neighboring
nuclei. As we will see from various figures below and exercises as
well, the separation energies display a varying behavior as function
of the number of neutrons or protons. These variations from one
nucleus to another one, laid the foundation for the introduction of
so-called magic numbers and a mean-field picture in order to describe
nuclei theoretically.
<!-- !split -->
## Mean-field picture
With a mean- or average-field picture we mean that a given nucleon (either a proton or a neutron) moves in an average potential field which is set up by all other nucleons in the system. Consider for example a nucleus like ${}^{17}\mbox{O}$ with nine neutrons and eight protons. Many properties of this nucleus can be interpreted in terms of a picture where we can view it as
one neutron on top of ${}^{16}\mbox{O}$. We infer from data and our theoretical interpretations that this additional neutron behaves almost as an individual neutron which *sees* an average interaction set up by the remaining 16 nucleons in ${}^{16}\mbox{O}$. A nucleus like ${}^{16}\mbox{O}$ is an example of what we in this course will denote as a good closed-shell nucleus. We will come back to what this means later.
<!-- !split -->
## Mean-field picture, which potential do we opt for?
A simple potential model which enjoys quite some popularity in nuclear
physics, is the **three-dimensional harmonic oscillator**. This potential
model captures some of the physics of deeply bound single-particle
states but fails in reproducing the less bound single-particle
states.
A parametrized, and more realistic, potential model which is
widely used in nuclear physics, is the so-called **Woods-Saxon**
potential. Both the harmonic oscillator and the Woods-Saxon potential
models define computational problems that can easily be solved (see
below), resulting (with the appropriate parameters) in a rather good
reproduction of experiment for nuclei which can be approximated as one
nucleon on top (or one nucleon removed) of a so-called closed-shell
system.
<!-- !split -->
## Too simple?
To be able to interpret a nucleus in such a way requires at least that
we are capable of parametrizing the abovementioned interactions in
order to reproduce say the excitation spectrum of a nucleus like
${}^{17}\mbox{O}$.
With such a parametrized interaction we are able to solve
Schroedinger's equation for the motion of one nucleon in a given
field. A nucleus is however a true and complicated many-nucleon
system, with extremely many degrees of freedom and complicated
correlations, rendering the ideal solution of the many-nucleon
Schroedinger equation an impossible enterprise. It is much easier to
solve a single-particle problem with say a Woods-Saxon
potential.
<!-- !split -->
## Motivation, better mean-fields
An improvement to these simpler single-nucleon potentials is given by
the Hartree-Fock method, where the variational principle is used to
define a mean-field which the nucleons move in. There are many
different classes of mean-field methods. An important difference
between these methods and the simpler parametrized mean-field
potentials like the harmonic oscillator and the Woods-Saxon
potentials, is that the resulting equations contain information about
the nuclear forces present in our models for solving Schroedinger's
equation. Hartree-Fock and other mean-field methods like density
functional theory form core topics in later lectures.
<!-- !split -->
## Aims here
The aim here is to present some of the experimental data we
will confront theory with. In particular, we will focus on separation
and shell-gap energies and use these to build a picture of nuclei in
terms of (from a philosophical stand we would call this a reductionist
approach) a single-particle picture. The harmonic oscillator will
serve as an excellent starting point in building nuclei from the
bottom and up. Here we will neglect nuclear forces, these are
introduced in the next section when we discuss the Hartree-Fock
method.
The aim of this course is to develop our physics intuition of nuclear systems using a theoretical approach where we describe data in terms of
the motion of individual nucleons and their mutual interactions.
**How our theoretical pictures and models can be used to interpret data is in essence what this course is about**. Our narrative will lead us along a path where we start with single-particle models and end with the theory of the nuclear shell-model. The latter will be used to understand and analyze excitation spectra and decay patterns of nuclei, linking our theoretical understanding with interpretations of experiment. The way we build up our theoretical descriptions and interpretations follows what we may call a standard reductionistic approach, that is we start with what we believe are our effective degrees of freedom (nucleons in our case) and interactions amongst these and solve thereafter the underlying equations of motions. This defines the nuclear many-body problem, and mean-field approaches like Hartree-Fock theory and the nuclear shell-model represent different approaches to our solutions of Schroedinger's equation.
<!-- !split -->
## Aims of this course
The aims of this course are to develop our physics intuition of nuclear
systems using a theoretical approach where we describe data in terms
of the motion of individual nucleons and their mutual interactions.
**How our theoretical pictures and models can be used to interpret data is in essence what this course is about**. Our narrative will lead us
along a path where we start with single-particle models and end with
the theory of the nuclear shell-model. The latter will be used to
understand and analyze excitation spectra and decay patterns of
nuclei, linking our theoretical understanding with interpretations of
experiment. The way we build up our theoretical descriptions and
interpretations follows what we may call a standard reductionistic
approach, that is we start with what we believe are our effective
degrees of freedom (nucleons in our case) and interactions amongst
these and solve thereafter the underlying equations of motions. This
defines the nuclear many-body problem, and mean-field approaches like
Hartree-Fock theory and the nuclear shell-model represent different
approaches to our solutions of Schroedinger's equation.
<!-- !split -->
## Back to the stability of matter questions
**Do we understand the physics of dripline systems?**
We start our tour of experimental data and our interpretations by
considering the chain of oxygen isotopes. In the exercises below you
will be asked to perform similar analyses for other chains of
isotopes.
The oxygen isotopes are the heaviest isotopes for which the drip line
is well established. The drip line is defined as the point where
adding one more nucleon leads to an unbound nucleus. Below we will see
that we can define the dripline by studying the separation
energy. Where the neutron (proton) separation energy changes sign as a
function of the number of neutrons (protons) defines the neutron
(proton) drip line.
<!-- !split -->
## Back to the stability of matter questions
**Do we understand the physics of dripline systems?**
The oxygen isotopes are simple enough to be described by some few
selected single-particle degrees of freedom.
* Two out of four stable even-even isotopes exhibit a doubly magic nature, namely ${}^{22}\mbox{O}$ ($Z=8$, $N=14$) and ${}^{24}\mbox{O}$ ($Z=8$, $N=16$).
* The structure of ${}^{22}\mbox{O}$ and ${}^{24}\mbox{O}$ is assumed to be governed by the evolution of the $1s_{1/2}$ and $0d_{5/2}$ one-quasiparticle states.
* The isotopes ${}^{25}\mbox{O}$, ${}^{26}\mbox{O}$, ${}^{27}\mbox{O}$ and ${}^{28}\mbox{O}$ are outside the drip line, since the $0d_{3/2}$ orbit is not bound.
<!-- !split -->
## Recent articles on Oxygen isotopes
**Many experiments and theoretical calculations worldwide!**
* ${}^{24}\mbox{O}$ and lighter: C. R. Hoffman *et al.*, Phys. Lett. B **672**, 17 (2009); R. Kanungo *et al*., Phys. Rev. Lett.~**102**, 152501 (2009); C. R. Hoffman *et al*., Phys. Rev. C **83**, 031303(R) (2011); Stanoiu *et al*., Phys. Rev. C **69**, 034312 (2004)
* ${}^{25}\mbox{O}$: C. R. Hoffman *et al*., Phys. Rev. Lett. **102**,152501 (2009).
* ${}^{26}\mbox{O}$: E. Lunderberg *et al*., Phys. Rev. Lett. **108**, 142503 (2012).
* ${}^{26}\mbox{O}$: Z. Kohley *et al*., Study of two-neutron radioactivity in the decay of 26O, Phys. Rev. Lett., **110**, 152501 (2013).
* Theory: Oxygen isotopes with three-body forces, Otsuka *et al*., Phys. Rev. Lett. **105**, 032501 (2010). Hagen *et al.*, Phys. Rev. Lett., **108**, 242501 (2012).
<!-- !split -->
## Do we understand the physics of dripline systems?
Our first approach in analyzing data theoretically, is to see if we can use experimental information to
* Extract information about a *so-called* single-particle behavior
* And interpret such a behavior in terms of the underlying forces and microscopic physics
The next step is to see if we could use these interpretations to say something about shell closures and magic numbers. Since we focus on single-particle properties, a quantity we can extract from experiment is the separation energy for protons and neutrons. Before we proceed, we need to define quantities like masses and binding energies. Two excellent reviews on
recent trends in the determination of nuclear masses can be found in the articles of [Lunney and co-workers](http://journals.aps.org/rmp/abstract/10.1103/RevModPhys.75.1021) and [Blaum and co-workers](http://iopscience.iop.org/1402-4896/2013/T152/014017/)
<!-- !split -->
## Masses and Binding energies
A basic quantity which can be measured for the ground states of nuclei is the atomic mass $M(N, Z)$ of the neutral atom with atomic mass number $A$ and charge $Z$. The number of neutrons is $N$.
Atomic masses are usually tabulated in terms of the mass excess defined by
$$
\Delta M(N, Z) = M(N, Z) - uA,
$$
where $u$ is the Atomic Mass Unit
$$
u = M(^{12}\mathrm{C})/12 = 931.49386 \hspace{0.1cm} \mathrm{MeV}/c^2.
$$
In this course we will mainly use
data from the 2003 compilation of [Audi, Wapstra and Thibault](http://www.sciencedirect.com/science/journal/03759474/729/1).
<!-- !split -->
## Masses and Binding energies
The nucleon masses are
$$
m_p = 938.27203(8)\hspace{0.1cm} \mathrm{MeV}/c^2 = 1.00727646688(13)u,
$$
and
$$
m_n = 939.56536(8)\hspace{0.1cm} \mathrm{MeV}/c^2 = 1.0086649156(6)u.
$$
In the 2003 mass evaluation there are 2127 nuclei measured with an accuracy of 0.2
MeV or better, and 101 nuclei measured with an accuracy of greater than 0.2 MeV. For
heavy nuclei one observes several chains of nuclei with a constant $N-Z$ value whose masses are obtained from the energy released in $\alpha$-decay.
<!-- !split -->
## Masses and Binding energies
The nuclear binding energy is defined as the energy required to break up a given nucleus
into its constituent parts of $N$ neutrons and $Z$ protons. In terms of the atomic masses $M(N, Z)$ the binding energy is defined by
$$
BE(N, Z) = ZM_H c^2 + Nm_n c^2 - M(N, Z)c^2 ,
$$
where $M_H$ is the mass of the hydrogen atom and $m_n$ is the mass of the neutron.
In terms of the mass excess the binding energy is given by
$$
BE(N, Z) = Z\Delta_H c^2 + N\Delta_n c^2 -\Delta(N, Z)c^2 ,
$$
where $\Delta_H c^2 = 7.2890$ MeV and $\Delta_n c^2 = 8.0713$ MeV.
<!-- !split -->
## Masses and Binding energies
The following python program reads in the experimental data on binding energies and, stored in the file bindingenergies.dat, plots them as function of the mass number $A$. One notices clearly a saturation of the binding energy per nucleon at $A\approx 56$.
```
%matplotlib inline
import numpy as np
from matplotlib import pyplot as plt
# Load in data file
data = np.loadtxt("datafiles/bindingenergies.dat")
# Make arrays containing x-axis and binding energies as function of A
x = data[:,2]
bexpt = data[:,3]
plt.plot(x, bexpt ,'ro')
plt.axis([0,270,-1, 10.0])
plt.xlabel(r'$A$')
plt.ylabel(r'Binding energies in [MeV]')
plt.legend(('Experiment'), loc='upper right')
plt.title(r'Binding energies from experiment')
plt.savefig('expbindingenergies.pdf')
plt.savefig('expbindingenergies.png')
plt.show()
```
## Liquid drop model as a simple parametrization of binding energies
A popular and physically intuitive model which can be used to parametrize
the experimental binding energies as function of $A$, is the so-called
the liquid drop model. The ansatz is based on the following expression
$$
BE(N,Z) = a_1A-a_2A^{2/3}-a_3\frac{Z^2}{A^{1/3}}-a_4\frac{(N-Z)^2}{A},
$$
where $A$ stands for the number of nucleons and the $a_i$s are parameters which are determined by a fit
to the experimental data.
## Liquid drop model as a simple parametrization of binding energies
To arrive at the above expression we have assumed that we can make the following assumptions:
* There is a volume term $a_1A$ proportional with the number of nucleons (the energy is also an extensive quantity). When an assembly of nucleons of the same size is packed together into the smallest volume, each interior nucleon has a certain number of other nucleons in contact with it. This contribution is proportional to the volume.
* There is a surface energy term $a_2A^{2/3}$. The assumption here is that a nucleon at the surface of a nucleus interacts with fewer other nucleons than one in the interior of the nucleus and hence its binding energy is less. This surface energy term takes that into account and is therefore negative and is proportional to the surface area.
## Liquid drop model as a simple parametrization of binding energies, continues
* There is a Coulomb energy term $a_3\frac{Z^2}{A^{1/3}}$. The electric repulsion between each pair of protons in a nucleus yields less binding.
* There is an asymmetry term $a_4\frac{(N-Z)^2}{A}$. This term is associated with the Pauli exclusion principle and reflectd the fact that the proton-neutron interaction is more attractive on the average than the neutron-neutron and proton-proton interactions.
We could also add a so-called pairing term, which is a correction term that
arises from the tendency of proton pairs and neutron pairs to
occur. An even number of particles is more stable than an odd number.
Performing a least-square fit to data, we obtain the following numerical values for the various constants
* $a_1=15.49$ MeV
* $a_2=17.23$ MeV
* $a_3=0.697$ MeV
* $a_4=22.6$ MeV
<!-- !split -->
## Masses and Binding energies
The following python program reads now in the experimental data on binding energies as well as the results from the above liquid drop model and plots these energies as function of the mass number $A$. One sees that for larger values of $A$, there is a better agreement with data.
```
import numpy as np
from matplotlib import pyplot as plt
# Load in data file
data = np.loadtxt("datafiles/bindingenergies.dat")
# Make arrays containing x-axis and binding energies as function of
x = data[:,2]
bexpt = data[:,3]
liquiddrop = data[:,4]
plt.plot(x, bexpt ,'b-o', x, liquiddrop, 'r-o')
plt.axis([0,270,-1, 10.0])
plt.xlabel(r'$A$')
plt.ylabel(r'Binding energies in [MeV]')
plt.legend(('Experiment','Liquid Drop'), loc='upper right')
plt.title(r'Binding energies from experiment and liquid drop')
plt.savefig('bindingenergies.pdf')
plt.savefig('bindingenergies.png')
plt.show()
```
<!-- !split -->
## Masses and Binding energies
The python program on the next slide reads now in the experimental data on binding energies and performs a nonlinear least square fitting of the data. In the example here we use only the parameters $a_1$ and $a_2$, leaving it as an exercise to the reader to perform the fit for all four paramters. The results are plotted and compared with the experimental values. To read more about non-linear least square methods, see for example the text of M.J. Box, D. Davies and W.H. Swann, Non-Linear optimisation Techniques, Oliver & Boyd, 1969.
<!-- !split -->
## Masses and Binding energies, the code
```
import numpy as np
from scipy.optimize import curve_fit
from matplotlib import pyplot as plt
# Load in data file
data = np.loadtxt("datafiles/bindingenergies.dat")
# Make arrays containing A on x-axis and binding energies
A = data[:,2]
bexpt = data[:,3]
# The function we want to fit to, only two terms here
def func(A,a1, a2):
return a1*A-a2*(A**(2.0/3.0))
# function to perform nonlinear least square with guess for a1 and a2
popt, pcov = curve_fit(func, A, bexpt, p0 = (16.0, 18.0))
a1 = popt[0]
a2 = popt[1]
liquiddrop = a1*A-a2*(A**(2.0/3.0))
plt.plot(A, bexpt ,'bo', A, liquiddrop, 'ro')
plt.axis([0,270,-1, 10.0])
plt.xlabel(r'$A$')
plt.ylabel(r'Binding energies in [MeV]')
plt.legend(('Experiment','Liquid Drop'), loc='upper right')
plt.title(r'Binding energies from experiment and liquid drop')
plt.savefig('bindingenergies.pdf')
plt.savefig('bindingenergies.png')
plt.show()
```
<!-- !split -->
## $Q$-values and separation energies
We are now interested in interpreting experimental binding energies in terms of a single-particle picture.
In order to do so, we consider first energy conservation for nuclear transformations that include, for
example, the fusion of two nuclei $a$ and $b$ into the combined system $c$
$$
{^{N_a+Z_a}}a+ {^{N_b+Z_b}}b\rightarrow {^{N_c+Z_c}}c
$$
or the decay of nucleus $c$ into two other nuclei $a$ and $b$
$$
^{N_c+Z_c}c \rightarrow ^{N_a+Z_a}a+ ^{N_b+Z_b}b
$$
<!-- !split -->
## $Q$-values and separation energies
In general we have the reactions
$$
\sum_i {^{N_i+Z_i}}i \rightarrow \sum_f {^{N_f+Z_f}}f
$$
We require also that the number of protons and neutrons (the total number of nucleons) is conserved in the initial stage and final stage, unless we have processes which violate baryon conservation,
$$
\sum_iN_i = \sum_f N_f \hspace{0.2cm}\mathrm{and} \hspace{0.2cm}\sum_iZ_i = \sum_f Z_f.
$$
<!-- !split -->
## Motivation
**Do we understand the physics of dripline systems?**
Artist's rendition of the emission of one proton from various oxygen isotopes. Protons are in red while neutrons are in blue. These processes could be interpreted as the decay
nucleus $c$ into two other nuclei $a$ and $b$
$$
^{N_c+Z_c}c \rightarrow ^{N_a+Z_a}a+ ^{N_b+Z_b}b .
$$
<!-- dom:FIGURE: [figslides/oxygens.jpg, width=600 frac=0.6] Artist's rendition of the emission of one proton from various oxygen isotopes. -->
<!-- begin figure -->
<p>Artist's rendition of the emission of one proton from various oxygen isotopes.</p>
<!-- end figure -->
<!-- !split -->
## $Q$-values and separation energies
The above processes can be characterized by an energy difference called the $Q$ value, defined as
$$
Q=\sum_i M(N_i, Z_i)c^2-\sum_f M(N_f, Z_f)c^2=\sum_i BE(N_f, Z_f)-\sum_i BE(N_i, Z_i)
$$
Spontaneous decay involves a single initial nuclear state and is allowed if $Q > 0$. In the decay, energy is released in the form of the kinetic energy of the final products. Reactions involving two initial nuclei are called endothermic (a net loss of energy) if $Q < 0$. The reactions are exothermic (a net release of energy) if $Q > 0$.
<!-- !split -->
## $Q$-values and separation energies
Let us study the Q values associated with the removal of one or two nucleons from
a nucleus. These are conventionally defined in terms of the one-nucleon and two-nucleon
separation energies. The neutron separation energy is defined as
$$
S_n= -Q_n= BE(N,Z)-BE(N-1,Z),
$$
and the proton separation energy reads
$$
S_p= -Q_p= BE(N,Z)-BE(N,Z-1).
$$
The two-neutron separation energy is defined as
$$
S_{2n}= -Q_{2n}= BE(N,Z)-BE(N-2,Z),
$$
and the two-proton separation energy is given by
$$
S_{2p}= -Q_{2p}= BE(N,Z)-BE(N,Z-2).
$$
<!-- !split -->
## Separation energies and energy gaps
Using say the neutron separation energies (alternatively the proton separation energies)
$$
S_n= -Q_n= BE(N,Z)-BE(N-1,Z),
$$
we can define the so-called energy gap for neutrons (or protons) as
$$
\Delta S_n= BE(N,Z)-BE(N-1,Z)-\left(BE(N+1,Z)-BE(N,Z)\right),
$$
or
$$
\Delta S_n= 2BE(N,Z)-BE(N-1,Z)-BE(N+1,Z).
$$
This quantity can in turn be used to determine which nuclei are magic or not.
For protons we would have
$$
\Delta S_p= 2BE(N,Z)-BE(N,Z-1)-BE(N,Z+1).
$$
We leave it as an exercise to the reader to define and interpret the two-neutron or two-proton gaps.
<!-- !split -->
## Separation energies for oxygen isotopes
The following python programs can now be used to plot the separation energies and the energy gaps for the oxygen isotopes. The following python code reads the separation energies from file for all oxygen isotopes from $A=13$ to $A=25$, The data are taken from the file *snox.dat*. This files contains the separation energies and the shell gap energies.
```
import numpy as np
from matplotlib import pyplot as plt
# Load in data file
data = np.loadtxt("datafiles/snox.dat")
# Make arrays containing x-axis and binding energies as function of
x = data[:,1]
y = data[:,2]
plt.plot(x, y,'b-+',markersize=6)
plt.axis([4,18,-1, 25.0])
plt.xlabel(r'Number of neutrons $N$',fontsize=20)
plt.ylabel(r'$S_n$ [MeV]',fontsize=20)
plt.legend(('Separation energies for oxygen isotpes'), loc='upper right')
plt.title(r'Separation energy for the oxygen isotopes')
plt.savefig('snoxygen.pdf')
plt.savefig('snoxygen.png')
plt.show()
```
<!-- !split -->
## Energy gaps for oxygen isotopes
Here we display the python program for plotting the corresponding results for shell gaps for the oxygen isotopes.
```
import numpy as np
from matplotlib import pyplot as plt
# Load in data file
data = np.loadtxt("datafiles/snox.dat")
# Make arrays containing x-axis and binding energies as function of
x = data[:,1]
y = data[:,3]
plt.plot(x, y,'b-+',markersize=6)
plt.axis([4,18,-7, 12.0])
plt.xlabel(r'Number of neutrons $N$',fontsize=20)
plt.ylabel(r'$\Delta S_n$ [MeV]',fontsize=20)
plt.legend(('Shell gap energies for oxygen isotpes'), loc='upper right')
plt.title(r'Shell gap energies for the oxygen isotopes')
plt.savefig('gapoxygen.pdf')
plt.savefig('gapoxygen.png')
plt.show()
```
## Features to be noted
Since we will focus in the beginning on single-particle degrees of freedom and mean-field approaches before we
start with nuclear forces and many-body approaches like the nuclear shell-model, there are some features to be noted
* In the discussion of the liquid drop model and binding energies, we note that the total binding energy is not that different from the sum of the individual neutron and proton masses.
One may thus infer that intrinsic properties of nucleons in a nucleus are close to those of free nucleons.
* In the discussion of the neutron separation energies for the oxygen isotopes, we note a clear staggering effect between odd and even isotopes with the even ones being more bound (larger separation energies). We will later link this to strong pairing correlations in nuclei.
## Features to be noted, continues
* The neutron separation energy becomes negative at ${}^{25}\mbox{O}$, making this nucleus unstable with respect to the emission of one neutron. A nucleus like ${}^{24}\mbox{O}$ is thus the last stable oxygen isotopes which has been observed. Oxygen-26 has been "found":"journals.aps.org/prl/abstract/10.1103/PhysRevLett.108.142503" to be unbound with respect to ${}^{24}\mbox{O}$.
* We note also that there are large shell-gaps for some nuclei, meaning that more energy is needed to remove one nucleon. These gaps are used to define so-called magic numbers. For the oxygen isotopes we see a clear gap for ${}^{16}\mbox{O}$. We will interpret this gap as one of several experimental properties that define so-called magic numbers. In our discussion below we will make a first interpretation using single-particle states from the harmonic oscillator and the Woods-Saxon potential.
In the exercises below you will be asked to perform a similar analysis for other chains of isotopes and interpret the results.
## Radii
The root-mean-square (rms) charge radius has been measured for the ground states of many
nuclei. For a spherical charge density, $\rho(\boldsymbol{r})$, the mean-square radius is defined by
$$
\langle r^2\rangle = \frac{ \int d \boldsymbol{r} \rho(\boldsymbol{r}) r^2}{ \int d \boldsymbol{r} \rho(\boldsymbol{r})},
$$
and the rms radius is the square root of this quantity denoted by
$$
R =\sqrt{ \langle r^2\rangle}.
$$
## Radii
Radii for most stable
nuclei have been deduced from electron scattering form
factors and/or from the x-ray transition energies of muonic atoms.
The relative radii for a
series of isotopes can be extracted from the isotope shifts of atomic x-ray transitions.
The rms radius for the nuclear point-proton density, $R_p$ is obtained from the rms charge radius by:
$$
R_p = \sqrt{R^2_{\mathrm{ch}}- R^2_{\mathrm{corr}}},
$$
where
$$
R^2_{\mathrm{corr}}= R^2_{\mathrm{op}}+(N/Z)R^2_{\mathrm{on}}+R^2_{\mathrm{rel}},
$$
where
$$
R_{\mathrm{op}}= 0.875(7) \mathrm{fm}.
$$
is the rms radius of the proton, $R^2_{\mathrm{on}} = 0.116(2)$ $\mbox{fm}^{2}$ is the
mean-square radius of the neutron and $R^2_{\mathrm{rel}} = 0.033$ $\mbox{fm}^{2}$ is the relativistic Darwin-Foldy correction. There are additional smaller nucleus-dependent corrections.
<!-- !split -->
## Definitions
We will now introduce the potential models we have discussex above, namely the harmonic oscillator and the Woods-Saxon potentials. In order to proceed, we need some definitions.
We define an operator as $\hat{O}$ throughout. Unless otherwise specified the total number of nucleons is
always $A$ and $d$ is the dimension of the system. In nuclear physics
we normally define the total number of particles to be $A=N+Z$, where
$N$ is total number of neutrons and $Z$ the total number of
protons. In case of other baryons such as isobars $\Delta$ or various
hyperons such as $\Lambda$ or $\Sigma$, one needs to add their
definitions. When we refer to a single neutron we will use the label $n$ and when we refer to a single proton we will use the label $p$. Unless otherwise specified, we will simply call these particles for nucleons.
## Definitions
The quantum numbers of a single-particle state in coordinate space are
defined by the variables
$$
x=(\boldsymbol{r},\sigma),
$$
where
$$
\boldsymbol{r}\in {\mathbb{R}}^{d},
$$
with $d=1,2,3$ represents the spatial coordinates and $\sigma$ is the eigenspin of the particle. For fermions with eigenspin $1/2$ this means that
$$
x\in {\mathbb{R}}^{d}\oplus (\frac{1}{2}),
$$
and the integral
$$
\int dx = \sum_{\sigma}\int d^dr = \sum_{\sigma}\int d\boldsymbol{r}.
$$
Since we are dealing with protons and neutrons we need to add isospin as a new degree of freedom.
## Definitions
Including isospin $\tau$ we have
$$
x=(\boldsymbol{r},\sigma,\tau),
$$
where
$$
\boldsymbol{r}\in {\mathbb{R}}^{3},
$$
For nucleons, which are fermions with eigenspin $1/2$ and isospin $1/2$ this means that
$$
x\in {\mathbb{R}}^{d}\oplus (\frac{1}{2})\oplus (\frac{1}{2}),
$$
and the integral
$$
\int dx = \sum_{\sigma\tau}\int d\boldsymbol{r},
$$
and
$$
\int d^Ax= \int dx_1\int dx_2\dots\int dx_A.
$$
We will use the standard nuclear physics definition of isospin, resulting in $\tau_z=-1/2$ for protons and $\tau_z=1/2$ for neutrons.
## Definitions
The quantum mechanical wave function of a given state with quantum numbers $\lambda$ (encompassing all quantum numbers needed to specify the system), ignoring time, is
$$
\Psi_{\lambda}=\Psi_{\lambda}(x_1,x_2,\dots,x_A),
$$
with $x_i=(\boldsymbol{r}_i,\sigma_i,\tau_i)$ and the projections of $\sigma_i$ and $\tau_i$ take the values
$\{-1/2,+1/2\}$.
We will hereafter always refer to $\Psi_{\lambda}$ as the exact wave function, and if the ground state is not degenerate we label it as
$$
\Psi_0=\Psi_0(x_1,x_2,\dots,x_A).
$$
## Definitions
Since the solution $\Psi_{\lambda}$ seldomly can be found in closed form, approximations are sought. In this text we define an approximative wave function or an ansatz to the exact wave function as
$$
\Phi_{\lambda}=\Phi_{\lambda}(x_1,x_2,\dots,x_A),
$$
with
$$
\Phi_{0}=\Phi_{0}(x_{1},x_{2},\dots,x_{A}),
$$
being the ansatz for the ground state.
## Definitions
The wave function $\Psi_{\lambda}$ is sought in the Hilbert space of either symmetric or anti-symmetric $N$-body functions, namely
$$
\Psi_{\lambda}\in {\cal H}_A:= {\cal H}_1\oplus{\cal H}_1\oplus\dots\oplus{\cal H}_1,
$$
where the single-particle Hilbert space $\hat{H}_1$ is the space of square integrable functions over $\in {\mathbb{R}}^{d}\oplus (\sigma)\oplus (\tau)$ resulting in
$$
{\cal H}_1:= L^2(\mathbb{R}^{d}\oplus (\sigma)\oplus (\tau)).
$$
## Definitions
Our Hamiltonian is invariant under the permutation (interchange) of two particles.
Since we deal with fermions however, the total wave function is antisymmetric.
Let $\hat{P}$ be an operator which interchanges two particles.
Due to the symmetries we have ascribed to our Hamiltonian, this operator commutes with the total Hamiltonian,
$$
[\hat{H},\hat{P}] = 0,
$$
meaning that $\Psi_{\lambda}(x_1, x_2, \dots , x_A)$ is an eigenfunction of
$\hat{P}$ as well, that is
$$
\hat{P}_{ij}\Psi_{\lambda}(x_1, x_2, \dots,x_i,\dots,x_j,\dots,x_A)=
\beta\Psi_{\lambda}(x_1, x_2, \dots,x_j,\dots,x_i,\dots,x_A),
$$
where $\beta$ is the eigenvalue of $\hat{P}$. We have introduced the suffix $ij$ in order to indicate that we permute particles $i$ and $j$.
The Pauli principle tells us that the total wave function for a system of fermions
has to be antisymmetric, resulting in the eigenvalue $\beta = -1$.
## Definitions and notations
The Schrodinger equation reads
<!-- Equation labels as ordinary links -->
<div id="eq:basicSE1"></div>
$$
\begin{equation}
\hat{H}(x_1, x_2, \dots , x_A) \Psi_{\lambda}(x_1, x_2, \dots , x_A) =
E_\lambda \Psi_\lambda(x_1, x_2, \dots , x_A), \label{eq:basicSE1} \tag{1}
\end{equation}
$$
where the vector $x_i$ represents the coordinates (spatial, spin and isospin) of particle $i$, $\lambda$ stands for all the quantum
numbers needed to classify a given $A$-particle state and $\Psi_{\lambda}$ is the pertaining eigenfunction. Throughout this course,
$\Psi$ refers to the exact eigenfunction, unless otherwise stated.
## Definitions and notations
We write the Hamilton operator, or Hamiltonian, in a generic way
$$
\hat{H} = \hat{T} + \hat{V}
$$
where $\hat{T}$ represents the kinetic energy of the system
$$
\hat{T} = \sum_{i=1}^A \frac{\mathbf{p}_i^2}{2m_i} = \sum_{i=1}^A \left( -\frac{\hbar^2}{2m_i} \mathbf{\nabla_i}^2 \right) =
\sum_{i=1}^A t(x_i)
$$
while the operator $\hat{V}$ for the potential energy is given by
<!-- Equation labels as ordinary links -->
<div id="eq:firstv"></div>
$$
\begin{equation}
\hat{V} = \sum_{i=1}^A \hat{u}_{\mathrm{ext}}(x_i) + \sum_{ji=1}^A v(x_i,x_j)+\sum_{ijk=1}^Av(x_i,x_j,x_k)+\dots
\label{eq:firstv} \tag{2}
\end{equation}
$$
Hereafter we use natural units, viz. $\hbar=c=e=1$, with $e$ the elementary charge and $c$ the speed of light. This means that momenta and masses
have dimension energy.
## Definitions and notations
The potential energy part includes also an external potential $\hat{u}_{\mathrm{ext}}(x_i)$.
In a non-relativistic approach to atomic physics, this external potential is given by the attraction an electron feels from the atomic nucleus. The latter being much heavier than the involved electrons, is often used to define a natural center of mass. In nuclear physics there is no such external potential. It is the nuclear force which results in binding in nuclear systems. In a non-relativistic framework, the nuclear force contains two-body, three-body and more complicated degrees of freedom. The potential energy reads then
$$
\hat{V} = \sum_{ij}^A v(x_i,x_j)+\sum_{ijk}^Av(x_i,x_j,x_k)+\dots
$$
## Definitions and notations, more complicated forces
Three-body and more complicated forces arise since we are dealing with protons and neutrons as effective degrees of freedom. We will come back to this topic later. Furthermore, in large parts of these lectures we will assume that the potential energy can be approximated by a two-body interaction only. Our Hamiltonian reads then
<!-- Equation labels as ordinary links -->
<div id="eq:firstH"></div>
$$
\begin{equation}
\hat{H} = \sum_{i=1}^A \frac{\mathbf{p}_i^2}{2m_i}+\sum_{ij}^A v(x_i,x_j).
\label{eq:firstH} \tag{3}
\end{equation}
$$
## A modified Hamiltonian
It is however, from a computational point of view, convenient to introduce an external potential $\hat{u}_{\mathrm{ext}}(x_i)$ by adding and substracting it to the original Hamiltonian.
This means that our Hamiltonian can be rewritten as
$$
\hat{H} = \hat{H}_0 + \hat{H}_I
= \sum_{i=1}^A \hat{h}_0(x_i) + \sum_{i < j=1}^A \hat{v}(x_{ij})-\sum_{i=1}^A\hat{u}_{\mathrm{ext}}(x_i),
$$
with
$$
\hat{H}_0=\sum_{i=1}^A \hat{h}_0(x_i) = \sum_{i=1}^A\left(\hat{t}(x_i) + \hat{u}_{\mathrm{ext}}(x_i)\right).
$$
The interaction (or potential energy term) reads now
$$
\hat{H}_I= \sum_{i < j=1}^A \hat{v}(x_{ij})-\sum_{i=1}^A\hat{u}_{\mathrm{ext}}(x_i).
$$
In nuclear physics the one-body part $u_{\mathrm{ext}}(x_i)$ is often approximated by a harmonic oscillator potential or a
Woods-Saxon potential. However, this is not fully correct, because as we have discussed, nuclei are self-bound systems and there is no external confining potential. As we will see later, *the $\hat{H}_0$ part of the hamiltonian cannot be used to compute the binding energy of a nucleus since it is not based on a model for the nuclear forces*. That is, the binding energy is not the sum of the individual single-particle energies.
## A modified Hamiltonian
Why do we introduce the Hamiltonian in the form
$$
\hat{H} = \hat{H}_0 + \hat{H}_I?
$$
There are many reasons for this. Let us look at some of them, using the harmonic oscillator in three dimensions as our starting point. For the harmonic oscillator we know that
$$
\hat{h}_0(x_i)\psi_{\alpha}(x_i)=\varepsilon_{\alpha}\psi_{\alpha}(x_i),
$$
where the eigenvalues are $\varepsilon_{\alpha}$ and the eigenfunctions are $\psi_{\alpha}(x_i)$. The subscript $\alpha$ represents quantum numbers like the orbital angular momentum $l_{\alpha}$, its projection $m_{l_{\alpha}}$ and the
principal quantum number $n_{\alpha}=0,1,2,\dots$.
The eigenvalues are
$$
\varepsilon_{\alpha} = \hbar\omega \left(2n_{\alpha}+l_{\alpha}+\frac{3}{2}\right).
$$
## A modified Hamiltonian
The following mathematical properties of the harmonic oscillator are handy.
* First of all we have a complete basis of orthogonal eigenvectors. These have well-know expressions and can be easily be encoded.
* With a complete basis $\psi_{\alpha}(x_i)$, we can construct a new basis $\phi_{\tau}(x_i)$ by expanding in terms of a harmonic oscillator basis, that is
$$
\phi_{\tau}(x_i)=\sum_{\alpha} C_{\tau\alpha}\psi_{\alpha}(x_i),
$$
where $C_{\tau\alpha}$ represents the overlap between the two basis sets.
* As we will see later, the harmonic oscillator basis allows us to compute in an expedient way matrix elements of the interactions between two nucleons. Using the above expansion we can in turn represent nuclear forces in terms of new basis, for example the Woods-Saxon basis to be discussed later here.
## A modified Hamiltonian
The harmonic oscillator (a shifted one by a negative constant) provides also a very good approximation to most bound single-particle states. Furthermore, it serves as a starting point in building up our picture of nuclei, in particular how we define magic numbers and systems with one nucleon added to (or removed from) a closed-shell core nucleus. The figure here shows
the various harmonic oscillator states, with those obtained with a Woods-Saxon potential as well, including a spin-orbit splitting (to be discussed below).
## A modified Hamiltonian, harmonic oscillator spectrum
<!-- dom:FIGURE: [figslides/singleparticle.png, width=500 frac=0.6] Single-particle spectrum and quantum numbers for a harmonic oscillator potential and a Woods-Saxon potential with and without a spin-orbit force. -->
<!-- begin figure -->
<p>Single-particle spectrum and quantum numbers for a harmonic oscillator potential and a Woods-Saxon potential with and without a spin-orbit force.</p>
<!-- end figure -->
## The harmonic oscillator Hamiltonian
In nuclear physics the one-body part $u_{\mathrm{ext}}(x_i)$ is often
approximated by a harmonic oscillator potential. However, as we also noted with the Woods-Saxon potential there is no
external confining potential in nuclei.
What many people do then, is to add and subtract a harmonic oscillator potential,
with
$$
\hat{u}_{\mathrm{ext}}(x_i)=\hat{u}_{\mathrm{ho}}(x_i)= \frac{1}{2}m\omega^2 r_i^2,
$$
where $\omega$ is the oscillator frequency. This leads to
$$
\hat{H} = \hat{H_0} + \hat{H_I}
= \sum_{i=1}^A \hat{h}_0(x_i) + \sum_{i < j=1}^A \hat{v}(x_{ij})-\sum_{i=1}^A\hat{u}_{\mathrm{ho}}(x_i),
$$
with
$$
H_0=\sum_{i=1}^A \hat{h}_0(x_i) = \sum_{i=1}^A\left(\hat{t}(x_i) + \hat{u}_{\mathrm{ho}}(x_i)\right).
$$
Many practitioners use this as the standard Hamiltonian when doing nuclear structure calculations.
This is ok if the number of nucleons is large, but still with this Hamiltonian, we do not obey translational invariance. How can we cure this?
## Translationally Invariant Hamiltonian
In setting up a translationally invariant Hamiltonian
the following expressions are helpful.
The center-of-mass (CoM) momentum is
$$
P=\sum_{i=1}^A\boldsymbol{p}_i,
$$
and we have that
$$
\sum_{i=1}^A\boldsymbol{p}_i^2 =
\frac{1}{A}\left[\boldsymbol{P}^2+\sum_{i < j}(\boldsymbol{p}_i-\boldsymbol{p}_j)^2\right]
$$
meaning that
$$
\left[\sum_{i=1}^A\frac{\boldsymbol{p}_i^2}{2m} -\frac{\boldsymbol{P}^2}{2mA}\right]
=\frac{1}{2mA}\sum_{i < j}(\boldsymbol{p}_i-\boldsymbol{p}_j)^2.
$$
## The harmonic oscillator Hamiltonian
In a similar fashion we can define the CoM coordinate
$$
\boldsymbol{R}=\frac{1}{A}\sum_{i=1}^{A}\boldsymbol{r}_i,
$$
which yields
$$
\sum_{i=1}^A\boldsymbol{r}_i^2 =
\frac{1}{A}\left[A^2\boldsymbol{R}^2+\sum_{i < j}(\boldsymbol{r}_i-\boldsymbol{r}_j)^2\right].
$$
## The harmonic oscillator Hamiltonian
If we then introduce the harmonic oscillator one-body Hamiltonian
$$
H_0= \sum_{i=1}^A\left(\frac{\boldsymbol{p}_i^2}{2m}+
\frac{1}{2}m\omega^2\boldsymbol{r}_i^2\right),
$$
with $\omega$ the oscillator frequency,
we can rewrite the latter as
<!-- Equation labels as ordinary links -->
<div id="eq:obho"></div>
$$
H_{\mathrm{HO}}= \frac{\boldsymbol{P}^2}{2mA}+\frac{mA\omega^2\boldsymbol{R}^2}{2}
+\frac{1}{2mA}\sum_{i < j}(\boldsymbol{p}_i-\boldsymbol{p}_j)^2
+\frac{m\omega^2}{2A}\sum_{i < j}(\boldsymbol{r}_i-\boldsymbol{r}_j)^2.
\label{eq:obho} \tag{4}
$$
## The harmonic oscillator Hamiltonian
Alternatively, we could write it as
$$
H_{\mathrm{HO}}= H_{\mathrm{CoM}}+\frac{1}{2mA}\sum_{i < j}(\boldsymbol{p}_i-\boldsymbol{p}_j)^2
+\frac{m\omega^2}{2A}\sum_{i < j}(\boldsymbol{r}_i-\boldsymbol{r}_j)^2,
$$
The center-of-mass term is defined as
$$
H_{\mathrm{CoM}}= \frac{\boldsymbol{P}^2}{2mA}+\frac{mA\omega^2\boldsymbol{R}^2}{2}.
$$
## Translationally Invariant Hamiltonian
The translationally invariant one- and two-body Hamiltonian reads for an A-nucleon system,
<!-- Equation labels as ordinary links -->
<div id="eq:ham"></div>
$$
\label{eq:ham} \tag{5}
\hat{H}=\left[\sum_{i=1}^A\frac{\boldsymbol{p}_i^2}{2m} -\frac{\boldsymbol{P}^2}{2mA}\right] +\sum_{i < j}^A V_{ij} \; ,
$$
where $V_{ij}$ is the nucleon-nucleon interaction. Adding zero as here
$$
\sum_{i=1}^A\frac{1}{2}m\omega^2\boldsymbol{r}_i^2-
\frac{m\omega^2}{2A}\left[\boldsymbol{R}^2+\sum_{i < j}(\boldsymbol{r}_i-\boldsymbol{r}_j)^2\right]=0.
$$
we can then rewrite the Hamiltonian as
$$
\hat{H}=\sum_{i=1}^A \left[ \frac{\boldsymbol{p}_i^2}{2m}
+\frac{1}{2}m\omega^2 \boldsymbol{r}^2_i
\right] + \sum_{i < j}^A \left[ V_{ij}-\frac{m\omega^2}{2A}
(\boldsymbol{r}_i-\boldsymbol{r}_j)^2
\right]-H_{\mathrm{CoM}}.
$$
## The Woods-Saxon potential
The Woods-Saxon potential is a mean field potential for the nucleons (protons and neutrons)
inside an atomic nucleus. It represent an average potential that a given nucleon feels from the forces applied on each nucleon.
The parametrization is
$$
\hat{u}_{\mathrm{ext}}(r)=-\frac{V_0}{1+\exp{(r-R)/a}},
$$
with $V_0\approx 50$ MeV representing the potential well depth, $a\approx 0.5$ fm
length representing the "surface thickness" of the nucleus and $R=r_0A^{1/3}$, with $r_0=1.25$ fm and $A$ the number of nucleons.
The value for $r_0$ can be extracted from a fit to data, see for example [M. Kirson's article](http://www.sciencedirect.com/science/article/pii/S037594740600769X).
## The Woods-Saxon potential
The following python code produces a plot of the Woods-Saxon potential with the above parameters.
```
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import rc, rcParams
import matplotlib.units as units
import matplotlib.ticker as ticker
rc('text',usetex=True)
rc('font',**{'family':'serif','serif':['Woods-Saxon potential']})
font = {'family' : 'serif',
'color' : 'darkred',
'weight' : 'normal',
'size' : 16,
}
v0 = 50
A = 100
a = 0.5
r0 = 1.25
R = r0*A**(0.3333)
x = np.linspace(0.0, 10.0)
y = -v0/(1+np.exp((x-R)/a))
plt.plot(x, y, 'b-')
plt.title(r'{\bf Woods-Saxon potential}', fontsize=20)
plt.text(3, -40, r'Parameters: $A=20$, $V_0=50$ [MeV]', fontdict=font)
plt.text(3, -44, r'$a=0.5$ [fm], $r_0=1.25$ [fm]', fontdict=font)
plt.xlabel(r'$r$ [fm]',fontsize=20)
plt.ylabel(r'$V(r)$ [MeV]',fontsize=20)
# Tweak spacing to prevent clipping of ylabel
plt.subplots_adjust(left=0.15)
plt.savefig('woodsaxon.pdf', format='pdf')
```
From the plot we notice that the potential
* rapidly approaches zero as $r$ goes to infinity, reflecting the short-distance nature of the strong nuclear force.
* For large $A$, it is approximately flat in the center.
* Nucleons near the surface of the nucleus experience a large force towards the center.
## Single-particle Hamiltonians and spin-orbit force
We have introduced a single-particle Hamiltonian
$$
H_0=\sum_{i=1}^A \hat{h}_0(x_i) = \sum_{i=1}^A\left(\hat{t}(x_i) + \hat{u}_{\mathrm{ext}}(x_i)\right),
$$
with an external and central symmetric potential $u_{\mathrm{ext}}(x_i)$, which is often
approximated by a harmonic oscillator potential or a Woods-Saxon potential. Being central symmetric leads to a degeneracy
in energy which is not observed experimentally. We see this from for example our discussion of separation energies and magic numbers. There are, in addition to the assumed magic numbers from a harmonic oscillator basis of $2,8,20,40,70\dots$ magic numbers like $28$, $50$, $82$ and $126$.
To produce these additional numbers, we need to add a phenomenological spin-orbit force which lifts the degeneracy, that is
$$
\hat{h}(x_i) = \hat{t}(x_i) + \hat{u}_{\mathrm{ext}}(x_i) +\xi(\boldsymbol{r})\boldsymbol{ls}=\hat{h}_0(x_i)+\xi(\boldsymbol{r})\boldsymbol{ls}.
$$
## Single-particle Hamiltonians and spin-orbit force
We have introduced a modified single-particle Hamiltonian
$$
\hat{h}(x_i) = \hat{t}(x_i) + \hat{u}_{\mathrm{ext}}(x_i) +\xi(\boldsymbol{r})\boldsymbol{ls}=\hat{h}_0(x_i)+\xi(\boldsymbol{r})\boldsymbol{ls}.
$$
We can calculate the expectation value of the latter using the fact that
$$
\xi(\boldsymbol{r})\boldsymbol{ls}=\frac{1}{2}\xi(\boldsymbol{r})\left(\boldsymbol{j}^2-\boldsymbol{l}^2-\boldsymbol{s}^2\right).
$$
For a single-particle state with quantum numbers $nlj$ (we suppress $s$ and $m_j$), with $s=1/2$, we obtain the single-particle energies
$$
\varepsilon_{nlj} = \varepsilon_{nlj}^{(0)}+\Delta\varepsilon_{nlj},
$$
with $\varepsilon_{nlj}^{(0)}$ being the single-particle energy obtained with $\hat{h}_0(x)$ and
$$
\Delta\varepsilon_{nlj}=\frac{C}{2}\left(j(j+1)-l(l+1)-\frac{3}{4}\right).
$$
## Single-particle Hamiltonians and spin-orbit force
The spin-orbit force gives thus an additional contribution to the energy
$$
\Delta\varepsilon_{nlj}=\frac{C}{2}\left(j(j+1)-l(l+1)-\frac{3}{4}\right),
$$
which lifts the degeneracy we have seen before in the harmonic oscillator or Woods-Saxon potentials. The value $C$ is the radial
integral involving $\xi(\boldsymbol{r})$. Depending on the value of $j=l\pm 1/2$, we obtain
$$
\Delta\varepsilon_{nlj=l-1/2}=\frac{C}{2}l,
$$
or
$$
\Delta\varepsilon_{nlj=l+1/2}=-\frac{C}{2}(l+1),
$$
clearly lifting the degeneracy. Note well that till now we have simply postulated the spin-orbit force in *ad hoc* way.
Later, we will see how this term arises from the two-nucleon force in a natural way.
## Single-particle Hamiltonians and spin-orbit force
With the spin-orbit force, we can modify our Woods-Saxon potential to
$$
\hat{u}_{\mathrm{ext}}(r)=-\frac{V_0}{1+\exp{(r-R)/a}}+V_{so}(r)\boldsymbol{ls},
$$
with
$$
V_{so}(r) = V_{so}\frac{1}{r}\frac{d f_{so}(r)}{dr},
$$
where we have
$$
f_{so}(r) = \frac{1}{1+\exp{(r-R_{so})/a_{so}}}.
$$
<!-- !split ===== Single-particle Hamiltonians and spin-orbit force ===== -->
We can also add, in case of proton, a Coulomb potential. The
Woods-Saxon potential has been widely used in parametrizations of
effective single-particle potentials.
**However, as was the case with
the harmonic oscillator, none of these potentials are linked directly
to the nuclear forces**.
Our next step is to build a mean field based
on the nucleon-nucleon interaction. This will lead us to our first
and simplest many-body theory, Hartree-Fock theory.
## Single-particle Hamiltonians and spin-orbit force
The Woods-Saxon potential does not give us closed-form or analytical solutions of the eigenvalue problem
$$
\hat{h}_0(x_i)\psi_{\alpha}(x_i)=\varepsilon_{\alpha}\psi_{\alpha}(x_i).
$$
For the harmonic oscillator in three dimensions we have closed-form expressions for the energies and analytical solutions for the eigenstates,
with the latter given by either Hermite polynomials (cartesian coordinates) or Laguerre polynomials (spherical coordinates).
To solve the above equation is however rather straightforward numerically.
## Numerical solution of the single-particle Schroedinger equation
We will illustrate the numerical solution of Schroedinger's equation by solving it for the harmonic oscillator in three dimensions.
It is straightforward to change the harmonic oscillator potential with a Woods-Saxon potential, or any other type of potentials.
We are interested in the solution of the radial part of Schroedinger's equation for one nucleon.
The angular momentum part is given by the so-called Spherical harmonics.
The radial equation reads
$$
-\frac{\hbar^2}{2 m} \left ( \frac{1}{r^2} \frac{d}{dr} r^2
\frac{d}{dr} - \frac{l (l + 1)}{r^2} \right )R(r)
+ V(r) R(r) = E R(r).
$$
## Numerical solution of the single-particle Schroedinger equation
In our case $V(r)$ is the harmonic oscillator potential $(1/2)kr^2$ with
$k=m\omega^2$ and $E$ is
the energy of the harmonic oscillator in three dimensions.
The oscillator frequency is $\omega$ and the energies are
$$
E_{nl}= \hbar \omega \left(2n+l+\frac{3}{2}\right),
$$
with $n=0,1,2,\dots$ and $l=0,1,2,\dots$.
## Numerical solution of the single-particle Schroedinger equation
Since we have made a transformation to spherical coordinates it means that
$r\in [0,\infty)$.
The quantum number
$l$ is the orbital momentum of the nucleon. Then we substitute $R(r) = (1/r) u(r)$ and obtain
$$
-\frac{\hbar^2}{2 m} \frac{d^2}{dr^2} u(r)
+ \left ( V(r) + \frac{l (l + 1)}{r^2}\frac{\hbar^2}{2 m}
\right ) u(r) = E u(r) .
$$
The boundary conditions are $u(0)=0$ and $u(\infty)=0$.
## Numerical solution of the single-particle Schroedinger equation
We introduce a dimensionless variable $\rho = (1/\alpha) r$
where $\alpha$ is a constant with dimension length and get
$$
-\frac{\hbar^2}{2 m \alpha^2} \frac{d^2}{d\rho^2} u(\rho)
+ \left ( V(\rho) + \frac{l (l + 1)}{\rho^2}
\frac{\hbar^2}{2 m\alpha^2} \right ) u(\rho) = E u(\rho) .
$$
Let us specialize to $l=0$.
Inserting $V(\rho) = (1/2) k \alpha^2\rho^2$ we end up with
$$
-\frac{\hbar^2}{2 m \alpha^2} \frac{d^2}{d\rho^2} u(\rho)
+ \frac{k}{2} \alpha^2\rho^2u(\rho) = E u(\rho) .
$$
We multiply thereafter with $2m\alpha^2/\hbar^2$ on both sides and obtain
$$
-\frac{d^2}{d\rho^2} u(\rho)
+ \frac{mk}{\hbar^2} \alpha^4\rho^2u(\rho) = \frac{2m\alpha^2}{\hbar^2}E u(\rho) .
$$
## Numerical solution of the single-particle Schroedinger equation
We have thus
$$
-\frac{d^2}{d\rho^2} u(\rho)
+ \frac{mk}{\hbar^2} \alpha^4\rho^2u(\rho) = \frac{2m\alpha^2}{\hbar^2}E u(\rho) .
$$
The constant $\alpha$ can now be fixed
so that
$$
\frac{mk}{\hbar^2} \alpha^4 = 1,
$$
or
$$
\alpha = \left(\frac{\hbar^2}{mk}\right)^{1/4}.
$$
## Numerical solution of the single-particle Schroedinger equation
Defining
$$
\lambda = \frac{2m\alpha^2}{\hbar^2}E,
$$
we can rewrite Schroedinger's equation as
$$
-\frac{d^2}{d\rho^2} u(\rho) + \rho^2u(\rho) = \lambda u(\rho) .
$$
This is the first equation to solve numerically. In three dimensions
the eigenvalues for $l=0$ are
$\lambda_0=3,\lambda_1=7,\lambda_2=11,\dots .$
## Numerical solution of the single-particle Schroedinger equation
We use the standard
expression for the second derivative of a function $u$
<!-- Equation labels as ordinary links -->
<div id="eq:diffoperation"></div>
$$
\begin{equation}
u''=\frac{u(\rho+h) -2u(\rho) +u(\rho-h)}{h^2} +O(h^2),
\label{eq:diffoperation} \tag{6}
\end{equation}
$$
where $h$ is our step.
Next we define minimum and maximum values for the variable $\rho$,
$\rho_{\mathrm{min}}=0$ and $\rho_{\mathrm{max}}$, respectively.
You need to check your results for the energies against different values
$\rho_{\mathrm{max}}$, since we cannot set
$\rho_{\mathrm{max}}=\infty$.
## Numerical solution of the single-particle Schroedinger equation
With a given number of steps, $n_{\mathrm{step}}$, we then
define the step $h$ as
$$
h=\frac{\rho_{\mathrm{max}}-\rho_{\mathrm{min}} }{n_{\mathrm{step}}}.
$$
Define an arbitrary value of $\rho$ as
$$
\rho_i= \rho_{\mathrm{min}} + ih \hspace{1cm} i=0,1,2,\dots , n_{\mathrm{step}}
$$
we can rewrite the Schroedinger equation for $\rho_i$ as
$$
-\frac{u(\rho_i+h) -2u(\rho_i) +u(\rho_i-h)}{h^2}+\rho_i^2u(\rho_i) = \lambda u(\rho_i),
$$
or in a more compact way
$$
-\frac{u_{i+1} -2u_i +u_{i-1}}{h^2}+\rho_i^2u_i=-\frac{u_{i+1} -2u_i +u_{i-1} }{h^2}+V_iu_i = \lambda u_i.
$$
## Numerical solution of the single-particle Schroedinger equation
Define first the diagonal matrix element
$$
d_i=\frac{2}{h^2}+V_i,
$$
and the non-diagonal matrix element
$$
e_i=-\frac{1}{h^2}.
$$
In this case the non-diagonal matrix elements are given by a mere constant. *All non-diagonal matrix elements are equal*.
## Numerical solution of the single-particle Schroedinger equation
With these definitions the Schroedinger equation takes the following form
$$
d_iu_i+e_{i-1}u_{i-1}+e_{i+1}u_{i+1} = \lambda u_i,
$$
where $u_i$ is unknown. We can write the
latter equation as a matrix eigenvalue problem
<!-- Equation labels as ordinary links -->
<div id="eq:sematrix"></div>
$$
\begin{equation}
\left( \begin{array}{ccccccc} d_1 & e_1 & 0 & 0 & \dots &0 & 0 \\
e_1 & d_2 & e_2 & 0 & \dots &0 &0 \\
0 & e_2 & d_3 & e_3 &0 &\dots & 0\\
\dots & \dots & \dots & \dots &\dots &\dots & \dots\\
0 & \dots & \dots & \dots &\dots &d_{n_{\mathrm{step}}-2} & e_{n_{\mathrm{step}}-1}\\
0 & \dots & \dots & \dots &\dots &e_{n_{\mathrm{step}}-1} & d_{n_{\mathrm{step}}-1}
\end{array} \right) \left( \begin{array}{c} u_{1} \\
u_{2} \\
\dots\\ \dots\\ \dots\\
u_{n_{\mathrm{step}}-1}
\end{array} \right)=\lambda \left( \begin{array}{c} u_{1} \\
u_{2} \\
\dots\\ \dots\\ \dots\\
u_{n_{\mathrm{step}}-1}
\end{array} \right)
\label{eq:sematrix} \tag{7}
\end{equation}
$$
## Numerical solution of the single-particle Schroedinger equation
To be more detailed we have
<!-- Equation labels as ordinary links -->
<div id="eq:matrixse"></div>
$$
\begin{equation}
\left( \begin{array}{ccccccc} \frac{2}{h^2}+V_1 & -\frac{1}{h^2} & 0 & 0 & \dots &0 & 0 \\
-\frac{1}{h^2} & \frac{2}{h^2}+V_2 & -\frac{1}{h^2} & 0 & \dots &0 &0 \\
0 & -\frac{1}{h^2} & \frac{2}{h^2}+V_3 & -\frac{1}{h^2} &0 &\dots & 0\\
\dots & \dots & \dots & \dots &\dots &\dots & \dots\\
0 & \dots & \dots & \dots &\dots &\frac{2}{h^2}+V_{n_{\mathrm{step}}-2} & -\frac{1}{h^2}\\
0 & \dots & \dots & \dots &\dots &-\frac{1}{h^2} & \frac{2}{h^2}+V_{n_{\mathrm{step}}-1}
\end{array} \right)
\label{eq:matrixse} \tag{8}
\end{equation}
$$
Recall that the solutions are known via the boundary conditions at
$i=n_{\mathrm{step}}$ and at the other end point, that is for $\rho_0$.
The solution is zero in both cases.
## Program to solve Schroedinger's equation
The following python program is an example of how one can obtain the eigenvalues for a single-nucleon moving in a harmonic oscillator potential. It is rather easy to change the onebody-potential with ones like a Woods-Saxon potential.
* The c++ and Fortran versions of this program can be found at <https://github.com/NuclearStructure/PHY981/tree/master/doc/pub/spdata/programs>.
* The c++ program uses the c++ library armadillo, see <http://arma.sourceforge.net/>.
## Program to solve Schroedinger's equation
The code sets up the Hamiltonian matrix by defining the the minimun and maximum values of $r$ with a
maximum value of integration points. These are set in the initialization function. It plots the
eigenfunctions of the three lowest eigenstates.
```
#Program which solves the one-particle Schrodinger equation
#for a potential specified in function
#potential(). This example is for the harmonic oscillator in 3d
from matplotlib import pyplot as plt
import numpy as np
#Function for initialization of parameters
def initialize():
RMin = 0.0
RMax = 10.0
lOrbital = 0
Dim = 400
return RMin, RMax, lOrbital, Dim
# Here we set up the harmonic oscillator potential
def potential(r):
return r*r
#Get the boundary, orbital momentum and number of integration points
RMin, RMax, lOrbital, Dim = initialize()
#Initialize constants
Step = RMax/(Dim+1)
DiagConst = 2.0 / (Step*Step)
NondiagConst = -1.0 / (Step*Step)
OrbitalFactor = lOrbital * (lOrbital + 1.0)
#Calculate array of potential values
v = np.zeros(Dim)
r = np.linspace(RMin,RMax,Dim)
for i in xrange(Dim):
r[i] = RMin + (i+1) * Step;
v[i] = potential(r[i]) + OrbitalFactor/(r[i]*r[i]);
#Setting up tridiagonal matrix and find eigenvectors and eigenvalues
Hamiltonian = np.zeros((Dim,Dim))
Hamiltonian[0,0] = DiagConst + v[0];
Hamiltonian[0,1] = NondiagConst;
for i in xrange(1,Dim-1):
Hamiltonian[i,i-1] = NondiagConst;
Hamiltonian[i,i] = DiagConst + v[i];
Hamiltonian[i,i+1] = NondiagConst;
Hamiltonian[Dim-1,Dim-2] = NondiagConst;
Hamiltonian[Dim-1,Dim-1] = DiagConst + v[Dim-1];
# diagonalize and obtain eigenvalues, not necessarily sorted
EigValues, EigVectors = np.linalg.eig(Hamiltonian)
# sort eigenvectors and eigenvalues
permute = EigValues.argsort()
EigValues = EigValues[permute]
EigVectors = EigVectors[:,permute]
# now plot the results for the three lowest lying eigenstates
for i in xrange(3):
print EigValues[i]
FirstEigvector = EigVectors[:,0]
SecondEigvector = EigVectors[:,1]
ThirdEigvector = EigVectors[:,2]
plt.plot(r, FirstEigvector**2 ,'b-',r, SecondEigvector**2 ,'g-',r, ThirdEigvector**2 ,'r-')
plt.axis([0,4.6,0.0, 0.025])
plt.xlabel(r'$r$')
plt.ylabel(r'Radial probability $r^2|R(r)|^2$')
plt.title(r'Radial probability distributions for three lowest-lying states')
plt.savefig('eigenvector.pdf')
plt.savefig('eigenvector.png')
plt.show()
```
<!-- --- begin exercise --- -->
## Exercise 1: Masses and binding energies
The data on binding energies can be found in the file bedata.dat at the github address of the [course](https://github.com/NuclearStructure/PHY981/tree/master/doc/pub/spdata/programs)
**a)**
Write a small program which reads in the proton and neutron numbers and the binding energies
and make a plot of all neutron separation energies for the chain of oxygen (O), calcium (Ca), nickel (Ni), tin (Sn) and lead (Pb) isotopes, that is you need to plot
$$
S_n= BE(N,Z)-BE(N-1,Z).
$$
Comment your results.
**b)**
Include in the same figure(s) the liquid drop model results of Eq. (2.17) of Alex Brown's text, namely
$$
BE(N,Z)= \alpha_1A-\alpha_2A^{2/3}-\alpha_3\frac{Z^2}{A^{1/3}}-\alpha_4\frac{(N-Z)^2}{A},
$$
with $\alpha_1=15.49$ MeV, $\alpha_2=17.23$ MeV, $\alpha_3=0.697$ MeV and $\alpha_4=22.6$ MeV. Comment your results
**c)**
Make a plot of the binding energies as function of the number of nucleons $A$ using the data in the file on bindingenergies and the above liquid drop model. Make a figure similar to figure 2.5 of Alex Brown where you set the various parameters $\alpha_i=0$. Comment your results.
**d)**
Use the liquid drop model to find the neutron drip lines for Z values up to 120.
Analyze then the fluorine isotopes and find, where available the corresponding experimental data, and compare the liquid drop model predicition with experiment. Comment your results.
A program example in C++ and the input data file *bedata.dat* can be found found at the github repository for the [course](https://github.com/NuclearStructure/PHY981/tree/master/doc/pub/spdata/programs)
<!-- --- end exercise --- -->
<!-- --- begin exercise --- -->
## Exercise 2: Eigenstates and eigenvalues of single-particle problems
The program for finding the eigenvalues of the harmonic oscillator are in the github folder
<https://github.com/NuclearStructure/PHY981/tree/master/doc/pub/spdata/programs>.
You can use this program to solve the exercise below, or write your own using your preferred programming language, be it python, fortran or c++ or other languages. Here I will mainly provide fortran, python and c++.
**a)**
Compute the eigenvalues of the three lowest states with a given orbital momentum and oscillator frequency $\omega$. Study these results as functions of the the maximum value of $r$ and the number of integration points $n$, starting with $r_{\mathrm{max}}=10$. Compare the computed ones with the exact values and comment your results.
**b)**
Plot thereafter the eigenfunctions as functions of $r$ for the lowest-lying state with a given orbital momentum $l$.
**c)**
Replace thereafter the harmonic oscillator potential with a Woods-Saxon potential using the parameters discussed above. Compute the lowest five eigenvalues and plot the eigenfunction of the lowest-lying state. How does this compare with the harmonic oscillator? Comment your results and possible implications for nuclear physics studies.
<!-- --- end exercise --- -->
<!-- --- begin exercise --- -->
## Exercise 3: Operators and Slater determinants
Consider the Slater determinant
$$
\Phi_{\lambda}^{AS}(x_{1}x_{2}\dots x_{N};\alpha_{1}\alpha_{2}\dots\alpha_{N})
=\frac{1}{\sqrt{N!}}\sum_{p}(-)^{p}P\prod_{i=1}^{N}\psi_{\alpha_{i}}(x_{i}).
$$
where $P$ is an operator which permutes the coordinates of two particles. We have assumed here that the
number of particles is the same as the number of available single-particle states, represented by the
greek letters $\alpha_{1}\alpha_{2}\dots\alpha_{N}$.
**a)**
Write out $\Phi^{AS}$ for $N=3$.
**b)**
Show that
$$
\int dx_{1}dx_{2}\dots dx_{N}\left\vert
\Phi_{\lambda}^{AS}(x_{1}x_{2}\dots x_{N};\alpha_{1}\alpha_{2}\dots\alpha_{N})
\right\vert^{2} = 1.
$$
**c)**
Define a general onebody operator $\hat{F} = \sum_{i}^N\hat{f}(x_{i})$ and a general twobody operator $\hat{G}=\sum_{i>j}^N\hat{g}(x_{i},x_{j})$ with $g$ being invariant under the interchange of the coordinates of particles $i$ and $j$. Calculate the matrix elements for a two-particle Slater determinant
$$
\langle\Phi_{\alpha_{1}\alpha_{2}}^{AS}|\hat{F}|\Phi_{\alpha_{1}\alpha_{2}}^{AS}\rangle,
$$
and
$$
\langle\Phi_{\alpha_{1}\alpha_{2}}^{AS}|\hat{G}|\Phi_{\alpha_{1}\alpha_{2}}^{AS}\rangle.
$$
Explain the short-hand notation for the Slater determinant.
Which properties do you expect these operators to have in addition to an eventual permutation
symmetry?
<!-- --- end exercise --- -->
<!-- --- begin exercise --- -->
## Exercise 4: First simple shell-model calculation
We will now consider a simple three-level problem, depicted in the figure below. This is our first and very simple model of a possible many-nucleon (or just fermion) problem and the shell-model.
The single-particle states are labelled by the quantum number $p$ and can accomodate up to two single particles, viz., every single-particle state is doubly degenerate (you could think of this as one state having spin up and the other spin down).
We let the spacing between the doubly degenerate single-particle states be constant, with value $d$. The first state
has energy $d$. There are only three available single-particle states, $p=1$, $p=2$ and $p=3$, as illustrated
in the figure.
**a)**
How many two-particle Slater determinants can we construct in this space?
We limit ourselves to a system with only the two lowest single-particle orbits and two particles, $p=1$ and $p=2$. We assume that we can write the Hamiltonian as
$$
\hat{H}=\hat{H}_0+\hat{H}_I,
$$
and that the onebody part of the Hamiltonian with single-particle operator $\hat{h}_0$ has the property
$$
\hat{h}_0\psi_{p\sigma} = p\times d \psi_{p\sigma},
$$
where we have added a spin quantum number $\sigma$.
We assume also that the only two-particle states that can exist are those where two particles are in the
same state $p$, as shown by the two possibilities to the left in the figure.
The two-particle matrix elements of $\hat{H}_I$ have all a constant value, $-g$.
**b)**
Show then that the Hamiltonian matrix can be written as
$$
\left(\begin{array}{cc}2d-g &-g \\
-g &4d-g \end{array}\right),
$$
**c)**
Find the eigenvalues and eigenvectors. What is mixing of the state with two particles in $p=2$ to the wave function with two-particles in $p=1$? Discuss your results in terms of a linear combination of Slater determinants.
**d)**
Add the possibility that the two particles can be in the state with $p=3$ as well and find the Hamiltonian matrix, the eigenvalues and the eigenvectors. We still insist that we only have two-particle states composed of two particles being in the same level $p$. You can diagonalize numerically your $3\times 3$ matrix.
This simple model catches several birds with a stone. It demonstrates how we can build linear combinations
of Slater determinants and interpret these as different admixtures to a given state. It represents also the way we are going to interpret these contributions. The two-particle states above $p=1$ will be interpreted as
excitations from the ground state configuration, $p=1$ here. The reliability of this ansatz for the ground state,
with two particles in $p=1$,
depends on the strength of the interaction $g$ and the single-particle spacing $d$.
Finally, this model is a simple schematic ansatz for studies of pairing correlations and thereby superfluidity/superconductivity
in fermionic systems.
<!-- dom:FIGURE: [figslides/simplemodel.png, width=500 frac=0.6] Schematic plot of the possible single-particle levels with double degeneracy. The filled circles indicate occupied particle states. The spacing between each level $p$ is constant in this picture. We show some possible two-particle states. -->
<!-- begin figure -->
<p>Schematic plot of the possible single-particle levels with double degeneracy. The filled circles indicate occupied particle states. The spacing between each level $p$ is constant in this picture. We show some possible two-particle states.</p>
<!-- end figure -->
<!-- --- end exercise --- -->
|
lemma locally_connected_3: assumes "\<And>t x. \<lbrakk>openin (top_of_set S) t; x \<in> t\<rbrakk> \<Longrightarrow> openin (top_of_set S) (connected_component_set t x)" "openin (top_of_set S) v" "x \<in> v" shows "\<exists>u. openin (top_of_set S) u \<and> connected u \<and> x \<in> u \<and> u \<subseteq> v"
|
State Before: b x✝ y x : ℝ
⊢ logb b x⁻¹ = -logb b x State After: no goals Tactic: simp [logb, neg_div]
|
[STATEMENT]
lemma convergent_series_Cauchy:
fixes a::\<open>nat \<Rightarrow> real\<close> and \<phi>::\<open>nat \<Rightarrow> 'a::metric_space\<close>
assumes \<open>\<exists>M. \<forall>n. sum a {0..n} \<le> M\<close> and \<open>\<And>n. dist (\<phi> (Suc n)) (\<phi> n) \<le> a n\<close>
shows \<open>Cauchy \<phi>\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Cauchy \<phi>
[PROOF STEP]
text\<open>
Explanation: Let \<^term>\<open>a\<close> be a real-valued sequence and let \<^term>\<open>\<phi>\<close> be sequence in a metric space.
If the partial sums of \<^term>\<open>a\<close> are uniformly bounded and the distance between consecutive terms of \<^term>\<open>\<phi>\<close>
are bounded by the sequence \<^term>\<open>a\<close>, then \<^term>\<open>\<phi>\<close> is Cauchy.\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Cauchy \<phi>
[PROOF STEP]
proof (unfold Cauchy_altdef2, rule, rule)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>e. 0 < e \<Longrightarrow> \<exists>N. \<forall>n\<ge>N. dist (\<phi> n) (\<phi> N) < e
[PROOF STEP]
fix e::real
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>e. 0 < e \<Longrightarrow> \<exists>N. \<forall>n\<ge>N. dist (\<phi> n) (\<phi> N) < e
[PROOF STEP]
assume \<open>e > 0\<close>
[PROOF STATE]
proof (state)
this:
0 < e
goal (1 subgoal):
1. \<And>e. 0 < e \<Longrightarrow> \<exists>N. \<forall>n\<ge>N. dist (\<phi> n) (\<phi> N) < e
[PROOF STEP]
have \<open>\<And>k. a k \<ge> 0\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>k. 0 \<le> a k
[PROOF STEP]
using \<open>\<And>n. dist (\<phi> (Suc n)) (\<phi> n) \<le> a n\<close> dual_order.trans zero_le_dist
[PROOF STATE]
proof (prove)
using this:
dist (\<phi> (Suc ?n)) (\<phi> ?n) \<le> a ?n
\<lbrakk>?b \<le> ?a; ?c \<le> ?b\<rbrakk> \<Longrightarrow> ?c \<le> ?a
0 \<le> dist ?x ?y
goal (1 subgoal):
1. \<And>k. 0 \<le> a k
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
0 \<le> a ?k
goal (1 subgoal):
1. \<And>e. 0 < e \<Longrightarrow> \<exists>N. \<forall>n\<ge>N. dist (\<phi> n) (\<phi> N) < e
[PROOF STEP]
hence \<open>Cauchy (\<lambda>k. sum a {0..k})\<close>
[PROOF STATE]
proof (prove)
using this:
0 \<le> a ?k
goal (1 subgoal):
1. Cauchy (\<lambda>k. sum a {0..k})
[PROOF STEP]
using \<open>\<exists>M. \<forall>n. sum a {0..n} \<le> M\<close> sum_Cauchy_positive
[PROOF STATE]
proof (prove)
using this:
0 \<le> a ?k
\<exists>M. \<forall>n. sum a {0..n} \<le> M
\<lbrakk>\<And>n. 0 \<le> ?a n; \<exists>K. \<forall>n. sum ?a {0..n} \<le> K\<rbrakk> \<Longrightarrow> Cauchy (\<lambda>n. sum ?a {0..n})
goal (1 subgoal):
1. Cauchy (\<lambda>k. sum a {0..k})
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
Cauchy (\<lambda>k. sum a {0..k})
goal (1 subgoal):
1. \<And>e. 0 < e \<Longrightarrow> \<exists>N. \<forall>n\<ge>N. dist (\<phi> n) (\<phi> N) < e
[PROOF STEP]
hence \<open>\<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. dist (sum a {0..m}) (sum a {0..n}) < e\<close>
[PROOF STATE]
proof (prove)
using this:
Cauchy (\<lambda>k. sum a {0..k})
goal (1 subgoal):
1. \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. dist (sum a {0..m}) (sum a {0..n}) < e
[PROOF STEP]
unfolding Cauchy_def
[PROOF STATE]
proof (prove)
using this:
\<forall>e>0. \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. dist (sum a {0..m}) (sum a {0..n}) < e
goal (1 subgoal):
1. \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. dist (sum a {0..m}) (sum a {0..n}) < e
[PROOF STEP]
using \<open>e > 0\<close>
[PROOF STATE]
proof (prove)
using this:
\<forall>e>0. \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. dist (sum a {0..m}) (sum a {0..n}) < e
0 < e
goal (1 subgoal):
1. \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. dist (sum a {0..m}) (sum a {0..n}) < e
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
\<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. dist (sum a {0..m}) (sum a {0..n}) < e
goal (1 subgoal):
1. \<And>e. 0 < e \<Longrightarrow> \<exists>N. \<forall>n\<ge>N. dist (\<phi> n) (\<phi> N) < e
[PROOF STEP]
hence \<open>\<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. m > n \<longrightarrow> dist (sum a {0..m}) (sum a {0..n}) < e\<close>
[PROOF STATE]
proof (prove)
using this:
\<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. dist (sum a {0..m}) (sum a {0..n}) < e
goal (1 subgoal):
1. \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. n < m \<longrightarrow> dist (sum a {0..m}) (sum a {0..n}) < e
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
\<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. n < m \<longrightarrow> dist (sum a {0..m}) (sum a {0..n}) < e
goal (1 subgoal):
1. \<And>e. 0 < e \<Longrightarrow> \<exists>N. \<forall>n\<ge>N. dist (\<phi> n) (\<phi> N) < e
[PROOF STEP]
have \<open>dist (sum a {0..m}) (sum a {0..n}) = sum a {Suc n..m}\<close> if \<open>n<m\<close> for m n
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. dist (sum a {0..m}) (sum a {0..n}) = sum a {Suc n..m}
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. dist (sum a {0..m}) (sum a {0..n}) = sum a {Suc n..m}
[PROOF STEP]
have \<open>n < Suc n\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. n < Suc n
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
n < Suc n
goal (1 subgoal):
1. dist (sum a {0..m}) (sum a {0..n}) = sum a {Suc n..m}
[PROOF STEP]
have \<open>finite {0..n}\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. finite {0..n}
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
finite {0..n}
goal (1 subgoal):
1. dist (sum a {0..m}) (sum a {0..n}) = sum a {Suc n..m}
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
finite {0..n}
goal (1 subgoal):
1. dist (sum a {0..m}) (sum a {0..n}) = sum a {Suc n..m}
[PROOF STEP]
have \<open>finite {Suc n..m}\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. finite {Suc n..m}
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
finite {Suc n..m}
goal (1 subgoal):
1. dist (sum a {0..m}) (sum a {0..n}) = sum a {Suc n..m}
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
finite {Suc n..m}
goal (1 subgoal):
1. dist (sum a {0..m}) (sum a {0..n}) = sum a {Suc n..m}
[PROOF STEP]
have \<open>{0..n} \<union> {Suc n..m} = {0..m}\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. {0..n} \<union> {Suc n..m} = {0..m}
[PROOF STEP]
using \<open>n < Suc n\<close> \<open>n < m\<close>
[PROOF STATE]
proof (prove)
using this:
n < Suc n
n < m
goal (1 subgoal):
1. {0..n} \<union> {Suc n..m} = {0..m}
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
{0..n} \<union> {Suc n..m} = {0..m}
goal (1 subgoal):
1. dist (sum a {0..m}) (sum a {0..n}) = sum a {Suc n..m}
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
{0..n} \<union> {Suc n..m} = {0..m}
goal (1 subgoal):
1. dist (sum a {0..m}) (sum a {0..n}) = sum a {Suc n..m}
[PROOF STEP]
have \<open>{0..n} \<inter> {Suc n..m} = {}\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. {0..n} \<inter> {Suc n..m} = {}
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
{0..n} \<inter> {Suc n..m} = {}
goal (1 subgoal):
1. dist (sum a {0..m}) (sum a {0..n}) = sum a {Suc n..m}
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
finite {0..n}
finite {Suc n..m}
{0..n} \<union> {Suc n..m} = {0..m}
{0..n} \<inter> {Suc n..m} = {}
[PROOF STEP]
have sum_plus: \<open>(sum a {0..n}) + sum a {Suc n..m} = (sum a {0..m})\<close>
[PROOF STATE]
proof (prove)
using this:
finite {0..n}
finite {Suc n..m}
{0..n} \<union> {Suc n..m} = {0..m}
{0..n} \<inter> {Suc n..m} = {}
goal (1 subgoal):
1. sum a {0..n} + sum a {Suc n..m} = sum a {0..m}
[PROOF STEP]
by (metis sum.union_disjoint)
[PROOF STATE]
proof (state)
this:
sum a {0..n} + sum a {Suc n..m} = sum a {0..m}
goal (1 subgoal):
1. dist (sum a {0..m}) (sum a {0..n}) = sum a {Suc n..m}
[PROOF STEP]
have \<open>dist (sum a {0..m}) (sum a {0..n}) = \<bar>(sum a {0..m}) - (sum a {0..n})\<bar>\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. dist (sum a {0..m}) (sum a {0..n}) = \<bar>sum a {0..m} - sum a {0..n}\<bar>
[PROOF STEP]
using dist_real_def
[PROOF STATE]
proof (prove)
using this:
dist ?x ?y = \<bar>?x - ?y\<bar>
goal (1 subgoal):
1. dist (sum a {0..m}) (sum a {0..n}) = \<bar>sum a {0..m} - sum a {0..n}\<bar>
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
dist (sum a {0..m}) (sum a {0..n}) = \<bar>sum a {0..m} - sum a {0..n}\<bar>
goal (1 subgoal):
1. dist (sum a {0..m}) (sum a {0..n}) = sum a {Suc n..m}
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
dist (sum a {0..m}) (sum a {0..n}) = \<bar>sum a {0..m} - sum a {0..n}\<bar>
goal (1 subgoal):
1. dist (sum a {0..m}) (sum a {0..n}) = sum a {Suc n..m}
[PROOF STEP]
have \<open>(sum a {0..m}) - (sum a {0..n}) = sum a {Suc n..m}\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. sum a {0..m} - sum a {0..n} = sum a {Suc n..m}
[PROOF STEP]
using sum_plus
[PROOF STATE]
proof (prove)
using this:
sum a {0..n} + sum a {Suc n..m} = sum a {0..m}
goal (1 subgoal):
1. sum a {0..m} - sum a {0..n} = sum a {Suc n..m}
[PROOF STEP]
by linarith
[PROOF STATE]
proof (state)
this:
sum a {0..m} - sum a {0..n} = sum a {Suc n..m}
goal (1 subgoal):
1. dist (sum a {0..m}) (sum a {0..n}) = sum a {Suc n..m}
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
dist (sum a {0..m}) (sum a {0..n}) = \<bar>sum a {0..m} - sum a {0..n}\<bar>
sum a {0..m} - sum a {0..n} = sum a {Suc n..m}
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
dist (sum a {0..m}) (sum a {0..n}) = \<bar>sum a {0..m} - sum a {0..n}\<bar>
sum a {0..m} - sum a {0..n} = sum a {Suc n..m}
goal (1 subgoal):
1. dist (sum a {0..m}) (sum a {0..n}) = sum a {Suc n..m}
[PROOF STEP]
by (simp add: \<open>\<And>k. 0 \<le> a k\<close> sum_nonneg)
[PROOF STATE]
proof (state)
this:
dist (sum a {0..m}) (sum a {0..n}) = sum a {Suc n..m}
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
?n < ?m \<Longrightarrow> dist (sum a {0..?m}) (sum a {0..?n}) = sum a {Suc ?n..?m}
goal (1 subgoal):
1. \<And>e. 0 < e \<Longrightarrow> \<exists>N. \<forall>n\<ge>N. dist (\<phi> n) (\<phi> N) < e
[PROOF STEP]
hence sum_a: \<open>\<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. m > n \<longrightarrow> sum a {Suc n..m} < e\<close>
[PROOF STATE]
proof (prove)
using this:
?n < ?m \<Longrightarrow> dist (sum a {0..?m}) (sum a {0..?n}) = sum a {Suc ?n..?m}
goal (1 subgoal):
1. \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. n < m \<longrightarrow> sum a {Suc n..m} < e
[PROOF STEP]
by (metis \<open>\<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. dist (sum a {0..m}) (sum a {0..n}) < e\<close>)
[PROOF STATE]
proof (state)
this:
\<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. n < m \<longrightarrow> sum a {Suc n..m} < e
goal (1 subgoal):
1. \<And>e. 0 < e \<Longrightarrow> \<exists>N. \<forall>n\<ge>N. dist (\<phi> n) (\<phi> N) < e
[PROOF STEP]
obtain M where \<open>\<forall>m\<ge>M. \<forall>n\<ge>M. m > n \<longrightarrow> sum a {Suc n..m} < e\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>M. \<forall>m\<ge>M. \<forall>n\<ge>M. n < m \<longrightarrow> sum a {Suc n..m} < e \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
using sum_a \<open>e > 0\<close>
[PROOF STATE]
proof (prove)
using this:
\<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. n < m \<longrightarrow> sum a {Suc n..m} < e
0 < e
goal (1 subgoal):
1. (\<And>M. \<forall>m\<ge>M. \<forall>n\<ge>M. n < m \<longrightarrow> sum a {Suc n..m} < e \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
\<forall>m\<ge>M. \<forall>n\<ge>M. n < m \<longrightarrow> sum a {Suc n..m} < e
goal (1 subgoal):
1. \<And>e. 0 < e \<Longrightarrow> \<exists>N. \<forall>n\<ge>N. dist (\<phi> n) (\<phi> N) < e
[PROOF STEP]
hence \<open>\<forall>m. \<forall>n. Suc m \<ge> Suc M \<and> Suc n \<ge> Suc M \<and> Suc m > Suc n \<longrightarrow> sum a {Suc n..Suc m - 1} < e\<close>
[PROOF STATE]
proof (prove)
using this:
\<forall>m\<ge>M. \<forall>n\<ge>M. n < m \<longrightarrow> sum a {Suc n..m} < e
goal (1 subgoal):
1. \<forall>m n. Suc M \<le> Suc m \<and> Suc M \<le> Suc n \<and> Suc n < Suc m \<longrightarrow> sum a {Suc n..Suc m - 1} < e
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
\<forall>m n. Suc M \<le> Suc m \<and> Suc M \<le> Suc n \<and> Suc n < Suc m \<longrightarrow> sum a {Suc n..Suc m - 1} < e
goal (1 subgoal):
1. \<And>e. 0 < e \<Longrightarrow> \<exists>N. \<forall>n\<ge>N. dist (\<phi> n) (\<phi> N) < e
[PROOF STEP]
hence \<open>\<forall>m\<ge>1. \<forall>n\<ge>1. m \<ge> Suc M \<and> n \<ge> Suc M \<and> m > n \<longrightarrow> sum a {n..m - 1} < e\<close>
[PROOF STATE]
proof (prove)
using this:
\<forall>m n. Suc M \<le> Suc m \<and> Suc M \<le> Suc n \<and> Suc n < Suc m \<longrightarrow> sum a {Suc n..Suc m - 1} < e
goal (1 subgoal):
1. \<forall>m\<ge>1. \<forall>n\<ge>1. Suc M \<le> m \<and> Suc M \<le> n \<and> n < m \<longrightarrow> sum a {n..m - 1} < e
[PROOF STEP]
by (metis Suc_le_D)
[PROOF STATE]
proof (state)
this:
\<forall>m\<ge>1. \<forall>n\<ge>1. Suc M \<le> m \<and> Suc M \<le> n \<and> n < m \<longrightarrow> sum a {n..m - 1} < e
goal (1 subgoal):
1. \<And>e. 0 < e \<Longrightarrow> \<exists>N. \<forall>n\<ge>N. dist (\<phi> n) (\<phi> N) < e
[PROOF STEP]
hence sum_a2: \<open>\<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. m > n \<longrightarrow> sum a {n..m-1} < e\<close>
[PROOF STATE]
proof (prove)
using this:
\<forall>m\<ge>1. \<forall>n\<ge>1. Suc M \<le> m \<and> Suc M \<le> n \<and> n < m \<longrightarrow> sum a {n..m - 1} < e
goal (1 subgoal):
1. \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. n < m \<longrightarrow> sum a {n..m - 1} < e
[PROOF STEP]
by (meson add_leE)
[PROOF STATE]
proof (state)
this:
\<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. n < m \<longrightarrow> sum a {n..m - 1} < e
goal (1 subgoal):
1. \<And>e. 0 < e \<Longrightarrow> \<exists>N. \<forall>n\<ge>N. dist (\<phi> n) (\<phi> N) < e
[PROOF STEP]
have \<open>dist (\<phi> (n+p+1)) (\<phi> n) \<le> sum a {n..n+p}\<close> for p n :: nat
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. dist (\<phi> (n + p + 1)) (\<phi> n) \<le> sum a {n..n + p}
[PROOF STEP]
proof(induction p)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. dist (\<phi> (n + 0 + 1)) (\<phi> n) \<le> sum a {n..n + 0}
2. \<And>p. dist (\<phi> (n + p + 1)) (\<phi> n) \<le> sum a {n..n + p} \<Longrightarrow> dist (\<phi> (n + Suc p + 1)) (\<phi> n) \<le> sum a {n..n + Suc p}
[PROOF STEP]
case 0
[PROOF STATE]
proof (state)
this:
goal (2 subgoals):
1. dist (\<phi> (n + 0 + 1)) (\<phi> n) \<le> sum a {n..n + 0}
2. \<And>p. dist (\<phi> (n + p + 1)) (\<phi> n) \<le> sum a {n..n + p} \<Longrightarrow> dist (\<phi> (n + Suc p + 1)) (\<phi> n) \<le> sum a {n..n + Suc p}
[PROOF STEP]
thus ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. dist (\<phi> (n + 0 + 1)) (\<phi> n) \<le> sum a {n..n + 0}
[PROOF STEP]
by (simp add: assms(2))
[PROOF STATE]
proof (state)
this:
dist (\<phi> (n + 0 + 1)) (\<phi> n) \<le> sum a {n..n + 0}
goal (1 subgoal):
1. \<And>p. dist (\<phi> (n + p + 1)) (\<phi> n) \<le> sum a {n..n + p} \<Longrightarrow> dist (\<phi> (n + Suc p + 1)) (\<phi> n) \<le> sum a {n..n + Suc p}
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>p. dist (\<phi> (n + p + 1)) (\<phi> n) \<le> sum a {n..n + p} \<Longrightarrow> dist (\<phi> (n + Suc p + 1)) (\<phi> n) \<le> sum a {n..n + Suc p}
[PROOF STEP]
case (Suc p)
[PROOF STATE]
proof (state)
this:
dist (\<phi> (n + p + 1)) (\<phi> n) \<le> sum a {n..n + p}
goal (1 subgoal):
1. \<And>p. dist (\<phi> (n + p + 1)) (\<phi> n) \<le> sum a {n..n + p} \<Longrightarrow> dist (\<phi> (n + Suc p + 1)) (\<phi> n) \<le> sum a {n..n + Suc p}
[PROOF STEP]
thus ?case
[PROOF STATE]
proof (prove)
using this:
dist (\<phi> (n + p + 1)) (\<phi> n) \<le> sum a {n..n + p}
goal (1 subgoal):
1. dist (\<phi> (n + Suc p + 1)) (\<phi> n) \<le> sum a {n..n + Suc p}
[PROOF STEP]
by (smt Suc_eq_plus1 add_Suc_right add_less_same_cancel1 assms(2) dist_self dist_triangle2
gr_implies_not0 sum.cl_ivl_Suc)
[PROOF STATE]
proof (state)
this:
dist (\<phi> (n + Suc p + 1)) (\<phi> n) \<le> sum a {n..n + Suc p}
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
dist (\<phi> (?n + ?p + 1)) (\<phi> ?n) \<le> sum a {?n..?n + ?p}
goal (1 subgoal):
1. \<And>e. 0 < e \<Longrightarrow> \<exists>N. \<forall>n\<ge>N. dist (\<phi> n) (\<phi> N) < e
[PROOF STEP]
hence \<open>m > n \<Longrightarrow> dist (\<phi> m) (\<phi> n) \<le> sum a {n..m-1}\<close> for m n :: nat
[PROOF STATE]
proof (prove)
using this:
dist (\<phi> (?n + ?p + 1)) (\<phi> ?n) \<le> sum a {?n..?n + ?p}
goal (1 subgoal):
1. n < m \<Longrightarrow> dist (\<phi> m) (\<phi> n) \<le> sum a {n..m - 1}
[PROOF STEP]
by (metis Suc_eq_plus1 Suc_le_D diff_Suc_1 gr0_implies_Suc less_eq_Suc_le less_imp_Suc_add
zero_less_Suc)
[PROOF STATE]
proof (state)
this:
?n < ?m \<Longrightarrow> dist (\<phi> ?m) (\<phi> ?n) \<le> sum a {?n..?m - 1}
goal (1 subgoal):
1. \<And>e. 0 < e \<Longrightarrow> \<exists>N. \<forall>n\<ge>N. dist (\<phi> n) (\<phi> N) < e
[PROOF STEP]
hence \<open>\<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. m > n \<longrightarrow> dist (\<phi> m) (\<phi> n) < e\<close>
[PROOF STATE]
proof (prove)
using this:
?n < ?m \<Longrightarrow> dist (\<phi> ?m) (\<phi> ?n) \<le> sum a {?n..?m - 1}
goal (1 subgoal):
1. \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. n < m \<longrightarrow> dist (\<phi> m) (\<phi> n) < e
[PROOF STEP]
using sum_a2 \<open>e > 0\<close>
[PROOF STATE]
proof (prove)
using this:
?n < ?m \<Longrightarrow> dist (\<phi> ?m) (\<phi> ?n) \<le> sum a {?n..?m - 1}
\<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. n < m \<longrightarrow> sum a {n..m - 1} < e
0 < e
goal (1 subgoal):
1. \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. n < m \<longrightarrow> dist (\<phi> m) (\<phi> n) < e
[PROOF STEP]
by smt
[PROOF STATE]
proof (state)
this:
\<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. n < m \<longrightarrow> dist (\<phi> m) (\<phi> n) < e
goal (1 subgoal):
1. \<And>e. 0 < e \<Longrightarrow> \<exists>N. \<forall>n\<ge>N. dist (\<phi> n) (\<phi> N) < e
[PROOF STEP]
thus "\<exists>N. \<forall>n\<ge>N. dist (\<phi> n) (\<phi> N) < e"
[PROOF STATE]
proof (prove)
using this:
\<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. n < m \<longrightarrow> dist (\<phi> m) (\<phi> n) < e
goal (1 subgoal):
1. \<exists>N. \<forall>n\<ge>N. dist (\<phi> n) (\<phi> N) < e
[PROOF STEP]
using \<open>0 < e\<close>
[PROOF STATE]
proof (prove)
using this:
\<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. n < m \<longrightarrow> dist (\<phi> m) (\<phi> n) < e
0 < e
goal (1 subgoal):
1. \<exists>N. \<forall>n\<ge>N. dist (\<phi> n) (\<phi> N) < e
[PROOF STEP]
by fastforce
[PROOF STATE]
proof (state)
this:
\<exists>N. \<forall>n\<ge>N. dist (\<phi> n) (\<phi> N) < e
goal:
No subgoals!
[PROOF STEP]
qed
|
[STATEMENT]
lemma of_circline_of_ocircline_pos_oriented [simp]:
assumes "pos_oriented H"
shows "of_circline (of_ocircline H) = H"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. of_circline (of_ocircline H) = H
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
pos_oriented H
goal (1 subgoal):
1. of_circline (of_ocircline H) = H
[PROOF STEP]
by (transfer, transfer, simp, rule_tac x=1 in exI, simp)
|
## some comments
"test.machine.chouette.something" <- function()
{
## some other comment
func <- function(infile, csch, predmod)
{
impnode <- zoo.test(
infile = "$infile"
, dot = "$dotdot"
, csch = csch
)
obj <- waouh(
impnode, nono, trnode
, inputs = list(infile = infile)
, outputs = list(predmod = predmod)
)
## one
## comment
exjs <- epr(unclass(tojs(obj)))
exjs <- epr(tojs(obj))
exjs <- epr(obj)
}
env(func) <- asNamespace("namesp")
## last
bdf <- within(iris, { spec == "setosa" } )
bf <- tempfile("bf", fet = ".txt")
ds(bdf, btx, ow = TRUE)
}
|
theorem le_antisymm (a b : mynat) (hab : a ≤ b) (hba : b ≤ a) : a = b :=
begin
cases hab with c hc,
cases hba with d hd,
rw hd at hc,
symmetry at hc,
rw add_assoc at hc,
have s := eq_zero_of_add_right_eq_self hc,
have t := add_right_eq_zero s,
rw t at hd,
exact hd,
end
|
using CmdStan
using Test
ProjDir = dirname(@__FILE__)
cd(ProjDir) do
bernoulli = "
data {
int<lower=0> N;
int<lower=0,upper=1> y[N];
}
parameters {
real<lower=0,upper=1> theta;
}
model {
theta ~ beta(1,1);
y ~ bernoulli(theta);
}
"
data = [
Dict("N" => 10, "y" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1]),
Dict("N" => 10, "y" => [0, 1, 0, 0, 0, 0, 1, 0, 0, 1]),
Dict("N" => 10, "y" => [0, 0, 0, 0, 0, 0, 1, 0, 1, 1]),
Dict("N" => 10, "y" => [0, 0, 0, 1, 0, 0, 0, 1, 0, 1])
]
m = Stanmodel(Optimize(), name="bernoulli", model=bernoulli);
m.command[1] = CmdStan.cmdline(m)
println()
show(IOContext(stdout, :compact => true), m)
println()
show(m)
@assert m.output.refresh == 100
s1 = Sample()
println()
show(IOContext(stdout, :compact => true), s1)
println()
show(s1)
n1 = CmdStan.Lbfgs()
n2 = CmdStan.Lbfgs(history_size=15)
@assert 3*n1.history_size == n2.history_size
b1 = CmdStan.Bfgs()
b2 = CmdStan.Bfgs(tol_obj=1//100000000)
@assert b1.tol_obj == b2.tol_obj
o1 = Optimize()
o2 = Optimize(CmdStan.Newton())
o3 = Optimize(CmdStan.Lbfgs(history_size=10))
o4 = Optimize(CmdStan.Bfgs(tol_obj=1e-9))
o5 = Optimize(method=CmdStan.Bfgs(tol_obj=1e-9), save_iterations=true)
@assert o5.method.tol_obj == o1.method.tol_obj/10
println()
show(IOContext(stdout, :compact => true), o5)
println()
show(o5)
d1 = Diagnose()
@assert d1.diagnostic.error == 1e-6
d2 = Diagnose(CmdStan.Gradient(error=1e-7))
@assert d2.diagnostic.error == 1e-7
println()
show(IOContext(stdout, :compact => true), d2)
println()
show(d2)
println()
m.command
cd(ProjDir)
isdir("tmp") &&
rm("tmp", recursive=true);
end # cd
|
{-# OPTIONS --without-K #-}
module function.extensionality.proof where
open import level
open import sum
open import equality
open import function.extensionality.core
open import hott.univalence
open import hott.level.core
open import hott.level.closure.core
open import hott.equivalence.core
open import sets.unit
top : ∀ {i} → Set i
top = ↑ _ ⊤
⊤-contr' : ∀ {i} → contr (↑ i ⊤)
⊤-contr' {i} = lift tt , λ { (lift tt) → refl }
-- this uses definitional η for ⊤
contr-exp-⊤ : ∀ {i j}{A : Set i} → contr (A → top {j})
contr-exp-⊤ = (λ _ → lift tt) , (λ f → refl)
module Weak where
→-contr : ∀ {i j}{A : Set i}{B : Set j}
→ contr B
→ contr (A → B)
→-contr {A = A}{B = B} hB = subst contr p contr-exp-⊤
where
p : (A → top) ≡ (A → B)
p = ap (λ X → A → X) (unique-contr ⊤-contr' hB)
funext : ∀ {i j}{A : Set i}{B : Set j}
→ (f : A → B)(b : B)(h : (x : A) → b ≡ f x)
→ (λ _ → b) ≡ f
funext f b h =
ap (λ u x → proj₁ (u x))
(contr⇒prop (→-contr (singl-contr b))
(λ _ → (b , refl))
(λ x → f x , h x))
abstract
Π-contr : ∀ {i j}{A : Set i}{B : A → Set j}
→ ((x : A) → contr (B x))
→ contr ((x : A) → B x)
Π-contr {i}{j}{A}{B} hB = subst contr p contr-exp-⊤
where
p₀ : (λ _ → top) ≡ B
p₀ = Weak.funext B top (λ x → unique-contr ⊤-contr' (hB x))
p : (A → top {j}) ≡ ((x : A) → B x)
p = ap (λ Z → (x : A) → Z x) p₀
private
funext₀ : ∀ {i j} → Extensionality' i j
funext₀ {i}{j}{X = X}{Y = Y}{f = f}{g = g} h = ap (λ u x → proj₁ (u x)) lem
where
C : X → Set j
C x = Σ (Y x) λ y → f x ≡ y
f' g' : (x : X) → C x
f' x = (f x , refl)
g' x = (g x , h x)
lem : f' ≡ g'
lem = contr⇒prop (Π-contr (λ x → singl-contr (f x))) f' g'
abstract
funext : ∀ {i j} → Extensionality' i j
funext h = funext₀ h · sym (funext₀ (λ _ → refl))
funext-id : ∀ {i j}{X : Set i}{Y : X → Set j}
→ (f : (x : X) → Y x)
→ funext (λ x → refl {x = f x}) ≡ refl
funext-id _ = left-inverse (funext₀ (λ _ → refl))
|
const tolerance_deg = 0.00001
"""
normalize(value::Float64[, lower::Float64 = 0.0, upper::Float64 = 360.0])
Normalize a `value` to stay within the `lower` and `upper` limit.
Example:
normalize(370.0, lower=0.0, upper=360.0)
10.0
"""
function normalize(value::Float64, lower::Float64 = 0.0, upper::Float64 = 360.0)
result = value
if result > upper || value == lower
value = lower + abs(value + upper) % (abs(lower) + abs(upper))
end
if result < lower || value == upper
value = upper - abs(value - lower) % (abs(lower) + abs(upper))
end
value == upper ? result = lower : result = value
return result
end
"""
normalize(point::Point)
Normalize the point to keep the longitude between -180 and 180 degrees and the
latitude between -90 and 90.
Source: gist.github.com/missinglink/ > wrap.js
"""
function normalize(point::Point)
ϕ, λ = _normalize(point.ϕ, point.λ)
return Point(ϕ, λ)
end
function _normalize(pointϕ::Float64, pointλ::Float64)
ϕ = pointϕ
λ = pointλ
quadrant = floor(Int64, abs(ϕ)/90) % 4
pole = ϕ > 0 ? 90.0 : -90.0
offset = ϕ % 90.0
if quadrant == 0
ϕ = offset
elseif quadrant == 1
ϕ = pole - offset
λ += 180.0
elseif quadrant == 2
ϕ = -offset
λ += 180.0
elseif quadrant == 3
ϕ = - pole + offset
end
if λ > 180.0 || λ < -180.0
λ -= floor((λ + 180.0) / 360) * 360
end
return ϕ, λ
end
|
\ getuid.f - get user id of current process
\ ------------------------------------------------------------------------
<headers
\ ------------------------------------------------------------------------
0 201 syscall <getuid32>
0 49 syscall <getuid>
\ ------------------------------------------------------------------------
headers>
: getuid ( --- uid | -1 )
<getuid32>
dup -1 <> ?exit
drop <getuid> ;
\ ------------------------------------------------------------------------
behead
\ ========================================================================
|
c Subroutine to correct record number if information available
c AJ_Kettle, 26Nov2019
SUBROUTINE fix_record_number(l_rgh_lines,l_lines,
+ i_vec_snow_qcmod_flag,i_cnt_recordnum,s_mat_recordnum,
+ s_vec_snow_recordnum)
IMPLICIT NONE
c************************************************************************
c Variables passed into subroutine
INTEGER :: l_rgh_lines
INTEGER :: l_lines
INTEGER :: i_vec_snow_qcmod_flag(l_rgh_lines)
INTEGER :: i_cnt_recordnum(l_rgh_lines)
CHARACTER(*) :: s_mat_recordnum(l_rgh_lines,6) !len=2
CHARACTER(*) :: s_vec_snow_recordnum(l_rgh_lines)
c*****
c Variables used in subroutine
INTEGER :: i,j,k,ii,jj,kk
INTEGER :: i_qcmod_new
CHARACTER(LEN=2) :: s_recordnum_new
c************************************************************************
DO i=1,l_lines
IF (i_vec_snow_qcmod_flag(i).GT.0) THEN
c No solution possible
IF (i_cnt_recordnum(i).EQ.0) THEN
i_qcmod_new=2 !assign flag for no solution
s_recordnum_new='' !no record number possible
ENDIF
c Workaround solution
IF (i_cnt_recordnum(i).GT.0) THEN
i_qcmod_new=1 !assign flag for workaround solution
s_recordnum_new=s_mat_recordnum(i,1) !first record number
ENDIF
i_vec_snow_qcmod_flag(i)=i_qcmod_new
s_vec_snow_recordnum(i) =s_recordnum_new
c print*,'i_cnt_recordnum=',i_cnt_recordnum(i)
c print*,'s_mat_recordnum=',
c + (s_mat_recordnum(i,ii),ii=1,i_cnt_recordnum(i))
c print*,'s_mat_variableid=',
c + (s_mat_variableid(i,ii),ii=1,i_cnt_recordnum(i))
c print*,'i_qcmod_new=',i_qcmod_new
c print*,'s_recordnum_new=',s_recordnum_new
ENDIF
ENDDO
RETURN
END
|
using Flux, LinearAlgebra, Polynomials, Plots
const n = 100
# target polynomial
c = ChebyshevT([-1,0,-2,0,1,0,1,2,3])
target = convert(Polynomial, c)
plot(target, (-1.,1.)...,label="target")
length(target.coeffs)
# mapping polynomial to circulant matrix
S = circshift(Matrix{Float64}(I, n, n),(1,0))
param = zeros(n)
param[1:9] = target.coeffs
Circulant = param
for k in 1:n-1
Circulant = hcat(Circulant, S^k*param)
end
# creating dataset
bs = 3000
x = randn(Float32,n,1,bs)
y = convert(Array{Float32},reshape(transpose(Circulant)*dropdims(x;dims=2) ,(n,1,bs)))
data = [(x,y)]
# padding function to work modulo n
function pad_cycl(x;l=1,r=1)
last = size(x,1)
xl = selectdim(x,1,last-l+1:last)
xr = selectdim(x,1,1:r)
cat(xl, x, xr, dims=1)
end
# neural network with 7 convolution layers
model = Chain(
x -> pad_cycl(x,l=0,r=2),
CrossCor((3,),1=>1,bias=Flux.Zeros()),
x -> pad_cycl(x,l=0,r=2),
CrossCor((3,),1=>1,bias=Flux.Zeros()),
x -> pad_cycl(x,l=0,r=2),
CrossCor((3,),1=>1,bias=Flux.Zeros()),
x -> pad_cycl(x,l=0,r=2),
CrossCor((3,),1=>1,bias=Flux.Zeros()),
x -> pad_cycl(x,l=0,r=2),
CrossCor((3,),1=>1,bias=Flux.Zeros()),
x -> pad_cycl(x,l=0,r=2),
CrossCor((3,),1=>1,bias=Flux.Zeros()),
x -> pad_cycl(x,l=0,r=2),
CrossCor((3,),1=>1,bias=Flux.Zeros())
)
loss(x, y) = Flux.Losses.mse(model(x), y)
ps = Flux.params(model)
loss_vector = Vector{Float32}()
logging_loss() = push!(loss_vector, loss(x, y))
opt = ADAM(0.2)
n_epochs = 1700
for epochs in 1:n_epochs
Flux.train!(loss, ps, data, opt, cb=logging_loss)
if epochs % 50 == 0
println("Epoch: ", epochs, " | Loss: ", loss(x,y))
end
end
plot(loss_vector)
pred = Polynomial([1])
for p in ps
if typeof(p) <: Array
pred *= Polynomial([p...])
end
end
plot(target, (-1.,1.)...,label="target")
ylims!((-10,10))
plot!(pred, (-1.,1.)...,label="pred")
|
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
p : α → Prop
x y z : α
h : x = y
f : Perm α
⊢ SameCycle f x y
[PROOFSTEP]
rw [h]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x y z : α
x✝ : SameCycle f x y
i : ℤ
hi : ↑(f ^ i) x = y
⊢ ↑(f ^ (-i)) y = x
[PROOFSTEP]
rw [zpow_neg, ← hi, inv_apply_self]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x y z : α
x✝¹ : SameCycle f x y
x✝ : SameCycle f y z
i : ℤ
hi : ↑(f ^ i) x = y
j : ℤ
hj : ↑(f ^ j) y = z
⊢ ↑(f ^ (j + i)) x = z
[PROOFSTEP]
rw [zpow_add, mul_apply, hi, hj]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x y z : α
⊢ SameCycle 1 x y ↔ x = y
[PROOFSTEP]
simp [SameCycle]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x y z : α
⊢ (∃ b, ↑(f⁻¹ ^ ↑(Equiv.neg ℤ).symm b) x = y) ↔ SameCycle f x y
[PROOFSTEP]
simp [SameCycle]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x y z : α
i : ℤ
⊢ ↑((g * f * g⁻¹) ^ i) x = y ↔ ↑(f ^ i) (↑g⁻¹ x) = ↑g⁻¹ y
[PROOFSTEP]
simp [conj_zpow, eq_inv_iff_eq]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x y z : α
⊢ SameCycle f x y → SameCycle (g * f * g⁻¹) (↑g x) (↑g y)
[PROOFSTEP]
simp [sameCycle_conj]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x y z : α
x✝ : SameCycle f x y
i : ℤ
hi : ↑(f ^ i) x = y
⊢ ↑f x = x ↔ ↑f y = y
[PROOFSTEP]
rw [← hi, ← mul_apply, ← zpow_one_add, add_comm, zpow_add_one, mul_apply, (f ^ i).injective.eq_iff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x y z : α
⊢ (∃ b, ↑(f ^ ↑(Equiv.addRight 1).symm b) (↑f x) = y) ↔ SameCycle f x y
[PROOFSTEP]
simp [zpow_sub, SameCycle, Int.add_neg_one, Function.comp]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x y z : α
⊢ SameCycle f x (↑f y) ↔ SameCycle f x y
[PROOFSTEP]
rw [sameCycle_comm, sameCycle_apply_left, sameCycle_comm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x y z : α
⊢ SameCycle f (↑f⁻¹ x) y ↔ SameCycle f x y
[PROOFSTEP]
rw [← sameCycle_apply_left, apply_inv_self]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x y z : α
⊢ SameCycle f x (↑f⁻¹ y) ↔ SameCycle f x y
[PROOFSTEP]
rw [← sameCycle_apply_right, apply_inv_self]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x y z : α
n : ℤ
⊢ (∃ b, ↑(f ^ ↑(Equiv.addRight n).symm b) (↑(f ^ n) x) = y) ↔ SameCycle f x y
[PROOFSTEP]
simp [SameCycle, zpow_add]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x y z : α
n : ℤ
⊢ SameCycle f x (↑(f ^ n) y) ↔ SameCycle f x y
[PROOFSTEP]
rw [sameCycle_comm, sameCycle_zpow_left, sameCycle_comm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x y z : α
n : ℕ
⊢ SameCycle f (↑(f ^ n) x) y ↔ SameCycle f x y
[PROOFSTEP]
rw [← zpow_ofNat, sameCycle_zpow_left]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x y z : α
n : ℕ
⊢ SameCycle f x (↑(f ^ n) y) ↔ SameCycle f x y
[PROOFSTEP]
rw [← zpow_ofNat, sameCycle_zpow_right]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x y z : α
n : ℕ
x✝ : SameCycle (f ^ n) x y
m : ℤ
h : ↑((f ^ n) ^ m) x = y
⊢ ↑(f ^ (↑n * m)) x = y
[PROOFSTEP]
simp [zpow_mul, h]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x y z : α
n : ℤ
x✝ : SameCycle (f ^ n) x y
m : ℤ
h : ↑((f ^ n) ^ m) x = y
⊢ ↑(f ^ (n * m)) x = y
[PROOFSTEP]
simp [zpow_mul, h]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x✝ y✝ z : α
h : ∀ (x : α), p x ↔ p (↑f x)
x y : { x // p x }
n : ℤ
⊢ ↑(subtypePerm f h ^ n) x = y ↔ ↑(f ^ n) ↑x = ↑y
[PROOFSTEP]
simp [Subtype.ext_iff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
p✝ : α → Prop
x y z : α
p : β → Prop
inst✝ : DecidablePred p
f : α ≃ Subtype p
n : ℤ
⊢ ↑(extendDomain g f ^ n) ↑(↑f x) = ↑(↑f y) ↔ ↑(g ^ n) x = y
[PROOFSTEP]
rw [← extendDomain_zpow, extendDomain_apply_image, Subtype.coe_inj, f.injective.eq_iff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x y z : α
inst✝ : Finite α
⊢ SameCycle f x y → ∃ i, i < orderOf f ∧ ↑(f ^ i) x = y
[PROOFSTEP]
classical
rintro ⟨k, rfl⟩
use(k % orderOf f).natAbs
have h₀ := Int.coe_nat_pos.mpr (orderOf_pos f)
have h₁ := Int.emod_nonneg k h₀.ne'
rw [← zpow_ofNat, Int.natAbs_of_nonneg h₁, ← zpow_eq_mod_orderOf]
refine' ⟨_, by rfl⟩
rw [← Int.ofNat_lt, Int.natAbs_of_nonneg h₁]
exact Int.emod_lt_of_pos _ h₀
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x y z : α
inst✝ : Finite α
⊢ SameCycle f x y → ∃ i, i < orderOf f ∧ ↑(f ^ i) x = y
[PROOFSTEP]
rintro ⟨k, rfl⟩
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x z : α
inst✝ : Finite α
k : ℤ
⊢ ∃ i, i < orderOf f ∧ ↑(f ^ i) x = ↑(f ^ k) x
[PROOFSTEP]
use(k % orderOf f).natAbs
[GOAL]
case h
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x z : α
inst✝ : Finite α
k : ℤ
⊢ Int.natAbs (k % ↑(orderOf f)) < orderOf f ∧ ↑(f ^ Int.natAbs (k % ↑(orderOf f))) x = ↑(f ^ k) x
[PROOFSTEP]
have h₀ := Int.coe_nat_pos.mpr (orderOf_pos f)
[GOAL]
case h
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x z : α
inst✝ : Finite α
k : ℤ
h₀ : 0 < ↑(orderOf f)
⊢ Int.natAbs (k % ↑(orderOf f)) < orderOf f ∧ ↑(f ^ Int.natAbs (k % ↑(orderOf f))) x = ↑(f ^ k) x
[PROOFSTEP]
have h₁ := Int.emod_nonneg k h₀.ne'
[GOAL]
case h
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x z : α
inst✝ : Finite α
k : ℤ
h₀ : 0 < ↑(orderOf f)
h₁ : 0 ≤ k % ↑(orderOf f)
⊢ Int.natAbs (k % ↑(orderOf f)) < orderOf f ∧ ↑(f ^ Int.natAbs (k % ↑(orderOf f))) x = ↑(f ^ k) x
[PROOFSTEP]
rw [← zpow_ofNat, Int.natAbs_of_nonneg h₁, ← zpow_eq_mod_orderOf]
[GOAL]
case h
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x z : α
inst✝ : Finite α
k : ℤ
h₀ : 0 < ↑(orderOf f)
h₁ : 0 ≤ k % ↑(orderOf f)
⊢ Int.natAbs (k % ↑(orderOf f)) < orderOf f ∧ ↑(f ^ k) x = ↑(f ^ k) x
[PROOFSTEP]
refine' ⟨_, by rfl⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x z : α
inst✝ : Finite α
k : ℤ
h₀ : 0 < ↑(orderOf f)
h₁ : 0 ≤ k % ↑(orderOf f)
⊢ ↑(f ^ k) x = ↑(f ^ k) x
[PROOFSTEP]
rfl
[GOAL]
case h
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x z : α
inst✝ : Finite α
k : ℤ
h₀ : 0 < ↑(orderOf f)
h₁ : 0 ≤ k % ↑(orderOf f)
⊢ Int.natAbs (k % ↑(orderOf f)) < orderOf f
[PROOFSTEP]
rw [← Int.ofNat_lt, Int.natAbs_of_nonneg h₁]
[GOAL]
case h
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x z : α
inst✝ : Finite α
k : ℤ
h₀ : 0 < ↑(orderOf f)
h₁ : 0 ≤ k % ↑(orderOf f)
⊢ k % ↑(orderOf f) < ↑(orderOf f)
[PROOFSTEP]
exact Int.emod_lt_of_pos _ h₀
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x y z : α
inst✝ : Finite α
h : SameCycle f x y
⊢ ∃ i x_1 x_2, ↑(f ^ i) x = y
[PROOFSTEP]
classical
obtain ⟨_ | i, hi, rfl⟩ := h.exists_pow_eq'
· refine' ⟨orderOf f, orderOf_pos f, le_rfl, _⟩
rw [pow_orderOf_eq_one, pow_zero]
· exact ⟨i.succ, i.zero_lt_succ, hi.le, by rfl⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x y z : α
inst✝ : Finite α
h : SameCycle f x y
⊢ ∃ i x_1 x_2, ↑(f ^ i) x = y
[PROOFSTEP]
obtain ⟨_ | i, hi, rfl⟩ := h.exists_pow_eq'
[GOAL]
case intro.zero.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x z : α
inst✝ : Finite α
hi : Nat.zero < orderOf f
h : SameCycle f x (↑(f ^ Nat.zero) x)
⊢ ∃ i x_1 x_2, ↑(f ^ i) x = ↑(f ^ Nat.zero) x
[PROOFSTEP]
refine' ⟨orderOf f, orderOf_pos f, le_rfl, _⟩
[GOAL]
case intro.zero.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x z : α
inst✝ : Finite α
hi : Nat.zero < orderOf f
h : SameCycle f x (↑(f ^ Nat.zero) x)
⊢ ↑(f ^ orderOf f) x = ↑(f ^ Nat.zero) x
[PROOFSTEP]
rw [pow_orderOf_eq_one, pow_zero]
[GOAL]
case intro.succ.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x z : α
inst✝ : Finite α
i : ℕ
hi : Nat.succ i < orderOf f
h : SameCycle f x (↑(f ^ Nat.succ i) x)
⊢ ∃ i_1 x_1 x_2, ↑(f ^ i_1) x = ↑(f ^ Nat.succ i) x
[PROOFSTEP]
exact ⟨i.succ, i.zero_lt_succ, hi.le, by rfl⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
p : α → Prop
x z : α
inst✝ : Finite α
i : ℕ
hi : Nat.succ i < orderOf f
h : SameCycle f x (↑(f ^ Nat.succ i) x)
⊢ ↑(f ^ Nat.succ i) x = ↑(f ^ Nat.succ i) x
[PROOFSTEP]
rfl
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
p : α → Prop
x✝¹ y✝ z : α
inst✝¹ : Fintype α
inst✝ : DecidableEq α
f : Perm α
x y : α
x✝ : SameCycle f x y
i : ℤ
hi : ↑(f ^ i) x = y
⊢ ↑(Int.natAbs (i % ↑(orderOf f))) < ↑(Fintype.card (Perm α))
[PROOFSTEP]
rw [Int.natAbs_of_nonneg (Int.emod_nonneg _ <| Int.coe_nat_ne_zero.2 (orderOf_pos _).ne')]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
p : α → Prop
x✝¹ y✝ z : α
inst✝¹ : Fintype α
inst✝ : DecidableEq α
f : Perm α
x y : α
x✝ : SameCycle f x y
i : ℤ
hi : ↑(f ^ i) x = y
⊢ i % ↑(orderOf f) < ↑(Fintype.card (Perm α))
[PROOFSTEP]
refine' (Int.emod_lt _ <| Int.coe_nat_ne_zero_iff_pos.2 <| orderOf_pos _).trans_le _
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
p : α → Prop
x✝¹ y✝ z : α
inst✝¹ : Fintype α
inst✝ : DecidableEq α
f : Perm α
x y : α
x✝ : SameCycle f x y
i : ℤ
hi : ↑(f ^ i) x = y
⊢ |↑(orderOf f)| ≤ ↑(Fintype.card (Perm α))
[PROOFSTEP]
simp [orderOf_le_card_univ]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
p : α → Prop
x✝¹ y✝ z : α
inst✝¹ : Fintype α
inst✝ : DecidableEq α
f : Perm α
x y : α
x✝ : SameCycle f x y
i : ℤ
hi : ↑(f ^ i) x = y
⊢ ↑(f ^ Int.natAbs (i % ↑(orderOf f))) x = y
[PROOFSTEP]
rw [← zpow_ofNat, Int.natAbs_of_nonneg (Int.emod_nonneg _ <| Int.coe_nat_ne_zero_iff_pos.2 <| orderOf_pos _), ←
zpow_eq_mod_orderOf, hi]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
h : IsCycle f
hf : f = 1
⊢ False
[PROOFSTEP]
simp [hf, IsCycle] at h
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g✝ : Perm α
x y : α
hf : IsCycle f
hx : ↑f x ≠ x
hy : ↑f y ≠ y
g : α
hg : ↑f g ≠ g ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f g y
a : ℤ
ha : ↑(f ^ a) g = x
b : ℤ
hb : ↑(f ^ b) g = y
⊢ ↑(f ^ (b - a)) x = y
[PROOFSTEP]
rw [← ha, ← mul_apply, ← zpow_add, sub_add_cancel, hb]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
⊢ IsCycle f → IsCycle (g * f * g⁻¹)
[PROOFSTEP]
rintro ⟨x, hx, h⟩
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x✝ y x : α
hx : ↑f x ≠ x
h : ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
⊢ IsCycle (g * f * g⁻¹)
[PROOFSTEP]
refine' ⟨g x, by simp [coe_mul, inv_apply_self, hx], fun y hy => _⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x✝ y x : α
hx : ↑f x ≠ x
h : ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
⊢ ↑(g * f * g⁻¹) (↑g x) ≠ ↑g x
[PROOFSTEP]
simp [coe_mul, inv_apply_self, hx]
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x✝ y✝ x : α
hx : ↑f x ≠ x
h : ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
y : α
hy : ↑(g * f * g⁻¹) y ≠ y
⊢ SameCycle (g * f * g⁻¹) (↑g x) y
[PROOFSTEP]
rw [← apply_inv_self g y]
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x✝ y✝ x : α
hx : ↑f x ≠ x
h : ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
y : α
hy : ↑(g * f * g⁻¹) y ≠ y
⊢ SameCycle (g * f * g⁻¹) (↑g x) (↑g (↑g⁻¹ y))
[PROOFSTEP]
exact (h <| eq_inv_iff_eq.not.2 hy).conj
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
p : β → Prop
inst✝ : DecidablePred p
f : α ≃ Subtype p
⊢ IsCycle g → IsCycle (extendDomain g f)
[PROOFSTEP]
rintro ⟨a, ha, ha'⟩
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
p : β → Prop
inst✝ : DecidablePred p
f : α ≃ Subtype p
a : α
ha : ↑g a ≠ a
ha' : ∀ ⦃y : α⦄, ↑g y ≠ y → SameCycle g a y
⊢ IsCycle (extendDomain g f)
[PROOFSTEP]
refine' ⟨f a, _, fun b hb => _⟩
[GOAL]
case intro.intro.refine'_1
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
p : β → Prop
inst✝ : DecidablePred p
f : α ≃ Subtype p
a : α
ha : ↑g a ≠ a
ha' : ∀ ⦃y : α⦄, ↑g y ≠ y → SameCycle g a y
⊢ ↑(extendDomain g f) ↑(↑f a) ≠ ↑(↑f a)
[PROOFSTEP]
rw [extendDomain_apply_image]
[GOAL]
case intro.intro.refine'_1
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
p : β → Prop
inst✝ : DecidablePred p
f : α ≃ Subtype p
a : α
ha : ↑g a ≠ a
ha' : ∀ ⦃y : α⦄, ↑g y ≠ y → SameCycle g a y
⊢ ↑(↑f (↑g a)) ≠ ↑(↑f a)
[PROOFSTEP]
exact Subtype.coe_injective.ne (f.injective.ne ha)
[GOAL]
case intro.intro.refine'_2
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
p : β → Prop
inst✝ : DecidablePred p
f : α ≃ Subtype p
a : α
ha : ↑g a ≠ a
ha' : ∀ ⦃y : α⦄, ↑g y ≠ y → SameCycle g a y
b : β
hb : ↑(extendDomain g f) b ≠ b
⊢ SameCycle (extendDomain g f) (↑(↑f a)) b
[PROOFSTEP]
have h : b = f (f.symm ⟨b, of_not_not <| hb ∘ extendDomain_apply_not_subtype _ _⟩) := by
rw [apply_symm_apply, Subtype.coe_mk]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
p : β → Prop
inst✝ : DecidablePred p
f : α ≃ Subtype p
a : α
ha : ↑g a ≠ a
ha' : ∀ ⦃y : α⦄, ↑g y ≠ y → SameCycle g a y
b : β
hb : ↑(extendDomain g f) b ≠ b
⊢ b = ↑(↑f (↑f.symm { val := b, property := (_ : p b) }))
[PROOFSTEP]
rw [apply_symm_apply, Subtype.coe_mk]
[GOAL]
case intro.intro.refine'_2
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
p : β → Prop
inst✝ : DecidablePred p
f : α ≃ Subtype p
a : α
ha : ↑g a ≠ a
ha' : ∀ ⦃y : α⦄, ↑g y ≠ y → SameCycle g a y
b : β
hb : ↑(extendDomain g f) b ≠ b
h : b = ↑(↑f (↑f.symm { val := b, property := (_ : p b) }))
⊢ SameCycle (extendDomain g f) (↑(↑f a)) b
[PROOFSTEP]
rw [h] at hb ⊢
[GOAL]
case intro.intro.refine'_2
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
p : β → Prop
inst✝ : DecidablePred p
f : α ≃ Subtype p
a : α
ha : ↑g a ≠ a
ha' : ∀ ⦃y : α⦄, ↑g y ≠ y → SameCycle g a y
b : β
hb✝ : ↑(extendDomain g f) b ≠ b
hb :
↑(extendDomain g f) ↑(↑f (↑f.symm { val := b, property := (_ : p b) })) ≠
↑(↑f (↑f.symm { val := b, property := (_ : p b) }))
h : b = ↑(↑f (↑f.symm { val := b, property := (_ : p b) }))
⊢ SameCycle (extendDomain g f) ↑(↑f a) ↑(↑f (↑f.symm { val := b, property := (_ : p b) }))
[PROOFSTEP]
simp only [extendDomain_apply_image, Subtype.coe_injective.ne_iff, f.injective.ne_iff] at hb
[GOAL]
case intro.intro.refine'_2
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
p : β → Prop
inst✝ : DecidablePred p
f : α ≃ Subtype p
a : α
ha : ↑g a ≠ a
ha' : ∀ ⦃y : α⦄, ↑g y ≠ y → SameCycle g a y
b : β
hb✝ : ↑(extendDomain g f) b ≠ b
h : b = ↑(↑f (↑f.symm { val := b, property := (_ : p b) }))
hb : ↑g (↑f.symm { val := b, property := (_ : p b) }) ≠ ↑f.symm { val := b, property := (_ : p b) }
⊢ SameCycle (extendDomain g f) ↑(↑f a) ↑(↑f (↑f.symm { val := b, property := (_ : p b) }))
[PROOFSTEP]
exact (ha' hb).extendDomain
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y✝ : α
hx : ↑f x ≠ x
hf : IsCycle f
y : α
x✝ : SameCycle f x y
hy : ↑f y = y
i : ℤ
hi : ↑(f ^ i) x = y
⊢ ↑f x = x
[PROOFSTEP]
rw [← zpow_apply_eq_self_of_apply_eq_self hy i, (f ^ i).injective.eq_iff] at hi
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y✝ : α
hx : ↑f x ≠ x
hf : IsCycle f
y : α
x✝ : SameCycle f x y
hy : ↑f y = y
i : ℤ
hi : x = y
⊢ ↑f x = x
[PROOFSTEP]
rw [hi, hy]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝ : Finite α
hf : IsCycle f
hx : ↑f x ≠ x
hy : ↑f y ≠ y
⊢ ∃ i, ↑(f ^ i) x = y
[PROOFSTEP]
let ⟨n, hn⟩ := hf.exists_zpow_eq hx hy
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝ : Finite α
hf : IsCycle f
hx : ↑f x ≠ x
hy : ↑f y ≠ y
n : ℤ
hn : ↑(f ^ n) x = y
⊢ ∃ i, ↑(f ^ i) x = y
[PROOFSTEP]
classical exact
⟨(n % orderOf f).toNat, by
{
have := n.emod_nonneg (Int.coe_nat_ne_zero.mpr (ne_of_gt (orderOf_pos f)))
rwa [← zpow_ofNat, Int.toNat_of_nonneg this, ← zpow_eq_mod_orderOf]
}⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝ : Finite α
hf : IsCycle f
hx : ↑f x ≠ x
hy : ↑f y ≠ y
n : ℤ
hn : ↑(f ^ n) x = y
⊢ ∃ i, ↑(f ^ i) x = y
[PROOFSTEP]
exact
⟨(n % orderOf f).toNat, by
{
have := n.emod_nonneg (Int.coe_nat_ne_zero.mpr (ne_of_gt (orderOf_pos f)))
rwa [← zpow_ofNat, Int.toNat_of_nonneg this, ← zpow_eq_mod_orderOf]
}⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝ : Finite α
hf : IsCycle f
hx : ↑f x ≠ x
hy : ↑f y ≠ y
n : ℤ
hn : ↑(f ^ n) x = y
⊢ ↑(f ^ Int.toNat (n % ↑(orderOf f))) x = y
[PROOFSTEP]
{ have := n.emod_nonneg (Int.coe_nat_ne_zero.mpr (ne_of_gt (orderOf_pos f)))
rwa [← zpow_ofNat, Int.toNat_of_nonneg this, ← zpow_eq_mod_orderOf]
}
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝ : Finite α
hf : IsCycle f
hx : ↑f x ≠ x
hy : ↑f y ≠ y
n : ℤ
hn : ↑(f ^ n) x = y
⊢ ↑(f ^ Int.toNat (n % ↑(orderOf f))) x = y
[PROOFSTEP]
have := n.emod_nonneg (Int.coe_nat_ne_zero.mpr (ne_of_gt (orderOf_pos f)))
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝ : Finite α
hf : IsCycle f
hx : ↑f x ≠ x
hy : ↑f y ≠ y
n : ℤ
hn : ↑(f ^ n) x = y
this : 0 ≤ n % ↑(orderOf f)
⊢ ↑(f ^ Int.toNat (n % ↑(orderOf f))) x = y
[PROOFSTEP]
rwa [← zpow_ofNat, Int.toNat_of_nonneg this, ← zpow_eq_mod_orderOf]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝ : DecidableEq α
hxy : x ≠ y
⊢ ↑(swap x y) y ≠ y
[PROOFSTEP]
rwa [swap_apply_right]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝ : DecidableEq α
hxy : x ≠ y
a : α
ha : (if a = x then y else if a = y then x else a) ≠ a
hya : ¬y = a
⊢ ↑(swap x y ^ 1) y = a
[PROOFSTEP]
rw [zpow_one, swap_apply_def]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝ : DecidableEq α
hxy : x ≠ y
a : α
ha : (if a = x then y else if a = y then x else a) ≠ a
hya : ¬y = a
⊢ (if y = x then y else if y = y then x else y) = a
[PROOFSTEP]
split_ifs at *
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝ : DecidableEq α
hxy : x ≠ y
a : α
hya : ¬y = a
h✝¹ : y = x
h✝ : a = x
ha : y ≠ a
⊢ y = a
[PROOFSTEP]
tauto
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝ : DecidableEq α
hxy : x ≠ y
a : α
hya : ¬y = a
h✝² : y = x
h✝¹ : ¬a = x
h✝ : a = y
ha : x ≠ a
⊢ y = a
[PROOFSTEP]
tauto
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝ : DecidableEq α
hxy : x ≠ y
a : α
hya : ¬y = a
h✝² : y = x
h✝¹ : ¬a = x
h✝ : ¬a = y
ha : a ≠ a
⊢ y = a
[PROOFSTEP]
tauto
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝ : DecidableEq α
hxy : x ≠ y
a : α
hya : ¬y = a
h✝² : ¬y = x
h✝¹ : y = y
h✝ : a = x
ha : y ≠ a
⊢ x = a
[PROOFSTEP]
tauto
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝ : DecidableEq α
hxy : x ≠ y
a : α
hya : ¬y = a
h✝³ : ¬y = x
h✝² : y = y
h✝¹ : ¬a = x
h✝ : a = y
ha : x ≠ a
⊢ x = a
[PROOFSTEP]
tauto
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝ : DecidableEq α
hxy : x ≠ y
a : α
hya : ¬y = a
h✝³ : ¬y = x
h✝² : y = y
h✝¹ : ¬a = x
h✝ : ¬a = y
ha : a ≠ a
⊢ x = a
[PROOFSTEP]
tauto
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝ : DecidableEq α
hxy : x ≠ y
a : α
hya : ¬y = a
h✝² : ¬y = x
h✝¹ : ¬y = y
h✝ : a = x
ha : y ≠ a
⊢ y = a
[PROOFSTEP]
tauto
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝ : DecidableEq α
hxy : x ≠ y
a : α
hya : ¬y = a
h✝³ : ¬y = x
h✝² : ¬y = y
h✝¹ : ¬a = x
h✝ : a = y
ha : x ≠ a
⊢ y = a
[PROOFSTEP]
tauto
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝ : DecidableEq α
hxy : x ≠ y
a : α
hya : ¬y = a
h✝³ : ¬y = x
h✝² : ¬y = y
h✝¹ : ¬a = x
h✝ : ¬a = y
ha : a ≠ a
⊢ y = a
[PROOFSTEP]
tauto
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝ : DecidableEq α
⊢ IsSwap f → IsCycle f
[PROOFSTEP]
rintro ⟨x, y, hxy, rfl⟩
[GOAL]
case intro.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
g : Perm α
x✝ y✝ : α
inst✝ : DecidableEq α
x y : α
hxy : x ≠ y
⊢ IsCycle (swap x y)
[PROOFSTEP]
exact isCycle_swap hxy
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
⊢ ∃ k x, f ^ k = 1
[PROOFSTEP]
classical
have : IsOfFinOrder f := by exact _root_.exists_pow_eq_one f
rw [isOfFinOrder_iff_pow_eq_one] at this
obtain ⟨x, hx, _⟩ := hf
obtain ⟨_ | _ | k, hk, hk'⟩ := this
· exact absurd hk (lt_asymm hk)
· rw [pow_one] at hk'
simp [hk'] at hx
· exact ⟨k + 2, by simp, hk'⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
⊢ ∃ k x, f ^ k = 1
[PROOFSTEP]
have : IsOfFinOrder f := by exact _root_.exists_pow_eq_one f
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
⊢ IsOfFinOrder f
[PROOFSTEP]
exact _root_.exists_pow_eq_one f
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
this : IsOfFinOrder f
⊢ ∃ k x, f ^ k = 1
[PROOFSTEP]
rw [isOfFinOrder_iff_pow_eq_one] at this
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
this : ∃ n, 0 < n ∧ f ^ n = 1
⊢ ∃ k x, f ^ k = 1
[PROOFSTEP]
obtain ⟨x, hx, _⟩ := hf
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
this : ∃ n, 0 < n ∧ f ^ n = 1
x : β
hx : ↑f x ≠ x
right✝ : ∀ ⦃y : β⦄, ↑f y ≠ y → SameCycle f x y
⊢ ∃ k x, f ^ k = 1
[PROOFSTEP]
obtain ⟨_ | _ | k, hk, hk'⟩ := this
[GOAL]
case intro.intro.intro.zero.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
x : β
hx : ↑f x ≠ x
right✝ : ∀ ⦃y : β⦄, ↑f y ≠ y → SameCycle f x y
hk : 0 < Nat.zero
hk' : f ^ Nat.zero = 1
⊢ ∃ k x, f ^ k = 1
[PROOFSTEP]
exact absurd hk (lt_asymm hk)
[GOAL]
case intro.intro.intro.succ.zero.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
x : β
hx : ↑f x ≠ x
right✝ : ∀ ⦃y : β⦄, ↑f y ≠ y → SameCycle f x y
hk : 0 < Nat.succ Nat.zero
hk' : f ^ Nat.succ Nat.zero = 1
⊢ ∃ k x, f ^ k = 1
[PROOFSTEP]
rw [pow_one] at hk'
[GOAL]
case intro.intro.intro.succ.zero.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
x : β
hx : ↑f x ≠ x
right✝ : ∀ ⦃y : β⦄, ↑f y ≠ y → SameCycle f x y
hk : 0 < Nat.succ Nat.zero
hk' : f = 1
⊢ ∃ k x, f ^ k = 1
[PROOFSTEP]
simp [hk'] at hx
[GOAL]
case intro.intro.intro.succ.succ.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
x : β
hx : ↑f x ≠ x
right✝ : ∀ ⦃y : β⦄, ↑f y ≠ y → SameCycle f x y
k : ℕ
hk : 0 < Nat.succ (Nat.succ k)
hk' : f ^ Nat.succ (Nat.succ k) = 1
⊢ ∃ k x, f ^ k = 1
[PROOFSTEP]
exact ⟨k + 2, by simp, hk'⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
x : β
hx : ↑f x ≠ x
right✝ : ∀ ⦃y : β⦄, ↑f y ≠ y → SameCycle f x y
k : ℕ
hk : 0 < Nat.succ (Nat.succ k)
hk' : f ^ Nat.succ (Nat.succ k) = 1
⊢ 1 < k + 2
[PROOFSTEP]
simp
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ : Perm α
hσ : IsCycle σ
τ : ↑↑(Subgroup.zpowers σ)
⊢ ↑↑τ (Classical.choose hσ) ∈ support σ
[PROOFSTEP]
obtain ⟨τ, n, rfl⟩ := τ
[GOAL]
case mk.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ : Perm α
hσ : IsCycle σ
n : ℤ
⊢ ↑↑{ val := (fun x x_1 => x ^ x_1) σ n,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ n) }
(Classical.choose hσ) ∈
support σ
[PROOFSTEP]
erw [Finset.mem_coe, Subtype.coe_mk, zpow_apply_mem_support, mem_support]
[GOAL]
case mk.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ : Perm α
hσ : IsCycle σ
n : ℤ
⊢ ↑σ (Classical.choose hσ) ≠ Classical.choose hσ
[PROOFSTEP]
exact (Classical.choose_spec hσ).1
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ : Perm α
hσ : IsCycle σ
⊢ Bijective fun τ => { val := ↑↑τ (Classical.choose hσ), property := (_ : ↑↑τ (Classical.choose hσ) ∈ support σ) }
[PROOFSTEP]
constructor
[GOAL]
case left
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ : Perm α
hσ : IsCycle σ
⊢ Injective fun τ => { val := ↑↑τ (Classical.choose hσ), property := (_ : ↑↑τ (Classical.choose hσ) ∈ support σ) }
[PROOFSTEP]
rintro ⟨a, m, rfl⟩ ⟨b, n, rfl⟩ h
[GOAL]
case left.mk.intro.mk.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ : Perm α
hσ : IsCycle σ
m n : ℤ
h :
(fun τ => { val := ↑↑τ (Classical.choose hσ), property := (_ : ↑↑τ (Classical.choose hσ) ∈ support σ) })
{ val := (fun x x_1 => x ^ x_1) σ m,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ m) } =
(fun τ => { val := ↑↑τ (Classical.choose hσ), property := (_ : ↑↑τ (Classical.choose hσ) ∈ support σ) })
{ val := (fun x x_1 => x ^ x_1) σ n,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ n) }
⊢ { val := (fun x x_1 => x ^ x_1) σ m,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ m) } =
{ val := (fun x x_1 => x ^ x_1) σ n,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ n) }
[PROOFSTEP]
ext y
[GOAL]
case left.mk.intro.mk.intro.a.H
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y✝ : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ : Perm α
hσ : IsCycle σ
m n : ℤ
h :
(fun τ => { val := ↑↑τ (Classical.choose hσ), property := (_ : ↑↑τ (Classical.choose hσ) ∈ support σ) })
{ val := (fun x x_1 => x ^ x_1) σ m,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ m) } =
(fun τ => { val := ↑↑τ (Classical.choose hσ), property := (_ : ↑↑τ (Classical.choose hσ) ∈ support σ) })
{ val := (fun x x_1 => x ^ x_1) σ n,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ n) }
y : α
⊢ ↑↑{ val := (fun x x_1 => x ^ x_1) σ m,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ m) }
y =
↑↑{ val := (fun x x_1 => x ^ x_1) σ n,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ n) }
y
[PROOFSTEP]
by_cases hy : σ y = y
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y✝ : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ : Perm α
hσ : IsCycle σ
m n : ℤ
h :
(fun τ => { val := ↑↑τ (Classical.choose hσ), property := (_ : ↑↑τ (Classical.choose hσ) ∈ support σ) })
{ val := (fun x x_1 => x ^ x_1) σ m,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ m) } =
(fun τ => { val := ↑↑τ (Classical.choose hσ), property := (_ : ↑↑τ (Classical.choose hσ) ∈ support σ) })
{ val := (fun x x_1 => x ^ x_1) σ n,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ n) }
y : α
hy : ↑σ y = y
⊢ ↑↑{ val := (fun x x_1 => x ^ x_1) σ m,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ m) }
y =
↑↑{ val := (fun x x_1 => x ^ x_1) σ n,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ n) }
y
[PROOFSTEP]
simp_rw [zpow_apply_eq_self_of_apply_eq_self hy]
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y✝ : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ : Perm α
hσ : IsCycle σ
m n : ℤ
h :
(fun τ => { val := ↑↑τ (Classical.choose hσ), property := (_ : ↑↑τ (Classical.choose hσ) ∈ support σ) })
{ val := (fun x x_1 => x ^ x_1) σ m,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ m) } =
(fun τ => { val := ↑↑τ (Classical.choose hσ), property := (_ : ↑↑τ (Classical.choose hσ) ∈ support σ) })
{ val := (fun x x_1 => x ^ x_1) σ n,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ n) }
y : α
hy : ¬↑σ y = y
⊢ ↑↑{ val := (fun x x_1 => x ^ x_1) σ m,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ m) }
y =
↑↑{ val := (fun x x_1 => x ^ x_1) σ n,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ n) }
y
[PROOFSTEP]
obtain ⟨i, rfl⟩ := (Classical.choose_spec hσ).2 hy
[GOAL]
case neg.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ : Perm α
hσ : IsCycle σ
m n : ℤ
h :
(fun τ => { val := ↑↑τ (Classical.choose hσ), property := (_ : ↑↑τ (Classical.choose hσ) ∈ support σ) })
{ val := (fun x x_1 => x ^ x_1) σ m,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ m) } =
(fun τ => { val := ↑↑τ (Classical.choose hσ), property := (_ : ↑↑τ (Classical.choose hσ) ∈ support σ) })
{ val := (fun x x_1 => x ^ x_1) σ n,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ n) }
i : ℤ
hy : ¬↑σ (↑(σ ^ i) (Classical.choose hσ)) = ↑(σ ^ i) (Classical.choose hσ)
⊢ ↑↑{ val := (fun x x_1 => x ^ x_1) σ m,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ m) }
(↑(σ ^ i) (Classical.choose hσ)) =
↑↑{ val := (fun x x_1 => x ^ x_1) σ n,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ n) }
(↑(σ ^ i) (Classical.choose hσ))
[PROOFSTEP]
rw [Subtype.coe_mk, Subtype.coe_mk, zpow_apply_comm σ m i, zpow_apply_comm σ n i]
[GOAL]
case neg.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ : Perm α
hσ : IsCycle σ
m n : ℤ
h :
(fun τ => { val := ↑↑τ (Classical.choose hσ), property := (_ : ↑↑τ (Classical.choose hσ) ∈ support σ) })
{ val := (fun x x_1 => x ^ x_1) σ m,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ m) } =
(fun τ => { val := ↑↑τ (Classical.choose hσ), property := (_ : ↑↑τ (Classical.choose hσ) ∈ support σ) })
{ val := (fun x x_1 => x ^ x_1) σ n,
property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = (fun x x_1 => x ^ x_1) σ n) }
i : ℤ
hy : ¬↑σ (↑(σ ^ i) (Classical.choose hσ)) = ↑(σ ^ i) (Classical.choose hσ)
⊢ ↑(σ ^ i) (↑(σ ^ m) (Classical.choose hσ)) = ↑(σ ^ i) (↑(σ ^ n) (Classical.choose hσ))
[PROOFSTEP]
exact congr_arg _ (Subtype.ext_iff.mp h)
[GOAL]
case right
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ : Perm α
hσ : IsCycle σ
⊢ Surjective fun τ => { val := ↑↑τ (Classical.choose hσ), property := (_ : ↑↑τ (Classical.choose hσ) ∈ support σ) }
[PROOFSTEP]
rintro ⟨y, hy⟩
[GOAL]
case right.mk
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y✝ : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ : Perm α
hσ : IsCycle σ
y : α
hy : y ∈ support σ
⊢ ∃ a,
(fun τ => { val := ↑↑τ (Classical.choose hσ), property := (_ : ↑↑τ (Classical.choose hσ) ∈ support σ) }) a =
{ val := y, property := hy }
[PROOFSTEP]
erw [Finset.mem_coe, mem_support] at hy
[GOAL]
case right.mk
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y✝ : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ : Perm α
hσ : IsCycle σ
y : α
hy✝ : y ∈ support σ
hy : ↑σ y ≠ y
⊢ ∃ a,
(fun τ => { val := ↑↑τ (Classical.choose hσ), property := (_ : ↑↑τ (Classical.choose hσ) ∈ support σ) }) a =
{ val := y, property := hy✝ }
[PROOFSTEP]
obtain ⟨n, rfl⟩ := (Classical.choose_spec hσ).2 hy
[GOAL]
case right.mk.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ : Perm α
hσ : IsCycle σ
n : ℤ
hy✝ : ↑(σ ^ n) (Classical.choose hσ) ∈ support σ
hy : ↑σ (↑(σ ^ n) (Classical.choose hσ)) ≠ ↑(σ ^ n) (Classical.choose hσ)
⊢ ∃ a,
(fun τ => { val := ↑↑τ (Classical.choose hσ), property := (_ : ↑↑τ (Classical.choose hσ) ∈ support σ) }) a =
{ val := ↑(σ ^ n) (Classical.choose hσ), property := hy✝ }
[PROOFSTEP]
exact ⟨⟨σ ^ n, n, rfl⟩, rfl⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
⊢ orderOf f = card (support f)
[PROOFSTEP]
rw [orderOf_eq_card_zpowers, ← Fintype.card_coe]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
⊢ Fintype.card { x // x ∈ Subgroup.zpowers f } = Fintype.card { x // x ∈ support f }
[PROOFSTEP]
convert Fintype.card_congr (IsCycle.zpowersEquivSupport hf)
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f g : Perm α✝
x y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
⊢ ∀ (n : ℕ) {b x : α} {f : Perm α},
↑(swap x (↑f x) * f) b ≠ b → ↑(f ^ n) (↑f x) = b → ∃ i, ↑((swap x (↑f x) * f) ^ i) (↑f x) = b
[PROOFSTEP]
intro n
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f g : Perm α✝
x y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℕ
⊢ ∀ {b x : α} {f : Perm α},
↑(swap x (↑f x) * f) b ≠ b → ↑(f ^ n) (↑f x) = b → ∃ i, ↑((swap x (↑f x) * f) ^ i) (↑f x) = b
[PROOFSTEP]
induction' n with n hn
[GOAL]
case zero
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f g : Perm α✝
x y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
⊢ ∀ {b x : α} {f : Perm α},
↑(swap x (↑f x) * f) b ≠ b → ↑(f ^ Nat.zero) (↑f x) = b → ∃ i, ↑((swap x (↑f x) * f) ^ i) (↑f x) = b
[PROOFSTEP]
exact fun _ h => ⟨0, h⟩
[GOAL]
case succ
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f g : Perm α✝
x y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℕ
hn :
∀ {b x : α} {f : Perm α},
↑(swap x (↑f x) * f) b ≠ b → ↑(f ^ n) (↑f x) = b → ∃ i, ↑((swap x (↑f x) * f) ^ i) (↑f x) = b
⊢ ∀ {b x : α} {f : Perm α},
↑(swap x (↑f x) * f) b ≠ b → ↑(f ^ Nat.succ n) (↑f x) = b → ∃ i, ↑((swap x (↑f x) * f) ^ i) (↑f x) = b
[PROOFSTEP]
intro b x f hb h
[GOAL]
case succ
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℕ
hn :
∀ {b x : α} {f : Perm α},
↑(swap x (↑f x) * f) b ≠ b → ↑(f ^ n) (↑f x) = b → ∃ i, ↑((swap x (↑f x) * f) ^ i) (↑f x) = b
b x : α
f : Perm α
hb : ↑(swap x (↑f x) * f) b ≠ b
h : ↑(f ^ Nat.succ n) (↑f x) = b
⊢ ∃ i, ↑((swap x (↑f x) * f) ^ i) (↑f x) = b
[PROOFSTEP]
exact
if hfbx : f x = b then ⟨0, hfbx⟩
else
have : f b ≠ b ∧ b ≠ x := ne_and_ne_of_swap_mul_apply_ne_self hb
have hb' : (swap x (f x) * f) (f⁻¹ b) ≠ f⁻¹ b :=
by
rw [mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (Ne.symm hfbx), Ne.def, ← f.injective.eq_iff,
apply_inv_self]
exact this.1
let ⟨i, hi⟩ := hn hb' (f.injective <| by rw [apply_inv_self]; rwa [pow_succ, mul_apply] at h )
⟨i + 1, by
rw [add_comm, zpow_add, mul_apply, hi, zpow_one, mul_apply, apply_inv_self,
swap_apply_of_ne_of_ne (ne_and_ne_of_swap_mul_apply_ne_self hb).2 (Ne.symm hfbx)]⟩
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℕ
hn :
∀ {b x : α} {f : Perm α},
↑(swap x (↑f x) * f) b ≠ b → ↑(f ^ n) (↑f x) = b → ∃ i, ↑((swap x (↑f x) * f) ^ i) (↑f x) = b
b x : α
f : Perm α
hb : ↑(swap x (↑f x) * f) b ≠ b
h : ↑(f ^ Nat.succ n) (↑f x) = b
hfbx : ¬↑f x = b
this : ↑f b ≠ b ∧ b ≠ x
⊢ ↑(swap x (↑f x) * f) (↑f⁻¹ b) ≠ ↑f⁻¹ b
[PROOFSTEP]
rw [mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (Ne.symm hfbx), Ne.def, ← f.injective.eq_iff,
apply_inv_self]
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℕ
hn :
∀ {b x : α} {f : Perm α},
↑(swap x (↑f x) * f) b ≠ b → ↑(f ^ n) (↑f x) = b → ∃ i, ↑((swap x (↑f x) * f) ^ i) (↑f x) = b
b x : α
f : Perm α
hb : ↑(swap x (↑f x) * f) b ≠ b
h : ↑(f ^ Nat.succ n) (↑f x) = b
hfbx : ¬↑f x = b
this : ↑f b ≠ b ∧ b ≠ x
⊢ ¬↑f b = b
[PROOFSTEP]
exact this.1
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℕ
hn :
∀ {b x : α} {f : Perm α},
↑(swap x (↑f x) * f) b ≠ b → ↑(f ^ n) (↑f x) = b → ∃ i, ↑((swap x (↑f x) * f) ^ i) (↑f x) = b
b x : α
f : Perm α
hb : ↑(swap x (↑f x) * f) b ≠ b
h : ↑(f ^ Nat.succ n) (↑f x) = b
hfbx : ¬↑f x = b
this : ↑f b ≠ b ∧ b ≠ x
hb' : ↑(swap x (↑f x) * f) (↑f⁻¹ b) ≠ ↑f⁻¹ b
⊢ ↑f (↑(f ^ n) (↑f x)) = ↑f (↑f⁻¹ b)
[PROOFSTEP]
rw [apply_inv_self]
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℕ
hn :
∀ {b x : α} {f : Perm α},
↑(swap x (↑f x) * f) b ≠ b → ↑(f ^ n) (↑f x) = b → ∃ i, ↑((swap x (↑f x) * f) ^ i) (↑f x) = b
b x : α
f : Perm α
hb : ↑(swap x (↑f x) * f) b ≠ b
h : ↑(f ^ Nat.succ n) (↑f x) = b
hfbx : ¬↑f x = b
this : ↑f b ≠ b ∧ b ≠ x
hb' : ↑(swap x (↑f x) * f) (↑f⁻¹ b) ≠ ↑f⁻¹ b
⊢ ↑f (↑(f ^ n) (↑f x)) = b
[PROOFSTEP]
rwa [pow_succ, mul_apply] at h
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℕ
hn :
∀ {b x : α} {f : Perm α},
↑(swap x (↑f x) * f) b ≠ b → ↑(f ^ n) (↑f x) = b → ∃ i, ↑((swap x (↑f x) * f) ^ i) (↑f x) = b
b x : α
f : Perm α
hb : ↑(swap x (↑f x) * f) b ≠ b
h : ↑(f ^ Nat.succ n) (↑f x) = b
hfbx : ¬↑f x = b
this : ↑f b ≠ b ∧ b ≠ x
hb' : ↑(swap x (↑f x) * f) (↑f⁻¹ b) ≠ ↑f⁻¹ b
i : ℤ
hi : ↑((swap x (↑f x) * f) ^ i) (↑f x) = ↑f⁻¹ b
⊢ ↑((swap x (↑f x) * f) ^ (i + 1)) (↑f x) = b
[PROOFSTEP]
rw [add_comm, zpow_add, mul_apply, hi, zpow_one, mul_apply, apply_inv_self,
swap_apply_of_ne_of_ne (ne_and_ne_of_swap_mul_apply_ne_self hb).2 (Ne.symm hfbx)]
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f g : Perm α✝
x y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
⊢ ∀ (n : ℤ) {b x : α} {f : Perm α},
↑(swap x (↑f x) * f) b ≠ b → ↑(f ^ n) (↑f x) = b → ∃ i, ↑((swap x (↑f x) * f) ^ i) (↑f x) = b
[PROOFSTEP]
intro n
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f g : Perm α✝
x y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℤ
⊢ ∀ {b x : α} {f : Perm α},
↑(swap x (↑f x) * f) b ≠ b → ↑(f ^ n) (↑f x) = b → ∃ i, ↑((swap x (↑f x) * f) ^ i) (↑f x) = b
[PROOFSTEP]
induction' n with n n
[GOAL]
case ofNat
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f g : Perm α✝
x y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℕ
⊢ ∀ {b x : α} {f : Perm α},
↑(swap x (↑f x) * f) b ≠ b → ↑(f ^ Int.ofNat n) (↑f x) = b → ∃ i, ↑((swap x (↑f x) * f) ^ i) (↑f x) = b
[PROOFSTEP]
exact isCycle_swap_mul_aux₁ n
[GOAL]
case negSucc
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f g : Perm α✝
x y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℕ
⊢ ∀ {b x : α} {f : Perm α},
↑(swap x (↑f x) * f) b ≠ b → ↑(f ^ Int.negSucc n) (↑f x) = b → ∃ i, ↑((swap x (↑f x) * f) ^ i) (↑f x) = b
[PROOFSTEP]
intro b x f hb h
[GOAL]
case negSucc
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℕ
b x : α
f : Perm α
hb : ↑(swap x (↑f x) * f) b ≠ b
h : ↑(f ^ Int.negSucc n) (↑f x) = b
⊢ ∃ i, ↑((swap x (↑f x) * f) ^ i) (↑f x) = b
[PROOFSTEP]
exact
if hfbx' : f x = b then ⟨0, hfbx'⟩
else
have : f b ≠ b ∧ b ≠ x := ne_and_ne_of_swap_mul_apply_ne_self hb
have hb : (swap x (f⁻¹ x) * f⁻¹) (f⁻¹ b) ≠ f⁻¹ b :=
by
rw [mul_apply, swap_apply_def]
split_ifs <;> simp only [inv_eq_iff_eq, Perm.mul_apply, zpow_negSucc, Ne.def, Perm.apply_inv_self] at * <;> tauto
let ⟨i, hi⟩ :=
isCycle_swap_mul_aux₁ n hb
(show (f⁻¹ ^ n) (f⁻¹ x) = f⁻¹ b by
rw [← zpow_ofNat, ← h, ← mul_apply, ← mul_apply, ← mul_apply, zpow_negSucc, ← inv_pow, pow_succ', mul_assoc,
mul_assoc, inv_mul_self, mul_one, zpow_ofNat, ← pow_succ', ← pow_succ])
have h : (swap x (f⁻¹ x) * f⁻¹) (f x) = f⁻¹ x := by rw [mul_apply, inv_apply_self, swap_apply_left]
⟨-i, by
rw [← add_sub_cancel i 1, neg_sub, sub_eq_add_neg, zpow_add, zpow_one, zpow_neg, ← inv_zpow, mul_inv_rev,
swap_inv, mul_swap_eq_swap_mul, inv_apply_self, swap_comm _ x, zpow_add, zpow_one, mul_apply, mul_apply (_ ^ i),
h, hi, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (Ne.symm hfbx')]⟩
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℕ
b x : α
f : Perm α
hb : ↑(swap x (↑f x) * f) b ≠ b
h : ↑(f ^ Int.negSucc n) (↑f x) = b
hfbx' : ¬↑f x = b
this : ↑f b ≠ b ∧ b ≠ x
⊢ ↑(swap x (↑f⁻¹ x) * f⁻¹) (↑f⁻¹ b) ≠ ↑f⁻¹ b
[PROOFSTEP]
rw [mul_apply, swap_apply_def]
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℕ
b x : α
f : Perm α
hb : ↑(swap x (↑f x) * f) b ≠ b
h : ↑(f ^ Int.negSucc n) (↑f x) = b
hfbx' : ¬↑f x = b
this : ↑f b ≠ b ∧ b ≠ x
⊢ (if ↑f⁻¹ (↑f⁻¹ b) = x then ↑f⁻¹ x else if ↑f⁻¹ (↑f⁻¹ b) = ↑f⁻¹ x then x else ↑f⁻¹ (↑f⁻¹ b)) ≠ ↑f⁻¹ b
[PROOFSTEP]
split_ifs
[GOAL]
case pos
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℕ
b x : α
f : Perm α
hb : ↑(swap x (↑f x) * f) b ≠ b
h : ↑(f ^ Int.negSucc n) (↑f x) = b
hfbx' : ¬↑f x = b
this : ↑f b ≠ b ∧ b ≠ x
h✝ : ↑f⁻¹ (↑f⁻¹ b) = x
⊢ ↑f⁻¹ x ≠ ↑f⁻¹ b
[PROOFSTEP]
simp only [inv_eq_iff_eq, Perm.mul_apply, zpow_negSucc, Ne.def, Perm.apply_inv_self] at *
[GOAL]
case pos
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℕ
b x : α
f : Perm α
hb : ↑(swap x (↑f x) * f) b ≠ b
h : ↑(f ^ Int.negSucc n) (↑f x) = b
hfbx' : ¬↑f x = b
this : ↑f b ≠ b ∧ b ≠ x
h✝¹ : ¬↑f⁻¹ (↑f⁻¹ b) = x
h✝ : ↑f⁻¹ (↑f⁻¹ b) = ↑f⁻¹ x
⊢ x ≠ ↑f⁻¹ b
[PROOFSTEP]
simp only [inv_eq_iff_eq, Perm.mul_apply, zpow_negSucc, Ne.def, Perm.apply_inv_self] at *
[GOAL]
case neg
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℕ
b x : α
f : Perm α
hb : ↑(swap x (↑f x) * f) b ≠ b
h : ↑(f ^ Int.negSucc n) (↑f x) = b
hfbx' : ¬↑f x = b
this : ↑f b ≠ b ∧ b ≠ x
h✝¹ : ¬↑f⁻¹ (↑f⁻¹ b) = x
h✝ : ¬↑f⁻¹ (↑f⁻¹ b) = ↑f⁻¹ x
⊢ ↑f⁻¹ (↑f⁻¹ b) ≠ ↑f⁻¹ b
[PROOFSTEP]
simp only [inv_eq_iff_eq, Perm.mul_apply, zpow_negSucc, Ne.def, Perm.apply_inv_self] at *
[GOAL]
case pos
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℕ
b x : α
f : Perm α
hb : ¬↑(swap x (↑f x)) (↑f b) = b
hfbx' : ¬↑f x = b
this : ¬↑f b = b ∧ ¬b = x
h : ↑f x = ↑(f ^ (n + 1)) b
h✝ : b = ↑f (↑f x)
⊢ ¬x = b
[PROOFSTEP]
tauto
[GOAL]
case pos
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℕ
b x : α
f : Perm α
hb : ¬↑(swap x (↑f x)) (↑f b) = b
hfbx' : ¬↑f x = b
this : ¬↑f b = b ∧ ¬b = x
h : ↑f x = ↑(f ^ (n + 1)) b
h✝¹ : ¬b = ↑f (↑f x)
h✝ : b = ↑f x
⊢ ¬x = ↑f⁻¹ b
[PROOFSTEP]
tauto
[GOAL]
case neg
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℕ
b x : α
f : Perm α
hb : ¬↑(swap x (↑f x)) (↑f b) = b
hfbx' : ¬↑f x = b
this : ¬↑f b = b ∧ ¬b = x
h : ↑f x = ↑(f ^ (n + 1)) b
h✝¹ : ¬b = ↑f (↑f x)
h✝ : ¬b = ↑f x
⊢ ¬b = ↑f b
[PROOFSTEP]
tauto
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℕ
b x : α
f : Perm α
hb✝ : ↑(swap x (↑f x) * f) b ≠ b
h : ↑(f ^ Int.negSucc n) (↑f x) = b
hfbx' : ¬↑f x = b
this : ↑f b ≠ b ∧ b ≠ x
hb : ↑(swap x (↑f⁻¹ x) * f⁻¹) (↑f⁻¹ b) ≠ ↑f⁻¹ b
⊢ ↑(f⁻¹ ^ n) (↑f⁻¹ x) = ↑f⁻¹ b
[PROOFSTEP]
rw [← zpow_ofNat, ← h, ← mul_apply, ← mul_apply, ← mul_apply, zpow_negSucc, ← inv_pow, pow_succ', mul_assoc, mul_assoc,
inv_mul_self, mul_one, zpow_ofNat, ← pow_succ', ← pow_succ]
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℕ
b x : α
f : Perm α
hb✝ : ↑(swap x (↑f x) * f) b ≠ b
h : ↑(f ^ Int.negSucc n) (↑f x) = b
hfbx' : ¬↑f x = b
this : ↑f b ≠ b ∧ b ≠ x
hb : ↑(swap x (↑f⁻¹ x) * f⁻¹) (↑f⁻¹ b) ≠ ↑f⁻¹ b
i : ℤ
hi : ↑((swap x (↑f⁻¹ x) * f⁻¹) ^ i) (↑f⁻¹ x) = ↑f⁻¹ b
⊢ ↑(swap x (↑f⁻¹ x) * f⁻¹) (↑f x) = ↑f⁻¹ x
[PROOFSTEP]
rw [mul_apply, inv_apply_self, swap_apply_left]
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
n : ℕ
b x : α
f : Perm α
hb✝ : ↑(swap x (↑f x) * f) b ≠ b
h✝ : ↑(f ^ Int.negSucc n) (↑f x) = b
hfbx' : ¬↑f x = b
this : ↑f b ≠ b ∧ b ≠ x
hb : ↑(swap x (↑f⁻¹ x) * f⁻¹) (↑f⁻¹ b) ≠ ↑f⁻¹ b
i : ℤ
hi : ↑((swap x (↑f⁻¹ x) * f⁻¹) ^ i) (↑f⁻¹ x) = ↑f⁻¹ b
h : ↑(swap x (↑f⁻¹ x) * f⁻¹) (↑f x) = ↑f⁻¹ x
⊢ ↑((swap x (↑f x) * f) ^ (-i)) (↑f x) = b
[PROOFSTEP]
rw [← add_sub_cancel i 1, neg_sub, sub_eq_add_neg, zpow_add, zpow_one, zpow_neg, ← inv_zpow, mul_inv_rev, swap_inv,
mul_swap_eq_swap_mul, inv_apply_self, swap_comm _ x, zpow_add, zpow_one, mul_apply, mul_apply (_ ^ i), h, hi,
mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (Ne.symm hfbx')]
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y✝ : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
x : α
hfx : ↑f x ≠ x
hffx : ↑f (↑f x) = x
y z : α
hz : ↑f z ≠ z ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f z y
i : ℤ
hi : ↑(f ^ i) z = x
hyx : y = x
⊢ ↑f y = ↑(swap x (↑f x)) y
[PROOFSTEP]
simp [hyx]
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y✝ : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
x : α
hfx : ↑f x ≠ x
hffx : ↑f (↑f x) = x
y z : α
hz : ↑f z ≠ z ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f z y
i : ℤ
hi : ↑(f ^ i) z = x
hyx : ¬y = x
hfyx : y = ↑f x
⊢ ↑f y = ↑(swap x (↑f x)) y
[PROOFSTEP]
simp [hfyx, hffx]
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y✝ : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
x : α
hfx : ↑f x ≠ x
hffx : ↑f (↑f x) = x
y z : α
hz : ↑f z ≠ z ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f z y
i : ℤ
hi : ↑(f ^ i) z = x
hyx : ¬y = x
hfyx : ¬y = ↑f x
⊢ ↑f y = ↑(swap x (↑f x)) y
[PROOFSTEP]
rw [swap_apply_of_ne_of_ne hyx hfyx]
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y✝ : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
x : α
hfx : ↑f x ≠ x
hffx : ↑f (↑f x) = x
y z : α
hz : ↑f z ≠ z ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f z y
i : ℤ
hi : ↑(f ^ i) z = x
hyx : ¬y = x
hfyx : ¬y = ↑f x
⊢ ↑f y = y
[PROOFSTEP]
refine' by_contradiction fun hy => _
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y✝ : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
x : α
hfx : ↑f x ≠ x
hffx : ↑f (↑f x) = x
y z : α
hz : ↑f z ≠ z ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f z y
i : ℤ
hi : ↑(f ^ i) z = x
hyx : ¬y = x
hfyx : ¬y = ↑f x
hy : ¬↑f y = y
⊢ False
[PROOFSTEP]
cases' hz.2 hy with j hj
[GOAL]
case intro
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y✝ : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
x : α
hfx : ↑f x ≠ x
hffx : ↑f (↑f x) = x
y z : α
hz : ↑f z ≠ z ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f z y
i : ℤ
hi : ↑(f ^ i) z = x
hyx : ¬y = x
hfyx : ¬y = ↑f x
hy : ¬↑f y = y
j : ℤ
hj : ↑(f ^ j) z = y
⊢ False
[PROOFSTEP]
rw [← sub_add_cancel j i, zpow_add, mul_apply, hi] at hj
[GOAL]
case intro
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y✝ : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
x : α
hfx : ↑f x ≠ x
hffx : ↑f (↑f x) = x
y z : α
hz : ↑f z ≠ z ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f z y
i : ℤ
hi : ↑(f ^ i) z = x
hyx : ¬y = x
hfyx : ¬y = ↑f x
hy : ¬↑f y = y
j : ℤ
hj : ↑(f ^ (j - i)) x = y
⊢ False
[PROOFSTEP]
cases' zpow_apply_eq_of_apply_apply_eq_self hffx (j - i) with hji hji
[GOAL]
case intro.inl
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y✝ : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
x : α
hfx : ↑f x ≠ x
hffx : ↑f (↑f x) = x
y z : α
hz : ↑f z ≠ z ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f z y
i : ℤ
hi : ↑(f ^ i) z = x
hyx : ¬y = x
hfyx : ¬y = ↑f x
hy : ¬↑f y = y
j : ℤ
hj : ↑(f ^ (j - i)) x = y
hji : ↑(f ^ (j - i)) x = x
⊢ False
[PROOFSTEP]
rw [← hj, hji] at hyx
[GOAL]
case intro.inl
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y✝ : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
x : α
hfx : ↑f x ≠ x
hffx : ↑f (↑f x) = x
y z : α
hz : ↑f z ≠ z ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f z y
i : ℤ
hi : ↑(f ^ i) z = x
hfyx : ¬y = ↑f x
hy : ¬↑f y = y
j : ℤ
hyx : ¬x = x
hj : ↑(f ^ (j - i)) x = y
hji : ↑(f ^ (j - i)) x = x
⊢ False
[PROOFSTEP]
tauto
[GOAL]
case intro.inr
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y✝ : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
x : α
hfx : ↑f x ≠ x
hffx : ↑f (↑f x) = x
y z : α
hz : ↑f z ≠ z ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f z y
i : ℤ
hi : ↑(f ^ i) z = x
hyx : ¬y = x
hfyx : ¬y = ↑f x
hy : ¬↑f y = y
j : ℤ
hj : ↑(f ^ (j - i)) x = y
hji : ↑(f ^ (j - i)) x = ↑f x
⊢ False
[PROOFSTEP]
rw [← hj, hji] at hfyx
[GOAL]
case intro.inr
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y✝ : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
x : α
hfx : ↑f x ≠ x
hffx : ↑f (↑f x) = x
y z : α
hz : ↑f z ≠ z ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f z y
i : ℤ
hi : ↑(f ^ i) z = x
hyx : ¬y = x
hy : ¬↑f y = y
j : ℤ
hfyx : ¬↑f x = ↑f x
hj : ↑(f ^ (j - i)) x = y
hji : ↑(f ^ (j - i)) x = ↑f x
⊢ False
[PROOFSTEP]
tauto
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x
hffx : ↑f (↑f x) ≠ x
⊢ ↑(swap x (↑f x) * f) (↑f x) ≠ ↑f x
[PROOFSTEP]
simp [swap_apply_def, mul_apply, if_neg hffx, f.injective.eq_iff, if_neg hx, hx]
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y✝ : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x
hffx : ↑f (↑f x) ≠ x
y : α
hy : ↑(swap x (↑f x) * f) y ≠ y
i : ℤ
hi : ↑(f ^ i) x = y
⊢ ↑(f ^ (i - 1)) (↑f x) = ↑(f ^ (i - 1) * f ^ 1) x
[PROOFSTEP]
simp
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
f✝ g : Perm α✝
x✝ y✝ : α✝
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
α : Type u_4
inst✝ : DecidableEq α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x
hffx : ↑f (↑f x) ≠ x
y : α
hy : ↑(swap x (↑f x) * f) y ≠ y
i : ℤ
hi : ↑(f ^ i) x = y
⊢ ↑(f ^ (i - 1) * f ^ 1) x = y
[PROOFSTEP]
rwa [← zpow_add, sub_add_cancel]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
⊢ ↑Perm.sign f = ↑Perm.sign (swap x (↑f x) * (swap x (↑f x) * f))
[PROOFSTEP]
{rw [← mul_assoc, mul_def, mul_def, swap_swap, trans_refl]
}
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
⊢ ↑Perm.sign f = ↑Perm.sign (swap x (↑f x) * (swap x (↑f x) * f))
[PROOFSTEP]
rw [← mul_assoc, mul_def, mul_def, swap_swap, trans_refl]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
h1 : ↑f (↑f x) = x
⊢ ↑Perm.sign (swap x (↑f x) * (swap x (↑f x) * f)) = -(-1) ^ card (support f)
[PROOFSTEP]
have h : swap x (f x) * f = 1 := by
simp only [mul_def, one_def]
rw [hf.eq_swap_of_apply_apply_eq_self hx.1 h1, swap_apply_left, swap_swap]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
h1 : ↑f (↑f x) = x
⊢ swap x (↑f x) * f = 1
[PROOFSTEP]
simp only [mul_def, one_def]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
h1 : ↑f (↑f x) = x
⊢ f.trans (swap x (↑f x)) = Equiv.refl α
[PROOFSTEP]
rw [hf.eq_swap_of_apply_apply_eq_self hx.1 h1, swap_apply_left, swap_swap]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
h1 : ↑f (↑f x) = x
h : swap x (↑f x) * f = 1
⊢ ↑Perm.sign (swap x (↑f x) * (swap x (↑f x) * f)) = -(-1) ^ card (support f)
[PROOFSTEP]
dsimp only
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
h1 : ↑f (↑f x) = x
h : swap x (↑f x) * f = 1
⊢ ↑Perm.sign (swap x (↑f x) * (swap x (↑f x) * f)) = -(-1) ^ card (support f)
[PROOFSTEP]
rw [sign_mul, sign_swap hx.1.symm, h, sign_one, hf.eq_swap_of_apply_apply_eq_self hx.1 h1, card_support_swap hx.1.symm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
h1 : ↑f (↑f x) = x
h : swap x (↑f x) * f = 1
⊢ -1 * 1 = -(-1) ^ 2
[PROOFSTEP]
rfl
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
h1 : ¬↑f (↑f x) = x
⊢ ↑Perm.sign (swap x (↑f x) * (swap x (↑f x) * f)) = -(-1) ^ card (support f)
[PROOFSTEP]
have h : card (support (swap x (f x) * f)) + 1 = card (support f) := by
rw [← insert_erase (mem_support.2 hx.1), support_swap_mul_eq _ _ h1, card_insert_of_not_mem (not_mem_erase _ _),
sdiff_singleton_eq_erase]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
h1 : ¬↑f (↑f x) = x
⊢ card (support (swap x (↑f x) * f)) + 1 = card (support f)
[PROOFSTEP]
rw [← insert_erase (mem_support.2 hx.1), support_swap_mul_eq _ _ h1, card_insert_of_not_mem (not_mem_erase _ _),
sdiff_singleton_eq_erase]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
h1 : ¬↑f (↑f x) = x
h : card (support (swap x (↑f x) * f)) + 1 = card (support f)
⊢ ↑Perm.sign (swap x (↑f x) * (swap x (↑f x) * f)) = -(-1) ^ card (support f)
[PROOFSTEP]
have : card (support (swap x (f x) * f)) < card (support f) := card_support_swap_mul hx.1
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
h1 : ¬↑f (↑f x) = x
h : card (support (swap x (↑f x) * f)) + 1 = card (support f)
this : card (support (swap x (↑f x) * f)) < card (support f)
⊢ ↑Perm.sign (swap x (↑f x) * (swap x (↑f x) * f)) = -(-1) ^ card (support f)
[PROOFSTEP]
dsimp only
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
h1 : ¬↑f (↑f x) = x
h : card (support (swap x (↑f x) * f)) + 1 = card (support f)
this : card (support (swap x (↑f x) * f)) < card (support f)
⊢ ↑Perm.sign (swap x (↑f x) * (swap x (↑f x) * f)) = -(-1) ^ card (support f)
[PROOFSTEP]
rw [sign_mul, sign_swap hx.1.symm, (hf.swap_mul hx.1 h1).sign, ← h]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f : Perm α
hf : IsCycle f
x : α
hx : ↑f x ≠ x ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
h1 : ¬↑f (↑f x) = x
h : card (support (swap x (↑f x) * f)) + 1 = card (support f)
this : card (support (swap x (↑f x) * f)) < card (support f)
⊢ -1 * -(-1) ^ card (support (swap x (↑f x) * f)) = -(-1) ^ (card (support (swap x (↑f x) * f)) + 1)
[PROOFSTEP]
simp only [mul_neg, neg_mul, one_mul, neg_neg, pow_add, pow_one, mul_one]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
n : ℕ
h1 : IsCycle (f ^ n)
h2 : support f ⊆ support (f ^ n)
⊢ IsCycle f
[PROOFSTEP]
have key : ∀ x : α, (f ^ n) x ≠ x ↔ f x ≠ x :=
by
simp_rw [← mem_support, ← Finset.ext_iff]
exact (support_pow_le _ n).antisymm h2
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
n : ℕ
h1 : IsCycle (f ^ n)
h2 : support f ⊆ support (f ^ n)
⊢ ∀ (x : α), ↑(f ^ n) x ≠ x ↔ ↑f x ≠ x
[PROOFSTEP]
simp_rw [← mem_support, ← Finset.ext_iff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
n : ℕ
h1 : IsCycle (f ^ n)
h2 : support f ⊆ support (f ^ n)
⊢ support (f ^ n) = support f
[PROOFSTEP]
exact (support_pow_le _ n).antisymm h2
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
n : ℕ
h1 : IsCycle (f ^ n)
h2 : support f ⊆ support (f ^ n)
key : ∀ (x : α), ↑(f ^ n) x ≠ x ↔ ↑f x ≠ x
⊢ IsCycle f
[PROOFSTEP]
obtain ⟨x, hx1, hx2⟩ := h1
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
n : ℕ
h2 : support f ⊆ support (f ^ n)
key : ∀ (x : α), ↑(f ^ n) x ≠ x ↔ ↑f x ≠ x
x : α
hx1 : ↑(f ^ n) x ≠ x
hx2 : ∀ ⦃y : α⦄, ↑(f ^ n) y ≠ y → SameCycle (f ^ n) x y
⊢ IsCycle f
[PROOFSTEP]
refine' ⟨x, (key x).mp hx1, fun y hy => _⟩
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x✝ y✝ : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
n : ℕ
h2 : support f ⊆ support (f ^ n)
key : ∀ (x : α), ↑(f ^ n) x ≠ x ↔ ↑f x ≠ x
x : α
hx1 : ↑(f ^ n) x ≠ x
hx2 : ∀ ⦃y : α⦄, ↑(f ^ n) y ≠ y → SameCycle (f ^ n) x y
y : α
hy : ↑f y ≠ y
⊢ SameCycle f x y
[PROOFSTEP]
cases' hx2 ((key y).mpr hy) with i _
[GOAL]
case intro.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x✝ y✝ : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
n : ℕ
h2 : support f ⊆ support (f ^ n)
key : ∀ (x : α), ↑(f ^ n) x ≠ x ↔ ↑f x ≠ x
x : α
hx1 : ↑(f ^ n) x ≠ x
hx2 : ∀ ⦃y : α⦄, ↑(f ^ n) y ≠ y → SameCycle (f ^ n) x y
y : α
hy : ↑f y ≠ y
i : ℤ
h✝ : ↑((f ^ n) ^ i) x = y
⊢ SameCycle f x y
[PROOFSTEP]
exact ⟨n * i, by rwa [zpow_mul]⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x✝ y✝ : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
n : ℕ
h2 : support f ⊆ support (f ^ n)
key : ∀ (x : α), ↑(f ^ n) x ≠ x ↔ ↑f x ≠ x
x : α
hx1 : ↑(f ^ n) x ≠ x
hx2 : ∀ ⦃y : α⦄, ↑(f ^ n) y ≠ y → SameCycle (f ^ n) x y
y : α
hy : ↑f y ≠ y
i : ℤ
h✝ : ↑((f ^ n) ^ i) x = y
⊢ ↑(f ^ (↑n * i)) x = y
[PROOFSTEP]
rwa [zpow_mul]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
n : ℤ
h1 : IsCycle (f ^ n)
h2 : support f ⊆ support (f ^ n)
⊢ IsCycle f
[PROOFSTEP]
cases n
[GOAL]
case ofNat
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
a✝ : ℕ
h1 : IsCycle (f ^ Int.ofNat a✝)
h2 : support f ⊆ support (f ^ Int.ofNat a✝)
⊢ IsCycle f
[PROOFSTEP]
exact h1.of_pow h2
[GOAL]
case negSucc
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
a✝ : ℕ
h1 : IsCycle (f ^ Int.negSucc a✝)
h2 : support f ⊆ support (f ^ Int.negSucc a✝)
⊢ IsCycle f
[PROOFSTEP]
simp only [le_eq_subset, zpow_negSucc, Perm.support_inv] at h1 h2
[GOAL]
case negSucc
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
a✝ : ℕ
h1 : IsCycle (f ^ (a✝ + 1))⁻¹
h2 : support f ⊆ support (f ^ (a✝ + 1))
⊢ IsCycle f
[PROOFSTEP]
exact (inv_inv (f ^ _) ▸ h1.inv).of_pow h2
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
hg : IsCycle g
h : support f ⊆ support g
h' : ∀ (x : α), x ∈ support f → ↑f x = ↑g x
⊢ f = g
[PROOFSTEP]
have : f.support = g.support := by
refine' le_antisymm h _
intro z hz
obtain ⟨x, hx, _⟩ := id hf
have hx' : g x ≠ x := by rwa [← h' x (mem_support.mpr hx)]
obtain ⟨m, hm⟩ := hg.exists_pow_eq hx' (mem_support.mp hz)
have h'' : ∀ x ∈ f.support ∩ g.support, f x = g x := by
intro x hx
exact h' x (mem_of_mem_inter_left hx)
rwa [← hm, ← pow_eq_on_of_mem_support h'' _ x (mem_inter_of_mem (mem_support.mpr hx) (mem_support.mpr hx')),
pow_apply_mem_support, mem_support]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
hg : IsCycle g
h : support f ⊆ support g
h' : ∀ (x : α), x ∈ support f → ↑f x = ↑g x
⊢ support f = support g
[PROOFSTEP]
refine' le_antisymm h _
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
hg : IsCycle g
h : support f ⊆ support g
h' : ∀ (x : α), x ∈ support f → ↑f x = ↑g x
⊢ support g ≤ support f
[PROOFSTEP]
intro z hz
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
hg : IsCycle g
h : support f ⊆ support g
h' : ∀ (x : α), x ∈ support f → ↑f x = ↑g x
z : α
hz : z ∈ support g
⊢ z ∈ support f
[PROOFSTEP]
obtain ⟨x, hx, _⟩ := id hf
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
hg : IsCycle g
h : support f ⊆ support g
h' : ∀ (x : α), x ∈ support f → ↑f x = ↑g x
z : α
hz : z ∈ support g
x : α
hx : ↑f x ≠ x
right✝ : ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
⊢ z ∈ support f
[PROOFSTEP]
have hx' : g x ≠ x := by rwa [← h' x (mem_support.mpr hx)]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
hg : IsCycle g
h : support f ⊆ support g
h' : ∀ (x : α), x ∈ support f → ↑f x = ↑g x
z : α
hz : z ∈ support g
x : α
hx : ↑f x ≠ x
right✝ : ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
⊢ ↑g x ≠ x
[PROOFSTEP]
rwa [← h' x (mem_support.mpr hx)]
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
hg : IsCycle g
h : support f ⊆ support g
h' : ∀ (x : α), x ∈ support f → ↑f x = ↑g x
z : α
hz : z ∈ support g
x : α
hx : ↑f x ≠ x
right✝ : ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
hx' : ↑g x ≠ x
⊢ z ∈ support f
[PROOFSTEP]
obtain ⟨m, hm⟩ := hg.exists_pow_eq hx' (mem_support.mp hz)
[GOAL]
case intro.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
hg : IsCycle g
h : support f ⊆ support g
h' : ∀ (x : α), x ∈ support f → ↑f x = ↑g x
z : α
hz : z ∈ support g
x : α
hx : ↑f x ≠ x
right✝ : ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
hx' : ↑g x ≠ x
m : ℕ
hm : ↑(g ^ m) x = z
⊢ z ∈ support f
[PROOFSTEP]
have h'' : ∀ x ∈ f.support ∩ g.support, f x = g x := by
intro x hx
exact h' x (mem_of_mem_inter_left hx)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
hg : IsCycle g
h : support f ⊆ support g
h' : ∀ (x : α), x ∈ support f → ↑f x = ↑g x
z : α
hz : z ∈ support g
x : α
hx : ↑f x ≠ x
right✝ : ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
hx' : ↑g x ≠ x
m : ℕ
hm : ↑(g ^ m) x = z
⊢ ∀ (x : α), x ∈ support f ∩ support g → ↑f x = ↑g x
[PROOFSTEP]
intro x hx
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x✝¹ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
hg : IsCycle g
h : support f ⊆ support g
h' : ∀ (x : α), x ∈ support f → ↑f x = ↑g x
z : α
hz : z ∈ support g
x✝ : α
hx✝ : ↑f x✝ ≠ x✝
right✝ : ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x✝ y
hx' : ↑g x✝ ≠ x✝
m : ℕ
hm : ↑(g ^ m) x✝ = z
x : α
hx : x ∈ support f ∩ support g
⊢ ↑f x = ↑g x
[PROOFSTEP]
exact h' x (mem_of_mem_inter_left hx)
[GOAL]
case intro.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
hg : IsCycle g
h : support f ⊆ support g
h' : ∀ (x : α), x ∈ support f → ↑f x = ↑g x
z : α
hz : z ∈ support g
x : α
hx : ↑f x ≠ x
right✝ : ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f x y
hx' : ↑g x ≠ x
m : ℕ
hm : ↑(g ^ m) x = z
h'' : ∀ (x : α), x ∈ support f ∩ support g → ↑f x = ↑g x
⊢ z ∈ support f
[PROOFSTEP]
rwa [← hm, ← pow_eq_on_of_mem_support h'' _ x (mem_inter_of_mem (mem_support.mpr hx) (mem_support.mpr hx')),
pow_apply_mem_support, mem_support]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
hg : IsCycle g
h : support f ⊆ support g
h' : ∀ (x : α), x ∈ support f → ↑f x = ↑g x
this : support f = support g
⊢ f = g
[PROOFSTEP]
refine' Equiv.Perm.support_congr h _
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
hg : IsCycle g
h : support f ⊆ support g
h' : ∀ (x : α), x ∈ support f → ↑f x = ↑g x
this : support f = support g
⊢ ∀ (x : α), x ∈ support g → ↑f x = ↑g x
[PROOFSTEP]
simpa [← this] using h'
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
hg : IsCycle g
h : ∀ (x : α), x ∈ support f ∩ support g → ↑f x = ↑g x
hx : ↑f x = ↑g x
hx' : x ∈ support f
⊢ f = g
[PROOFSTEP]
have hx'' : x ∈ g.support := by rwa [mem_support, ← hx, ← mem_support]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
hg : IsCycle g
h : ∀ (x : α), x ∈ support f ∩ support g → ↑f x = ↑g x
hx : ↑f x = ↑g x
hx' : x ∈ support f
⊢ x ∈ support g
[PROOFSTEP]
rwa [mem_support, ← hx, ← mem_support]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
hg : IsCycle g
h : ∀ (x : α), x ∈ support f ∩ support g → ↑f x = ↑g x
hx : ↑f x = ↑g x
hx' : x ∈ support f
hx'' : x ∈ support g
⊢ f = g
[PROOFSTEP]
have : f.support ⊆ g.support := by
intro y hy
obtain ⟨k, rfl⟩ := hf.exists_pow_eq (mem_support.mp hx') (mem_support.mp hy)
rwa [pow_eq_on_of_mem_support h _ _ (mem_inter_of_mem hx' hx''), pow_apply_mem_support]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
hg : IsCycle g
h : ∀ (x : α), x ∈ support f ∩ support g → ↑f x = ↑g x
hx : ↑f x = ↑g x
hx' : x ∈ support f
hx'' : x ∈ support g
⊢ support f ⊆ support g
[PROOFSTEP]
intro y hy
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y✝ : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
hg : IsCycle g
h : ∀ (x : α), x ∈ support f ∩ support g → ↑f x = ↑g x
hx : ↑f x = ↑g x
hx' : x ∈ support f
hx'' : x ∈ support g
y : α
hy : y ∈ support f
⊢ y ∈ support g
[PROOFSTEP]
obtain ⟨k, rfl⟩ := hf.exists_pow_eq (mem_support.mp hx') (mem_support.mp hy)
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
hg : IsCycle g
h : ∀ (x : α), x ∈ support f ∩ support g → ↑f x = ↑g x
hx : ↑f x = ↑g x
hx' : x ∈ support f
hx'' : x ∈ support g
k : ℕ
hy : ↑(f ^ k) x ∈ support f
⊢ ↑(f ^ k) x ∈ support g
[PROOFSTEP]
rwa [pow_eq_on_of_mem_support h _ _ (mem_inter_of_mem hx' hx''), pow_apply_mem_support]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
hg : IsCycle g
h : ∀ (x : α), x ∈ support f ∩ support g → ↑f x = ↑g x
hx : ↑f x = ↑g x
hx' : x ∈ support f
hx'' : x ∈ support g
this : support f ⊆ support g
⊢ f = g
[PROOFSTEP]
rw [(inter_eq_left_iff_subset _ _).mpr this] at h
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
hg : IsCycle g
h : ∀ (x : α), x ∈ support f → ↑f x = ↑g x
hx : ↑f x = ↑g x
hx' : x ∈ support f
hx'' : x ∈ support g
this : support f ⊆ support g
⊢ f = g
[PROOFSTEP]
exact hf.support_congr hg this h
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
n : ℕ
⊢ support (f ^ n) = support f ↔ ¬orderOf f ∣ n
[PROOFSTEP]
rw [orderOf_dvd_iff_pow_eq_one]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
n : ℕ
⊢ support (f ^ n) = support f ↔ ¬f ^ n = 1
[PROOFSTEP]
constructor
[GOAL]
case mp
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
n : ℕ
⊢ support (f ^ n) = support f → ¬f ^ n = 1
[PROOFSTEP]
intro h H
[GOAL]
case mp
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
n : ℕ
h : support (f ^ n) = support f
H : f ^ n = 1
⊢ False
[PROOFSTEP]
refine' hf.ne_one _
[GOAL]
case mp
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
n : ℕ
h : support (f ^ n) = support f
H : f ^ n = 1
⊢ f = 1
[PROOFSTEP]
rw [← support_eq_empty_iff, ← h, H, support_one]
[GOAL]
case mpr
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
n : ℕ
⊢ ¬f ^ n = 1 → support (f ^ n) = support f
[PROOFSTEP]
intro H
[GOAL]
case mpr
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
n : ℕ
H : ¬f ^ n = 1
⊢ support (f ^ n) = support f
[PROOFSTEP]
apply le_antisymm (support_pow_le _ n) _
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
n : ℕ
H : ¬f ^ n = 1
⊢ support f ≤ support (f ^ n)
[PROOFSTEP]
intro x hx
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
n : ℕ
H : ¬f ^ n = 1
x : α
hx : x ∈ support f
⊢ x ∈ support (f ^ n)
[PROOFSTEP]
contrapose! H
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
n : ℕ
x : α
hx : x ∈ support f
H : ¬x ∈ support (f ^ n)
⊢ f ^ n = 1
[PROOFSTEP]
ext z
[GOAL]
case H
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
n : ℕ
x : α
hx : x ∈ support f
H : ¬x ∈ support (f ^ n)
z : α
⊢ ↑(f ^ n) z = ↑1 z
[PROOFSTEP]
by_cases hz : f z = z
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
n : ℕ
x : α
hx : x ∈ support f
H : ¬x ∈ support (f ^ n)
z : α
hz : ↑f z = z
⊢ ↑(f ^ n) z = ↑1 z
[PROOFSTEP]
rw [pow_apply_eq_self_of_apply_eq_self hz, one_apply]
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x✝ y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
n : ℕ
x : α
hx : x ∈ support f
H : ¬x ∈ support (f ^ n)
z : α
hz : ¬↑f z = z
⊢ ↑(f ^ n) z = ↑1 z
[PROOFSTEP]
obtain ⟨k, rfl⟩ := hf.exists_pow_eq hz (mem_support.mp hx)
[GOAL]
case neg.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
n : ℕ
z : α
hz : ¬↑f z = z
k : ℕ
hx : ↑(f ^ k) z ∈ support f
H : ¬↑(f ^ k) z ∈ support (f ^ n)
⊢ ↑(f ^ n) z = ↑1 z
[PROOFSTEP]
apply (f ^ k).injective
[GOAL]
case neg.intro.a
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
n : ℕ
z : α
hz : ¬↑f z = z
k : ℕ
hx : ↑(f ^ k) z ∈ support f
H : ¬↑(f ^ k) z ∈ support (f ^ n)
⊢ ↑(f ^ k) (↑(f ^ n) z) = ↑(f ^ k) (↑1 z)
[PROOFSTEP]
rw [← mul_apply, (Commute.pow_pow_self _ _ _).eq, mul_apply]
[GOAL]
case neg.intro.a
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
x y : α
inst✝¹ : DecidableEq α
inst✝ : Fintype α
hf : IsCycle f
n : ℕ
z : α
hz : ¬↑f z = z
k : ℕ
hx : ↑(f ^ k) z ∈ support f
H : ¬↑(f ^ k) z ∈ support (f ^ n)
⊢ ↑(f ^ n) (↑(f ^ k) z) = ↑(f ^ k) (↑1 z)
[PROOFSTEP]
simpa using H
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
⊢ IsCycle (f ^ n) ↔ Nat.coprime n (orderOf f)
[PROOFSTEP]
classical
cases nonempty_fintype β
constructor
· intro h
have hr : support (f ^ n) = support f := by
rw [hf.support_pow_eq_iff]
rintro ⟨k, rfl⟩
refine' h.ne_one _
simp [pow_mul, pow_orderOf_eq_one]
have : orderOf (f ^ n) = orderOf f := by rw [h.orderOf, hr, hf.orderOf]
rw [orderOf_pow, Nat.div_eq_self] at this
cases' this with h
· exact absurd h (orderOf_pos _).ne'
· rwa [Nat.coprime_iff_gcd_eq_one, Nat.gcd_comm]
· intro h
obtain ⟨m, hm⟩ := exists_pow_eq_self_of_coprime h
have hf' : IsCycle ((f ^ n) ^ m) := by rwa [hm]
refine' hf'.of_pow fun x hx => _
rw [hm]
exact support_pow_le _ n hx
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
⊢ IsCycle (f ^ n) ↔ Nat.coprime n (orderOf f)
[PROOFSTEP]
cases nonempty_fintype β
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
⊢ IsCycle (f ^ n) ↔ Nat.coprime n (orderOf f)
[PROOFSTEP]
constructor
[GOAL]
case intro.mp
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
⊢ IsCycle (f ^ n) → Nat.coprime n (orderOf f)
[PROOFSTEP]
intro h
[GOAL]
case intro.mp
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
h : IsCycle (f ^ n)
⊢ Nat.coprime n (orderOf f)
[PROOFSTEP]
have hr : support (f ^ n) = support f := by
rw [hf.support_pow_eq_iff]
rintro ⟨k, rfl⟩
refine' h.ne_one _
simp [pow_mul, pow_orderOf_eq_one]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
h : IsCycle (f ^ n)
⊢ support (f ^ n) = support f
[PROOFSTEP]
rw [hf.support_pow_eq_iff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
h : IsCycle (f ^ n)
⊢ ¬orderOf f ∣ n
[PROOFSTEP]
rintro ⟨k, rfl⟩
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
val✝ : Fintype β
k : ℕ
h : IsCycle (f ^ (orderOf f * k))
⊢ False
[PROOFSTEP]
refine' h.ne_one _
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
val✝ : Fintype β
k : ℕ
h : IsCycle (f ^ (orderOf f * k))
⊢ f ^ (orderOf f * k) = 1
[PROOFSTEP]
simp [pow_mul, pow_orderOf_eq_one]
[GOAL]
case intro.mp
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
h : IsCycle (f ^ n)
hr : support (f ^ n) = support f
⊢ Nat.coprime n (orderOf f)
[PROOFSTEP]
have : orderOf (f ^ n) = orderOf f := by rw [h.orderOf, hr, hf.orderOf]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
h : IsCycle (f ^ n)
hr : support (f ^ n) = support f
⊢ orderOf (f ^ n) = orderOf f
[PROOFSTEP]
rw [h.orderOf, hr, hf.orderOf]
[GOAL]
case intro.mp
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
h : IsCycle (f ^ n)
hr : support (f ^ n) = support f
this : orderOf (f ^ n) = orderOf f
⊢ Nat.coprime n (orderOf f)
[PROOFSTEP]
rw [orderOf_pow, Nat.div_eq_self] at this
[GOAL]
case intro.mp
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
h : IsCycle (f ^ n)
hr : support (f ^ n) = support f
this : orderOf f = 0 ∨ Nat.gcd (orderOf f) n = 1
⊢ Nat.coprime n (orderOf f)
[PROOFSTEP]
cases' this with h
[GOAL]
case intro.mp.inl
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
h✝ : IsCycle (f ^ n)
hr : support (f ^ n) = support f
h : orderOf f = 0
⊢ Nat.coprime n (orderOf f)
[PROOFSTEP]
exact absurd h (orderOf_pos _).ne'
[GOAL]
case intro.mp.inr
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
h : IsCycle (f ^ n)
hr : support (f ^ n) = support f
h✝ : Nat.gcd (orderOf f) n = 1
⊢ Nat.coprime n (orderOf f)
[PROOFSTEP]
rwa [Nat.coprime_iff_gcd_eq_one, Nat.gcd_comm]
[GOAL]
case intro.mpr
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
⊢ Nat.coprime n (orderOf f) → IsCycle (f ^ n)
[PROOFSTEP]
intro h
[GOAL]
case intro.mpr
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
h : Nat.coprime n (orderOf f)
⊢ IsCycle (f ^ n)
[PROOFSTEP]
obtain ⟨m, hm⟩ := exists_pow_eq_self_of_coprime h
[GOAL]
case intro.mpr.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
h : Nat.coprime n (orderOf f)
m : ℕ
hm : (f ^ n) ^ m = f
⊢ IsCycle (f ^ n)
[PROOFSTEP]
have hf' : IsCycle ((f ^ n) ^ m) := by rwa [hm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
h : Nat.coprime n (orderOf f)
m : ℕ
hm : (f ^ n) ^ m = f
⊢ IsCycle ((f ^ n) ^ m)
[PROOFSTEP]
rwa [hm]
[GOAL]
case intro.mpr.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
h : Nat.coprime n (orderOf f)
m : ℕ
hm : (f ^ n) ^ m = f
hf' : IsCycle ((f ^ n) ^ m)
⊢ IsCycle (f ^ n)
[PROOFSTEP]
refine' hf'.of_pow fun x hx => _
[GOAL]
case intro.mpr.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
h : Nat.coprime n (orderOf f)
m : ℕ
hm : (f ^ n) ^ m = f
hf' : IsCycle ((f ^ n) ^ m)
x : β
hx : x ∈ support (f ^ n)
⊢ x ∈ support ((f ^ n) ^ m)
[PROOFSTEP]
rw [hm]
[GOAL]
case intro.mpr.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
h : Nat.coprime n (orderOf f)
m : ℕ
hm : (f ^ n) ^ m = f
hf' : IsCycle ((f ^ n) ^ m)
x : β
hx : x ∈ support (f ^ n)
⊢ x ∈ support f
[PROOFSTEP]
exact support_pow_le _ n hx
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
⊢ f ^ n = 1 ↔ ∃ x, ↑f x ≠ x ∧ ↑(f ^ n) x = x
[PROOFSTEP]
classical
cases nonempty_fintype β
constructor
· intro h
obtain ⟨x, hx, -⟩ := id hf
exact ⟨x, hx, by simp [h]⟩
· rintro ⟨x, hx, hx'⟩
by_cases h : support (f ^ n) = support f
· rw [← mem_support, ← h, mem_support] at hx
contradiction
· rw [hf.support_pow_eq_iff, Classical.not_not] at h
obtain ⟨k, rfl⟩ := h
rw [pow_mul, pow_orderOf_eq_one, one_pow]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
⊢ f ^ n = 1 ↔ ∃ x, ↑f x ≠ x ∧ ↑(f ^ n) x = x
[PROOFSTEP]
cases nonempty_fintype β
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
⊢ f ^ n = 1 ↔ ∃ x, ↑f x ≠ x ∧ ↑(f ^ n) x = x
[PROOFSTEP]
constructor
[GOAL]
case intro.mp
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
⊢ f ^ n = 1 → ∃ x, ↑f x ≠ x ∧ ↑(f ^ n) x = x
[PROOFSTEP]
intro h
[GOAL]
case intro.mp
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
h : f ^ n = 1
⊢ ∃ x, ↑f x ≠ x ∧ ↑(f ^ n) x = x
[PROOFSTEP]
obtain ⟨x, hx, -⟩ := id hf
[GOAL]
case intro.mp.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
h : f ^ n = 1
x : β
hx : ↑f x ≠ x
⊢ ∃ x, ↑f x ≠ x ∧ ↑(f ^ n) x = x
[PROOFSTEP]
exact ⟨x, hx, by simp [h]⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
h : f ^ n = 1
x : β
hx : ↑f x ≠ x
⊢ ↑(f ^ n) x = x
[PROOFSTEP]
simp [h]
[GOAL]
case intro.mpr
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
⊢ (∃ x, ↑f x ≠ x ∧ ↑(f ^ n) x = x) → f ^ n = 1
[PROOFSTEP]
rintro ⟨x, hx, hx'⟩
[GOAL]
case intro.mpr.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
x : β
hx : ↑f x ≠ x
hx' : ↑(f ^ n) x = x
⊢ f ^ n = 1
[PROOFSTEP]
by_cases h : support (f ^ n) = support f
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
x : β
hx : ↑f x ≠ x
hx' : ↑(f ^ n) x = x
h : support (f ^ n) = support f
⊢ f ^ n = 1
[PROOFSTEP]
rw [← mem_support, ← h, mem_support] at hx
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
x : β
hx✝ : ↑f x ≠ x
hx : ↑(f ^ n) x ≠ x
hx' : ↑(f ^ n) x = x
h : support (f ^ n) = support f
⊢ f ^ n = 1
[PROOFSTEP]
contradiction
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
x : β
hx : ↑f x ≠ x
hx' : ↑(f ^ n) x = x
h : ¬support (f ^ n) = support f
⊢ f ^ n = 1
[PROOFSTEP]
rw [hf.support_pow_eq_iff, Classical.not_not] at h
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
n : ℕ
val✝ : Fintype β
x : β
hx : ↑f x ≠ x
hx' : ↑(f ^ n) x = x
h : orderOf f ∣ n
⊢ f ^ n = 1
[PROOFSTEP]
obtain ⟨k, rfl⟩ := h
[GOAL]
case neg.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
val✝ : Fintype β
x : β
hx : ↑f x ≠ x
k : ℕ
hx' : ↑(f ^ (orderOf f * k)) x = x
⊢ f ^ (orderOf f * k) = 1
[PROOFSTEP]
rw [pow_mul, pow_orderOf_eq_one, one_pow]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
a b : ℕ
⊢ f ^ a = f ^ b ↔ ∃ x, ↑f x ≠ x ∧ ↑(f ^ a) x = ↑(f ^ b) x
[PROOFSTEP]
classical
cases nonempty_fintype β
constructor
· intro h
obtain ⟨x, hx, -⟩ := id hf
exact ⟨x, hx, by simp [h]⟩
· rintro ⟨x, hx, hx'⟩
wlog hab : a ≤ b generalizing a b
· exact (this hx'.symm (le_of_not_le hab)).symm
suffices f ^ (b - a) = 1 by
rw [pow_sub _ hab, mul_inv_eq_one] at this
rw [this]
rw [hf.pow_eq_one_iff]
by_cases hfa : (f ^ a) x ∈ f.support
· refine' ⟨(f ^ a) x, mem_support.mp hfa, _⟩
simp only [pow_sub _ hab, Equiv.Perm.coe_mul, Function.comp_apply, inv_apply_self, ← hx']
· have h := @Equiv.Perm.zpow_apply_comm _ f 1 a x
simp only [zpow_one, zpow_ofNat] at h
rw [not_mem_support, h, Function.Injective.eq_iff (f ^ a).injective] at hfa
contradiction
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
a b : ℕ
⊢ f ^ a = f ^ b ↔ ∃ x, ↑f x ≠ x ∧ ↑(f ^ a) x = ↑(f ^ b) x
[PROOFSTEP]
cases nonempty_fintype β
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
a b : ℕ
val✝ : Fintype β
⊢ f ^ a = f ^ b ↔ ∃ x, ↑f x ≠ x ∧ ↑(f ^ a) x = ↑(f ^ b) x
[PROOFSTEP]
constructor
[GOAL]
case intro.mp
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
a b : ℕ
val✝ : Fintype β
⊢ f ^ a = f ^ b → ∃ x, ↑f x ≠ x ∧ ↑(f ^ a) x = ↑(f ^ b) x
[PROOFSTEP]
intro h
[GOAL]
case intro.mp
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
a b : ℕ
val✝ : Fintype β
h : f ^ a = f ^ b
⊢ ∃ x, ↑f x ≠ x ∧ ↑(f ^ a) x = ↑(f ^ b) x
[PROOFSTEP]
obtain ⟨x, hx, -⟩ := id hf
[GOAL]
case intro.mp.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
a b : ℕ
val✝ : Fintype β
h : f ^ a = f ^ b
x : β
hx : ↑f x ≠ x
⊢ ∃ x, ↑f x ≠ x ∧ ↑(f ^ a) x = ↑(f ^ b) x
[PROOFSTEP]
exact ⟨x, hx, by simp [h]⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
a b : ℕ
val✝ : Fintype β
h : f ^ a = f ^ b
x : β
hx : ↑f x ≠ x
⊢ ↑(f ^ a) x = ↑(f ^ b) x
[PROOFSTEP]
simp [h]
[GOAL]
case intro.mpr
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
a b : ℕ
val✝ : Fintype β
⊢ (∃ x, ↑f x ≠ x ∧ ↑(f ^ a) x = ↑(f ^ b) x) → f ^ a = f ^ b
[PROOFSTEP]
rintro ⟨x, hx, hx'⟩
[GOAL]
case intro.mpr.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
a b : ℕ
val✝ : Fintype β
x : β
hx : ↑f x ≠ x
hx' : ↑(f ^ a) x = ↑(f ^ b) x
⊢ f ^ a = f ^ b
[PROOFSTEP]
wlog hab : a ≤ b generalizing a b
[GOAL]
case intro.mpr.intro.intro.inr
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
a b : ℕ
val✝ : Fintype β
x : β
hx : ↑f x ≠ x
hx' : ↑(f ^ a) x = ↑(f ^ b) x
this : ∀ {a b : ℕ}, ↑(f ^ a) x = ↑(f ^ b) x → a ≤ b → f ^ a = f ^ b
hab : ¬a ≤ b
⊢ f ^ a = f ^ b
[PROOFSTEP]
exact (this hx'.symm (le_of_not_le hab)).symm
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
val✝ : Fintype β
x : β
hx : ↑f x ≠ x
a b : ℕ
hx' : ↑(f ^ a) x = ↑(f ^ b) x
hab : a ≤ b
⊢ f ^ a = f ^ b
[PROOFSTEP]
suffices f ^ (b - a) = 1 by
rw [pow_sub _ hab, mul_inv_eq_one] at this
rw [this]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
val✝ : Fintype β
x : β
hx : ↑f x ≠ x
a b : ℕ
hx' : ↑(f ^ a) x = ↑(f ^ b) x
hab : a ≤ b
this : f ^ (b - a) = 1
⊢ f ^ a = f ^ b
[PROOFSTEP]
rw [pow_sub _ hab, mul_inv_eq_one] at this
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
val✝ : Fintype β
x : β
hx : ↑f x ≠ x
a b : ℕ
hx' : ↑(f ^ a) x = ↑(f ^ b) x
hab : a ≤ b
this : f ^ b = f ^ a
⊢ f ^ a = f ^ b
[PROOFSTEP]
rw [this]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
val✝ : Fintype β
x : β
hx : ↑f x ≠ x
a b : ℕ
hx' : ↑(f ^ a) x = ↑(f ^ b) x
hab : a ≤ b
⊢ f ^ (b - a) = 1
[PROOFSTEP]
rw [hf.pow_eq_one_iff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
val✝ : Fintype β
x : β
hx : ↑f x ≠ x
a b : ℕ
hx' : ↑(f ^ a) x = ↑(f ^ b) x
hab : a ≤ b
⊢ ∃ x, ↑f x ≠ x ∧ ↑(f ^ (b - a)) x = x
[PROOFSTEP]
by_cases hfa : (f ^ a) x ∈ f.support
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
val✝ : Fintype β
x : β
hx : ↑f x ≠ x
a b : ℕ
hx' : ↑(f ^ a) x = ↑(f ^ b) x
hab : a ≤ b
hfa : ↑(f ^ a) x ∈ support f
⊢ ∃ x, ↑f x ≠ x ∧ ↑(f ^ (b - a)) x = x
[PROOFSTEP]
refine' ⟨(f ^ a) x, mem_support.mp hfa, _⟩
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
val✝ : Fintype β
x : β
hx : ↑f x ≠ x
a b : ℕ
hx' : ↑(f ^ a) x = ↑(f ^ b) x
hab : a ≤ b
hfa : ↑(f ^ a) x ∈ support f
⊢ ↑(f ^ (b - a)) (↑(f ^ a) x) = ↑(f ^ a) x
[PROOFSTEP]
simp only [pow_sub _ hab, Equiv.Perm.coe_mul, Function.comp_apply, inv_apply_self, ← hx']
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
val✝ : Fintype β
x : β
hx : ↑f x ≠ x
a b : ℕ
hx' : ↑(f ^ a) x = ↑(f ^ b) x
hab : a ≤ b
hfa : ¬↑(f ^ a) x ∈ support f
⊢ ∃ x, ↑f x ≠ x ∧ ↑(f ^ (b - a)) x = x
[PROOFSTEP]
have h := @Equiv.Perm.zpow_apply_comm _ f 1 a x
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
val✝ : Fintype β
x : β
hx : ↑f x ≠ x
a b : ℕ
hx' : ↑(f ^ a) x = ↑(f ^ b) x
hab : a ≤ b
hfa : ¬↑(f ^ a) x ∈ support f
h : ↑(f ^ 1) (↑(f ^ ↑a) x) = ↑(f ^ ↑a) (↑(f ^ 1) x)
⊢ ∃ x, ↑f x ≠ x ∧ ↑(f ^ (b - a)) x = x
[PROOFSTEP]
simp only [zpow_one, zpow_ofNat] at h
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
val✝ : Fintype β
x : β
hx : ↑f x ≠ x
a b : ℕ
hx' : ↑(f ^ a) x = ↑(f ^ b) x
hab : a ≤ b
hfa : ¬↑(f ^ a) x ∈ support f
h : ↑f (↑(f ^ a) x) = ↑(f ^ a) (↑f x)
⊢ ∃ x, ↑f x ≠ x ∧ ↑(f ^ (b - a)) x = x
[PROOFSTEP]
rw [not_mem_support, h, Function.Injective.eq_iff (f ^ a).injective] at hfa
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x✝ y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
val✝ : Fintype β
x : β
hx : ↑f x ≠ x
a b : ℕ
hx' : ↑(f ^ a) x = ↑(f ^ b) x
hab : a ≤ b
hfa : ↑f x = x
h : ↑f (↑(f ^ a) x) = ↑(f ^ a) (↑f x)
⊢ ∃ x, ↑f x ≠ x ∧ ↑(f ^ (b - a)) x = x
[PROOFSTEP]
contradiction
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
hf' : Nat.Prime (orderOf f)
n : ℕ
hn : 0 < n
hn' : n < orderOf f
⊢ IsCycle (f ^ n)
[PROOFSTEP]
classical
cases nonempty_fintype β
have : n.coprime (orderOf f) := by
refine' Nat.coprime.symm _
rw [Nat.Prime.coprime_iff_not_dvd hf']
exact Nat.not_dvd_of_pos_of_lt hn hn'
obtain ⟨m, hm⟩ := exists_pow_eq_self_of_coprime this
have hf'' := hf
rw [← hm] at hf''
refine' hf''.of_pow _
rw [hm]
exact support_pow_le f n
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
hf' : Nat.Prime (orderOf f)
n : ℕ
hn : 0 < n
hn' : n < orderOf f
⊢ IsCycle (f ^ n)
[PROOFSTEP]
cases nonempty_fintype β
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
hf' : Nat.Prime (orderOf f)
n : ℕ
hn : 0 < n
hn' : n < orderOf f
val✝ : Fintype β
⊢ IsCycle (f ^ n)
[PROOFSTEP]
have : n.coprime (orderOf f) := by
refine' Nat.coprime.symm _
rw [Nat.Prime.coprime_iff_not_dvd hf']
exact Nat.not_dvd_of_pos_of_lt hn hn'
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
hf' : Nat.Prime (orderOf f)
n : ℕ
hn : 0 < n
hn' : n < orderOf f
val✝ : Fintype β
⊢ Nat.coprime n (orderOf f)
[PROOFSTEP]
refine' Nat.coprime.symm _
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
hf' : Nat.Prime (orderOf f)
n : ℕ
hn : 0 < n
hn' : n < orderOf f
val✝ : Fintype β
⊢ Nat.coprime (orderOf f) n
[PROOFSTEP]
rw [Nat.Prime.coprime_iff_not_dvd hf']
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
hf' : Nat.Prime (orderOf f)
n : ℕ
hn : 0 < n
hn' : n < orderOf f
val✝ : Fintype β
⊢ ¬orderOf f ∣ n
[PROOFSTEP]
exact Nat.not_dvd_of_pos_of_lt hn hn'
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
hf' : Nat.Prime (orderOf f)
n : ℕ
hn : 0 < n
hn' : n < orderOf f
val✝ : Fintype β
this : Nat.coprime n (orderOf f)
⊢ IsCycle (f ^ n)
[PROOFSTEP]
obtain ⟨m, hm⟩ := exists_pow_eq_self_of_coprime this
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
hf' : Nat.Prime (orderOf f)
n : ℕ
hn : 0 < n
hn' : n < orderOf f
val✝ : Fintype β
this : Nat.coprime n (orderOf f)
m : ℕ
hm : (f ^ n) ^ m = f
⊢ IsCycle (f ^ n)
[PROOFSTEP]
have hf'' := hf
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
hf' : Nat.Prime (orderOf f)
n : ℕ
hn : 0 < n
hn' : n < orderOf f
val✝ : Fintype β
this : Nat.coprime n (orderOf f)
m : ℕ
hm : (f ^ n) ^ m = f
hf'' : IsCycle f
⊢ IsCycle (f ^ n)
[PROOFSTEP]
rw [← hm] at hf''
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
hf' : Nat.Prime (orderOf f)
n : ℕ
hn : 0 < n
hn' : n < orderOf f
val✝ : Fintype β
this : Nat.coprime n (orderOf f)
m : ℕ
hm : (f ^ n) ^ m = f
hf'' : IsCycle ((f ^ n) ^ m)
⊢ IsCycle (f ^ n)
[PROOFSTEP]
refine' hf''.of_pow _
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
hf' : Nat.Prime (orderOf f)
n : ℕ
hn : 0 < n
hn' : n < orderOf f
val✝ : Fintype β
this : Nat.coprime n (orderOf f)
m : ℕ
hm : (f ^ n) ^ m = f
hf'' : IsCycle ((f ^ n) ^ m)
⊢ support (f ^ n) ⊆ support ((f ^ n) ^ m)
[PROOFSTEP]
rw [hm]
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
x y : α
inst✝² : DecidableEq α
inst✝¹ : Fintype α
inst✝ : Finite β
f : Perm β
hf : IsCycle f
hf' : Nat.Prime (orderOf f)
n : ℕ
hn : 0 < n
hn' : n < orderOf f
val✝ : Fintype β
this : Nat.coprime n (orderOf f)
m : ℕ
hm : (f ^ n) ^ m = f
hf'' : IsCycle ((f ^ n) ^ m)
⊢ support (f ^ n) ⊆ support f
[PROOFSTEP]
exact support_pow_le f n
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
⊢ IsCycleOn f ∅
[PROOFSTEP]
simp [IsCycleOn, Set.bijOn_empty]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
⊢ IsCycleOn 1 s ↔ Set.Subsingleton s
[PROOFSTEP]
simp [IsCycleOn, Set.bijOn_id, Set.Subsingleton]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
⊢ IsCycleOn f {a} ↔ ↑f a = a
[PROOFSTEP]
simp [IsCycleOn, SameCycle.rfl]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
⊢ IsCycleOn f⁻¹ s ↔ IsCycleOn f s
[PROOFSTEP]
simp only [IsCycleOn, sameCycle_inv, and_congr_left_iff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
⊢ (∀ ⦃x : α⦄, x ∈ s → ∀ ⦃y : α⦄, y ∈ s → SameCycle f x y) → (Set.BijOn (↑f⁻¹) s s ↔ Set.BijOn (↑f) s s)
[PROOFSTEP]
exact fun _ ↦ ⟨fun h ↦ Set.BijOn.perm_inv h, fun h ↦ Set.BijOn.perm_inv h⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x✝ y✝ : α
h : IsCycleOn f s
x : α
hx : x ∈ ↑g '' s
y : α
hy : y ∈ ↑g '' s
⊢ SameCycle (g * f * g⁻¹) x y
[PROOFSTEP]
rw [← preimage_inv] at hx hy
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x✝ y✝ : α
h : IsCycleOn f s
x : α
hx : x ∈ ↑g⁻¹ ⁻¹' s
y : α
hy : y ∈ ↑g⁻¹ ⁻¹' s
⊢ SameCycle (g * f * g⁻¹) x y
[PROOFSTEP]
convert Equiv.Perm.SameCycle.conj (h.2 hx hy) (g := g)
[GOAL]
case h.e'_3
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x✝ y✝ : α
h : IsCycleOn f s
x : α
hx : x ∈ ↑g⁻¹ ⁻¹' s
y : α
hy : y ∈ ↑g⁻¹ ⁻¹' s
⊢ x = ↑g (↑g⁻¹ x)
[PROOFSTEP]
rw [apply_inv_self]
[GOAL]
case h.e'_4
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x✝ y✝ : α
h : IsCycleOn f s
x : α
hx : x ∈ ↑g⁻¹ ⁻¹' s
y : α
hy : y ∈ ↑g⁻¹ ⁻¹' s
⊢ y = ↑g (↑g⁻¹ y)
[PROOFSTEP]
rw [apply_inv_self]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
inst✝ : DecidableEq α
hab : a ≠ b
⊢ a ∈ {a, b}
[PROOFSTEP]
simp
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
inst✝ : DecidableEq α
hab : a ≠ b
⊢ b ∈ {a, b}
[PROOFSTEP]
simp
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x✝ y✝ : α
inst✝ : DecidableEq α
hab : a ≠ b
x : α
hx : x ∈ {a, b}
y : α
hy : y ∈ {a, b}
⊢ SameCycle (swap a b) x y
[PROOFSTEP]
rw [Set.mem_insert_iff, Set.mem_singleton_iff] at hx hy
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x✝ y✝ : α
inst✝ : DecidableEq α
hab : a ≠ b
x : α
hx : x = a ∨ x = b
y : α
hy : y = a ∨ y = b
⊢ SameCycle (swap a b) x y
[PROOFSTEP]
obtain rfl | rfl := hx
[GOAL]
case inl
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
b x✝ y✝ : α
inst✝ : DecidableEq α
x y : α
hab : x ≠ b
hy : y = x ∨ y = b
⊢ SameCycle (swap x b) x y
[PROOFSTEP]
obtain rfl | rfl := hy
[GOAL]
case inr
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a x✝ y✝ : α
inst✝ : DecidableEq α
x y : α
hab : a ≠ x
hy : y = a ∨ y = x
⊢ SameCycle (swap a x) x y
[PROOFSTEP]
obtain rfl | rfl := hy
[GOAL]
case inl.inl
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
b x y✝ : α
inst✝ : DecidableEq α
y : α
hab : y ≠ b
⊢ SameCycle (swap y b) y y
[PROOFSTEP]
exact ⟨0, by rw [zpow_zero, coe_one, id.def]⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
b x y✝ : α
inst✝ : DecidableEq α
y : α
hab : y ≠ b
⊢ ↑(swap y b ^ 0) y = y
[PROOFSTEP]
rw [zpow_zero, coe_one, id.def]
[GOAL]
case inl.inr
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
x✝ y✝ : α
inst✝ : DecidableEq α
x y : α
hab : x ≠ y
⊢ SameCycle (swap x y) x y
[PROOFSTEP]
exact ⟨1, by rw [zpow_one, swap_apply_left]⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
x✝ y✝ : α
inst✝ : DecidableEq α
x y : α
hab : x ≠ y
⊢ ↑(swap x y ^ 1) x = y
[PROOFSTEP]
rw [zpow_one, swap_apply_left]
[GOAL]
case inr.inl
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
x✝ y✝ : α
inst✝ : DecidableEq α
x y : α
hab : y ≠ x
⊢ SameCycle (swap y x) x y
[PROOFSTEP]
exact ⟨1, by rw [zpow_one, swap_apply_right]⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
x✝ y✝ : α
inst✝ : DecidableEq α
x y : α
hab : y ≠ x
⊢ ↑(swap y x ^ 1) x = y
[PROOFSTEP]
rw [zpow_one, swap_apply_right]
[GOAL]
case inr.inr
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a x y✝ : α
inst✝ : DecidableEq α
y : α
hab : a ≠ y
⊢ SameCycle (swap a y) y y
[PROOFSTEP]
exact ⟨0, by rw [zpow_zero, coe_one, id.def]⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a x y✝ : α
inst✝ : DecidableEq α
y : α
hab : a ≠ y
⊢ ↑(swap a y ^ 0) y = y
[PROOFSTEP]
rw [zpow_zero, coe_one, id.def]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
hf : IsCycleOn f s
hs : Set.Nontrivial s
ha : a ∈ s
⊢ ↑f a ≠ a
[PROOFSTEP]
obtain ⟨b, hb, hba⟩ := hs.exists_ne a
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b✝ x y : α
hf : IsCycleOn f s
hs : Set.Nontrivial s
ha : a ∈ s
b : α
hb : b ∈ s
hba : b ≠ a
⊢ ↑f a ≠ a
[PROOFSTEP]
obtain ⟨n, rfl⟩ := hf.2 ha hb
[GOAL]
case intro.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
hf : IsCycleOn f s
hs : Set.Nontrivial s
ha : a ∈ s
n : ℤ
hb : ↑(f ^ n) a ∈ s
hba : ↑(f ^ n) a ≠ a
⊢ ↑f a ≠ a
[PROOFSTEP]
exact fun h => hba (IsFixedPt.perm_zpow h n)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
⊢ IsCycle f ↔ ∃ s, Set.Nontrivial s ∧ IsCycleOn f s ∧ ∀ ⦃x : α⦄, ¬IsFixedPt (↑f) x → x ∈ s
[PROOFSTEP]
refine' ⟨fun hf => ⟨{x | f x ≠ x}, _, hf.isCycleOn, fun _ => id⟩, _⟩
[GOAL]
case refine'_1
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
hf : IsCycle f
⊢ Set.Nontrivial {x | ↑f x ≠ x}
[PROOFSTEP]
obtain ⟨a, ha⟩ := hf
[GOAL]
case refine'_1.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a✝ b x y a : α
ha : ↑f a ≠ a ∧ ∀ ⦃y : α⦄, ↑f y ≠ y → SameCycle f a y
⊢ Set.Nontrivial {x | ↑f x ≠ x}
[PROOFSTEP]
exact ⟨f a, f.injective.ne ha.1, a, ha.1, ha.1⟩
[GOAL]
case refine'_2
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
⊢ (∃ s, Set.Nontrivial s ∧ IsCycleOn f s ∧ ∀ ⦃x : α⦄, ¬IsFixedPt (↑f) x → x ∈ s) → IsCycle f
[PROOFSTEP]
rintro ⟨s, hs, hf, hsf⟩
[GOAL]
case refine'_2.intro.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s✝ t : Set α
a b x y : α
s : Set α
hs : Set.Nontrivial s
hf : IsCycleOn f s
hsf : ∀ ⦃x : α⦄, ¬IsFixedPt (↑f) x → x ∈ s
⊢ IsCycle f
[PROOFSTEP]
obtain ⟨a, ha⟩ := hs.nonempty
[GOAL]
case refine'_2.intro.intro.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s✝ t : Set α
a✝ b x y : α
s : Set α
hs : Set.Nontrivial s
hf : IsCycleOn f s
hsf : ∀ ⦃x : α⦄, ¬IsFixedPt (↑f) x → x ∈ s
a : α
ha : a ∈ s
⊢ IsCycle f
[PROOFSTEP]
exact ⟨a, hf.apply_ne hs ha, fun b hb => hf.2 ha <| hsf hb⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
hf : IsCycleOn f s
hx : ↑f x ∈ s
⊢ x ∈ s
[PROOFSTEP]
convert hf.1.perm_inv.1 hx
[GOAL]
case h.e'_4
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
hf : IsCycleOn f s
hx : ↑f x ∈ s
⊢ x = ↑f⁻¹ (↑f x)
[PROOFSTEP]
rw [inv_apply_self]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
hf : IsCycleOn f s
hs : Set.Nontrivial s
⊢ IsCycle (subtypePerm f (_ : ∀ (x : α), x ∈ s ↔ ↑f x ∈ s))
[PROOFSTEP]
obtain ⟨a, ha⟩ := hs.nonempty
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a✝ b x y : α
hf : IsCycleOn f s
hs : Set.Nontrivial s
a : α
ha : a ∈ s
⊢ IsCycle (subtypePerm f (_ : ∀ (x : α), x ∈ s ↔ ↑f x ∈ s))
[PROOFSTEP]
exact ⟨⟨a, ha⟩, ne_of_apply_ne ((↑) : s → α) (hf.apply_ne hs ha), fun b _ => (hf.2 (⟨a, ha⟩ : s).2 b.2).subtypePerm⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
hf : IsCycleOn f s
⊢ IsCycleOn (subtypePerm f (_ : ∀ (x : α), x ∈ s ↔ ↑f x ∈ s)) _root_.Set.univ
[PROOFSTEP]
obtain hs | hs := s.subsingleton_or_nontrivial
[GOAL]
case inl
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
hf : IsCycleOn f s
hs : Set.Subsingleton s
⊢ IsCycleOn (subtypePerm f (_ : ∀ (x : α), x ∈ s ↔ ↑f x ∈ s)) _root_.Set.univ
[PROOFSTEP]
haveI := hs.coe_sort
[GOAL]
case inl
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
hf : IsCycleOn f s
hs : Set.Subsingleton s
this : Subsingleton ↑s
⊢ IsCycleOn (subtypePerm f (_ : ∀ (x : α), x ∈ s ↔ ↑f x ∈ s)) _root_.Set.univ
[PROOFSTEP]
exact isCycleOn_of_subsingleton _ _
[GOAL]
case inr
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
hf : IsCycleOn f s
hs : Set.Nontrivial s
⊢ IsCycleOn (subtypePerm f (_ : ∀ (x : α), x ∈ s ↔ ↑f x ∈ s)) _root_.Set.univ
[PROOFSTEP]
convert (hf.isCycle_subtypePerm hs).isCycleOn
[GOAL]
case h.e'_3
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
hf : IsCycleOn f s
hs : Set.Nontrivial s
⊢ _root_.Set.univ = {x | ↑(subtypePerm f (_ : ∀ (x : α), x ∈ s ↔ ↑f x ∈ s)) x ≠ x}
[PROOFSTEP]
rw [eq_comm, Set.eq_univ_iff_forall]
[GOAL]
case h.e'_3
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
hf : IsCycleOn f s
hs : Set.Nontrivial s
⊢ ∀ (x : { x // x ∈ s }), x ∈ {x | ↑(subtypePerm f (_ : ∀ (x : α), x ∈ s ↔ ↑f x ∈ s)) x ≠ x}
[PROOFSTEP]
exact fun x => ne_of_apply_ne ((↑) : s → α) (hf.apply_ne hs x.2)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s✝ t : Set α
a b x y : α
s : Finset α
hf : IsCycleOn f ↑s
ha : a ∈ s
n : ℕ
⊢ ↑(f ^ n) a = a ↔ card s ∣ n
[PROOFSTEP]
obtain rfl | hs := Finset.eq_singleton_or_nontrivial ha
[GOAL]
case inl
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
n : ℕ
hf : IsCycleOn f ↑{a}
ha : a ∈ {a}
⊢ ↑(f ^ n) a = a ↔ card {a} ∣ n
[PROOFSTEP]
rw [coe_singleton, isCycleOn_singleton] at hf
[GOAL]
case inl
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
n : ℕ
hf : ↑f a = a
ha : a ∈ {a}
⊢ ↑(f ^ n) a = a ↔ card {a} ∣ n
[PROOFSTEP]
simpa using IsFixedPt.iterate hf n
[GOAL]
case inr
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s✝ t : Set α
a b x y : α
s : Finset α
hf : IsCycleOn f ↑s
ha : a ∈ s
n : ℕ
hs : Set.Nontrivial ↑s
⊢ ↑(f ^ n) a = a ↔ card s ∣ n
[PROOFSTEP]
classical
have h : ∀ x ∈ s.attach, ¬f ↑x = ↑x := fun x _ => hf.apply_ne hs x.2
have := (hf.isCycle_subtypePerm hs).orderOf
simp only [coe_sort_coe, support_subtype_perm, ne_eq, decide_not, Bool.not_eq_true', decide_eq_false_iff_not,
mem_attach, forall_true_left, Subtype.forall, filter_true_of_mem h, card_attach] at this
rw [← this, orderOf_dvd_iff_pow_eq_one,
(hf.isCycle_subtypePerm hs).pow_eq_one_iff' (ne_of_apply_ne ((↑) : s → α) <| hf.apply_ne hs (⟨a, ha⟩ : s).2)]
simp
[GOAL]
case inr
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s✝ t : Set α
a b x y : α
s : Finset α
hf : IsCycleOn f ↑s
ha : a ∈ s
n : ℕ
hs : Set.Nontrivial ↑s
⊢ ↑(f ^ n) a = a ↔ card s ∣ n
[PROOFSTEP]
have h : ∀ x ∈ s.attach, ¬f ↑x = ↑x := fun x _ => hf.apply_ne hs x.2
[GOAL]
case inr
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s✝ t : Set α
a b x y : α
s : Finset α
hf : IsCycleOn f ↑s
ha : a ∈ s
n : ℕ
hs : Set.Nontrivial ↑s
h : ∀ (x : { x // x ∈ s }), x ∈ attach s → ¬↑f ↑x = ↑x
⊢ ↑(f ^ n) a = a ↔ card s ∣ n
[PROOFSTEP]
have := (hf.isCycle_subtypePerm hs).orderOf
[GOAL]
case inr
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s✝ t : Set α
a b x y : α
s : Finset α
hf : IsCycleOn f ↑s
ha : a ∈ s
n : ℕ
hs : Set.Nontrivial ↑s
h : ∀ (x : { x // x ∈ s }), x ∈ attach s → ¬↑f ↑x = ↑x
this :
orderOf (subtypePerm f (_ : ∀ (x : α), x ∈ ↑s ↔ ↑f x ∈ ↑s)) =
card (support (subtypePerm f (_ : ∀ (x : α), x ∈ ↑s ↔ ↑f x ∈ ↑s)))
⊢ ↑(f ^ n) a = a ↔ card s ∣ n
[PROOFSTEP]
simp only [coe_sort_coe, support_subtype_perm, ne_eq, decide_not, Bool.not_eq_true', decide_eq_false_iff_not,
mem_attach, forall_true_left, Subtype.forall, filter_true_of_mem h, card_attach] at this
[GOAL]
case inr
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s✝ t : Set α
a b x y : α
s : Finset α
hf : IsCycleOn f ↑s
ha : a ∈ s
n : ℕ
hs : Set.Nontrivial ↑s
h : ∀ (x : { x // x ∈ s }), x ∈ attach s → ¬↑f ↑x = ↑x
this : orderOf (subtypePerm f (_ : ∀ (x : α), x ∈ ↑s ↔ ↑f x ∈ ↑s)) = card s
⊢ ↑(f ^ n) a = a ↔ card s ∣ n
[PROOFSTEP]
rw [← this, orderOf_dvd_iff_pow_eq_one,
(hf.isCycle_subtypePerm hs).pow_eq_one_iff' (ne_of_apply_ne ((↑) : s → α) <| hf.apply_ne hs (⟨a, ha⟩ : s).2)]
[GOAL]
case inr
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s✝ t : Set α
a b x y : α
s : Finset α
hf : IsCycleOn f ↑s
ha : a ∈ s
n : ℕ
hs : Set.Nontrivial ↑s
h : ∀ (x : { x // x ∈ s }), x ∈ attach s → ¬↑f ↑x = ↑x
this : orderOf (subtypePerm f (_ : ∀ (x : α), x ∈ ↑s ↔ ↑f x ∈ ↑s)) = card s
⊢ ↑(f ^ n) a = a ↔
↑(subtypePerm f (_ : ∀ (x : α), x ∈ ↑s ↔ ↑f x ∈ ↑s) ^ n) { val := a, property := ha } = { val := a, property := ha }
[PROOFSTEP]
simp
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s✝ t : Set α
a b x y : α
s : Finset α
hf : IsCycleOn f ↑s
ha : a ∈ s
n : ℕ
⊢ ↑(f ^ Int.negSucc n) a = a ↔ ↑(card s) ∣ Int.negSucc n
[PROOFSTEP]
rw [zpow_negSucc, ← inv_pow]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s✝ t : Set α
a b x y : α
s : Finset α
hf : IsCycleOn f ↑s
ha : a ∈ s
n : ℕ
⊢ ↑(f⁻¹ ^ (n + 1)) a = a ↔ ↑(card s) ∣ Int.negSucc n
[PROOFSTEP]
exact (hf.inv.pow_apply_eq ha).trans (dvd_neg.trans Int.coe_nat_dvd).symm
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s✝ t : Set α
a b x y : α
s : Finset α
hf : IsCycleOn f ↑s
ha : a ∈ s
m n : ℕ
⊢ ↑(f ^ m) a = ↑(f ^ n) a ↔ m ≡ n [MOD card s]
[PROOFSTEP]
rw [Nat.modEq_iff_dvd, ← hf.zpow_apply_eq ha]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s✝ t : Set α
a b x y : α
s : Finset α
hf : IsCycleOn f ↑s
ha : a ∈ s
m n : ℕ
⊢ ↑(f ^ m) a = ↑(f ^ n) a ↔ ↑(f ^ (↑n - ↑m)) a = a
[PROOFSTEP]
simp [sub_eq_neg_add, zpow_add, eq_inv_iff_eq, eq_comm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s✝ t : Set α
a b x y : α
s : Finset α
hf : IsCycleOn f ↑s
ha : a ∈ s
m n : ℤ
⊢ ↑(f ^ m) a = ↑(f ^ n) a ↔ m ≡ n [ZMOD ↑(card s)]
[PROOFSTEP]
rw [Int.modEq_iff_dvd, ← hf.zpow_apply_eq ha]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s✝ t : Set α
a b x y : α
s : Finset α
hf : IsCycleOn f ↑s
ha : a ∈ s
m n : ℤ
⊢ ↑(f ^ m) a = ↑(f ^ n) a ↔ ↑(f ^ (n - m)) a = a
[PROOFSTEP]
simp [sub_eq_neg_add, zpow_add, eq_inv_iff_eq, eq_comm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s✝ t : Set α
a b x y : α
s : Finset α
hf : IsCycleOn f ↑s
ha : a ∈ s
hb : b ∈ s
⊢ ∃ n, n < card s ∧ ↑(f ^ n) a = b
[PROOFSTEP]
classical
obtain ⟨n, rfl⟩ := hf.2 ha hb
obtain ⟨k, hk⟩ := (Int.mod_modEq n s.card).symm.dvd
refine' ⟨n.natMod s.card, Int.natMod_lt (Nonempty.card_pos ⟨a, ha⟩).ne', _⟩
rw [← zpow_ofNat, Int.natMod,
Int.toNat_of_nonneg (Int.emod_nonneg _ <| Nat.cast_ne_zero.2 (Nonempty.card_pos ⟨a, ha⟩).ne'),
sub_eq_iff_eq_add'.1 hk, zpow_add, zpow_mul]
simp only [zpow_coe_nat, coe_mul, comp_apply, EmbeddingLike.apply_eq_iff_eq]
exact IsFixedPt.perm_zpow (hf.pow_card_apply ha) _
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s✝ t : Set α
a b x y : α
s : Finset α
hf : IsCycleOn f ↑s
ha : a ∈ s
hb : b ∈ s
⊢ ∃ n, n < card s ∧ ↑(f ^ n) a = b
[PROOFSTEP]
obtain ⟨n, rfl⟩ := hf.2 ha hb
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s✝ t : Set α
a x y : α
s : Finset α
hf : IsCycleOn f ↑s
ha : a ∈ s
n : ℤ
hb : ↑(f ^ n) a ∈ s
⊢ ∃ n_1, n_1 < card s ∧ ↑(f ^ n_1) a = ↑(f ^ n) a
[PROOFSTEP]
obtain ⟨k, hk⟩ := (Int.mod_modEq n s.card).symm.dvd
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s✝ t : Set α
a x y : α
s : Finset α
hf : IsCycleOn f ↑s
ha : a ∈ s
n : ℤ
hb : ↑(f ^ n) a ∈ s
k : ℤ
hk : n % ↑(card s) - n = ↑(card s) * k
⊢ ∃ n_1, n_1 < card s ∧ ↑(f ^ n_1) a = ↑(f ^ n) a
[PROOFSTEP]
refine' ⟨n.natMod s.card, Int.natMod_lt (Nonempty.card_pos ⟨a, ha⟩).ne', _⟩
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s✝ t : Set α
a x y : α
s : Finset α
hf : IsCycleOn f ↑s
ha : a ∈ s
n : ℤ
hb : ↑(f ^ n) a ∈ s
k : ℤ
hk : n % ↑(card s) - n = ↑(card s) * k
⊢ ↑(f ^ Int.natMod n ↑(card s)) a = ↑(f ^ n) a
[PROOFSTEP]
rw [← zpow_ofNat, Int.natMod,
Int.toNat_of_nonneg (Int.emod_nonneg _ <| Nat.cast_ne_zero.2 (Nonempty.card_pos ⟨a, ha⟩).ne'),
sub_eq_iff_eq_add'.1 hk, zpow_add, zpow_mul]
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s✝ t : Set α
a x y : α
s : Finset α
hf : IsCycleOn f ↑s
ha : a ∈ s
n : ℤ
hb : ↑(f ^ n) a ∈ s
k : ℤ
hk : n % ↑(card s) - n = ↑(card s) * k
⊢ ↑(f ^ n * (f ^ ↑(card s)) ^ k) a = ↑(f ^ n) a
[PROOFSTEP]
simp only [zpow_coe_nat, coe_mul, comp_apply, EmbeddingLike.apply_eq_iff_eq]
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s✝ t : Set α
a x y : α
s : Finset α
hf : IsCycleOn f ↑s
ha : a ∈ s
n : ℤ
hb : ↑(f ^ n) a ∈ s
k : ℤ
hk : n % ↑(card s) - n = ↑(card s) * k
⊢ ↑((f ^ card s) ^ k) a = a
[PROOFSTEP]
exact IsFixedPt.perm_zpow (hf.pow_card_apply ha) _
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
hs : Set.Finite s
hf : IsCycleOn f s
ha : a ∈ s
hb : b ∈ s
⊢ ∃ n, ↑(f ^ n) a = b
[PROOFSTEP]
lift s to Finset α using id hs
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
t : Set α
a b x y : α
s : Finset α
hs : Set.Finite ↑s
hf : IsCycleOn f ↑s
ha : a ∈ ↑s
hb : b ∈ ↑s
⊢ ∃ n, ↑(f ^ n) a = b
[PROOFSTEP]
obtain ⟨n, -, hn⟩ := hf.exists_pow_eq ha hb
[GOAL]
case intro.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
t : Set α
a b x y : α
s : Finset α
hs : Set.Finite ↑s
hf : IsCycleOn f ↑s
ha : a ∈ ↑s
hb : b ∈ ↑s
n : ℕ
hn : ↑(f ^ n) a = b
⊢ ∃ n, ↑(f ^ n) a = b
[PROOFSTEP]
exact ⟨n, hn⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
s t : Set α
a b x y : α
p : β → Prop
inst✝ : DecidablePred p
f : α ≃ Subtype p
h : IsCycleOn g s
⊢ ∀ ⦃x : β⦄, x ∈ Subtype.val ∘ ↑f '' s → ∀ ⦃y : β⦄, y ∈ Subtype.val ∘ ↑f '' s → SameCycle (Perm.extendDomain g f) x y
[PROOFSTEP]
rintro _ ⟨a, ha, rfl⟩ _ ⟨b, hb, rfl⟩
[GOAL]
case intro.intro.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f✝ g : Perm α
s t : Set α
a✝ b✝ x y : α
p : β → Prop
inst✝ : DecidablePred p
f : α ≃ Subtype p
h : IsCycleOn g s
a : α
ha : a ∈ s
b : α
hb : b ∈ s
⊢ SameCycle (Perm.extendDomain g f) ((Subtype.val ∘ ↑f) a) ((Subtype.val ∘ ↑f) b)
[PROOFSTEP]
exact (h.2 ha hb).extendDomain
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a b x y : α
hs : IsCycleOn f s
⊢ Set.Countable s
[PROOFSTEP]
obtain rfl | ⟨a, ha⟩ := s.eq_empty_or_nonempty
[GOAL]
case inl
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
t : Set α
a b x y : α
hs : IsCycleOn f ∅
⊢ Set.Countable ∅
[PROOFSTEP]
exact Set.countable_empty
[GOAL]
case inr.intro
ι : Type u_1
α : Type u_2
β : Type u_3
f g : Perm α
s t : Set α
a✝ b x y : α
hs : IsCycleOn f s
a : α
ha : a ∈ s
⊢ Set.Countable s
[PROOFSTEP]
exact (Set.countable_range fun n : ℤ => (⇑(f ^ n) : α → α) a).mono (hs.2 ha)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y✝ : α
f : Perm α
x y : α
⊢ ↑(cycleOf f x) y = if SameCycle f x y then ↑f y else y
[PROOFSTEP]
dsimp only [cycleOf]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y✝ : α
f : Perm α
x y : α
⊢ ↑(↑ofSubtype (subtypePerm f (_ : ∀ (x_1 : α), SameCycle f x x_1 ↔ SameCycle f x (↑f x_1)))) y =
if SameCycle f x y then ↑f y else y
[PROOFSTEP]
split_ifs with h
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y✝ : α
f : Perm α
x y : α
h : SameCycle f x y
⊢ ↑(↑ofSubtype (subtypePerm f (_ : ∀ (x_1 : α), SameCycle f x x_1 ↔ SameCycle f x (↑f x_1)))) y = ↑f y
[PROOFSTEP]
apply ofSubtype_apply_of_mem
[GOAL]
case pos.ha
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y✝ : α
f : Perm α
x y : α
h : SameCycle f x y
⊢ SameCycle f x y
[PROOFSTEP]
exact h
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y✝ : α
f : Perm α
x y : α
h : ¬SameCycle f x y
⊢ ↑(↑ofSubtype (subtypePerm f (_ : ∀ (x_1 : α), SameCycle f x x_1 ↔ SameCycle f x (↑f x_1)))) y = y
[PROOFSTEP]
apply ofSubtype_apply_of_not_mem
[GOAL]
case neg.ha
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y✝ : α
f : Perm α
x y : α
h : ¬SameCycle f x y
⊢ ¬SameCycle f x y
[PROOFSTEP]
exact h
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y✝ : α
f : Perm α
x y : α
⊢ ↑(cycleOf f x)⁻¹ y = ↑(cycleOf f⁻¹ x) y
[PROOFSTEP]
rw [inv_eq_iff_eq, cycleOf_apply, cycleOf_apply]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y✝ : α
f : Perm α
x y : α
⊢ y =
if SameCycle f x (if SameCycle f⁻¹ x y then ↑f⁻¹ y else y) then ↑f (if SameCycle f⁻¹ x y then ↑f⁻¹ y else y)
else if SameCycle f⁻¹ x y then ↑f⁻¹ y else y
[PROOFSTEP]
split_ifs
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y✝ : α
f : Perm α
x y : α
h✝¹ : SameCycle f⁻¹ x y
h✝ : SameCycle f x (↑f⁻¹ y)
⊢ y = ↑f (if SameCycle f⁻¹ x y then ↑f⁻¹ y else y)
[PROOFSTEP]
simp_all [sameCycle_inv, sameCycle_inv_apply_right]
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y✝ : α
f : Perm α
x y : α
h✝¹ : SameCycle f⁻¹ x y
h✝ : ¬SameCycle f x (↑f⁻¹ y)
⊢ y = ↑f⁻¹ y
[PROOFSTEP]
simp_all [sameCycle_inv, sameCycle_inv_apply_right]
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y✝ : α
f : Perm α
x y : α
h✝¹ : ¬SameCycle f⁻¹ x y
h✝ : SameCycle f x y
⊢ y = ↑f (if SameCycle f⁻¹ x y then ↑f⁻¹ y else y)
[PROOFSTEP]
simp_all [sameCycle_inv, sameCycle_inv_apply_right]
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y✝ : α
f : Perm α
x y : α
h✝¹ : ¬SameCycle f⁻¹ x y
h✝ : ¬SameCycle f x y
⊢ y = y
[PROOFSTEP]
simp_all [sameCycle_inv, sameCycle_inv_apply_right]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y : α
f : Perm α
x : α
⊢ ∀ (n : ℕ), ↑(cycleOf f x ^ n) x = ↑(f ^ n) x
[PROOFSTEP]
intro n
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y : α
f : Perm α
x : α
n : ℕ
⊢ ↑(cycleOf f x ^ n) x = ↑(f ^ n) x
[PROOFSTEP]
induction' n with n hn
[GOAL]
case zero
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y : α
f : Perm α
x : α
⊢ ↑(cycleOf f x ^ Nat.zero) x = ↑(f ^ Nat.zero) x
[PROOFSTEP]
rfl
[GOAL]
case succ
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y : α
f : Perm α
x : α
n : ℕ
hn : ↑(cycleOf f x ^ n) x = ↑(f ^ n) x
⊢ ↑(cycleOf f x ^ Nat.succ n) x = ↑(f ^ Nat.succ n) x
[PROOFSTEP]
rw [pow_succ, mul_apply, cycleOf_apply, hn, if_pos, pow_succ, mul_apply]
[GOAL]
case succ.hc
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y : α
f : Perm α
x : α
n : ℕ
hn : ↑(cycleOf f x ^ n) x = ↑(f ^ n) x
⊢ SameCycle f x (↑(f ^ n) x)
[PROOFSTEP]
simpa [SameCycle] using ⟨n, rfl⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y : α
f : Perm α
x : α
⊢ ∀ (n : ℤ), ↑(cycleOf f x ^ n) x = ↑(f ^ n) x
[PROOFSTEP]
intro z
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y : α
f : Perm α
x : α
z : ℤ
⊢ ↑(cycleOf f x ^ z) x = ↑(f ^ z) x
[PROOFSTEP]
induction' z with z hz
[GOAL]
case ofNat
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y : α
f : Perm α
x : α
z : ℕ
⊢ ↑(cycleOf f x ^ Int.ofNat z) x = ↑(f ^ Int.ofNat z) x
[PROOFSTEP]
exact cycleOf_pow_apply_self f x z
[GOAL]
case negSucc
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y : α
f : Perm α
x : α
hz : ℕ
⊢ ↑(cycleOf f x ^ Int.negSucc hz) x = ↑(f ^ Int.negSucc hz) x
[PROOFSTEP]
rw [zpow_negSucc, ← inv_pow, cycleOf_inv, zpow_negSucc, ← inv_pow, cycleOf_pow_apply_self]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
h : SameCycle f x y
⊢ cycleOf f x = cycleOf f y
[PROOFSTEP]
ext z
[GOAL]
case H
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
h : SameCycle f x y
z : α
⊢ ↑(cycleOf f x) z = ↑(cycleOf f y) z
[PROOFSTEP]
rw [Equiv.Perm.cycleOf_apply]
[GOAL]
case H
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
h : SameCycle f x y
z : α
⊢ (if SameCycle f x z then ↑f z else z) = ↑(cycleOf f y) z
[PROOFSTEP]
split_ifs with hz
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
h : SameCycle f x y
z : α
hz : SameCycle f x z
⊢ ↑f z = ↑(cycleOf f y) z
[PROOFSTEP]
exact (h.symm.trans hz).cycleOf_apply.symm
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
h : SameCycle f x y
z : α
hz : ¬SameCycle f x z
⊢ z = ↑(cycleOf f y) z
[PROOFSTEP]
exact (cycleOf_apply_of_not_sameCycle (mt h.trans hz)).symm
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y : α
f : Perm α
x : α
k : ℤ
⊢ ↑(cycleOf f x) (↑(f ^ k) x) = ↑(f ^ (k + 1)) x
[PROOFSTEP]
rw [SameCycle.cycleOf_apply]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y : α
f : Perm α
x : α
k : ℤ
⊢ ↑f (↑(f ^ k) x) = ↑(f ^ (k + 1)) x
[PROOFSTEP]
rw [add_comm, zpow_add, zpow_one, mul_apply]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y : α
f : Perm α
x : α
k : ℤ
⊢ SameCycle f x (↑(f ^ k) x)
[PROOFSTEP]
exact ⟨k, rfl⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y : α
f : Perm α
x : α
k : ℕ
⊢ ↑(cycleOf f x) (↑(f ^ k) x) = ↑(f ^ (k + 1)) x
[PROOFSTEP]
convert cycleOf_apply_apply_zpow_self f x k using 1
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y : α
f : Perm α
x : α
⊢ ↑(cycleOf f x) (↑f x) = ↑f (↑f x)
[PROOFSTEP]
convert cycleOf_apply_apply_pow_self f x 1 using 1
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y✝ : α
hf : IsCycle f
hx : ↑f x ≠ x
y : α
h : SameCycle f x y
⊢ ↑(cycleOf f x) y = ↑f y
[PROOFSTEP]
rw [h.cycleOf_apply]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y✝ : α
hf : IsCycle f
hx : ↑f x ≠ x
y : α
h : ¬SameCycle f x y
⊢ ↑(cycleOf f x) y = ↑f y
[PROOFSTEP]
rw [cycleOf_apply_of_not_sameCycle h, Classical.not_not.1 (mt ((isCycle_iff_sameCycle hx).1 hf).2 h)]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y : α
f : Perm α
⊢ cycleOf f x = 1 ↔ ↑f x = x
[PROOFSTEP]
simp_rw [ext_iff, cycleOf_apply, one_apply]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y : α
f : Perm α
⊢ (∀ (x_1 : α), (if SameCycle f x x_1 then ↑f x_1 else x_1) = x_1) ↔ ↑f x = x
[PROOFSTEP]
refine' ⟨fun h => (if_pos (SameCycle.refl f x)).symm.trans (h x), fun h y => _⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y✝ : α
f : Perm α
h : ↑f x = x
y : α
⊢ (if SameCycle f x y then ↑f y else y) = y
[PROOFSTEP]
by_cases hy : f y = y
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y✝ : α
f : Perm α
h : ↑f x = x
y : α
hy : ↑f y = y
⊢ (if SameCycle f x y then ↑f y else y) = y
[PROOFSTEP]
rw [hy, ite_self]
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y✝ : α
f : Perm α
h : ↑f x = x
y : α
hy : ¬↑f y = y
⊢ (if SameCycle f x y then ↑f y else y) = y
[PROOFSTEP]
exact if_neg (mt SameCycle.apply_eq_self_iff (by tauto))
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y✝ : α
f : Perm α
h : ↑f x = x
y : α
hy : ¬↑f y = y
⊢ ¬(↑f x = x ↔ ↑f y = y)
[PROOFSTEP]
tauto
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
hf : IsCycle f
⊢ cycleOf f x = if ↑f x = x then 1 else f
[PROOFSTEP]
by_cases hx : f x = x
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
hf : IsCycle f
hx : ↑f x = x
⊢ cycleOf f x = if ↑f x = x then 1 else f
[PROOFSTEP]
rwa [if_pos hx, cycleOf_eq_one_iff]
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
hf : IsCycle f
hx : ¬↑f x = x
⊢ cycleOf f x = if ↑f x = x then 1 else f
[PROOFSTEP]
rwa [if_neg hx, hf.cycleOf_eq]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y : α
f : Perm α
hx : ↑f x ≠ x
⊢ ↑(cycleOf f x) x ≠ x
[PROOFSTEP]
rwa [SameCycle.rfl.cycleOf_apply]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y✝ : α
f : Perm α
hx : ↑f x ≠ x
this : ↑(cycleOf f x) x ≠ x
y : α
h : ↑(cycleOf f x) y ≠ y
hxy : SameCycle f x y
i : ℤ
hi : ↑(f ^ i) x = y
⊢ ↑(cycleOf f x ^ i) x = y
[PROOFSTEP]
rw [cycleOf_zpow_apply_self, hi]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y✝ : α
f : Perm α
hx : ↑f x ≠ x
this : ↑(cycleOf f x) x ≠ x
y : α
h : ↑(cycleOf f x) y ≠ y
hxy : ¬SameCycle f x y
⊢ SameCycle (cycleOf f x) x y
[PROOFSTEP]
rw [cycleOf_apply_of_not_sameCycle hxy] at h
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y✝ : α
f : Perm α
hx : ↑f x ≠ x
this : ↑(cycleOf f x) x ≠ x
y : α
h : y ≠ y
hxy : ¬SameCycle f x y
⊢ SameCycle (cycleOf f x) x y
[PROOFSTEP]
exact (h rfl).elim
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
⊢ 2 ≤ card (support (cycleOf f x)) ↔ ↑f x ≠ x
[PROOFSTEP]
refine' ⟨fun h => _, fun h => by simpa using (isCycle_cycleOf _ h).two_le_card_support⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
h : ↑f x ≠ x
⊢ 2 ≤ card (support (cycleOf f x))
[PROOFSTEP]
simpa using (isCycle_cycleOf _ h).two_le_card_support
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
h : 2 ≤ card (support (cycleOf f x))
⊢ ↑f x ≠ x
[PROOFSTEP]
contrapose! h
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
h : ↑f x = x
⊢ card (support (cycleOf f x)) < 2
[PROOFSTEP]
rw [← cycleOf_eq_one_iff] at h
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
h✝ : ↑f x = x
h : cycleOf f x = 1
⊢ card (support (cycleOf f x)) < 2
[PROOFSTEP]
simp [h]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
⊢ 0 < card (support (cycleOf f x)) ↔ ↑f x ≠ x
[PROOFSTEP]
rw [← two_le_card_support_cycleOf_iff, ← Nat.succ_le_iff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
⊢ Nat.succ 0 ≤ card (support (cycleOf f x)) ↔ 2 ≤ card (support (cycleOf f x))
[PROOFSTEP]
exact ⟨fun h => Or.resolve_left h.eq_or_lt (card_support_ne_one _).symm, zero_lt_two.trans_le⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y : α
f : Perm α
n : ℕ
x : α
⊢ ↑(f ^ n) x = ↑(f ^ (n % orderOf (cycleOf f x))) x
[PROOFSTEP]
rw [← cycleOf_pow_apply_self f, ← cycleOf_pow_apply_self f, pow_eq_mod_orderOf]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x✝ y : α
h : Commute f g
x : α
hx : ↑g x = x
⊢ cycleOf (f * g) x = cycleOf f x
[PROOFSTEP]
ext y
[GOAL]
case H
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x✝ y✝ : α
h : Commute f g
x : α
hx : ↑g x = x
y : α
⊢ ↑(cycleOf (f * g) x) y = ↑(cycleOf f x) y
[PROOFSTEP]
by_cases hxy : (f * g).SameCycle x y
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x✝ y✝ : α
h : Commute f g
x : α
hx : ↑g x = x
y : α
hxy : SameCycle (f * g) x y
⊢ ↑(cycleOf (f * g) x) y = ↑(cycleOf f x) y
[PROOFSTEP]
obtain ⟨z, rfl⟩ := hxy
[GOAL]
case pos.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x✝ y : α
h : Commute f g
x : α
hx : ↑g x = x
z : ℤ
⊢ ↑(cycleOf (f * g) x) (↑((f * g) ^ z) x) = ↑(cycleOf f x) (↑((f * g) ^ z) x)
[PROOFSTEP]
rw [cycleOf_apply_apply_zpow_self]
[GOAL]
case pos.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x✝ y : α
h : Commute f g
x : α
hx : ↑g x = x
z : ℤ
⊢ ↑((f * g) ^ (z + 1)) x = ↑(cycleOf f x) (↑((f * g) ^ z) x)
[PROOFSTEP]
simp [h.mul_zpow, zpow_apply_eq_self_of_apply_eq_self hx]
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x✝ y✝ : α
h : Commute f g
x : α
hx : ↑g x = x
y : α
hxy : ¬SameCycle (f * g) x y
⊢ ↑(cycleOf (f * g) x) y = ↑(cycleOf f x) y
[PROOFSTEP]
rw [cycleOf_apply_of_not_sameCycle hxy, cycleOf_apply_of_not_sameCycle]
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x✝ y✝ : α
h : Commute f g
x : α
hx : ↑g x = x
y : α
hxy : ¬SameCycle (f * g) x y
⊢ ¬SameCycle f x y
[PROOFSTEP]
contrapose! hxy
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x✝ y✝ : α
h : Commute f g
x : α
hx : ↑g x = x
y : α
hxy : SameCycle f x y
⊢ SameCycle (f * g) x y
[PROOFSTEP]
obtain ⟨z, rfl⟩ := hxy
[GOAL]
case neg.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x✝ y : α
h : Commute f g
x : α
hx : ↑g x = x
z : ℤ
⊢ SameCycle (f * g) x (↑(f ^ z) x)
[PROOFSTEP]
refine' ⟨z, _⟩
[GOAL]
case neg.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x✝ y : α
h : Commute f g
x : α
hx : ↑g x = x
z : ℤ
⊢ ↑((f * g) ^ z) x = ↑(f ^ z) x
[PROOFSTEP]
simp [h.mul_zpow, zpow_apply_eq_self_of_apply_eq_self hx]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x✝ y : α
h : Disjoint f g
x : α
⊢ cycleOf (f * g) x = cycleOf f x * cycleOf g x
[PROOFSTEP]
cases' (disjoint_iff_eq_or_eq.mp h) x with hfx hgx
[GOAL]
case inl
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x✝ y : α
h : Disjoint f g
x : α
hfx : ↑f x = x
⊢ cycleOf (f * g) x = cycleOf f x * cycleOf g x
[PROOFSTEP]
simp [h.commute.eq, cycleOf_mul_of_apply_right_eq_self h.symm.commute, hfx]
[GOAL]
case inr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x✝ y : α
h : Disjoint f g
x : α
hgx : ↑g x = x
⊢ cycleOf (f * g) x = cycleOf f x * cycleOf g x
[PROOFSTEP]
simp [cycleOf_mul_of_apply_right_eq_self h.commute, hgx]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
⊢ support (cycleOf f x) = ∅ ↔ ¬x ∈ support f
[PROOFSTEP]
simp
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y : α
f : Perm α
x : α
⊢ support (cycleOf f x) ≤ support f
[PROOFSTEP]
intro y hy
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y✝ : α
f : Perm α
x y : α
hy : y ∈ support (cycleOf f x)
⊢ y ∈ support f
[PROOFSTEP]
rw [mem_support, cycleOf_apply] at hy
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y✝ : α
f : Perm α
x y : α
hy : (if SameCycle f x y then ↑f y else y) ≠ y
⊢ y ∈ support f
[PROOFSTEP]
split_ifs at hy
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y✝ : α
f : Perm α
x y : α
h✝ : SameCycle f x y
hy : ↑f y ≠ y
⊢ y ∈ support f
[PROOFSTEP]
exact mem_support.mpr hy
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y✝ : α
f : Perm α
x y : α
h✝ : ¬SameCycle f x y
hy : y ≠ y
⊢ y ∈ support f
[PROOFSTEP]
exact absurd rfl hy
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
⊢ y ∈ support (cycleOf f x) ↔ SameCycle f x y ∧ x ∈ support f
[PROOFSTEP]
by_cases hx : f x = x
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
hx : ↑f x = x
⊢ y ∈ support (cycleOf f x) ↔ SameCycle f x y ∧ x ∈ support f
[PROOFSTEP]
rw [(cycleOf_eq_one_iff _).mpr hx]
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
hx : ↑f x = x
⊢ y ∈ support 1 ↔ SameCycle f x y ∧ x ∈ support f
[PROOFSTEP]
simp [hx]
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
hx : ¬↑f x = x
⊢ y ∈ support (cycleOf f x) ↔ SameCycle f x y ∧ x ∈ support f
[PROOFSTEP]
rw [mem_support, cycleOf_apply]
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
hx : ¬↑f x = x
⊢ (if SameCycle f x y then ↑f y else y) ≠ y ↔ SameCycle f x y ∧ x ∈ support f
[PROOFSTEP]
split_ifs with hy
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
hx : ¬↑f x = x
hy : SameCycle f x y
⊢ ↑f y ≠ y ↔ SameCycle f x y ∧ x ∈ support f
[PROOFSTEP]
simp only [hx, hy, iff_true_iff, Ne.def, not_false_iff, and_self_iff, mem_support]
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
hx : ¬↑f x = x
hy : SameCycle f x y
⊢ ¬↑f y = y
[PROOFSTEP]
rcases hy with ⟨k, rfl⟩
[GOAL]
case pos.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x : α
hx : ¬↑f x = x
k : ℤ
⊢ ¬↑f (↑(f ^ k) x) = ↑(f ^ k) x
[PROOFSTEP]
rw [← not_mem_support]
[GOAL]
case pos.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x : α
hx : ¬↑f x = x
k : ℤ
⊢ ¬¬↑(f ^ k) x ∈ support f
[PROOFSTEP]
simpa using hx
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
hx : ¬↑f x = x
hy : ¬SameCycle f x y
⊢ y ≠ y ↔ SameCycle f x y ∧ x ∈ support f
[PROOFSTEP]
simpa [hx] using hy
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
hx : ↑f x ≠ x
⊢ y ∈ support (cycleOf f x) ↔ SameCycle f x y
[PROOFSTEP]
rw [mem_support_cycleOf_iff, and_iff_left (mem_support.2 hx)]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y : α
f : Perm α
n : ℕ
x : α
⊢ ↑(f ^ (n % card (support (cycleOf f x)))) x = ↑(f ^ n) x
[PROOFSTEP]
by_cases hx : f x = x
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y : α
f : Perm α
n : ℕ
x : α
hx : ↑f x = x
⊢ ↑(f ^ (n % card (support (cycleOf f x)))) x = ↑(f ^ n) x
[PROOFSTEP]
rw [pow_apply_eq_self_of_apply_eq_self hx, pow_apply_eq_self_of_apply_eq_self hx]
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y : α
f : Perm α
n : ℕ
x : α
hx : ¬↑f x = x
⊢ ↑(f ^ (n % card (support (cycleOf f x)))) x = ↑(f ^ n) x
[PROOFSTEP]
rw [← cycleOf_pow_apply_self, ← cycleOf_pow_apply_self f, ← (isCycle_cycleOf f hx).orderOf, ← pow_eq_mod_orderOf]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y : α
f : Perm α
⊢ IsCycle (cycleOf f x) ↔ ↑f x ≠ x
[PROOFSTEP]
refine' ⟨fun hx => _, f.isCycle_cycleOf⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y : α
f : Perm α
hx : IsCycle (cycleOf f x)
⊢ ↑f x ≠ x
[PROOFSTEP]
rw [Ne.def, ← cycleOf_eq_one_iff f]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y : α
f : Perm α
hx : IsCycle (cycleOf f x)
⊢ ¬cycleOf f x = 1
[PROOFSTEP]
exact hx.ne_one
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y : α
f : Perm α
x : α
⊢ ∀ (a : α), ↑f a ∈ ↑(support (cycleOf f x)) ↔ a ∈ ↑(support (cycleOf f x))
[PROOFSTEP]
refine fun _ ↦ ⟨fun h ↦ mem_support_cycleOf_iff.2 ?_, fun h ↦ mem_support_cycleOf_iff.2 ?_⟩
[GOAL]
case refine_1
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝¹ y : α
f : Perm α
x x✝ : α
h : ↑f x✝ ∈ ↑(support (cycleOf f x))
⊢ SameCycle f x x✝ ∧ x ∈ support f
[PROOFSTEP]
exact ⟨sameCycle_apply_right.1 (mem_support_cycleOf_iff.1 h).1, (mem_support_cycleOf_iff.1 h).2⟩
[GOAL]
case refine_2
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝¹ y : α
f : Perm α
x x✝ : α
h : x✝ ∈ ↑(support (cycleOf f x))
⊢ SameCycle f x (↑f x✝) ∧ x ∈ support f
[PROOFSTEP]
exact ⟨sameCycle_apply_right.2 (mem_support_cycleOf_iff.1 h).1, (mem_support_cycleOf_iff.1 h).2⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y : α
f : Perm α
x a : α
ha : a ∈ ↑(support (cycleOf f x))
b : α
hb : b ∈ ↑(support (cycleOf f x))
⊢ SameCycle f a b
[PROOFSTEP]
rw [mem_coe, mem_support_cycleOf_iff] at ha hb
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x✝ y : α
f : Perm α
x a : α
ha : SameCycle f x a ∧ x ∈ support f
b : α
hb : SameCycle f x b ∧ x ∈ support f
⊢ SameCycle f a b
[PROOFSTEP]
exact ha.1.symm.trans hb.1
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
h : SameCycle f x y
hx : x ∈ support f
⊢ ∃ i x_1, ↑(f ^ i) x = y
[PROOFSTEP]
rw [mem_support] at hx
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
h : SameCycle f x y
hx : ↑f x ≠ x
⊢ ∃ i x_1, ↑(f ^ i) x = y
[PROOFSTEP]
have :=
Equiv.Perm.IsCycleOn.exists_pow_eq (b := y) (f.isCycleOn_support_cycleOf x) (by rw [mem_support_cycleOf_iff' hx])
(by rwa [mem_support_cycleOf_iff' hx])
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
h : SameCycle f x y
hx : ↑f x ≠ x
⊢ ?m.2768163 ∈ support (cycleOf f x)
[PROOFSTEP]
rw [mem_support_cycleOf_iff' hx]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
h : SameCycle f x y
hx : ↑f x ≠ x
⊢ y ∈ support (cycleOf f x)
[PROOFSTEP]
rwa [mem_support_cycleOf_iff' hx]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
h : SameCycle f x y
hx : ↑f x ≠ x
this : ∃ n, n < card (support (cycleOf f x)) ∧ ↑(f ^ n) x = y
⊢ ∃ i x_1, ↑(f ^ i) x = y
[PROOFSTEP]
simp_rw [← exists_prop] at this
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
x y : α
h : SameCycle f x y
hx : ↑f x ≠ x
this : ∃ n _h, ↑(f ^ n) x = y
⊢ ∃ i x_1, ↑(f ^ i) x = y
[PROOFSTEP]
exact this
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y : α
f : Perm α
h : SameCycle f x y
⊢ ∃ i x_1 x_2, ↑(f ^ i) x = y
[PROOFSTEP]
by_cases hx : x ∈ f.support
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y : α
f : Perm α
h : SameCycle f x y
hx : x ∈ support f
⊢ ∃ i x_1 x_2, ↑(f ^ i) x = y
[PROOFSTEP]
obtain ⟨k, hk, hk'⟩ := h.exists_pow_eq_of_mem_support hx
[GOAL]
case pos.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y : α
f : Perm α
h : SameCycle f x y
hx : x ∈ support f
k : ℕ
hk : k < card (support (cycleOf f x))
hk' : ↑(f ^ k) x = y
⊢ ∃ i x_1 x_2, ↑(f ^ i) x = y
[PROOFSTEP]
cases' k with k
[GOAL]
case pos.intro.intro.zero
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y : α
f : Perm α
h : SameCycle f x y
hx : x ∈ support f
hk : Nat.zero < card (support (cycleOf f x))
hk' : ↑(f ^ Nat.zero) x = y
⊢ ∃ i x_1 x_2, ↑(f ^ i) x = y
[PROOFSTEP]
refine' ⟨(f.cycleOf x).support.card, _, self_le_add_right _ _, _⟩
[GOAL]
case pos.intro.intro.zero.refine'_1
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y : α
f : Perm α
h : SameCycle f x y
hx : x ∈ support f
hk : Nat.zero < card (support (cycleOf f x))
hk' : ↑(f ^ Nat.zero) x = y
⊢ 0 < card (support (cycleOf f x))
[PROOFSTEP]
refine' zero_lt_one.trans (one_lt_card_support_of_ne_one _)
[GOAL]
case pos.intro.intro.zero.refine'_1
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y : α
f : Perm α
h : SameCycle f x y
hx : x ∈ support f
hk : Nat.zero < card (support (cycleOf f x))
hk' : ↑(f ^ Nat.zero) x = y
⊢ cycleOf f x ≠ 1
[PROOFSTEP]
simpa using hx
[GOAL]
case pos.intro.intro.zero.refine'_2
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y : α
f : Perm α
h : SameCycle f x y
hx : x ∈ support f
hk : Nat.zero < card (support (cycleOf f x))
hk' : ↑(f ^ Nat.zero) x = y
⊢ ↑(f ^ card (support (cycleOf f x))) x = y
[PROOFSTEP]
simp only [Nat.zero_eq, pow_zero, coe_one, id_eq] at hk'
[GOAL]
case pos.intro.intro.zero.refine'_2
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y : α
f : Perm α
h : SameCycle f x y
hx : x ∈ support f
hk : Nat.zero < card (support (cycleOf f x))
hk' : x = y
⊢ ↑(f ^ card (support (cycleOf f x))) x = y
[PROOFSTEP]
subst hk'
[GOAL]
case pos.intro.intro.zero.refine'_2
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x : α
f : Perm α
hx : x ∈ support f
hk : Nat.zero < card (support (cycleOf f x))
h : SameCycle f x x
⊢ ↑(f ^ card (support (cycleOf f x))) x = x
[PROOFSTEP]
rw [← (isCycle_cycleOf _ <| mem_support.1 hx).orderOf, ← cycleOf_pow_apply_self, pow_orderOf_eq_one, one_apply]
[GOAL]
case pos.intro.intro.succ
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y : α
f : Perm α
h : SameCycle f x y
hx : x ∈ support f
k : ℕ
hk : Nat.succ k < card (support (cycleOf f x))
hk' : ↑(f ^ Nat.succ k) x = y
⊢ ∃ i x_1 x_2, ↑(f ^ i) x = y
[PROOFSTEP]
exact ⟨k + 1, by simp, Nat.le_succ_of_le hk.le, hk'⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y : α
f : Perm α
h : SameCycle f x y
hx : x ∈ support f
k : ℕ
hk : Nat.succ k < card (support (cycleOf f x))
hk' : ↑(f ^ Nat.succ k) x = y
⊢ 0 < k + 1
[PROOFSTEP]
simp
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y : α
f : Perm α
h : SameCycle f x y
hx : ¬x ∈ support f
⊢ ∃ i x_1 x_2, ↑(f ^ i) x = y
[PROOFSTEP]
refine' ⟨1, zero_lt_one, by simp, _⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y : α
f : Perm α
h : SameCycle f x y
hx : ¬x ∈ support f
⊢ 1 ≤ card (support (cycleOf f x)) + 1
[PROOFSTEP]
simp
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x y : α
f : Perm α
h : SameCycle f x y
hx : ¬x ∈ support f
⊢ ↑(f ^ 1) x = y
[PROOFSTEP]
obtain ⟨k, rfl⟩ := h
[GOAL]
case neg.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x : α
f : Perm α
hx : ¬x ∈ support f
k : ℤ
⊢ ↑(f ^ 1) x = ↑(f ^ k) x
[PROOFSTEP]
rw [not_mem_support] at hx
[GOAL]
case neg.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ g : Perm α
x : α
f : Perm α
hx : ↑f x = x
k : ℤ
⊢ ↑(f ^ 1) x = ↑(f ^ k) x
[PROOFSTEP]
rw [pow_apply_eq_self_of_apply_eq_self hx, zpow_apply_eq_self_of_apply_eq_self hx]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
⊢ (l : List α) →
(f : Perm α) →
(∀ {x : α}, ↑f x ≠ x → x ∈ l) →
{ l // List.prod l = f ∧ (∀ (g : Perm α), g ∈ l → IsCycle g) ∧ List.Pairwise Disjoint l }
[PROOFSTEP]
intro l f h
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
l : List α
f : Perm α
h : ∀ {x : α}, ↑f x ≠ x → x ∈ l
⊢ { l // List.prod l = f ∧ (∀ (g : Perm α), g ∈ l → IsCycle g) ∧ List.Pairwise Disjoint l }
[PROOFSTEP]
exact
match l with
| [] =>
⟨[], by
{
simp only [imp_false, List.Pairwise.nil, List.not_mem_nil, forall_const, and_true_iff, forall_prop_of_false,
Classical.not_not, not_false_iff, List.prod_nil] at *
ext
simp [*]
}⟩
| x :: l =>
if hx : f x = x then
cycleFactorsAux l f (by intro y hy; exact List.mem_of_ne_of_mem (fun h => hy (by rwa [h])) (h hy))
else
let ⟨m, hm₁, hm₂, hm₃⟩ :=
cycleFactorsAux l ((cycleOf f x)⁻¹ * f)
(by
intro y hy
exact
List.mem_of_ne_of_mem
(fun h : y = x => by
rw [h, mul_apply, Ne.def, inv_eq_iff_eq, cycleOf_apply_self] at hy
exact hy rfl)
(h fun h : f y = y =>
by
rw [mul_apply, h, Ne.def, inv_eq_iff_eq, cycleOf_apply] at hy
split_ifs at hy <;> tauto))
⟨cycleOf f x :: m, by
rw [List.prod_cons, hm₁]
simp, fun g hg ↦ ((List.mem_cons).1 hg).elim (fun hg => hg.symm ▸ isCycle_cycleOf _ hx) (hm₂ g),
List.pairwise_cons.2
⟨fun g hg y =>
or_iff_not_imp_left.2 fun hfy =>
have hxy : SameCycle f x y := Classical.not_not.1 (mt cycleOf_apply_of_not_sameCycle hfy)
have hgm : (g :: m.erase g) ~ m := List.cons_perm_iff_perm_erase.2 ⟨hg, List.Perm.refl _⟩
have : ∀ h ∈ m.erase g, Disjoint g h :=
(List.pairwise_cons.1 ((hgm.pairwise_iff fun a b (h : Disjoint a b) => h.symm).2 hm₃)).1
by_cases id fun hgy : g y ≠ y =>
(disjoint_prod_right _ this y).resolve_right <|
by
have hsc : SameCycle f⁻¹ x (f y) := by rwa [sameCycle_inv, sameCycle_apply_right]
rw [disjoint_prod_perm hm₃ hgm.symm, List.prod_cons, ← eq_inv_mul_iff_mul_eq] at hm₁
rwa [hm₁, mul_apply, mul_apply, cycleOf_inv, hsc.cycleOf_apply, inv_apply_self, inv_eq_iff_eq,
eq_comm],
hm₃⟩⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
l : List α
f : Perm α
h : ∀ {x : α}, ↑f x ≠ x → x ∈ []
⊢ List.prod [] = f ∧ (∀ (g : Perm α), g ∈ [] → IsCycle g) ∧ List.Pairwise Disjoint []
[PROOFSTEP]
{ simp only [imp_false, List.Pairwise.nil, List.not_mem_nil, forall_const, and_true_iff, forall_prop_of_false,
Classical.not_not, not_false_iff, List.prod_nil] at *
ext
simp [*]
}
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
l : List α
f : Perm α
h : ∀ {x : α}, ↑f x ≠ x → x ∈ []
⊢ List.prod [] = f ∧ (∀ (g : Perm α), g ∈ [] → IsCycle g) ∧ List.Pairwise Disjoint []
[PROOFSTEP]
simp only [imp_false, List.Pairwise.nil, List.not_mem_nil, forall_const, and_true_iff, forall_prop_of_false,
Classical.not_not, not_false_iff, List.prod_nil] at *
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
l : List α
f : Perm α
h : ∀ {x : α}, ↑f x = x
⊢ 1 = f
[PROOFSTEP]
ext
[GOAL]
case H
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
l : List α
f : Perm α
h : ∀ {x : α}, ↑f x = x
x✝ : α
⊢ ↑1 x✝ = ↑f x✝
[PROOFSTEP]
simp [*]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
l✝ : List α
f : Perm α
x : α
l : List α
h : ∀ {x_1 : α}, ↑f x_1 ≠ x_1 → x_1 ∈ x :: l
hx : ↑f x = x
⊢ ∀ {x : α}, ↑f x ≠ x → x ∈ l
[PROOFSTEP]
intro y hy
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
l✝ : List α
f : Perm α
x : α
l : List α
h : ∀ {x_1 : α}, ↑f x_1 ≠ x_1 → x_1 ∈ x :: l
hx : ↑f x = x
y : α
hy : ↑f y ≠ y
⊢ y ∈ l
[PROOFSTEP]
exact List.mem_of_ne_of_mem (fun h => hy (by rwa [h])) (h hy)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
l✝ : List α
f : Perm α
x : α
l : List α
h✝ : ∀ {x_1 : α}, ↑f x_1 ≠ x_1 → x_1 ∈ x :: l
hx : ↑f x = x
y : α
hy : ↑f y ≠ y
h : y = x
⊢ ↑f y = y
[PROOFSTEP]
rwa [h]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
l✝ : List α
f : Perm α
x : α
l : List α
h : ∀ {x_1 : α}, ↑f x_1 ≠ x_1 → x_1 ∈ x :: l
hx : ¬↑f x = x
⊢ ∀ {x_1 : α}, ↑((cycleOf f x)⁻¹ * f) x_1 ≠ x_1 → x_1 ∈ l
[PROOFSTEP]
intro y hy
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
l✝ : List α
f : Perm α
x : α
l : List α
h : ∀ {x_1 : α}, ↑f x_1 ≠ x_1 → x_1 ∈ x :: l
hx : ¬↑f x = x
y : α
hy : ↑((cycleOf f x)⁻¹ * f) y ≠ y
⊢ y ∈ l
[PROOFSTEP]
exact
List.mem_of_ne_of_mem
(fun h : y = x => by
rw [h, mul_apply, Ne.def, inv_eq_iff_eq, cycleOf_apply_self] at hy
exact hy rfl)
(h fun h : f y = y => by
rw [mul_apply, h, Ne.def, inv_eq_iff_eq, cycleOf_apply] at hy
split_ifs at hy <;> tauto)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
l✝ : List α
f : Perm α
x : α
l : List α
h✝ : ∀ {x_1 : α}, ↑f x_1 ≠ x_1 → x_1 ∈ x :: l
hx : ¬↑f x = x
y : α
hy : ↑((cycleOf f x)⁻¹ * f) y ≠ y
h : y = x
⊢ False
[PROOFSTEP]
rw [h, mul_apply, Ne.def, inv_eq_iff_eq, cycleOf_apply_self] at hy
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
l✝ : List α
f : Perm α
x : α
l : List α
h✝ : ∀ {x_1 : α}, ↑f x_1 ≠ x_1 → x_1 ∈ x :: l
hx : ¬↑f x = x
y : α
hy : ¬↑f x = ↑f x
h : y = x
⊢ False
[PROOFSTEP]
exact hy rfl
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
l✝ : List α
f : Perm α
x : α
l : List α
h✝ : ∀ {x_1 : α}, ↑f x_1 ≠ x_1 → x_1 ∈ x :: l
hx : ¬↑f x = x
y : α
hy : ↑((cycleOf f x)⁻¹ * f) y ≠ y
h : ↑f y = y
⊢ False
[PROOFSTEP]
rw [mul_apply, h, Ne.def, inv_eq_iff_eq, cycleOf_apply] at hy
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
l✝ : List α
f : Perm α
x : α
l : List α
h✝ : ∀ {x_1 : α}, ↑f x_1 ≠ x_1 → x_1 ∈ x :: l
hx : ¬↑f x = x
y : α
hy : ¬y = if SameCycle f x y then ↑f y else y
h : ↑f y = y
⊢ False
[PROOFSTEP]
split_ifs at hy
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
l✝ : List α
f : Perm α
x : α
l : List α
h✝¹ : ∀ {x_1 : α}, ↑f x_1 ≠ x_1 → x_1 ∈ x :: l
hx : ¬↑f x = x
y : α
h : ↑f y = y
h✝ : SameCycle f x y
hy : ¬y = ↑f y
⊢ False
[PROOFSTEP]
tauto
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
l✝ : List α
f : Perm α
x : α
l : List α
h✝¹ : ∀ {x_1 : α}, ↑f x_1 ≠ x_1 → x_1 ∈ x :: l
hx : ¬↑f x = x
y : α
h : ↑f y = y
h✝ : ¬SameCycle f x y
hy : ¬y = y
⊢ False
[PROOFSTEP]
tauto
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
l✝ : List α
f : Perm α
x : α
l : List α
h : ∀ {x_1 : α}, ↑f x_1 ≠ x_1 → x_1 ∈ x :: l
hx : ¬↑f x = x
m : List (Perm α)
hm₁ : List.prod m = (cycleOf f x)⁻¹ * f
hm₂ : ∀ (g : Perm α), g ∈ m → IsCycle g
hm₃ : List.Pairwise Disjoint m
⊢ List.prod (cycleOf f x :: m) = f
[PROOFSTEP]
rw [List.prod_cons, hm₁]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
l✝ : List α
f : Perm α
x : α
l : List α
h : ∀ {x_1 : α}, ↑f x_1 ≠ x_1 → x_1 ∈ x :: l
hx : ¬↑f x = x
m : List (Perm α)
hm₁ : List.prod m = (cycleOf f x)⁻¹ * f
hm₂ : ∀ (g : Perm α), g ∈ m → IsCycle g
hm₃ : List.Pairwise Disjoint m
⊢ cycleOf f x * ((cycleOf f x)⁻¹ * f) = f
[PROOFSTEP]
simp
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
l✝ : List α
f : Perm α
x : α
l : List α
h : ∀ {x_1 : α}, ↑f x_1 ≠ x_1 → x_1 ∈ x :: l
hx : ¬↑f x = x
m : List (Perm α)
hm₁ : List.prod m = (cycleOf f x)⁻¹ * f
hm₂ : ∀ (g : Perm α), g ∈ m → IsCycle g
hm₃ : List.Pairwise Disjoint m
g : Perm α
hg : g ∈ m
y : α
hfy : ¬↑(cycleOf f x) y = y
hxy : SameCycle f x y
hgm : g :: List.erase m g ~ m
this : ∀ (h : Perm α), h ∈ List.erase m g → Disjoint g h
hgy : ↑g y ≠ y
⊢ ¬↑(List.prod (List.erase m g)) y = y
[PROOFSTEP]
have hsc : SameCycle f⁻¹ x (f y) := by rwa [sameCycle_inv, sameCycle_apply_right]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
l✝ : List α
f : Perm α
x : α
l : List α
h : ∀ {x_1 : α}, ↑f x_1 ≠ x_1 → x_1 ∈ x :: l
hx : ¬↑f x = x
m : List (Perm α)
hm₁ : List.prod m = (cycleOf f x)⁻¹ * f
hm₂ : ∀ (g : Perm α), g ∈ m → IsCycle g
hm₃ : List.Pairwise Disjoint m
g : Perm α
hg : g ∈ m
y : α
hfy : ¬↑(cycleOf f x) y = y
hxy : SameCycle f x y
hgm : g :: List.erase m g ~ m
this : ∀ (h : Perm α), h ∈ List.erase m g → Disjoint g h
hgy : ↑g y ≠ y
⊢ SameCycle f⁻¹ x (↑f y)
[PROOFSTEP]
rwa [sameCycle_inv, sameCycle_apply_right]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
l✝ : List α
f : Perm α
x : α
l : List α
h : ∀ {x_1 : α}, ↑f x_1 ≠ x_1 → x_1 ∈ x :: l
hx : ¬↑f x = x
m : List (Perm α)
hm₁ : List.prod m = (cycleOf f x)⁻¹ * f
hm₂ : ∀ (g : Perm α), g ∈ m → IsCycle g
hm₃ : List.Pairwise Disjoint m
g : Perm α
hg : g ∈ m
y : α
hfy : ¬↑(cycleOf f x) y = y
hxy : SameCycle f x y
hgm : g :: List.erase m g ~ m
this : ∀ (h : Perm α), h ∈ List.erase m g → Disjoint g h
hgy : ↑g y ≠ y
hsc : SameCycle f⁻¹ x (↑f y)
⊢ ¬↑(List.prod (List.erase m g)) y = y
[PROOFSTEP]
rw [disjoint_prod_perm hm₃ hgm.symm, List.prod_cons, ← eq_inv_mul_iff_mul_eq] at hm₁
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
l✝ : List α
f : Perm α
x : α
l : List α
h : ∀ {x_1 : α}, ↑f x_1 ≠ x_1 → x_1 ∈ x :: l
hx : ¬↑f x = x
m : List (Perm α)
hm₂ : ∀ (g : Perm α), g ∈ m → IsCycle g
hm₃ : List.Pairwise Disjoint m
g : Perm α
hm₁ : List.prod (List.erase m g) = g⁻¹ * ((cycleOf f x)⁻¹ * f)
hg : g ∈ m
y : α
hfy : ¬↑(cycleOf f x) y = y
hxy : SameCycle f x y
hgm : g :: List.erase m g ~ m
this : ∀ (h : Perm α), h ∈ List.erase m g → Disjoint g h
hgy : ↑g y ≠ y
hsc : SameCycle f⁻¹ x (↑f y)
⊢ ¬↑(List.prod (List.erase m g)) y = y
[PROOFSTEP]
rwa [hm₁, mul_apply, mul_apply, cycleOf_inv, hsc.cycleOf_apply, inv_apply_self, inv_eq_iff_eq, eq_comm]
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
⊢ σ ∈ l ↔ IsCycle σ ∧ ∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a
[PROOFSTEP]
suffices σ.IsCycle → (σ ∈ l ↔ ∀ (a : α) (_ : σ a ≠ a), σ a = l.prod a) by
exact ⟨fun hσ => ⟨h1 σ hσ, (this (h1 σ hσ)).mp hσ⟩, fun hσ => (this hσ.1).mpr hσ.2⟩
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
this : IsCycle σ → (σ ∈ l ↔ ∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a)
⊢ σ ∈ l ↔ IsCycle σ ∧ ∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a
[PROOFSTEP]
exact ⟨fun hσ => ⟨h1 σ hσ, (this (h1 σ hσ)).mp hσ⟩, fun hσ => (this hσ.1).mpr hσ.2⟩
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
⊢ IsCycle σ → (σ ∈ l ↔ ∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a)
[PROOFSTEP]
intro h3
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
h3 : IsCycle σ
⊢ σ ∈ l ↔ ∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a
[PROOFSTEP]
classical
cases nonempty_fintype α
constructor
· intro h a ha
exact eq_on_support_mem_disjoint h h2 _ (mem_support.mpr ha)
· intro h
have hσl : σ.support ⊆ l.prod.support := by
intro x hx
rw [mem_support] at hx
rwa [mem_support, ← h _ hx]
obtain ⟨a, ha, -⟩ := id h3
rw [← mem_support] at ha
obtain ⟨τ, hτ, hτa⟩ := exists_mem_support_of_mem_support_prod (hσl ha)
have hτl : ∀ x ∈ τ.support, τ x = l.prod x := eq_on_support_mem_disjoint hτ h2
have key : ∀ x ∈ σ.support ∩ τ.support, σ x = τ x := by
intro x hx
rw [h x (mem_support.mp (mem_of_mem_inter_left hx)), hτl x (mem_of_mem_inter_right hx)]
convert hτ
refine' h3.eq_on_support_inter_nonempty_congr (h1 _ hτ) key _ ha
exact key a (mem_inter_of_mem ha hτa)
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
h3 : IsCycle σ
⊢ σ ∈ l ↔ ∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a
[PROOFSTEP]
cases nonempty_fintype α
[GOAL]
case intro
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
h3 : IsCycle σ
val✝ : Fintype α
⊢ σ ∈ l ↔ ∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a
[PROOFSTEP]
constructor
[GOAL]
case intro.mp
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
h3 : IsCycle σ
val✝ : Fintype α
⊢ σ ∈ l → ∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a
[PROOFSTEP]
intro h a ha
[GOAL]
case intro.mp
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
h3 : IsCycle σ
val✝ : Fintype α
h : σ ∈ l
a : α
ha : ↑σ a ≠ a
⊢ ↑σ a = ↑(List.prod l) a
[PROOFSTEP]
exact eq_on_support_mem_disjoint h h2 _ (mem_support.mpr ha)
[GOAL]
case intro.mpr
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
h3 : IsCycle σ
val✝ : Fintype α
⊢ (∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a) → σ ∈ l
[PROOFSTEP]
intro h
[GOAL]
case intro.mpr
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
h3 : IsCycle σ
val✝ : Fintype α
h : ∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a
⊢ σ ∈ l
[PROOFSTEP]
have hσl : σ.support ⊆ l.prod.support := by
intro x hx
rw [mem_support] at hx
rwa [mem_support, ← h _ hx]
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
h3 : IsCycle σ
val✝ : Fintype α
h : ∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a
⊢ support σ ⊆ support (List.prod l)
[PROOFSTEP]
intro x hx
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
h3 : IsCycle σ
val✝ : Fintype α
h : ∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a
x : α
hx : x ∈ support σ
⊢ x ∈ support (List.prod l)
[PROOFSTEP]
rw [mem_support] at hx
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
h3 : IsCycle σ
val✝ : Fintype α
h : ∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a
x : α
hx : ↑σ x ≠ x
⊢ x ∈ support (List.prod l)
[PROOFSTEP]
rwa [mem_support, ← h _ hx]
[GOAL]
case intro.mpr
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
h3 : IsCycle σ
val✝ : Fintype α
h : ∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a
hσl : support σ ⊆ support (List.prod l)
⊢ σ ∈ l
[PROOFSTEP]
obtain ⟨a, ha, -⟩ := id h3
[GOAL]
case intro.mpr.intro.intro
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
h3 : IsCycle σ
val✝ : Fintype α
h : ∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a
hσl : support σ ⊆ support (List.prod l)
a : α
ha : ↑σ a ≠ a
⊢ σ ∈ l
[PROOFSTEP]
rw [← mem_support] at ha
[GOAL]
case intro.mpr.intro.intro
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
h3 : IsCycle σ
val✝ : Fintype α
h : ∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a
hσl : support σ ⊆ support (List.prod l)
a : α
ha✝ : ↑σ a ≠ a
ha : a ∈ support σ
⊢ σ ∈ l
[PROOFSTEP]
obtain ⟨τ, hτ, hτa⟩ := exists_mem_support_of_mem_support_prod (hσl ha)
[GOAL]
case intro.mpr.intro.intro.intro.intro
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
h3 : IsCycle σ
val✝ : Fintype α
h : ∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a
hσl : support σ ⊆ support (List.prod l)
a : α
ha✝ : ↑σ a ≠ a
ha : a ∈ support σ
τ : Perm α
hτ : τ ∈ l
hτa : a ∈ support τ
⊢ σ ∈ l
[PROOFSTEP]
have hτl : ∀ x ∈ τ.support, τ x = l.prod x := eq_on_support_mem_disjoint hτ h2
[GOAL]
case intro.mpr.intro.intro.intro.intro
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
h3 : IsCycle σ
val✝ : Fintype α
h : ∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a
hσl : support σ ⊆ support (List.prod l)
a : α
ha✝ : ↑σ a ≠ a
ha : a ∈ support σ
τ : Perm α
hτ : τ ∈ l
hτa : a ∈ support τ
hτl : ∀ (x : α), x ∈ support τ → ↑τ x = ↑(List.prod l) x
⊢ σ ∈ l
[PROOFSTEP]
have key : ∀ x ∈ σ.support ∩ τ.support, σ x = τ x := by
intro x hx
rw [h x (mem_support.mp (mem_of_mem_inter_left hx)), hτl x (mem_of_mem_inter_right hx)]
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
h3 : IsCycle σ
val✝ : Fintype α
h : ∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a
hσl : support σ ⊆ support (List.prod l)
a : α
ha✝ : ↑σ a ≠ a
ha : a ∈ support σ
τ : Perm α
hτ : τ ∈ l
hτa : a ∈ support τ
hτl : ∀ (x : α), x ∈ support τ → ↑τ x = ↑(List.prod l) x
⊢ ∀ (x : α), x ∈ support σ ∩ support τ → ↑σ x = ↑τ x
[PROOFSTEP]
intro x hx
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
h3 : IsCycle σ
val✝ : Fintype α
h : ∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a
hσl : support σ ⊆ support (List.prod l)
a : α
ha✝ : ↑σ a ≠ a
ha : a ∈ support σ
τ : Perm α
hτ : τ ∈ l
hτa : a ∈ support τ
hτl : ∀ (x : α), x ∈ support τ → ↑τ x = ↑(List.prod l) x
x : α
hx : x ∈ support σ ∩ support τ
⊢ ↑σ x = ↑τ x
[PROOFSTEP]
rw [h x (mem_support.mp (mem_of_mem_inter_left hx)), hτl x (mem_of_mem_inter_right hx)]
[GOAL]
case intro.mpr.intro.intro.intro.intro
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
h3 : IsCycle σ
val✝ : Fintype α
h : ∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a
hσl : support σ ⊆ support (List.prod l)
a : α
ha✝ : ↑σ a ≠ a
ha : a ∈ support σ
τ : Perm α
hτ : τ ∈ l
hτa : a ∈ support τ
hτl : ∀ (x : α), x ∈ support τ → ↑τ x = ↑(List.prod l) x
key : ∀ (x : α), x ∈ support σ ∩ support τ → ↑σ x = ↑τ x
⊢ σ ∈ l
[PROOFSTEP]
convert hτ
[GOAL]
case h.e'_4
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
h3 : IsCycle σ
val✝ : Fintype α
h : ∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a
hσl : support σ ⊆ support (List.prod l)
a : α
ha✝ : ↑σ a ≠ a
ha : a ∈ support σ
τ : Perm α
hτ : τ ∈ l
hτa : a ∈ support τ
hτl : ∀ (x : α), x ∈ support τ → ↑τ x = ↑(List.prod l) x
key : ∀ (x : α), x ∈ support σ ∩ support τ → ↑σ x = ↑τ x
⊢ σ = τ
[PROOFSTEP]
refine' h3.eq_on_support_inter_nonempty_congr (h1 _ hτ) key _ ha
[GOAL]
case h.e'_4
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l : List (Perm α)
h1 : ∀ (σ : Perm α), σ ∈ l → IsCycle σ
h2 : List.Pairwise Disjoint l
σ : Perm α
h3 : IsCycle σ
val✝ : Fintype α
h : ∀ (a : α), ↑σ a ≠ a → ↑σ a = ↑(List.prod l) a
hσl : support σ ⊆ support (List.prod l)
a : α
ha✝ : ↑σ a ≠ a
ha : a ∈ support σ
τ : Perm α
hτ : τ ∈ l
hτa : a ∈ support τ
hτl : ∀ (x : α), x ∈ support τ → ↑τ x = ↑(List.prod l) x
key : ∀ (x : α), x ∈ support σ ∩ support τ → ↑σ x = ↑τ x
⊢ ↑σ a = ↑τ a
[PROOFSTEP]
exact key a (mem_inter_of_mem ha hτa)
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l₁ l₂ : List (Perm α)
h₀ : List.prod l₁ = List.prod l₂
h₁l₁ : ∀ (σ : Perm α), σ ∈ l₁ → IsCycle σ
h₁l₂ : ∀ (σ : Perm α), σ ∈ l₂ → IsCycle σ
h₂l₁ : List.Pairwise Disjoint l₁
h₂l₂ : List.Pairwise Disjoint l₂
⊢ l₁ ~ l₂
[PROOFSTEP]
classical
refine'
(List.perm_ext (nodup_of_pairwise_disjoint_cycles h₁l₁ h₂l₁) (nodup_of_pairwise_disjoint_cycles h₁l₂ h₂l₂)).mpr
fun σ => _
by_cases hσ : σ.IsCycle
· obtain _ := not_forall.mp (mt ext hσ.ne_one)
rw [mem_list_cycles_iff h₁l₁ h₂l₁, mem_list_cycles_iff h₁l₂ h₂l₂, h₀]
· exact iff_of_false (mt (h₁l₁ σ) hσ) (mt (h₁l₂ σ) hσ)
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l₁ l₂ : List (Perm α)
h₀ : List.prod l₁ = List.prod l₂
h₁l₁ : ∀ (σ : Perm α), σ ∈ l₁ → IsCycle σ
h₁l₂ : ∀ (σ : Perm α), σ ∈ l₂ → IsCycle σ
h₂l₁ : List.Pairwise Disjoint l₁
h₂l₂ : List.Pairwise Disjoint l₂
⊢ l₁ ~ l₂
[PROOFSTEP]
refine'
(List.perm_ext (nodup_of_pairwise_disjoint_cycles h₁l₁ h₂l₁) (nodup_of_pairwise_disjoint_cycles h₁l₂ h₂l₂)).mpr
fun σ => _
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l₁ l₂ : List (Perm α)
h₀ : List.prod l₁ = List.prod l₂
h₁l₁ : ∀ (σ : Perm α), σ ∈ l₁ → IsCycle σ
h₁l₂ : ∀ (σ : Perm α), σ ∈ l₂ → IsCycle σ
h₂l₁ : List.Pairwise Disjoint l₁
h₂l₂ : List.Pairwise Disjoint l₂
σ : Perm α
⊢ σ ∈ l₁ ↔ σ ∈ l₂
[PROOFSTEP]
by_cases hσ : σ.IsCycle
[GOAL]
case pos
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l₁ l₂ : List (Perm α)
h₀ : List.prod l₁ = List.prod l₂
h₁l₁ : ∀ (σ : Perm α), σ ∈ l₁ → IsCycle σ
h₁l₂ : ∀ (σ : Perm α), σ ∈ l₂ → IsCycle σ
h₂l₁ : List.Pairwise Disjoint l₁
h₂l₂ : List.Pairwise Disjoint l₂
σ : Perm α
hσ : IsCycle σ
⊢ σ ∈ l₁ ↔ σ ∈ l₂
[PROOFSTEP]
obtain _ := not_forall.mp (mt ext hσ.ne_one)
[GOAL]
case pos
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l₁ l₂ : List (Perm α)
h₀ : List.prod l₁ = List.prod l₂
h₁l₁ : ∀ (σ : Perm α), σ ∈ l₁ → IsCycle σ
h₁l₂ : ∀ (σ : Perm α), σ ∈ l₂ → IsCycle σ
h₂l₁ : List.Pairwise Disjoint l₁
h₂l₂ : List.Pairwise Disjoint l₂
σ : Perm α
hσ : IsCycle σ
x✝ : ∃ x, ¬↑σ x = ↑1 x
⊢ σ ∈ l₁ ↔ σ ∈ l₂
[PROOFSTEP]
rw [mem_list_cycles_iff h₁l₁ h₂l₁, mem_list_cycles_iff h₁l₂ h₂l₂, h₀]
[GOAL]
case neg
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α✝
α : Type u_4
inst✝ : Finite α
l₁ l₂ : List (Perm α)
h₀ : List.prod l₁ = List.prod l₂
h₁l₁ : ∀ (σ : Perm α), σ ∈ l₁ → IsCycle σ
h₁l₂ : ∀ (σ : Perm α), σ ∈ l₂ → IsCycle σ
h₂l₁ : List.Pairwise Disjoint l₁
h₂l₂ : List.Pairwise Disjoint l₂
σ : Perm α
hσ : ¬IsCycle σ
⊢ σ ∈ l₁ ↔ σ ∈ l₂
[PROOFSTEP]
exact iff_of_false (mt (h₁l₁ σ) hσ) (mt (h₁l₂ σ) hσ)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f σ : Perm α
l : List (Perm α)
hn : List.Nodup l
⊢ cycleFactorsFinset σ = List.toFinset l ↔
(∀ (f : Perm α), f ∈ l → IsCycle f) ∧ List.Pairwise Disjoint l ∧ List.prod l = σ
[PROOFSTEP]
obtain ⟨⟨l', hp', hc', hd'⟩, hl⟩ := Trunc.exists_rep σ.truncCycleFactors
[GOAL]
case intro.mk.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f σ : Perm α
l : List (Perm α)
hn : List.Nodup l
l' : List (Perm α)
hp' : List.prod l' = σ
hc' : ∀ (g : Perm α), g ∈ l' → IsCycle g
hd' : List.Pairwise Disjoint l'
hl :
Trunc.mk
{ val := l',
property := (_ : List.prod l' = σ ∧ (∀ (g : Perm α), g ∈ l' → IsCycle g) ∧ List.Pairwise Disjoint l') } =
truncCycleFactors σ
⊢ cycleFactorsFinset σ = List.toFinset l ↔
(∀ (f : Perm α), f ∈ l → IsCycle f) ∧ List.Pairwise Disjoint l ∧ List.prod l = σ
[PROOFSTEP]
have ht : cycleFactorsFinset σ = l'.toFinset := by rw [cycleFactorsFinset, ← hl, Trunc.lift_mk]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f σ : Perm α
l : List (Perm α)
hn : List.Nodup l
l' : List (Perm α)
hp' : List.prod l' = σ
hc' : ∀ (g : Perm α), g ∈ l' → IsCycle g
hd' : List.Pairwise Disjoint l'
hl :
Trunc.mk
{ val := l',
property := (_ : List.prod l' = σ ∧ (∀ (g : Perm α), g ∈ l' → IsCycle g) ∧ List.Pairwise Disjoint l') } =
truncCycleFactors σ
⊢ cycleFactorsFinset σ = List.toFinset l'
[PROOFSTEP]
rw [cycleFactorsFinset, ← hl, Trunc.lift_mk]
[GOAL]
case intro.mk.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f σ : Perm α
l : List (Perm α)
hn : List.Nodup l
l' : List (Perm α)
hp' : List.prod l' = σ
hc' : ∀ (g : Perm α), g ∈ l' → IsCycle g
hd' : List.Pairwise Disjoint l'
hl :
Trunc.mk
{ val := l',
property := (_ : List.prod l' = σ ∧ (∀ (g : Perm α), g ∈ l' → IsCycle g) ∧ List.Pairwise Disjoint l') } =
truncCycleFactors σ
ht : cycleFactorsFinset σ = List.toFinset l'
⊢ cycleFactorsFinset σ = List.toFinset l ↔
(∀ (f : Perm α), f ∈ l → IsCycle f) ∧ List.Pairwise Disjoint l ∧ List.prod l = σ
[PROOFSTEP]
rw [ht]
[GOAL]
case intro.mk.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f σ : Perm α
l : List (Perm α)
hn : List.Nodup l
l' : List (Perm α)
hp' : List.prod l' = σ
hc' : ∀ (g : Perm α), g ∈ l' → IsCycle g
hd' : List.Pairwise Disjoint l'
hl :
Trunc.mk
{ val := l',
property := (_ : List.prod l' = σ ∧ (∀ (g : Perm α), g ∈ l' → IsCycle g) ∧ List.Pairwise Disjoint l') } =
truncCycleFactors σ
ht : cycleFactorsFinset σ = List.toFinset l'
⊢ List.toFinset l' = List.toFinset l ↔ (∀ (f : Perm α), f ∈ l → IsCycle f) ∧ List.Pairwise Disjoint l ∧ List.prod l = σ
[PROOFSTEP]
constructor
[GOAL]
case intro.mk.intro.intro.mp
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f σ : Perm α
l : List (Perm α)
hn : List.Nodup l
l' : List (Perm α)
hp' : List.prod l' = σ
hc' : ∀ (g : Perm α), g ∈ l' → IsCycle g
hd' : List.Pairwise Disjoint l'
hl :
Trunc.mk
{ val := l',
property := (_ : List.prod l' = σ ∧ (∀ (g : Perm α), g ∈ l' → IsCycle g) ∧ List.Pairwise Disjoint l') } =
truncCycleFactors σ
ht : cycleFactorsFinset σ = List.toFinset l'
⊢ List.toFinset l' = List.toFinset l → (∀ (f : Perm α), f ∈ l → IsCycle f) ∧ List.Pairwise Disjoint l ∧ List.prod l = σ
[PROOFSTEP]
intro h
[GOAL]
case intro.mk.intro.intro.mp
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f σ : Perm α
l : List (Perm α)
hn : List.Nodup l
l' : List (Perm α)
hp' : List.prod l' = σ
hc' : ∀ (g : Perm α), g ∈ l' → IsCycle g
hd' : List.Pairwise Disjoint l'
hl :
Trunc.mk
{ val := l',
property := (_ : List.prod l' = σ ∧ (∀ (g : Perm α), g ∈ l' → IsCycle g) ∧ List.Pairwise Disjoint l') } =
truncCycleFactors σ
ht : cycleFactorsFinset σ = List.toFinset l'
h : List.toFinset l' = List.toFinset l
⊢ (∀ (f : Perm α), f ∈ l → IsCycle f) ∧ List.Pairwise Disjoint l ∧ List.prod l = σ
[PROOFSTEP]
have hn' : l'.Nodup := nodup_of_pairwise_disjoint_cycles hc' hd'
[GOAL]
case intro.mk.intro.intro.mp
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f σ : Perm α
l : List (Perm α)
hn : List.Nodup l
l' : List (Perm α)
hp' : List.prod l' = σ
hc' : ∀ (g : Perm α), g ∈ l' → IsCycle g
hd' : List.Pairwise Disjoint l'
hl :
Trunc.mk
{ val := l',
property := (_ : List.prod l' = σ ∧ (∀ (g : Perm α), g ∈ l' → IsCycle g) ∧ List.Pairwise Disjoint l') } =
truncCycleFactors σ
ht : cycleFactorsFinset σ = List.toFinset l'
h : List.toFinset l' = List.toFinset l
hn' : List.Nodup l'
⊢ (∀ (f : Perm α), f ∈ l → IsCycle f) ∧ List.Pairwise Disjoint l ∧ List.prod l = σ
[PROOFSTEP]
have hperm : l ~ l' := List.perm_of_nodup_nodup_toFinset_eq hn hn' h.symm
[GOAL]
case intro.mk.intro.intro.mp
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f σ : Perm α
l : List (Perm α)
hn : List.Nodup l
l' : List (Perm α)
hp' : List.prod l' = σ
hc' : ∀ (g : Perm α), g ∈ l' → IsCycle g
hd' : List.Pairwise Disjoint l'
hl :
Trunc.mk
{ val := l',
property := (_ : List.prod l' = σ ∧ (∀ (g : Perm α), g ∈ l' → IsCycle g) ∧ List.Pairwise Disjoint l') } =
truncCycleFactors σ
ht : cycleFactorsFinset σ = List.toFinset l'
h : List.toFinset l' = List.toFinset l
hn' : List.Nodup l'
hperm : l ~ l'
⊢ (∀ (f : Perm α), f ∈ l → IsCycle f) ∧ List.Pairwise Disjoint l ∧ List.prod l = σ
[PROOFSTEP]
refine' ⟨_, _, _⟩
[GOAL]
case intro.mk.intro.intro.mp.refine'_1
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f σ : Perm α
l : List (Perm α)
hn : List.Nodup l
l' : List (Perm α)
hp' : List.prod l' = σ
hc' : ∀ (g : Perm α), g ∈ l' → IsCycle g
hd' : List.Pairwise Disjoint l'
hl :
Trunc.mk
{ val := l',
property := (_ : List.prod l' = σ ∧ (∀ (g : Perm α), g ∈ l' → IsCycle g) ∧ List.Pairwise Disjoint l') } =
truncCycleFactors σ
ht : cycleFactorsFinset σ = List.toFinset l'
h : List.toFinset l' = List.toFinset l
hn' : List.Nodup l'
hperm : l ~ l'
⊢ ∀ (f : Perm α), f ∈ l → IsCycle f
[PROOFSTEP]
exact fun _ h => hc' _ (hperm.subset h)
[GOAL]
case intro.mk.intro.intro.mp.refine'_2
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f σ : Perm α
l : List (Perm α)
hn : List.Nodup l
l' : List (Perm α)
hp' : List.prod l' = σ
hc' : ∀ (g : Perm α), g ∈ l' → IsCycle g
hd' : List.Pairwise Disjoint l'
hl :
Trunc.mk
{ val := l',
property := (_ : List.prod l' = σ ∧ (∀ (g : Perm α), g ∈ l' → IsCycle g) ∧ List.Pairwise Disjoint l') } =
truncCycleFactors σ
ht : cycleFactorsFinset σ = List.toFinset l'
h : List.toFinset l' = List.toFinset l
hn' : List.Nodup l'
hperm : l ~ l'
⊢ List.Pairwise Disjoint l
[PROOFSTEP]
rwa [List.Perm.pairwise_iff Disjoint.symmetric hperm]
[GOAL]
case intro.mk.intro.intro.mp.refine'_3
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f σ : Perm α
l : List (Perm α)
hn : List.Nodup l
l' : List (Perm α)
hp' : List.prod l' = σ
hc' : ∀ (g : Perm α), g ∈ l' → IsCycle g
hd' : List.Pairwise Disjoint l'
hl :
Trunc.mk
{ val := l',
property := (_ : List.prod l' = σ ∧ (∀ (g : Perm α), g ∈ l' → IsCycle g) ∧ List.Pairwise Disjoint l') } =
truncCycleFactors σ
ht : cycleFactorsFinset σ = List.toFinset l'
h : List.toFinset l' = List.toFinset l
hn' : List.Nodup l'
hperm : l ~ l'
⊢ List.prod l = σ
[PROOFSTEP]
rw [← hp', hperm.symm.prod_eq']
[GOAL]
case intro.mk.intro.intro.mp.refine'_3
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f σ : Perm α
l : List (Perm α)
hn : List.Nodup l
l' : List (Perm α)
hp' : List.prod l' = σ
hc' : ∀ (g : Perm α), g ∈ l' → IsCycle g
hd' : List.Pairwise Disjoint l'
hl :
Trunc.mk
{ val := l',
property := (_ : List.prod l' = σ ∧ (∀ (g : Perm α), g ∈ l' → IsCycle g) ∧ List.Pairwise Disjoint l') } =
truncCycleFactors σ
ht : cycleFactorsFinset σ = List.toFinset l'
h : List.toFinset l' = List.toFinset l
hn' : List.Nodup l'
hperm : l ~ l'
⊢ List.Pairwise Commute l'
[PROOFSTEP]
refine' hd'.imp _
[GOAL]
case intro.mk.intro.intro.mp.refine'_3
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f σ : Perm α
l : List (Perm α)
hn : List.Nodup l
l' : List (Perm α)
hp' : List.prod l' = σ
hc' : ∀ (g : Perm α), g ∈ l' → IsCycle g
hd' : List.Pairwise Disjoint l'
hl :
Trunc.mk
{ val := l',
property := (_ : List.prod l' = σ ∧ (∀ (g : Perm α), g ∈ l' → IsCycle g) ∧ List.Pairwise Disjoint l') } =
truncCycleFactors σ
ht : cycleFactorsFinset σ = List.toFinset l'
h : List.toFinset l' = List.toFinset l
hn' : List.Nodup l'
hperm : l ~ l'
⊢ ∀ {a b : Perm α}, Disjoint a b → Commute a b
[PROOFSTEP]
exact Disjoint.commute
[GOAL]
case intro.mk.intro.intro.mpr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f σ : Perm α
l : List (Perm α)
hn : List.Nodup l
l' : List (Perm α)
hp' : List.prod l' = σ
hc' : ∀ (g : Perm α), g ∈ l' → IsCycle g
hd' : List.Pairwise Disjoint l'
hl :
Trunc.mk
{ val := l',
property := (_ : List.prod l' = σ ∧ (∀ (g : Perm α), g ∈ l' → IsCycle g) ∧ List.Pairwise Disjoint l') } =
truncCycleFactors σ
ht : cycleFactorsFinset σ = List.toFinset l'
⊢ (∀ (f : Perm α), f ∈ l → IsCycle f) ∧ List.Pairwise Disjoint l ∧ List.prod l = σ → List.toFinset l' = List.toFinset l
[PROOFSTEP]
rintro ⟨hc, hd, hp⟩
[GOAL]
case intro.mk.intro.intro.mpr.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f σ : Perm α
l : List (Perm α)
hn : List.Nodup l
l' : List (Perm α)
hp' : List.prod l' = σ
hc' : ∀ (g : Perm α), g ∈ l' → IsCycle g
hd' : List.Pairwise Disjoint l'
hl :
Trunc.mk
{ val := l',
property := (_ : List.prod l' = σ ∧ (∀ (g : Perm α), g ∈ l' → IsCycle g) ∧ List.Pairwise Disjoint l') } =
truncCycleFactors σ
ht : cycleFactorsFinset σ = List.toFinset l'
hc : ∀ (f : Perm α), f ∈ l → IsCycle f
hd : List.Pairwise Disjoint l
hp : List.prod l = σ
⊢ List.toFinset l' = List.toFinset l
[PROOFSTEP]
refine' List.toFinset_eq_of_perm _ _ _
[GOAL]
case intro.mk.intro.intro.mpr.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f σ : Perm α
l : List (Perm α)
hn : List.Nodup l
l' : List (Perm α)
hp' : List.prod l' = σ
hc' : ∀ (g : Perm α), g ∈ l' → IsCycle g
hd' : List.Pairwise Disjoint l'
hl :
Trunc.mk
{ val := l',
property := (_ : List.prod l' = σ ∧ (∀ (g : Perm α), g ∈ l' → IsCycle g) ∧ List.Pairwise Disjoint l') } =
truncCycleFactors σ
ht : cycleFactorsFinset σ = List.toFinset l'
hc : ∀ (f : Perm α), f ∈ l → IsCycle f
hd : List.Pairwise Disjoint l
hp : List.prod l = σ
⊢ l' ~ l
[PROOFSTEP]
refine' list_cycles_perm_list_cycles _ hc' hc hd' hd
[GOAL]
case intro.mk.intro.intro.mpr.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f σ : Perm α
l : List (Perm α)
hn : List.Nodup l
l' : List (Perm α)
hp' : List.prod l' = σ
hc' : ∀ (g : Perm α), g ∈ l' → IsCycle g
hd' : List.Pairwise Disjoint l'
hl :
Trunc.mk
{ val := l',
property := (_ : List.prod l' = σ ∧ (∀ (g : Perm α), g ∈ l' → IsCycle g) ∧ List.Pairwise Disjoint l') } =
truncCycleFactors σ
ht : cycleFactorsFinset σ = List.toFinset l'
hc : ∀ (f : Perm α), f ∈ l → IsCycle f
hd : List.Pairwise Disjoint l
hp : List.prod l = σ
⊢ List.prod l' = List.prod l
[PROOFSTEP]
rw [hp, hp']
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f σ : Perm α
s : Finset (Perm α)
⊢ cycleFactorsFinset σ = s ↔
(∀ (f : Perm α), f ∈ s → IsCycle f) ∧
∃ h, noncommProd s id (_ : Set.Pairwise ↑s fun a b => Commute (id a) (id b)) = σ
[PROOFSTEP]
obtain ⟨l, hl, rfl⟩ := s.exists_list_nodup_eq
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f σ : Perm α
l : List (Perm α)
hl : List.Nodup l
⊢ cycleFactorsFinset σ = List.toFinset l ↔
(∀ (f : Perm α), f ∈ List.toFinset l → IsCycle f) ∧
∃ h, noncommProd (List.toFinset l) id (_ : Set.Pairwise ↑(List.toFinset l) fun a b => Commute (id a) (id b)) = σ
[PROOFSTEP]
simp [cycleFactorsFinset_eq_list_toFinset, hl]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f p : Perm α
⊢ p ∈ cycleFactorsFinset f ↔ IsCycle p ∧ ∀ (a : α), a ∈ support p → ↑p a = ↑f a
[PROOFSTEP]
obtain ⟨l, hl, hl'⟩ := f.cycleFactorsFinset.exists_list_nodup_eq
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f p : Perm α
l : List (Perm α)
hl : List.Nodup l
hl' : List.toFinset l = cycleFactorsFinset f
⊢ p ∈ cycleFactorsFinset f ↔ IsCycle p ∧ ∀ (a : α), a ∈ support p → ↑p a = ↑f a
[PROOFSTEP]
rw [← hl']
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f p : Perm α
l : List (Perm α)
hl : List.Nodup l
hl' : List.toFinset l = cycleFactorsFinset f
⊢ p ∈ List.toFinset l ↔ IsCycle p ∧ ∀ (a : α), a ∈ support p → ↑p a = ↑f a
[PROOFSTEP]
rw [eq_comm, cycleFactorsFinset_eq_list_toFinset hl] at hl'
[GOAL]
case intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f p : Perm α
l : List (Perm α)
hl : List.Nodup l
hl' : (∀ (f : Perm α), f ∈ l → IsCycle f) ∧ List.Pairwise Disjoint l ∧ List.prod l = f
⊢ p ∈ List.toFinset l ↔ IsCycle p ∧ ∀ (a : α), a ∈ support p → ↑p a = ↑f a
[PROOFSTEP]
simpa [List.mem_toFinset, Ne.def, ← hl'.right.right] using mem_list_cycles_iff hl'.left hl'.right.left
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f : Perm α
x : α
⊢ cycleOf f x ∈ cycleFactorsFinset f ↔ x ∈ support f
[PROOFSTEP]
rw [mem_cycleFactorsFinset_iff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f : Perm α
x : α
⊢ (IsCycle (cycleOf f x) ∧ ∀ (a : α), a ∈ support (cycleOf f x) → ↑(cycleOf f x) a = ↑f a) ↔ x ∈ support f
[PROOFSTEP]
constructor
[GOAL]
case mp
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f : Perm α
x : α
⊢ (IsCycle (cycleOf f x) ∧ ∀ (a : α), a ∈ support (cycleOf f x) → ↑(cycleOf f x) a = ↑f a) → x ∈ support f
[PROOFSTEP]
rintro ⟨hc, _⟩
[GOAL]
case mp.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f : Perm α
x : α
hc : IsCycle (cycleOf f x)
right✝ : ∀ (a : α), a ∈ support (cycleOf f x) → ↑(cycleOf f x) a = ↑f a
⊢ x ∈ support f
[PROOFSTEP]
contrapose! hc
[GOAL]
case mp.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f : Perm α
x : α
right✝ : ∀ (a : α), a ∈ support (cycleOf f x) → ↑(cycleOf f x) a = ↑f a
hc : ¬x ∈ support f
⊢ ¬IsCycle (cycleOf f x)
[PROOFSTEP]
rw [not_mem_support, ← cycleOf_eq_one_iff] at hc
[GOAL]
case mp.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f : Perm α
x : α
right✝ : ∀ (a : α), a ∈ support (cycleOf f x) → ↑(cycleOf f x) a = ↑f a
hc✝ : ↑f x = x
hc : cycleOf f x = 1
⊢ ¬IsCycle (cycleOf f x)
[PROOFSTEP]
simp [hc]
[GOAL]
case mpr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f : Perm α
x : α
⊢ x ∈ support f → IsCycle (cycleOf f x) ∧ ∀ (a : α), a ∈ support (cycleOf f x) → ↑(cycleOf f x) a = ↑f a
[PROOFSTEP]
intro hx
[GOAL]
case mpr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f : Perm α
x : α
hx : x ∈ support f
⊢ IsCycle (cycleOf f x) ∧ ∀ (a : α), a ∈ support (cycleOf f x) → ↑(cycleOf f x) a = ↑f a
[PROOFSTEP]
refine' ⟨isCycle_cycleOf _ (mem_support.mp hx), _⟩
[GOAL]
case mpr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f : Perm α
x : α
hx : x ∈ support f
⊢ ∀ (a : α), a ∈ support (cycleOf f x) → ↑(cycleOf f x) a = ↑f a
[PROOFSTEP]
intro y hy
[GOAL]
case mpr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f : Perm α
x : α
hx : x ∈ support f
y : α
hy : y ∈ support (cycleOf f x)
⊢ ↑(cycleOf f x) y = ↑f y
[PROOFSTEP]
rw [mem_support] at hy
[GOAL]
case mpr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f : Perm α
x : α
hx : x ∈ support f
y : α
hy : ↑(cycleOf f x) y ≠ y
⊢ ↑(cycleOf f x) y = ↑f y
[PROOFSTEP]
rw [cycleOf_apply]
[GOAL]
case mpr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f : Perm α
x : α
hx : x ∈ support f
y : α
hy : ↑(cycleOf f x) y ≠ y
⊢ (if SameCycle f x y then ↑f y else y) = ↑f y
[PROOFSTEP]
split_ifs with H
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f : Perm α
x : α
hx : x ∈ support f
y : α
hy : ↑(cycleOf f x) y ≠ y
H : SameCycle f x y
⊢ ↑f y = ↑f y
[PROOFSTEP]
rfl
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f : Perm α
x : α
hx : x ∈ support f
y : α
hy : ↑(cycleOf f x) y ≠ y
H : ¬SameCycle f x y
⊢ y = ↑f y
[PROOFSTEP]
rw [cycleOf_apply_of_not_sameCycle H] at hy
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f : Perm α
x : α
hx : x ∈ support f
y : α
hy : y ≠ y
H : ¬SameCycle f x y
⊢ y = ↑f y
[PROOFSTEP]
contradiction
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ p f : Perm α
h : p ∈ cycleFactorsFinset f
⊢ support p ≤ support f
[PROOFSTEP]
rw [mem_cycleFactorsFinset_iff] at h
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ p f : Perm α
h : IsCycle p ∧ ∀ (a : α), a ∈ support p → ↑p a = ↑f a
⊢ support p ≤ support f
[PROOFSTEP]
intro x hx
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ p f : Perm α
h : IsCycle p ∧ ∀ (a : α), a ∈ support p → ↑p a = ↑f a
x : α
hx : x ∈ support p
⊢ x ∈ support f
[PROOFSTEP]
rwa [mem_support, ← h.right x hx, ← mem_support]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f : Perm α
⊢ cycleFactorsFinset f = ∅ ↔ f = 1
[PROOFSTEP]
simpa [cycleFactorsFinset_eq_finset] using eq_comm
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f : Perm α
⊢ cycleFactorsFinset 1 = ∅
[PROOFSTEP]
simp [cycleFactorsFinset_eq_empty_iff]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f : Perm α
⊢ cycleFactorsFinset f = {f} ↔ IsCycle f
[PROOFSTEP]
simp [cycleFactorsFinset_eq_finset]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
⊢ cycleFactorsFinset f = {g} ↔ IsCycle f ∧ f = g
[PROOFSTEP]
suffices f = g → (g.IsCycle ↔ f.IsCycle) by
rw [cycleFactorsFinset_eq_finset]
simpa [eq_comm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
this : f = g → (IsCycle g ↔ IsCycle f)
⊢ cycleFactorsFinset f = {g} ↔ IsCycle f ∧ f = g
[PROOFSTEP]
rw [cycleFactorsFinset_eq_finset]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
this : f = g → (IsCycle g ↔ IsCycle f)
⊢ ((∀ (f : Perm α), f ∈ {g} → IsCycle f) ∧
∃ h, noncommProd {g} id (_ : Set.Pairwise ↑{g} fun a b => Commute (id a) (id b)) = f) ↔
IsCycle f ∧ f = g
[PROOFSTEP]
simpa [eq_comm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
⊢ f = g → (IsCycle g ↔ IsCycle f)
[PROOFSTEP]
rintro rfl
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f : Perm α
⊢ IsCycle f ↔ IsCycle f
[PROOFSTEP]
exact Iff.rfl
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f : Perm α
⊢ Injective cycleFactorsFinset
[PROOFSTEP]
intro f g h
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h : cycleFactorsFinset f = cycleFactorsFinset g
⊢ f = g
[PROOFSTEP]
rw [← cycleFactorsFinset_noncommProd f]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h : cycleFactorsFinset f = cycleFactorsFinset g
⊢ noncommProd (cycleFactorsFinset f) id (_ : Set.Pairwise (↑(cycleFactorsFinset f)) Commute) = g
[PROOFSTEP]
simpa [h] using cycleFactorsFinset_noncommProd g
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h : Disjoint f g
⊢ _root_.Disjoint (cycleFactorsFinset f) (cycleFactorsFinset g)
[PROOFSTEP]
rw [disjoint_iff_disjoint_support] at h
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h✝ : Disjoint f g
h : _root_.Disjoint (support f) (support g)
⊢ _root_.Disjoint (cycleFactorsFinset f) (cycleFactorsFinset g)
[PROOFSTEP]
rw [Finset.disjoint_left]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h✝ : Disjoint f g
h : _root_.Disjoint (support f) (support g)
⊢ ∀ ⦃a : Perm α⦄, a ∈ cycleFactorsFinset f → ¬a ∈ cycleFactorsFinset g
[PROOFSTEP]
intro x hx hy
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h✝ : Disjoint f g
h : _root_.Disjoint (support f) (support g)
x : Perm α
hx : x ∈ cycleFactorsFinset f
hy : x ∈ cycleFactorsFinset g
⊢ False
[PROOFSTEP]
simp only [mem_cycleFactorsFinset_iff, mem_support] at hx hy
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h✝ : Disjoint f g
h : _root_.Disjoint (support f) (support g)
x : Perm α
hx : IsCycle x ∧ ∀ (a : α), ↑x a ≠ a → ↑x a = ↑f a
hy : IsCycle x ∧ ∀ (a : α), ↑x a ≠ a → ↑x a = ↑g a
⊢ False
[PROOFSTEP]
obtain ⟨⟨⟨a, ha, -⟩, hf⟩, -, hg⟩ := hx, hy
[GOAL]
case intro.intro.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h✝ : Disjoint f g
h : _root_.Disjoint (support f) (support g)
x : Perm α
hf : ∀ (a : α), ↑x a ≠ a → ↑x a = ↑f a
a : α
ha : ↑x a ≠ a
hg : ∀ (a : α), ↑x a ≠ a → ↑x a = ↑g a
⊢ False
[PROOFSTEP]
have := h.le_bot (by simp [ha, ← hf a ha, ← hg a ha] : a ∈ f.support ∩ g.support)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h✝ : Disjoint f g
h : _root_.Disjoint (support f) (support g)
x : Perm α
hf : ∀ (a : α), ↑x a ≠ a → ↑x a = ↑f a
a : α
ha : ↑x a ≠ a
hg : ∀ (a : α), ↑x a ≠ a → ↑x a = ↑g a
⊢ a ∈ support f ∩ support g
[PROOFSTEP]
simp [ha, ← hf a ha, ← hg a ha]
[GOAL]
case intro.intro.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h✝ : Disjoint f g
h : _root_.Disjoint (support f) (support g)
x : Perm α
hf : ∀ (a : α), ↑x a ≠ a → ↑x a = ↑f a
a : α
ha : ↑x a ≠ a
hg : ∀ (a : α), ↑x a ≠ a → ↑x a = ↑g a
this : a ∈ ⊥
⊢ False
[PROOFSTEP]
tauto
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h : Disjoint f g
⊢ cycleFactorsFinset (f * g) = cycleFactorsFinset f ∪ cycleFactorsFinset g
[PROOFSTEP]
rw [cycleFactorsFinset_eq_finset]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h : Disjoint f g
⊢ (∀ (f_1 : Perm α), f_1 ∈ cycleFactorsFinset f ∪ cycleFactorsFinset g → IsCycle f_1) ∧
∃ h,
noncommProd (cycleFactorsFinset f ∪ cycleFactorsFinset g) id
(_ : Set.Pairwise ↑(cycleFactorsFinset f ∪ cycleFactorsFinset g) fun a b => Commute (id a) (id b)) =
f * g
[PROOFSTEP]
refine' ⟨_, _, _⟩
[GOAL]
case refine'_1
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h : Disjoint f g
⊢ ∀ (f_1 : Perm α), f_1 ∈ cycleFactorsFinset f ∪ cycleFactorsFinset g → IsCycle f_1
[PROOFSTEP]
simp [or_imp, mem_cycleFactorsFinset_iff, forall_swap]
[GOAL]
case refine'_2
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h : Disjoint f g
⊢ Set.Pairwise (↑(cycleFactorsFinset f ∪ cycleFactorsFinset g)) Disjoint
[PROOFSTEP]
rw [coe_union, Set.pairwise_union_of_symmetric Disjoint.symmetric]
[GOAL]
case refine'_2
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h : Disjoint f g
⊢ Set.Pairwise (↑(cycleFactorsFinset f)) Disjoint ∧
Set.Pairwise (↑(cycleFactorsFinset g)) Disjoint ∧
∀ (a : Perm α), a ∈ ↑(cycleFactorsFinset f) → ∀ (b : Perm α), b ∈ ↑(cycleFactorsFinset g) → a ≠ b → Disjoint a b
[PROOFSTEP]
exact
⟨cycleFactorsFinset_pairwise_disjoint _, cycleFactorsFinset_pairwise_disjoint _, fun x hx y hy _ =>
h.mono (mem_cycleFactorsFinset_support_le hx) (mem_cycleFactorsFinset_support_le hy)⟩
[GOAL]
case refine'_3
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h : Disjoint f g
⊢ noncommProd (cycleFactorsFinset f ∪ cycleFactorsFinset g) id
(_ : Set.Pairwise ↑(cycleFactorsFinset f ∪ cycleFactorsFinset g) fun a b => Commute (id a) (id b)) =
f * g
[PROOFSTEP]
rw [noncommProd_union_of_disjoint h.disjoint_cycleFactorsFinset]
[GOAL]
case refine'_3
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h : Disjoint f g
⊢ noncommProd (cycleFactorsFinset f) id (_ : Set.Pairwise ↑(cycleFactorsFinset f) fun a b => Commute (id a) (id b)) *
noncommProd (cycleFactorsFinset g) id
(_ : Set.Pairwise ↑(cycleFactorsFinset g) fun a b => Commute (id a) (id b)) =
f * g
[PROOFSTEP]
rw [cycleFactorsFinset_noncommProd, cycleFactorsFinset_noncommProd]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h : f ∈ cycleFactorsFinset g
⊢ Disjoint (g * f⁻¹) f
[PROOFSTEP]
rw [mem_cycleFactorsFinset_iff] at h
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑g a
⊢ Disjoint (g * f⁻¹) f
[PROOFSTEP]
intro x
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑g a
x : α
⊢ ↑(g * f⁻¹) x = x ∨ ↑f x = x
[PROOFSTEP]
by_cases hx : f x = x
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑g a
x : α
hx : ↑f x = x
⊢ ↑(g * f⁻¹) x = x ∨ ↑f x = x
[PROOFSTEP]
exact Or.inr hx
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑g a
x : α
hx : ¬↑f x = x
⊢ ↑(g * f⁻¹) x = x ∨ ↑f x = x
[PROOFSTEP]
refine' Or.inl _
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑g a
x : α
hx : ¬↑f x = x
⊢ ↑(g * f⁻¹) x = x
[PROOFSTEP]
rw [mul_apply, ← h.right, apply_inv_self]
[GOAL]
case neg.a
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f g : Perm α
h : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑g a
x : α
hx : ¬↑f x = x
⊢ ↑f⁻¹ x ∈ support f
[PROOFSTEP]
rwa [← support_inv, apply_mem_support, support_inv, mem_support]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f c : Perm α
a : α
ha : a ∈ support c
hc : c ∈ cycleFactorsFinset f
⊢ c = cycleOf f a
[PROOFSTEP]
suffices f.cycleOf a = c.cycleOf a by
rw [this]
apply symm
exact Equiv.Perm.IsCycle.cycleOf_eq (Equiv.Perm.mem_cycleFactorsFinset_iff.mp hc).left (Equiv.Perm.mem_support.mp ha)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f c : Perm α
a : α
ha : a ∈ support c
hc : c ∈ cycleFactorsFinset f
this : cycleOf f a = cycleOf c a
⊢ c = cycleOf f a
[PROOFSTEP]
rw [this]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f c : Perm α
a : α
ha : a ∈ support c
hc : c ∈ cycleFactorsFinset f
this : cycleOf f a = cycleOf c a
⊢ c = cycleOf c a
[PROOFSTEP]
apply symm
[GOAL]
case a
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f c : Perm α
a : α
ha : a ∈ support c
hc : c ∈ cycleFactorsFinset f
this : cycleOf f a = cycleOf c a
⊢ cycleOf c a = c
[PROOFSTEP]
exact Equiv.Perm.IsCycle.cycleOf_eq (Equiv.Perm.mem_cycleFactorsFinset_iff.mp hc).left (Equiv.Perm.mem_support.mp ha)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f c : Perm α
a : α
ha : a ∈ support c
hc : c ∈ cycleFactorsFinset f
⊢ cycleOf f a = cycleOf c a
[PROOFSTEP]
let hfc := (Equiv.Perm.disjoint_mul_inv_of_mem_cycleFactorsFinset hc).symm
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f c : Perm α
a : α
ha : a ∈ support c
hc : c ∈ cycleFactorsFinset f
hfc : Disjoint c (f * c⁻¹) := Disjoint.symm (disjoint_mul_inv_of_mem_cycleFactorsFinset hc)
⊢ cycleOf f a = cycleOf c a
[PROOFSTEP]
let hfc2 := Perm.Disjoint.commute hfc
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f c : Perm α
a : α
ha : a ∈ support c
hc : c ∈ cycleFactorsFinset f
hfc : Disjoint c (f * c⁻¹) := Disjoint.symm (disjoint_mul_inv_of_mem_cycleFactorsFinset hc)
hfc2 : Commute c (f * c⁻¹) := Disjoint.commute hfc
⊢ cycleOf f a = cycleOf c a
[PROOFSTEP]
rw [← Equiv.Perm.cycleOf_mul_of_apply_right_eq_self hfc2]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f c : Perm α
a : α
ha : a ∈ support c
hc : c ∈ cycleFactorsFinset f
hfc : Disjoint c (f * c⁻¹) := Disjoint.symm (disjoint_mul_inv_of_mem_cycleFactorsFinset hc)
hfc2 : Commute c (f * c⁻¹) := Disjoint.commute hfc
⊢ cycleOf f a = cycleOf (c * (f * c⁻¹)) a
case hx
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f c : Perm α
a : α
ha : a ∈ support c
hc : c ∈ cycleFactorsFinset f
hfc : Disjoint c (f * c⁻¹) := Disjoint.symm (disjoint_mul_inv_of_mem_cycleFactorsFinset hc)
hfc2 : Commute c (f * c⁻¹) := Disjoint.commute hfc
⊢ ↑(f * c⁻¹) a = a
[PROOFSTEP]
simp only [hfc2.eq, inv_mul_cancel_right]
-- a est dans le support de c, donc pas dans celui de g c⁻¹
[GOAL]
case hx
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f✝ f c : Perm α
a : α
ha : a ∈ support c
hc : c ∈ cycleFactorsFinset f
hfc : Disjoint c (f * c⁻¹) := Disjoint.symm (disjoint_mul_inv_of_mem_cycleFactorsFinset hc)
hfc2 : Commute c (f * c⁻¹) := Disjoint.commute hfc
⊢ ↑(f * c⁻¹) a = a
[PROOFSTEP]
exact Equiv.Perm.not_mem_support.mp (Finset.disjoint_left.mp (Equiv.Perm.Disjoint.disjoint_support hfc) ha)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Finite β
P : Perm β → Prop
σ : Perm β
base_one : P 1
base_cycles : ∀ (σ : Perm β), IsCycle σ → P σ
induction_disjoint : ∀ (σ τ : Perm β), Disjoint σ τ → IsCycle σ → P σ → P τ → P (σ * τ)
⊢ P σ
[PROOFSTEP]
cases nonempty_fintype β
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Finite β
P : Perm β → Prop
σ : Perm β
base_one : P 1
base_cycles : ∀ (σ : Perm β), IsCycle σ → P σ
induction_disjoint : ∀ (σ τ : Perm β), Disjoint σ τ → IsCycle σ → P σ → P τ → P (σ * τ)
val✝ : Fintype β
⊢ P σ
[PROOFSTEP]
suffices ∀ l : List (Perm β), (∀ τ : Perm β, τ ∈ l → τ.IsCycle) → l.Pairwise Disjoint → P l.prod by
classical
let x := σ.truncCycleFactors.out
exact (congr_arg P x.2.1).mp (this x.1 x.2.2.1 x.2.2.2)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Finite β
P : Perm β → Prop
σ : Perm β
base_one : P 1
base_cycles : ∀ (σ : Perm β), IsCycle σ → P σ
induction_disjoint : ∀ (σ τ : Perm β), Disjoint σ τ → IsCycle σ → P σ → P τ → P (σ * τ)
val✝ : Fintype β
this : ∀ (l : List (Perm β)), (∀ (τ : Perm β), τ ∈ l → IsCycle τ) → List.Pairwise Disjoint l → P (List.prod l)
⊢ P σ
[PROOFSTEP]
classical
let x := σ.truncCycleFactors.out
exact (congr_arg P x.2.1).mp (this x.1 x.2.2.1 x.2.2.2)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Finite β
P : Perm β → Prop
σ : Perm β
base_one : P 1
base_cycles : ∀ (σ : Perm β), IsCycle σ → P σ
induction_disjoint : ∀ (σ τ : Perm β), Disjoint σ τ → IsCycle σ → P σ → P τ → P (σ * τ)
val✝ : Fintype β
this : ∀ (l : List (Perm β)), (∀ (τ : Perm β), τ ∈ l → IsCycle τ) → List.Pairwise Disjoint l → P (List.prod l)
⊢ P σ
[PROOFSTEP]
let x := σ.truncCycleFactors.out
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Finite β
P : Perm β → Prop
σ : Perm β
base_one : P 1
base_cycles : ∀ (σ : Perm β), IsCycle σ → P σ
induction_disjoint : ∀ (σ τ : Perm β), Disjoint σ τ → IsCycle σ → P σ → P τ → P (σ * τ)
val✝ : Fintype β
this : ∀ (l : List (Perm β)), (∀ (τ : Perm β), τ ∈ l → IsCycle τ) → List.Pairwise Disjoint l → P (List.prod l)
x : { l // List.prod l = σ ∧ (∀ (g : Perm β), g ∈ l → IsCycle g) ∧ List.Pairwise Disjoint l } :=
Trunc.out (truncCycleFactors σ)
⊢ P σ
[PROOFSTEP]
exact (congr_arg P x.2.1).mp (this x.1 x.2.2.1 x.2.2.2)
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Finite β
P : Perm β → Prop
σ : Perm β
base_one : P 1
base_cycles : ∀ (σ : Perm β), IsCycle σ → P σ
induction_disjoint : ∀ (σ τ : Perm β), Disjoint σ τ → IsCycle σ → P σ → P τ → P (σ * τ)
val✝ : Fintype β
⊢ ∀ (l : List (Perm β)), (∀ (τ : Perm β), τ ∈ l → IsCycle τ) → List.Pairwise Disjoint l → P (List.prod l)
[PROOFSTEP]
intro l
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Finite β
P : Perm β → Prop
σ : Perm β
base_one : P 1
base_cycles : ∀ (σ : Perm β), IsCycle σ → P σ
induction_disjoint : ∀ (σ τ : Perm β), Disjoint σ τ → IsCycle σ → P σ → P τ → P (σ * τ)
val✝ : Fintype β
l : List (Perm β)
⊢ (∀ (τ : Perm β), τ ∈ l → IsCycle τ) → List.Pairwise Disjoint l → P (List.prod l)
[PROOFSTEP]
induction' l with σ l ih
[GOAL]
case intro.nil
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Finite β
P : Perm β → Prop
σ : Perm β
base_one : P 1
base_cycles : ∀ (σ : Perm β), IsCycle σ → P σ
induction_disjoint : ∀ (σ τ : Perm β), Disjoint σ τ → IsCycle σ → P σ → P τ → P (σ * τ)
val✝ : Fintype β
⊢ (∀ (τ : Perm β), τ ∈ [] → IsCycle τ) → List.Pairwise Disjoint [] → P (List.prod [])
[PROOFSTEP]
exact fun _ _ => base_one
[GOAL]
case intro.cons
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Finite β
P : Perm β → Prop
σ✝ : Perm β
base_one : P 1
base_cycles : ∀ (σ : Perm β), IsCycle σ → P σ
induction_disjoint : ∀ (σ τ : Perm β), Disjoint σ τ → IsCycle σ → P σ → P τ → P (σ * τ)
val✝ : Fintype β
σ : Perm β
l : List (Perm β)
ih : (∀ (τ : Perm β), τ ∈ l → IsCycle τ) → List.Pairwise Disjoint l → P (List.prod l)
⊢ (∀ (τ : Perm β), τ ∈ σ :: l → IsCycle τ) → List.Pairwise Disjoint (σ :: l) → P (List.prod (σ :: l))
[PROOFSTEP]
intro h1 h2
[GOAL]
case intro.cons
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Finite β
P : Perm β → Prop
σ✝ : Perm β
base_one : P 1
base_cycles : ∀ (σ : Perm β), IsCycle σ → P σ
induction_disjoint : ∀ (σ τ : Perm β), Disjoint σ τ → IsCycle σ → P σ → P τ → P (σ * τ)
val✝ : Fintype β
σ : Perm β
l : List (Perm β)
ih : (∀ (τ : Perm β), τ ∈ l → IsCycle τ) → List.Pairwise Disjoint l → P (List.prod l)
h1 : ∀ (τ : Perm β), τ ∈ σ :: l → IsCycle τ
h2 : List.Pairwise Disjoint (σ :: l)
⊢ P (List.prod (σ :: l))
[PROOFSTEP]
rw [List.prod_cons]
[GOAL]
case intro.cons
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Finite β
P : Perm β → Prop
σ✝ : Perm β
base_one : P 1
base_cycles : ∀ (σ : Perm β), IsCycle σ → P σ
induction_disjoint : ∀ (σ τ : Perm β), Disjoint σ τ → IsCycle σ → P σ → P τ → P (σ * τ)
val✝ : Fintype β
σ : Perm β
l : List (Perm β)
ih : (∀ (τ : Perm β), τ ∈ l → IsCycle τ) → List.Pairwise Disjoint l → P (List.prod l)
h1 : ∀ (τ : Perm β), τ ∈ σ :: l → IsCycle τ
h2 : List.Pairwise Disjoint (σ :: l)
⊢ P (σ * List.prod l)
[PROOFSTEP]
exact
induction_disjoint σ l.prod (disjoint_prod_right _ (List.pairwise_cons.mp h2).1) (h1 _ (List.mem_cons_self _ _))
(base_cycles σ (h1 σ (l.mem_cons_self σ))) (ih (fun τ hτ => h1 τ (List.mem_cons_of_mem σ hτ)) h2.of_cons)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
f g : Perm α
h : f ∈ cycleFactorsFinset g
⊢ cycleFactorsFinset (g * f⁻¹) = cycleFactorsFinset g \ {f}
[PROOFSTEP]
revert f
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g : Perm α
⊢ ∀ {f : Perm α}, f ∈ cycleFactorsFinset g → cycleFactorsFinset (g * f⁻¹) = cycleFactorsFinset g \ {f}
[PROOFSTEP]
refine'
cycle_induction_on (P := fun {g : Perm α} ↦
∀ {f}, (f ∈ cycleFactorsFinset g) → cycleFactorsFinset (g * f⁻¹) = cycleFactorsFinset g \ { f }) _ _ _ _
[GOAL]
case refine'_1
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ : Perm α
⊢ fun {g} => ∀ {f : Perm α}, f ∈ cycleFactorsFinset g → cycleFactorsFinset (g * f⁻¹) = cycleFactorsFinset g \ {f}
[PROOFSTEP]
simp
[GOAL]
case refine'_2
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ : Perm α
⊢ ∀ (σ : Perm α),
IsCycle σ → fun {g} =>
∀ {f : Perm α}, f ∈ cycleFactorsFinset g → cycleFactorsFinset (g * f⁻¹) = cycleFactorsFinset g \ {f}
[PROOFSTEP]
intro σ hσ f hf
[GOAL]
case refine'_2
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ : Perm α
hσ : IsCycle σ
f : Perm α
hf : f ∈ cycleFactorsFinset σ
⊢ cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
[PROOFSTEP]
simp only [cycleFactorsFinset_eq_singleton_self_iff.mpr hσ, mem_singleton] at hf ⊢
[GOAL]
case refine'_2
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ : Perm α
hσ : IsCycle σ
f : Perm α
hf : f = σ
⊢ cycleFactorsFinset (σ * f⁻¹) = {σ} \ {f}
[PROOFSTEP]
simp [hf]
[GOAL]
case refine'_3
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ : Perm α
⊢ ∀ (σ τ : Perm α),
Disjoint σ τ →
IsCycle σ →
(fun {g} =>
∀ {f : Perm α}, f ∈ cycleFactorsFinset g → cycleFactorsFinset (g * f⁻¹) = cycleFactorsFinset g \ {f}) →
(fun {g} =>
∀ {f : Perm α}, f ∈ cycleFactorsFinset g → cycleFactorsFinset (g * f⁻¹) = cycleFactorsFinset g \ {f}) →
fun {g} =>
∀ {f : Perm α}, f ∈ cycleFactorsFinset g → cycleFactorsFinset (g * f⁻¹) = cycleFactorsFinset g \ {f}
[PROOFSTEP]
intro σ τ hd _ hσ hτ f
[GOAL]
case refine'_3
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
⊢ f ∈ cycleFactorsFinset (σ * τ) → cycleFactorsFinset (σ * τ * f⁻¹) = cycleFactorsFinset (σ * τ) \ {f}
[PROOFSTEP]
simp_rw [hd.cycleFactorsFinset_mul_eq_union, mem_union]
-- if only `wlog` could work here...
[GOAL]
case refine'_3
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
⊢ f ∈ cycleFactorsFinset σ ∨ f ∈ cycleFactorsFinset τ →
cycleFactorsFinset (σ * τ * f⁻¹) = (cycleFactorsFinset σ ∪ cycleFactorsFinset τ) \ {f}
[PROOFSTEP]
rintro (hf | hf)
[GOAL]
case refine'_3.inl
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : f ∈ cycleFactorsFinset σ
⊢ cycleFactorsFinset (σ * τ * f⁻¹) = (cycleFactorsFinset σ ∪ cycleFactorsFinset τ) \ {f}
[PROOFSTEP]
rw [hd.commute.eq, union_comm, union_sdiff_distrib, sdiff_singleton_eq_erase, erase_eq_of_not_mem, mul_assoc,
Disjoint.cycleFactorsFinset_mul_eq_union, hσ hf]
[GOAL]
case refine'_3.inl
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : f ∈ cycleFactorsFinset σ
⊢ Disjoint τ (σ * f⁻¹)
[PROOFSTEP]
rw [mem_cycleFactorsFinset_iff] at hf
[GOAL]
case refine'_3.inl
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑σ a
⊢ Disjoint τ (σ * f⁻¹)
[PROOFSTEP]
intro x
[GOAL]
case refine'_3.inl
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑σ a
x : α
⊢ ↑τ x = x ∨ ↑(σ * f⁻¹) x = x
[PROOFSTEP]
cases' hd.symm x with hx hx
[GOAL]
case refine'_3.inl.inl
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑σ a
x : α
hx : ↑τ x = x
⊢ ↑τ x = x ∨ ↑(σ * f⁻¹) x = x
[PROOFSTEP]
exact Or.inl hx
[GOAL]
case refine'_3.inl.inr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑σ a
x : α
hx : ↑σ x = x
⊢ ↑τ x = x ∨ ↑(σ * f⁻¹) x = x
[PROOFSTEP]
refine' Or.inr _
[GOAL]
case refine'_3.inl.inr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑σ a
x : α
hx : ↑σ x = x
⊢ ↑(σ * f⁻¹) x = x
[PROOFSTEP]
by_cases hfx : f x = x
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑σ a
x : α
hx : ↑σ x = x
hfx : ↑f x = x
⊢ ↑(σ * f⁻¹) x = x
[PROOFSTEP]
rw [← hfx]
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑σ a
x : α
hx : ↑σ x = x
hfx : ↑f x = x
⊢ ↑(σ * f⁻¹) (↑f x) = ↑f x
[PROOFSTEP]
simpa [hx] using hfx.symm
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑σ a
x : α
hx : ↑σ x = x
hfx : ¬↑f x = x
⊢ ↑(σ * f⁻¹) x = x
[PROOFSTEP]
rw [mul_apply]
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑σ a
x : α
hx : ↑σ x = x
hfx : ¬↑f x = x
⊢ ↑σ (↑f⁻¹ x) = x
[PROOFSTEP]
rw [← hf.right _ (mem_support.mpr hfx)] at hx
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑σ a
x : α
hx : ↑f x = x
hfx : ¬↑f x = x
⊢ ↑σ (↑f⁻¹ x) = x
[PROOFSTEP]
contradiction
[GOAL]
case refine'_3.inl
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : f ∈ cycleFactorsFinset σ
⊢ ¬f ∈ cycleFactorsFinset τ
[PROOFSTEP]
exact fun H => not_mem_empty _ (hd.disjoint_cycleFactorsFinset.le_bot (mem_inter_of_mem hf H))
[GOAL]
case refine'_3.inr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : f ∈ cycleFactorsFinset τ
⊢ cycleFactorsFinset (σ * τ * f⁻¹) = (cycleFactorsFinset σ ∪ cycleFactorsFinset τ) \ {f}
[PROOFSTEP]
rw [union_sdiff_distrib, sdiff_singleton_eq_erase, erase_eq_of_not_mem, mul_assoc,
Disjoint.cycleFactorsFinset_mul_eq_union, hτ hf]
[GOAL]
case refine'_3.inr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : f ∈ cycleFactorsFinset τ
⊢ Disjoint σ (τ * f⁻¹)
[PROOFSTEP]
rw [mem_cycleFactorsFinset_iff] at hf
[GOAL]
case refine'_3.inr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑τ a
⊢ Disjoint σ (τ * f⁻¹)
[PROOFSTEP]
intro x
[GOAL]
case refine'_3.inr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑τ a
x : α
⊢ ↑σ x = x ∨ ↑(τ * f⁻¹) x = x
[PROOFSTEP]
cases' hd x with hx hx
[GOAL]
case refine'_3.inr.inl
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑τ a
x : α
hx : ↑σ x = x
⊢ ↑σ x = x ∨ ↑(τ * f⁻¹) x = x
[PROOFSTEP]
exact Or.inl hx
[GOAL]
case refine'_3.inr.inr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑τ a
x : α
hx : ↑τ x = x
⊢ ↑σ x = x ∨ ↑(τ * f⁻¹) x = x
[PROOFSTEP]
refine' Or.inr _
[GOAL]
case refine'_3.inr.inr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑τ a
x : α
hx : ↑τ x = x
⊢ ↑(τ * f⁻¹) x = x
[PROOFSTEP]
by_cases hfx : f x = x
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑τ a
x : α
hx : ↑τ x = x
hfx : ↑f x = x
⊢ ↑(τ * f⁻¹) x = x
[PROOFSTEP]
rw [← hfx]
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑τ a
x : α
hx : ↑τ x = x
hfx : ↑f x = x
⊢ ↑(τ * f⁻¹) (↑f x) = ↑f x
[PROOFSTEP]
simpa [hx] using hfx.symm
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑τ a
x : α
hx : ↑τ x = x
hfx : ¬↑f x = x
⊢ ↑(τ * f⁻¹) x = x
[PROOFSTEP]
rw [mul_apply]
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑τ a
x : α
hx : ↑τ x = x
hfx : ¬↑f x = x
⊢ ↑τ (↑f⁻¹ x) = x
[PROOFSTEP]
rw [← hf.right _ (mem_support.mpr hfx)] at hx
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : IsCycle f ∧ ∀ (a : α), a ∈ support f → ↑f a = ↑τ a
x : α
hx : ↑f x = x
hfx : ¬↑f x = x
⊢ ↑τ (↑f⁻¹ x) = x
[PROOFSTEP]
contradiction
[GOAL]
case refine'_3.inr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
g f✝ σ τ : Perm α
hd : Disjoint σ τ
a✝ : IsCycle σ
hσ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset σ → cycleFactorsFinset (σ * f⁻¹) = cycleFactorsFinset σ \ {f}
hτ : ∀ {f : Perm α}, f ∈ cycleFactorsFinset τ → cycleFactorsFinset (τ * f⁻¹) = cycleFactorsFinset τ \ {f}
f : Perm α
hf : f ∈ cycleFactorsFinset τ
⊢ ¬f ∈ cycleFactorsFinset σ
[PROOFSTEP]
exact fun H => not_mem_empty _ (hd.disjoint_cycleFactorsFinset.le_bot (mem_inter_of_mem H hf))
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Finite β
⊢ closure {σ | IsCycle σ} = ⊤
[PROOFSTEP]
classical
cases nonempty_fintype β
exact top_le_iff.mp (le_trans (ge_of_eq closure_isSwap) (closure_mono fun _ => IsSwap.isCycle))
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Finite β
⊢ closure {σ | IsCycle σ} = ⊤
[PROOFSTEP]
cases nonempty_fintype β
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Finite β
val✝ : Fintype β
⊢ closure {σ | IsCycle σ} = ⊤
[PROOFSTEP]
exact top_le_iff.mp (le_trans (ge_of_eq closure_isSwap) (closure_mono fun _ => IsSwap.isCycle))
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
⊢ closure {σ, swap x (↑σ x)} = ⊤
[PROOFSTEP]
let H := closure ({σ, swap x (σ x)} : Set (Perm α))
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
⊢ closure {σ, swap x (↑σ x)} = ⊤
[PROOFSTEP]
have h3 : σ ∈ H := subset_closure (Set.mem_insert σ _)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
⊢ closure {σ, swap x (↑σ x)} = ⊤
[PROOFSTEP]
have h4 : swap x (σ x) ∈ H := subset_closure (Set.mem_insert_of_mem _ (Set.mem_singleton _))
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
⊢ closure {σ, swap x (↑σ x)} = ⊤
[PROOFSTEP]
have step1 : ∀ n : ℕ, swap ((σ ^ n) x) ((σ ^ (n + 1) : Perm α) x) ∈ H :=
by
intro n
induction' n with n ih
· exact subset_closure (Set.mem_insert_of_mem _ (Set.mem_singleton _))
· convert H.mul_mem (H.mul_mem h3 ih) (H.inv_mem h3)
simp_rw [mul_swap_eq_swap_mul, mul_inv_cancel_right, pow_succ]
rfl
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
⊢ ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
[PROOFSTEP]
intro n
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
n : ℕ
⊢ swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
[PROOFSTEP]
induction' n with n ih
[GOAL]
case zero
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
⊢ swap (↑(σ ^ Nat.zero) x) (↑(σ ^ (Nat.zero + 1)) x) ∈ H
[PROOFSTEP]
exact subset_closure (Set.mem_insert_of_mem _ (Set.mem_singleton _))
[GOAL]
case succ
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
n : ℕ
ih : swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
⊢ swap (↑(σ ^ Nat.succ n) x) (↑(σ ^ (Nat.succ n + 1)) x) ∈ H
[PROOFSTEP]
convert H.mul_mem (H.mul_mem h3 ih) (H.inv_mem h3)
[GOAL]
case h.e'_4
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
n : ℕ
ih : swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
⊢ swap (↑(σ ^ Nat.succ n) x) (↑(σ ^ (Nat.succ n + 1)) x) = σ * swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) * σ⁻¹
[PROOFSTEP]
simp_rw [mul_swap_eq_swap_mul, mul_inv_cancel_right, pow_succ]
[GOAL]
case h.e'_4
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
n : ℕ
ih : swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
⊢ swap (↑(σ * σ ^ n) x) (↑(σ * (σ * σ ^ n)) x) = swap (↑σ (↑(σ ^ n) x)) (↑σ (↑(σ * σ ^ n) x))
[PROOFSTEP]
rfl
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
⊢ closure {σ, swap x (↑σ x)} = ⊤
[PROOFSTEP]
have step2 : ∀ n : ℕ, swap x ((σ ^ n) x) ∈ H := by
intro n
induction' n with n ih
· simp only [Nat.zero_eq, pow_zero, coe_one, id_eq, swap_self, Set.mem_singleton_iff]
convert H.one_mem
· by_cases h5 : x = (σ ^ n) x
· rw [pow_succ, mul_apply, ← h5]
exact h4
by_cases h6 : x = (σ ^ (n + 1) : Perm α) x
· rw [← h6, swap_self]
exact H.one_mem
rw [swap_comm, ← swap_mul_swap_mul_swap h5 h6]
exact H.mul_mem (H.mul_mem (step1 n) ih) (step1 n)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
⊢ ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
[PROOFSTEP]
intro n
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
n : ℕ
⊢ swap x (↑(σ ^ n) x) ∈ H
[PROOFSTEP]
induction' n with n ih
[GOAL]
case zero
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
⊢ swap x (↑(σ ^ Nat.zero) x) ∈ H
[PROOFSTEP]
simp only [Nat.zero_eq, pow_zero, coe_one, id_eq, swap_self, Set.mem_singleton_iff]
[GOAL]
case zero
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
⊢ Equiv.refl α ∈ closure {σ, swap x (↑σ x)}
[PROOFSTEP]
convert H.one_mem
[GOAL]
case succ
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
n : ℕ
ih : swap x (↑(σ ^ n) x) ∈ H
⊢ swap x (↑(σ ^ Nat.succ n) x) ∈ H
[PROOFSTEP]
by_cases h5 : x = (σ ^ n) x
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
n : ℕ
ih : swap x (↑(σ ^ n) x) ∈ H
h5 : x = ↑(σ ^ n) x
⊢ swap x (↑(σ ^ Nat.succ n) x) ∈ H
[PROOFSTEP]
rw [pow_succ, mul_apply, ← h5]
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
n : ℕ
ih : swap x (↑(σ ^ n) x) ∈ H
h5 : x = ↑(σ ^ n) x
⊢ swap x (↑σ x) ∈ H
[PROOFSTEP]
exact h4
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
n : ℕ
ih : swap x (↑(σ ^ n) x) ∈ H
h5 : ¬x = ↑(σ ^ n) x
⊢ swap x (↑(σ ^ Nat.succ n) x) ∈ H
[PROOFSTEP]
by_cases h6 : x = (σ ^ (n + 1) : Perm α) x
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
n : ℕ
ih : swap x (↑(σ ^ n) x) ∈ H
h5 : ¬x = ↑(σ ^ n) x
h6 : x = ↑(σ ^ (n + 1)) x
⊢ swap x (↑(σ ^ Nat.succ n) x) ∈ H
[PROOFSTEP]
rw [← h6, swap_self]
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
n : ℕ
ih : swap x (↑(σ ^ n) x) ∈ H
h5 : ¬x = ↑(σ ^ n) x
h6 : x = ↑(σ ^ (n + 1)) x
⊢ Equiv.refl α ∈ H
[PROOFSTEP]
exact H.one_mem
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
n : ℕ
ih : swap x (↑(σ ^ n) x) ∈ H
h5 : ¬x = ↑(σ ^ n) x
h6 : ¬x = ↑(σ ^ (n + 1)) x
⊢ swap x (↑(σ ^ Nat.succ n) x) ∈ H
[PROOFSTEP]
rw [swap_comm, ← swap_mul_swap_mul_swap h5 h6]
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
n : ℕ
ih : swap x (↑(σ ^ n) x) ∈ H
h5 : ¬x = ↑(σ ^ n) x
h6 : ¬x = ↑(σ ^ (n + 1)) x
⊢ swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) * swap x (↑(σ ^ n) x) * swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
[PROOFSTEP]
exact H.mul_mem (H.mul_mem (step1 n) ih) (step1 n)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
⊢ closure {σ, swap x (↑σ x)} = ⊤
[PROOFSTEP]
have step3 : ∀ y : α, swap x y ∈ H := by
intro y
have hx : x ∈ (⊤ : Finset α) := Finset.mem_univ x
rw [← h2, mem_support] at hx
have hy : y ∈ (⊤ : Finset α) := Finset.mem_univ y
rw [← h2, mem_support] at hy
cases' IsCycle.exists_pow_eq h1 hx hy with n hn
rw [← hn]
exact step2 n
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
⊢ ∀ (y : α), swap x y ∈ H
[PROOFSTEP]
intro y
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
y : α
⊢ swap x y ∈ H
[PROOFSTEP]
have hx : x ∈ (⊤ : Finset α) := Finset.mem_univ x
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
y : α
hx : x ∈ ⊤
⊢ swap x y ∈ H
[PROOFSTEP]
rw [← h2, mem_support] at hx
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
y : α
hx : ↑σ x ≠ x
⊢ swap x y ∈ H
[PROOFSTEP]
have hy : y ∈ (⊤ : Finset α) := Finset.mem_univ y
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
y : α
hx : ↑σ x ≠ x
hy : y ∈ ⊤
⊢ swap x y ∈ H
[PROOFSTEP]
rw [← h2, mem_support] at hy
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
y : α
hx : ↑σ x ≠ x
hy : ↑σ y ≠ y
⊢ swap x y ∈ H
[PROOFSTEP]
cases' IsCycle.exists_pow_eq h1 hx hy with n hn
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
y : α
hx : ↑σ x ≠ x
hy : ↑σ y ≠ y
n : ℕ
hn : ↑(σ ^ n) x = y
⊢ swap x y ∈ H
[PROOFSTEP]
rw [← hn]
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
y : α
hx : ↑σ x ≠ x
hy : ↑σ y ≠ y
n : ℕ
hn : ↑(σ ^ n) x = y
⊢ swap x (↑(σ ^ n) x) ∈ H
[PROOFSTEP]
exact step2 n
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
step3 : ∀ (y : α), swap x y ∈ H
⊢ closure {σ, swap x (↑σ x)} = ⊤
[PROOFSTEP]
have step4 : ∀ y z : α, swap y z ∈ H := by
intro y z
by_cases h5 : z = x
· rw [h5, swap_comm]
exact step3 y
by_cases h6 : z = y
· rw [h6, swap_self]
exact H.one_mem
rw [← swap_mul_swap_mul_swap h5 h6, swap_comm z x]
exact H.mul_mem (H.mul_mem (step3 y) (step3 z)) (step3 y)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
step3 : ∀ (y : α), swap x y ∈ H
⊢ ∀ (y z : α), swap y z ∈ H
[PROOFSTEP]
intro y z
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
step3 : ∀ (y : α), swap x y ∈ H
y z : α
⊢ swap y z ∈ H
[PROOFSTEP]
by_cases h5 : z = x
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
step3 : ∀ (y : α), swap x y ∈ H
y z : α
h5 : z = x
⊢ swap y z ∈ H
[PROOFSTEP]
rw [h5, swap_comm]
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
step3 : ∀ (y : α), swap x y ∈ H
y z : α
h5 : z = x
⊢ swap x y ∈ H
[PROOFSTEP]
exact step3 y
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
step3 : ∀ (y : α), swap x y ∈ H
y z : α
h5 : ¬z = x
⊢ swap y z ∈ H
[PROOFSTEP]
by_cases h6 : z = y
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
step3 : ∀ (y : α), swap x y ∈ H
y z : α
h5 : ¬z = x
h6 : z = y
⊢ swap y z ∈ H
[PROOFSTEP]
rw [h6, swap_self]
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
step3 : ∀ (y : α), swap x y ∈ H
y z : α
h5 : ¬z = x
h6 : z = y
⊢ Equiv.refl α ∈ H
[PROOFSTEP]
exact H.one_mem
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
step3 : ∀ (y : α), swap x y ∈ H
y z : α
h5 : ¬z = x
h6 : ¬z = y
⊢ swap y z ∈ H
[PROOFSTEP]
rw [← swap_mul_swap_mul_swap h5 h6, swap_comm z x]
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
step3 : ∀ (y : α), swap x y ∈ H
y z : α
h5 : ¬z = x
h6 : ¬z = y
⊢ swap x y * swap x z * swap x y ∈ H
[PROOFSTEP]
exact H.mul_mem (H.mul_mem (step3 y) (step3 z)) (step3 y)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
step3 : ∀ (y : α), swap x y ∈ H
step4 : ∀ (y z : α), swap y z ∈ H
⊢ closure {σ, swap x (↑σ x)} = ⊤
[PROOFSTEP]
rw [eq_top_iff, ← closure_isSwap, closure_le]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
step3 : ∀ (y : α), swap x y ∈ H
step4 : ∀ (y z : α), swap y z ∈ H
⊢ {σ | IsSwap σ} ⊆ ↑(closure {σ, swap x (↑σ x)})
[PROOFSTEP]
rintro τ ⟨y, z, _, h6⟩
[GOAL]
case intro.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
step3 : ∀ (y : α), swap x y ∈ H
step4 : ∀ (y z : α), swap y z ∈ H
τ : Perm α
y z : α
left✝ : y ≠ z
h6 : τ = swap y z
⊢ τ ∈ ↑(closure {σ, swap x (↑σ x)})
[PROOFSTEP]
rw [h6]
[GOAL]
case intro.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ : Perm α
h1 : IsCycle σ
h2 : support σ = ⊤
x : α
H : Subgroup (Perm α) := closure {σ, swap x (↑σ x)}
h3 : σ ∈ H
h4 : swap x (↑σ x) ∈ H
step1 : ∀ (n : ℕ), swap (↑(σ ^ n) x) (↑(σ ^ (n + 1)) x) ∈ H
step2 : ∀ (n : ℕ), swap x (↑(σ ^ n) x) ∈ H
step3 : ∀ (y : α), swap x y ∈ H
step4 : ∀ (y z : α), swap y z ∈ H
τ : Perm α
y z : α
left✝ : y ≠ z
h6 : τ = swap y z
⊢ swap y z ∈ ↑(closure {σ, swap x (↑σ x)})
[PROOFSTEP]
exact step4 y z
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
n : ℕ
σ : Perm α
h0 : Nat.coprime n (Fintype.card α)
h1 : IsCycle σ
h2 : support σ = univ
x : α
⊢ closure {σ, swap x (↑(σ ^ n) x)} = ⊤
[PROOFSTEP]
rw [← Finset.card_univ, ← h2, ← h1.orderOf] at h0
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
n : ℕ
σ : Perm α
h0 : Nat.coprime n (orderOf σ)
h1 : IsCycle σ
h2 : support σ = univ
x : α
⊢ closure {σ, swap x (↑(σ ^ n) x)} = ⊤
[PROOFSTEP]
cases' exists_pow_eq_self_of_coprime h0 with m hm
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
n : ℕ
σ : Perm α
h0 : Nat.coprime n (orderOf σ)
h1 : IsCycle σ
h2 : support σ = univ
x : α
m : ℕ
hm : (σ ^ n) ^ m = σ
⊢ closure {σ, swap x (↑(σ ^ n) x)} = ⊤
[PROOFSTEP]
have h2' : (σ ^ n).support = ⊤ := Eq.trans (support_pow_coprime h0) h2
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
n : ℕ
σ : Perm α
h0 : Nat.coprime n (orderOf σ)
h1 : IsCycle σ
h2 : support σ = univ
x : α
m : ℕ
hm : (σ ^ n) ^ m = σ
h2' : support (σ ^ n) = ⊤
⊢ closure {σ, swap x (↑(σ ^ n) x)} = ⊤
[PROOFSTEP]
have h1' : IsCycle ((σ ^ n) ^ (m : ℤ)) := by rwa [← hm] at h1
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
n : ℕ
σ : Perm α
h0 : Nat.coprime n (orderOf σ)
h1 : IsCycle σ
h2 : support σ = univ
x : α
m : ℕ
hm : (σ ^ n) ^ m = σ
h2' : support (σ ^ n) = ⊤
⊢ IsCycle ((σ ^ n) ^ ↑m)
[PROOFSTEP]
rwa [← hm] at h1
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
n : ℕ
σ : Perm α
h0 : Nat.coprime n (orderOf σ)
h1 : IsCycle σ
h2 : support σ = univ
x : α
m : ℕ
hm : (σ ^ n) ^ m = σ
h2' : support (σ ^ n) = ⊤
h1' : IsCycle ((σ ^ n) ^ ↑m)
⊢ closure {σ, swap x (↑(σ ^ n) x)} = ⊤
[PROOFSTEP]
replace h1' : IsCycle (σ ^ n) := h1'.of_pow (le_trans (support_pow_le σ n) (ge_of_eq (congr_arg support hm)))
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
n : ℕ
σ : Perm α
h0 : Nat.coprime n (orderOf σ)
h1 : IsCycle σ
h2 : support σ = univ
x : α
m : ℕ
hm : (σ ^ n) ^ m = σ
h2' : support (σ ^ n) = ⊤
h1' : IsCycle (σ ^ n)
⊢ closure {σ, swap x (↑(σ ^ n) x)} = ⊤
[PROOFSTEP]
rw [eq_top_iff, ← closure_cycle_adjacent_swap h1' h2' x, closure_le, Set.insert_subset_iff]
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
n : ℕ
σ : Perm α
h0 : Nat.coprime n (orderOf σ)
h1 : IsCycle σ
h2 : support σ = univ
x : α
m : ℕ
hm : (σ ^ n) ^ m = σ
h2' : support (σ ^ n) = ⊤
h1' : IsCycle (σ ^ n)
⊢ σ ^ n ∈ ↑(closure {σ, swap x (↑(σ ^ n) x)}) ∧ {swap x (↑(σ ^ n) x)} ⊆ ↑(closure {σ, swap x (↑(σ ^ n) x)})
[PROOFSTEP]
exact
⟨Subgroup.pow_mem (closure _) (subset_closure (Set.mem_insert σ _)) n,
Set.singleton_subset_iff.mpr (subset_closure (Set.mem_insert_of_mem _ (Set.mem_singleton _)))⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ τ : Perm α
h0 : Nat.Prime (Fintype.card α)
h1 : IsCycle σ
h2 : support σ = univ
h3 : IsSwap τ
⊢ closure {σ, τ} = ⊤
[PROOFSTEP]
obtain ⟨x, y, h4, h5⟩ := h3
[GOAL]
case intro.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ τ : Perm α
h0 : Nat.Prime (Fintype.card α)
h1 : IsCycle σ
h2 : support σ = univ
x y : α
h4 : x ≠ y
h5 : τ = swap x y
⊢ closure {σ, τ} = ⊤
[PROOFSTEP]
obtain ⟨i, hi⟩ :=
h1.exists_pow_eq (mem_support.mp ((Finset.ext_iff.mp h2 x).mpr (Finset.mem_univ x)))
(mem_support.mp ((Finset.ext_iff.mp h2 y).mpr (Finset.mem_univ y)))
[GOAL]
case intro.intro.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ τ : Perm α
h0 : Nat.Prime (Fintype.card α)
h1 : IsCycle σ
h2 : support σ = univ
x y : α
h4 : x ≠ y
h5 : τ = swap x y
i : ℕ
hi : ↑(σ ^ i) x = y
⊢ closure {σ, τ} = ⊤
[PROOFSTEP]
rw [h5, ← hi]
[GOAL]
case intro.intro.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ τ : Perm α
h0 : Nat.Prime (Fintype.card α)
h1 : IsCycle σ
h2 : support σ = univ
x y : α
h4 : x ≠ y
h5 : τ = swap x y
i : ℕ
hi : ↑(σ ^ i) x = y
⊢ closure {σ, swap x (↑(σ ^ i) x)} = ⊤
[PROOFSTEP]
refine' closure_cycle_coprime_swap (Nat.coprime.symm (h0.coprime_iff_not_dvd.mpr fun h => h4 _)) h1 h2 x
[GOAL]
case intro.intro.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ τ : Perm α
h0 : Nat.Prime (Fintype.card α)
h1 : IsCycle σ
h2 : support σ = univ
x y : α
h4 : x ≠ y
h5 : τ = swap x y
i : ℕ
hi : ↑(σ ^ i) x = y
h : Fintype.card α ∣ i
⊢ x = y
[PROOFSTEP]
cases' h with m hm
[GOAL]
case intro.intro.intro.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Finite β
inst✝ : Fintype α
σ τ : Perm α
h0 : Nat.Prime (Fintype.card α)
h1 : IsCycle σ
h2 : support σ = univ
x y : α
h4 : x ≠ y
h5 : τ = swap x y
i : ℕ
hi : ↑(σ ^ i) x = y
m : ℕ
hm : i = Fintype.card α * m
⊢ x = y
[PROOFSTEP]
rwa [hm, pow_mul, ← Finset.card_univ, ← h2, ← h1.orderOf, pow_orderOf_eq_one, one_pow, one_apply] at hi
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
f : { x // x ∈ ↑(support σ) } ≃ { x // x ∈ ↑(support τ) }
hf :
∀ (x : α) (hx : x ∈ ↑(support σ)),
↑(↑f { val := ↑σ x, property := (_ : ↑σ x ∈ support σ) }) = ↑τ ↑(↑f { val := x, property := hx })
⊢ IsConj σ τ
[PROOFSTEP]
refine' isConj_iff.2 ⟨Equiv.extendSubtype f, _⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
f : { x // x ∈ ↑(support σ) } ≃ { x // x ∈ ↑(support τ) }
hf :
∀ (x : α) (hx : x ∈ ↑(support σ)),
↑(↑f { val := ↑σ x, property := (_ : ↑σ x ∈ support σ) }) = ↑τ ↑(↑f { val := x, property := hx })
⊢ extendSubtype f * σ * (extendSubtype f)⁻¹ = τ
[PROOFSTEP]
rw [mul_inv_eq_iff_eq_mul]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
f : { x // x ∈ ↑(support σ) } ≃ { x // x ∈ ↑(support τ) }
hf :
∀ (x : α) (hx : x ∈ ↑(support σ)),
↑(↑f { val := ↑σ x, property := (_ : ↑σ x ∈ support σ) }) = ↑τ ↑(↑f { val := x, property := hx })
⊢ extendSubtype f * σ = τ * extendSubtype f
[PROOFSTEP]
ext x
[GOAL]
case H
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
f : { x // x ∈ ↑(support σ) } ≃ { x // x ∈ ↑(support τ) }
hf :
∀ (x : α) (hx : x ∈ ↑(support σ)),
↑(↑f { val := ↑σ x, property := (_ : ↑σ x ∈ support σ) }) = ↑τ ↑(↑f { val := x, property := hx })
x : α
⊢ ↑(extendSubtype f * σ) x = ↑(τ * extendSubtype f) x
[PROOFSTEP]
simp only [Perm.mul_apply]
[GOAL]
case H
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
f : { x // x ∈ ↑(support σ) } ≃ { x // x ∈ ↑(support τ) }
hf :
∀ (x : α) (hx : x ∈ ↑(support σ)),
↑(↑f { val := ↑σ x, property := (_ : ↑σ x ∈ support σ) }) = ↑τ ↑(↑f { val := x, property := hx })
x : α
⊢ ↑(extendSubtype f) (↑σ x) = ↑τ (↑(extendSubtype f) x)
[PROOFSTEP]
by_cases hx : x ∈ σ.support
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
f : { x // x ∈ ↑(support σ) } ≃ { x // x ∈ ↑(support τ) }
hf :
∀ (x : α) (hx : x ∈ ↑(support σ)),
↑(↑f { val := ↑σ x, property := (_ : ↑σ x ∈ support σ) }) = ↑τ ↑(↑f { val := x, property := hx })
x : α
hx : x ∈ support σ
⊢ ↑(extendSubtype f) (↑σ x) = ↑τ (↑(extendSubtype f) x)
[PROOFSTEP]
rw [Equiv.extendSubtype_apply_of_mem, Equiv.extendSubtype_apply_of_mem]
[GOAL]
case pos
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
f : { x // x ∈ ↑(support σ) } ≃ { x // x ∈ ↑(support τ) }
hf :
∀ (x : α) (hx : x ∈ ↑(support σ)),
↑(↑f { val := ↑σ x, property := (_ : ↑σ x ∈ support σ) }) = ↑τ ↑(↑f { val := x, property := hx })
x : α
hx : x ∈ support σ
⊢ ↑(↑f { val := ↑σ x, property := ?pos.hx✝ }) = ↑τ ↑(↑f { val := x, property := ?pos.hx✝ })
[PROOFSTEP]
exact hf x (Finset.mem_coe.2 hx)
[GOAL]
case neg
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
f : { x // x ∈ ↑(support σ) } ≃ { x // x ∈ ↑(support τ) }
hf :
∀ (x : α) (hx : x ∈ ↑(support σ)),
↑(↑f { val := ↑σ x, property := (_ : ↑σ x ∈ support σ) }) = ↑τ ↑(↑f { val := x, property := hx })
x : α
hx : ¬x ∈ support σ
⊢ ↑(extendSubtype f) (↑σ x) = ↑τ (↑(extendSubtype f) x)
[PROOFSTEP]
rwa [Classical.not_not.1 ((not_congr mem_support).1 (Equiv.extendSubtype_not_mem f _ _)),
Classical.not_not.1 ((not_congr mem_support).mp hx)]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
hσ : IsCycle σ
hτ : IsCycle τ
h : card (support σ) = card (support τ)
⊢ IsConj σ τ
[PROOFSTEP]
refine'
isConj_of_support_equiv
(hσ.zpowersEquivSupport.symm.trans <|
(zpowersEquivZpowers <| by rw [hσ.orderOf, h, hτ.orderOf]).trans hτ.zpowersEquivSupport)
_
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
hσ : IsCycle σ
hτ : IsCycle τ
h : card (support σ) = card (support τ)
⊢ orderOf σ = orderOf τ
[PROOFSTEP]
rw [hσ.orderOf, h, hτ.orderOf]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
hσ : IsCycle σ
hτ : IsCycle τ
h : card (support σ) = card (support τ)
⊢ ∀ (x : α) (hx : x ∈ ↑(support σ)),
↑(↑((zpowersEquivSupport hσ).symm.trans
((zpowersEquivZpowers (_ : orderOf σ = orderOf τ)).trans (zpowersEquivSupport hτ)))
{ val := ↑σ x, property := (_ : ↑σ x ∈ support σ) }) =
↑τ
↑(↑((zpowersEquivSupport hσ).symm.trans
((zpowersEquivZpowers (_ : orderOf σ = orderOf τ)).trans (zpowersEquivSupport hτ)))
{ val := x, property := hx })
[PROOFSTEP]
intro x hx
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
hσ : IsCycle σ
hτ : IsCycle τ
h : card (support σ) = card (support τ)
x : α
hx : x ∈ ↑(support σ)
⊢ ↑(↑((zpowersEquivSupport hσ).symm.trans
((zpowersEquivZpowers (_ : orderOf σ = orderOf τ)).trans (zpowersEquivSupport hτ)))
{ val := ↑σ x, property := (_ : ↑σ x ∈ support σ) }) =
↑τ
↑(↑((zpowersEquivSupport hσ).symm.trans
((zpowersEquivZpowers (_ : orderOf σ = orderOf τ)).trans (zpowersEquivSupport hτ)))
{ val := x, property := hx })
[PROOFSTEP]
simp only [Perm.mul_apply, Equiv.trans_apply, Equiv.sumCongr_apply]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
hσ : IsCycle σ
hτ : IsCycle τ
h : card (support σ) = card (support τ)
x : α
hx : x ∈ ↑(support σ)
⊢ ↑(↑(zpowersEquivSupport hτ)
(↑(zpowersEquivZpowers (_ : orderOf σ = orderOf τ))
(↑(zpowersEquivSupport hσ).symm { val := ↑σ x, property := (_ : ↑σ x ∈ support σ) }))) =
↑τ
↑(↑(zpowersEquivSupport hτ)
(↑(zpowersEquivZpowers (_ : orderOf σ = orderOf τ))
(↑(zpowersEquivSupport hσ).symm { val := x, property := hx })))
[PROOFSTEP]
obtain ⟨n, rfl⟩ := hσ.exists_pow_eq (Classical.choose_spec hσ).1 (mem_support.1 hx)
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
hσ : IsCycle σ
hτ : IsCycle τ
h : card (support σ) = card (support τ)
n : ℕ
hx : ↑(σ ^ n) (Classical.choose hσ) ∈ ↑(support σ)
⊢ ↑(↑(zpowersEquivSupport hτ)
(↑(zpowersEquivZpowers (_ : orderOf σ = orderOf τ))
(↑(zpowersEquivSupport hσ).symm
{ val := ↑σ (↑(σ ^ n) (Classical.choose hσ)),
property := (_ : ↑σ (↑(σ ^ n) (Classical.choose hσ)) ∈ support σ) }))) =
↑τ
↑(↑(zpowersEquivSupport hτ)
(↑(zpowersEquivZpowers (_ : orderOf σ = orderOf τ))
(↑(zpowersEquivSupport hσ).symm { val := ↑(σ ^ n) (Classical.choose hσ), property := hx })))
[PROOFSTEP]
apply Eq.trans _ (congr rfl (congr rfl (congr rfl (congr rfl (hσ.zpowersEquivSupport_symm_apply n).symm))))
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
hσ : IsCycle σ
hτ : IsCycle τ
h : card (support σ) = card (support τ)
n : ℕ
hx : ↑(σ ^ n) (Classical.choose hσ) ∈ ↑(support σ)
⊢ ↑(↑(zpowersEquivSupport hτ)
(↑(zpowersEquivZpowers (_ : orderOf σ = orderOf τ))
(↑(zpowersEquivSupport hσ).symm
{ val := ↑σ (↑(σ ^ n) (Classical.choose hσ)),
property := (_ : ↑σ (↑(σ ^ n) (Classical.choose hσ)) ∈ support σ) }))) =
↑τ
↑(↑(zpowersEquivSupport hτ)
(↑(zpowersEquivZpowers (_ : orderOf σ = orderOf τ))
{ val := σ ^ n, property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = σ ^ n) }))
[PROOFSTEP]
apply (congr rfl (congr rfl (congr rfl (hσ.zpowersEquivSupport_symm_apply (n + 1))))).trans _
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
hσ : IsCycle σ
hτ : IsCycle τ
h : card (support σ) = card (support τ)
n : ℕ
hx : ↑(σ ^ n) (Classical.choose hσ) ∈ ↑(support σ)
⊢ ↑(↑(zpowersEquivSupport hτ)
(↑(zpowersEquivZpowers (_ : orderOf σ = orderOf τ))
{ val := σ ^ (n + 1), property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = σ ^ (n + 1)) })) =
↑τ
↑(↑(zpowersEquivSupport hτ)
(↑(zpowersEquivZpowers (_ : orderOf σ = orderOf τ))
{ val := σ ^ n, property := (_ : ∃ y, (fun x x_1 => x ^ x_1) σ y = σ ^ n) }))
[PROOFSTEP]
simp only [Ne.def, IsCycle.zpowersEquivSupport_apply, Subtype.coe_mk, zpowersEquivZpowers_apply]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
hσ : IsCycle σ
hτ : IsCycle τ
h : card (support σ) = card (support τ)
n : ℕ
hx : ↑(σ ^ n) (Classical.choose hσ) ∈ ↑(support σ)
⊢ ↑(↑(zpowersEquivSupport hτ) { val := τ ^ (n + 1), property := (_ : ∃ y, (fun x x_1 => x ^ x_1) τ y = τ ^ (n + 1)) }) =
↑τ ↑(↑(zpowersEquivSupport hτ) { val := τ ^ n, property := (_ : ∃ y, (fun x x_1 => x ^ x_1) τ y = τ ^ n) })
[PROOFSTEP]
dsimp
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
hσ : IsCycle σ
hτ : IsCycle τ
h : card (support σ) = card (support τ)
n : ℕ
hx : ↑(σ ^ n) (Classical.choose hσ) ∈ ↑(support σ)
⊢ ↑(τ ^ (n + 1)) (Classical.choose hτ) = ↑τ (↑(τ ^ n) (Classical.choose hτ))
[PROOFSTEP]
rw [pow_succ, Perm.mul_apply]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
hσ : IsCycle σ
hτ : IsCycle τ
⊢ IsConj σ τ → card (support σ) = card (support τ)
[PROOFSTEP]
intro h
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
hσ : IsCycle σ
hτ : IsCycle τ
h : IsConj σ τ
⊢ card (support σ) = card (support τ)
[PROOFSTEP]
obtain ⟨π, rfl⟩ := (_root_.isConj_iff).1 h
[GOAL]
case intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ : Perm α
hσ : IsCycle σ
π : Perm α
hτ : IsCycle (π * σ * π⁻¹)
h : IsConj σ (π * σ * π⁻¹)
⊢ card (support σ) = card (support (π * σ * π⁻¹))
[PROOFSTEP]
refine' Finset.card_congr (fun a _ => π a) (fun _ ha => _) (fun _ _ _ _ ab => π.injective ab) fun b hb => _
[GOAL]
case intro.refine'_1
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ : Perm α
hσ : IsCycle σ
π : Perm α
hτ : IsCycle (π * σ * π⁻¹)
h : IsConj σ (π * σ * π⁻¹)
x✝ : α
ha : x✝ ∈ support σ
⊢ (fun a x => ↑π a) x✝ ha ∈ support (π * σ * π⁻¹)
[PROOFSTEP]
simp [mem_support.1 ha]
[GOAL]
case intro.refine'_2
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ : Perm α
hσ : IsCycle σ
π : Perm α
hτ : IsCycle (π * σ * π⁻¹)
h : IsConj σ (π * σ * π⁻¹)
b : α
hb : b ∈ support (π * σ * π⁻¹)
⊢ ∃ a ha, (fun a x => ↑π a) a ha = b
[PROOFSTEP]
refine' ⟨π⁻¹ b, ⟨_, π.apply_inv_self b⟩⟩
[GOAL]
case intro.refine'_2
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ : Perm α
hσ : IsCycle σ
π : Perm α
hτ : IsCycle (π * σ * π⁻¹)
h : IsConj σ (π * σ * π⁻¹)
b : α
hb : b ∈ support (π * σ * π⁻¹)
⊢ ↑π⁻¹ b ∈ support σ
[PROOFSTEP]
contrapose! hb
[GOAL]
case intro.refine'_2
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ : Perm α
hσ : IsCycle σ
π : Perm α
hτ : IsCycle (π * σ * π⁻¹)
h : IsConj σ (π * σ * π⁻¹)
b : α
hb : ¬↑π⁻¹ b ∈ support σ
⊢ ¬b ∈ support (π * σ * π⁻¹)
[PROOFSTEP]
rw [mem_support, Classical.not_not] at hb
[GOAL]
case intro.refine'_2
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ : Perm α
hσ : IsCycle σ
π : Perm α
hτ : IsCycle (π * σ * π⁻¹)
h : IsConj σ (π * σ * π⁻¹)
b : α
hb : ↑σ (↑π⁻¹ b) = ↑π⁻¹ b
⊢ ¬b ∈ support (π * σ * π⁻¹)
[PROOFSTEP]
rw [mem_support, Classical.not_not, Perm.mul_apply, Perm.mul_apply, hb, Perm.apply_inv_self]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
⊢ support (σ * τ * σ⁻¹) = map (Equiv.toEmbedding σ) (support τ)
[PROOFSTEP]
ext
[GOAL]
case a
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
a✝ : α
⊢ a✝ ∈ support (σ * τ * σ⁻¹) ↔ a✝ ∈ map (Equiv.toEmbedding σ) (support τ)
[PROOFSTEP]
simp only [mem_map_equiv, Perm.coe_mul, Function.comp_apply, Ne.def, Perm.mem_support, Equiv.eq_symm_apply]
[GOAL]
case a
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
a✝ : α
⊢ ¬↑σ (↑τ (↑σ⁻¹ a✝)) = a✝ ↔ ¬↑σ (↑τ (↑σ.symm a✝)) = a✝
[PROOFSTEP]
rfl
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ : DecidableEq α
inst✝ : Fintype α
σ τ : Perm α
⊢ card (support (σ * τ * σ⁻¹)) = card (support τ)
[PROOFSTEP]
simp
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ π ρ : Perm α
hc1 : IsConj σ π
hc2 : IsConj τ ρ
hd1 : Disjoint σ τ
hd2 : Disjoint π ρ
⊢ IsConj (σ * τ) (π * ρ)
[PROOFSTEP]
classical
cases nonempty_fintype α
obtain ⟨f, rfl⟩ := isConj_iff.1 hc1
obtain ⟨g, rfl⟩ := isConj_iff.1 hc2
have hd1' := coe_inj.2 hd1.support_mul
have hd2' := coe_inj.2 hd2.support_mul
rw [coe_union] at *
have hd1'' := disjoint_coe.2 (disjoint_iff_disjoint_support.1 hd1)
have hd2'' := disjoint_coe.2 (disjoint_iff_disjoint_support.1 hd2)
refine' isConj_of_support_equiv _ _
·
refine'
((Equiv.Set.ofEq hd1').trans (Equiv.Set.union hd1''.le_bot)).trans
((Equiv.sumCongr (subtypeEquiv f fun a => _) (subtypeEquiv g fun a => _)).trans
((Equiv.Set.ofEq hd2').trans (Equiv.Set.union hd2''.le_bot)).symm) <;>
· simp only [Set.mem_image, toEmbedding_apply, exists_eq_right, support_conj, coe_map, apply_eq_iff_eq]
· intro x hx
simp only [trans_apply, symm_trans_apply, Equiv.Set.ofEq_apply, Equiv.Set.ofEq_symm_apply, Equiv.sumCongr_apply]
rw [hd1', Set.mem_union] at hx
cases' hx with hxσ hxτ
· rw [mem_coe, mem_support] at hxσ
rw [Set.union_apply_left hd1''.le_bot _, Set.union_apply_left hd1''.le_bot _]
simp only [subtypeEquiv_apply, Perm.coe_mul, Sum.map_inl, comp_apply, Set.union_symm_apply_left, Subtype.coe_mk,
apply_eq_iff_eq]
· have h := (hd2 (f x)).resolve_left ?_
· rw [mul_apply, mul_apply] at h
rw [h, inv_apply_self, (hd1 x).resolve_left hxσ]
· rwa [mul_apply, mul_apply, inv_apply_self, apply_eq_iff_eq]
· rwa [Subtype.coe_mk, Perm.mul_apply, (hd1 x).resolve_left hxσ, mem_coe, apply_mem_support, mem_support]
· rwa [Subtype.coe_mk, mem_coe, mem_support]
· rw [mem_coe, ← apply_mem_support, mem_support] at hxτ
rw [Set.union_apply_right hd1''.le_bot _, Set.union_apply_right hd1''.le_bot _]
simp only [subtypeEquiv_apply, Perm.coe_mul, Sum.map_inr, comp_apply, Set.union_symm_apply_right, Subtype.coe_mk,
apply_eq_iff_eq]
· have h := (hd2 (g (τ x))).resolve_right ?_
· rw [mul_apply, mul_apply] at h
rw [inv_apply_self, h, (hd1 (τ x)).resolve_right hxτ]
· rwa [mul_apply, mul_apply, inv_apply_self, apply_eq_iff_eq]
· rwa [Subtype.coe_mk, Perm.mul_apply, (hd1 (τ x)).resolve_right hxτ, mem_coe, mem_support]
· rwa [Subtype.coe_mk, mem_coe, ← apply_mem_support, mem_support]
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ π ρ : Perm α
hc1 : IsConj σ π
hc2 : IsConj τ ρ
hd1 : Disjoint σ τ
hd2 : Disjoint π ρ
⊢ IsConj (σ * τ) (π * ρ)
[PROOFSTEP]
cases nonempty_fintype α
[GOAL]
case intro
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ π ρ : Perm α
hc1 : IsConj σ π
hc2 : IsConj τ ρ
hd1 : Disjoint σ τ
hd2 : Disjoint π ρ
val✝ : Fintype α
⊢ IsConj (σ * τ) (π * ρ)
[PROOFSTEP]
obtain ⟨f, rfl⟩ := isConj_iff.1 hc1
[GOAL]
case intro.intro
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ ρ : Perm α
hc2 : IsConj τ ρ
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) ρ
⊢ IsConj (σ * τ) (f * σ * f⁻¹ * ρ)
[PROOFSTEP]
obtain ⟨g, rfl⟩ := isConj_iff.1 hc2
[GOAL]
case intro.intro.intro
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
⊢ IsConj (σ * τ) (f * σ * f⁻¹ * (g * τ * g⁻¹))
[PROOFSTEP]
have hd1' := coe_inj.2 hd1.support_mul
[GOAL]
case intro.intro.intro
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ ∪ support τ)
⊢ IsConj (σ * τ) (f * σ * f⁻¹ * (g * τ * g⁻¹))
[PROOFSTEP]
have hd2' := coe_inj.2 hd2.support_mul
[GOAL]
case intro.intro.intro
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ ∪ support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹) ∪ support (g * τ * g⁻¹))
⊢ IsConj (σ * τ) (f * σ * f⁻¹ * (g * τ * g⁻¹))
[PROOFSTEP]
rw [coe_union] at *
[GOAL]
case intro.intro.intro
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
⊢ IsConj (σ * τ) (f * σ * f⁻¹ * (g * τ * g⁻¹))
[PROOFSTEP]
have hd1'' := disjoint_coe.2 (disjoint_iff_disjoint_support.1 hd1)
[GOAL]
case intro.intro.intro
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
⊢ IsConj (σ * τ) (f * σ * f⁻¹ * (g * τ * g⁻¹))
[PROOFSTEP]
have hd2'' := disjoint_coe.2 (disjoint_iff_disjoint_support.1 hd2)
[GOAL]
case intro.intro.intro
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
⊢ IsConj (σ * τ) (f * σ * f⁻¹ * (g * τ * g⁻¹))
[PROOFSTEP]
refine' isConj_of_support_equiv _ _
[GOAL]
case intro.intro.intro.refine'_1
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
⊢ { x // x ∈ ↑(support (σ * τ)) } ≃ { x // x ∈ ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) }
[PROOFSTEP]
refine'
((Equiv.Set.ofEq hd1').trans (Equiv.Set.union hd1''.le_bot)).trans
((Equiv.sumCongr (subtypeEquiv f fun a => _) (subtypeEquiv g fun a => _)).trans
((Equiv.Set.ofEq hd2').trans (Equiv.Set.union hd2''.le_bot)).symm)
[GOAL]
case intro.intro.intro.refine'_1.refine'_1
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
a : α
⊢ a ∈ ↑(support σ) ↔ ↑f a ∈ ↑(support (f * σ * f⁻¹))
[PROOFSTEP]
simp only [Set.mem_image, toEmbedding_apply, exists_eq_right, support_conj, coe_map, apply_eq_iff_eq]
[GOAL]
case intro.intro.intro.refine'_1.refine'_2
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
a : α
⊢ a ∈ ↑(support τ) ↔ ↑g a ∈ ↑(support (g * τ * g⁻¹))
[PROOFSTEP]
simp only [Set.mem_image, toEmbedding_apply, exists_eq_right, support_conj, coe_map, apply_eq_iff_eq]
[GOAL]
case intro.intro.intro.refine'_2
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
⊢ ∀ (x : α) (hx : x ∈ ↑(support (σ * τ))),
↑(↑(((Set.ofEq hd1').trans (Set.union (_ : ↑(support σ) ⊓ ↑(support τ) ≤ ⊥))).trans
((Equiv.sumCongr (subtypeEquiv f (_ : ∀ (a : α), a ∈ ↑(support σ) ↔ ↑f a ∈ ↑(support (f * σ * f⁻¹))))
(subtypeEquiv g (_ : ∀ (a : α), a ∈ ↑(support τ) ↔ ↑g a ∈ ↑(support (g * τ * g⁻¹))))).trans
((Set.ofEq hd2').trans (Set.union (_ : ↑(support (f * σ * f⁻¹)) ⊓ ↑(support (g * τ * g⁻¹)) ≤ ⊥))).symm))
{ val := ↑(σ * τ) x, property := (_ : ↑(σ * τ) x ∈ support (σ * τ)) }) =
↑(f * σ * f⁻¹ * (g * τ * g⁻¹))
↑(↑(((Set.ofEq hd1').trans (Set.union (_ : ↑(support σ) ⊓ ↑(support τ) ≤ ⊥))).trans
((Equiv.sumCongr (subtypeEquiv f (_ : ∀ (a : α), a ∈ ↑(support σ) ↔ ↑f a ∈ ↑(support (f * σ * f⁻¹))))
(subtypeEquiv g (_ : ∀ (a : α), a ∈ ↑(support τ) ↔ ↑g a ∈ ↑(support (g * τ * g⁻¹))))).trans
((Set.ofEq hd2').trans
(Set.union (_ : ↑(support (f * σ * f⁻¹)) ⊓ ↑(support (g * τ * g⁻¹)) ≤ ⊥))).symm))
{ val := x, property := hx })
[PROOFSTEP]
intro x hx
[GOAL]
case intro.intro.intro.refine'_2
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
⊢ ↑(↑(((Set.ofEq hd1').trans (Set.union (_ : ↑(support σ) ⊓ ↑(support τ) ≤ ⊥))).trans
((Equiv.sumCongr (subtypeEquiv f (_ : ∀ (a : α), a ∈ ↑(support σ) ↔ ↑f a ∈ ↑(support (f * σ * f⁻¹))))
(subtypeEquiv g (_ : ∀ (a : α), a ∈ ↑(support τ) ↔ ↑g a ∈ ↑(support (g * τ * g⁻¹))))).trans
((Set.ofEq hd2').trans (Set.union (_ : ↑(support (f * σ * f⁻¹)) ⊓ ↑(support (g * τ * g⁻¹)) ≤ ⊥))).symm))
{ val := ↑(σ * τ) x, property := (_ : ↑(σ * τ) x ∈ support (σ * τ)) }) =
↑(f * σ * f⁻¹ * (g * τ * g⁻¹))
↑(↑(((Set.ofEq hd1').trans (Set.union (_ : ↑(support σ) ⊓ ↑(support τ) ≤ ⊥))).trans
((Equiv.sumCongr (subtypeEquiv f (_ : ∀ (a : α), a ∈ ↑(support σ) ↔ ↑f a ∈ ↑(support (f * σ * f⁻¹))))
(subtypeEquiv g (_ : ∀ (a : α), a ∈ ↑(support τ) ↔ ↑g a ∈ ↑(support (g * τ * g⁻¹))))).trans
((Set.ofEq hd2').trans (Set.union (_ : ↑(support (f * σ * f⁻¹)) ⊓ ↑(support (g * τ * g⁻¹)) ≤ ⊥))).symm))
{ val := x, property := hx })
[PROOFSTEP]
simp only [trans_apply, symm_trans_apply, Equiv.Set.ofEq_apply, Equiv.Set.ofEq_symm_apply, Equiv.sumCongr_apply]
[GOAL]
case intro.intro.intro.refine'_2
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
⊢ ↑(↑(Set.union (_ : ↑(support (f * σ * f⁻¹)) ⊓ ↑(support (g * τ * g⁻¹)) ≤ ⊥)).symm
(Sum.map (↑(subtypeEquiv f (_ : ∀ (a : α), a ∈ ↑(support σ) ↔ ↑f a ∈ ↑(support (f * σ * f⁻¹)))))
(↑(subtypeEquiv g (_ : ∀ (a : α), a ∈ ↑(support τ) ↔ ↑g a ∈ ↑(support (g * τ * g⁻¹)))))
(↑(Set.union (_ : ↑(support σ) ⊓ ↑(support τ) ≤ ⊥))
{ val := ↑(σ * τ) x,
property :=
(_ :
↑(Equiv.refl α) ↑{ val := ↑(σ * τ) x, property := (_ : ↑(σ * τ) x ∈ support (σ * τ)) } ∈
↑(support σ) ∪ ↑(support τ)) }))) =
↑(f * σ * f⁻¹ * (g * τ * g⁻¹))
↑(↑(Set.union (_ : ↑(support (f * σ * f⁻¹)) ⊓ ↑(support (g * τ * g⁻¹)) ≤ ⊥)).symm
(Sum.map (↑(subtypeEquiv f (_ : ∀ (a : α), a ∈ ↑(support σ) ↔ ↑f a ∈ ↑(support (f * σ * f⁻¹)))))
(↑(subtypeEquiv g (_ : ∀ (a : α), a ∈ ↑(support τ) ↔ ↑g a ∈ ↑(support (g * τ * g⁻¹)))))
(↑(Set.union (_ : ↑(support σ) ⊓ ↑(support τ) ≤ ⊥))
{ val := x,
property := (_ : ↑(Equiv.refl α) ↑{ val := x, property := hx } ∈ ↑(support σ) ∪ ↑(support τ)) })))
[PROOFSTEP]
rw [hd1', Set.mem_union] at hx
[GOAL]
case intro.intro.intro.refine'_2
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx✝ : x ∈ ↑(support (σ * τ))
hx : x ∈ ↑(support σ) ∨ x ∈ ↑(support τ)
⊢ ↑(↑(Set.union (_ : ↑(support (f * σ * f⁻¹)) ⊓ ↑(support (g * τ * g⁻¹)) ≤ ⊥)).symm
(Sum.map (↑(subtypeEquiv f (_ : ∀ (a : α), a ∈ ↑(support σ) ↔ ↑f a ∈ ↑(support (f * σ * f⁻¹)))))
(↑(subtypeEquiv g (_ : ∀ (a : α), a ∈ ↑(support τ) ↔ ↑g a ∈ ↑(support (g * τ * g⁻¹)))))
(↑(Set.union (_ : ↑(support σ) ⊓ ↑(support τ) ≤ ⊥))
{ val := ↑(σ * τ) x,
property :=
(_ :
↑(Equiv.refl α) ↑{ val := ↑(σ * τ) x, property := (_ : ↑(σ * τ) x ∈ support (σ * τ)) } ∈
↑(support σ) ∪ ↑(support τ)) }))) =
↑(f * σ * f⁻¹ * (g * τ * g⁻¹))
↑(↑(Set.union (_ : ↑(support (f * σ * f⁻¹)) ⊓ ↑(support (g * τ * g⁻¹)) ≤ ⊥)).symm
(Sum.map (↑(subtypeEquiv f (_ : ∀ (a : α), a ∈ ↑(support σ) ↔ ↑f a ∈ ↑(support (f * σ * f⁻¹)))))
(↑(subtypeEquiv g (_ : ∀ (a : α), a ∈ ↑(support τ) ↔ ↑g a ∈ ↑(support (g * τ * g⁻¹)))))
(↑(Set.union (_ : ↑(support σ) ⊓ ↑(support τ) ≤ ⊥))
{ val := x,
property := (_ : ↑(Equiv.refl α) ↑{ val := x, property := hx✝ } ∈ ↑(support σ) ∪ ↑(support τ)) })))
[PROOFSTEP]
cases' hx with hxσ hxτ
[GOAL]
case intro.intro.intro.refine'_2.inl
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxσ : x ∈ ↑(support σ)
⊢ ↑(↑(Set.union (_ : ↑(support (f * σ * f⁻¹)) ⊓ ↑(support (g * τ * g⁻¹)) ≤ ⊥)).symm
(Sum.map (↑(subtypeEquiv f (_ : ∀ (a : α), a ∈ ↑(support σ) ↔ ↑f a ∈ ↑(support (f * σ * f⁻¹)))))
(↑(subtypeEquiv g (_ : ∀ (a : α), a ∈ ↑(support τ) ↔ ↑g a ∈ ↑(support (g * τ * g⁻¹)))))
(↑(Set.union (_ : ↑(support σ) ⊓ ↑(support τ) ≤ ⊥))
{ val := ↑(σ * τ) x,
property :=
(_ :
↑(Equiv.refl α) ↑{ val := ↑(σ * τ) x, property := (_ : ↑(σ * τ) x ∈ support (σ * τ)) } ∈
↑(support σ) ∪ ↑(support τ)) }))) =
↑(f * σ * f⁻¹ * (g * τ * g⁻¹))
↑(↑(Set.union (_ : ↑(support (f * σ * f⁻¹)) ⊓ ↑(support (g * τ * g⁻¹)) ≤ ⊥)).symm
(Sum.map (↑(subtypeEquiv f (_ : ∀ (a : α), a ∈ ↑(support σ) ↔ ↑f a ∈ ↑(support (f * σ * f⁻¹)))))
(↑(subtypeEquiv g (_ : ∀ (a : α), a ∈ ↑(support τ) ↔ ↑g a ∈ ↑(support (g * τ * g⁻¹)))))
(↑(Set.union (_ : ↑(support σ) ⊓ ↑(support τ) ≤ ⊥))
{ val := x,
property := (_ : ↑(Equiv.refl α) ↑{ val := x, property := hx } ∈ ↑(support σ) ∪ ↑(support τ)) })))
[PROOFSTEP]
rw [mem_coe, mem_support] at hxσ
[GOAL]
case intro.intro.intro.refine'_2.inl
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxσ : ↑σ x ≠ x
⊢ ↑(↑(Set.union (_ : ↑(support (f * σ * f⁻¹)) ⊓ ↑(support (g * τ * g⁻¹)) ≤ ⊥)).symm
(Sum.map (↑(subtypeEquiv f (_ : ∀ (a : α), a ∈ ↑(support σ) ↔ ↑f a ∈ ↑(support (f * σ * f⁻¹)))))
(↑(subtypeEquiv g (_ : ∀ (a : α), a ∈ ↑(support τ) ↔ ↑g a ∈ ↑(support (g * τ * g⁻¹)))))
(↑(Set.union (_ : ↑(support σ) ⊓ ↑(support τ) ≤ ⊥))
{ val := ↑(σ * τ) x,
property :=
(_ :
↑(Equiv.refl α) ↑{ val := ↑(σ * τ) x, property := (_ : ↑(σ * τ) x ∈ support (σ * τ)) } ∈
↑(support σ) ∪ ↑(support τ)) }))) =
↑(f * σ * f⁻¹ * (g * τ * g⁻¹))
↑(↑(Set.union (_ : ↑(support (f * σ * f⁻¹)) ⊓ ↑(support (g * τ * g⁻¹)) ≤ ⊥)).symm
(Sum.map (↑(subtypeEquiv f (_ : ∀ (a : α), a ∈ ↑(support σ) ↔ ↑f a ∈ ↑(support (f * σ * f⁻¹)))))
(↑(subtypeEquiv g (_ : ∀ (a : α), a ∈ ↑(support τ) ↔ ↑g a ∈ ↑(support (g * τ * g⁻¹)))))
(↑(Set.union (_ : ↑(support σ) ⊓ ↑(support τ) ≤ ⊥))
{ val := x,
property := (_ : ↑(Equiv.refl α) ↑{ val := x, property := hx } ∈ ↑(support σ) ∪ ↑(support τ)) })))
[PROOFSTEP]
rw [Set.union_apply_left hd1''.le_bot _, Set.union_apply_left hd1''.le_bot _]
[GOAL]
case intro.intro.intro.refine'_2.inl
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxσ : ↑σ x ≠ x
⊢ ↑(↑(Set.union (_ : ↑(support (f * σ * f⁻¹)) ⊓ ↑(support (g * τ * g⁻¹)) ≤ ⊥)).symm
(Sum.map (↑(subtypeEquiv f (_ : ∀ (a : α), a ∈ ↑(support σ) ↔ ↑f a ∈ ↑(support (f * σ * f⁻¹)))))
(↑(subtypeEquiv g (_ : ∀ (a : α), a ∈ ↑(support τ) ↔ ↑g a ∈ ↑(support (g * τ * g⁻¹)))))
(Sum.inl
{
val :=
↑{ val := ↑(σ * τ) x,
property :=
(_ :
↑(Equiv.refl α) ↑{ val := ↑(σ * τ) x, property := (_ : ↑(σ * τ) x ∈ support (σ * τ)) } ∈
↑(support σ) ∪ ↑(support τ)) },
property := ?m.3180485 }))) =
↑(f * σ * f⁻¹ * (g * τ * g⁻¹))
↑(↑(Set.union (_ : ↑(support (f * σ * f⁻¹)) ⊓ ↑(support (g * τ * g⁻¹)) ≤ ⊥)).symm
(Sum.map (↑(subtypeEquiv f (_ : ∀ (a : α), a ∈ ↑(support σ) ↔ ↑f a ∈ ↑(support (f * σ * f⁻¹)))))
(↑(subtypeEquiv g (_ : ∀ (a : α), a ∈ ↑(support τ) ↔ ↑g a ∈ ↑(support (g * τ * g⁻¹)))))
(Sum.inl
{
val :=
↑{ val := x,
property := (_ : ↑(Equiv.refl α) ↑{ val := x, property := hx } ∈ ↑(support σ) ∪ ↑(support τ)) },
property := ?m.3180859 })))
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxσ : ↑σ x ≠ x
⊢ ↑{ val := ↑(σ * τ) x,
property :=
(_ :
↑(Equiv.refl α) ↑{ val := ↑(σ * τ) x, property := (_ : ↑(σ * τ) x ∈ support (σ * τ)) } ∈
↑(support σ) ∪ ↑(support τ)) } ∈
↑(support σ)
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxσ : ↑σ x ≠ x
⊢ ↑{ val := x, property := (_ : ↑(Equiv.refl α) ↑{ val := x, property := hx } ∈ ↑(support σ) ∪ ↑(support τ)) } ∈
↑(support σ)
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxσ : ↑σ x ≠ x
⊢ ↑{ val := ↑(σ * τ) x,
property :=
(_ :
↑(Equiv.refl α) ↑{ val := ↑(σ * τ) x, property := (_ : ↑(σ * τ) x ∈ support (σ * τ)) } ∈
↑(support σ) ∪ ↑(support τ)) } ∈
↑(support σ)
[PROOFSTEP]
simp only [subtypeEquiv_apply, Perm.coe_mul, Sum.map_inl, comp_apply, Set.union_symm_apply_left, Subtype.coe_mk,
apply_eq_iff_eq]
[GOAL]
case intro.intro.intro.refine'_2.inl
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxσ : ↑σ x ≠ x
⊢ ↑τ x = ↑f⁻¹ (↑g (↑τ (↑g⁻¹ (↑f x))))
[PROOFSTEP]
have h := (hd2 (f x)).resolve_left ?_
[GOAL]
case intro.intro.intro.refine'_2.inl.refine_2
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxσ : ↑σ x ≠ x
h : ↑(g * τ * g⁻¹) (↑f x) = ↑f x
⊢ ↑τ x = ↑f⁻¹ (↑g (↑τ (↑g⁻¹ (↑f x))))
[PROOFSTEP]
rw [mul_apply, mul_apply] at h
[GOAL]
case intro.intro.intro.refine'_2.inl.refine_2
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxσ : ↑σ x ≠ x
h : ↑g (↑τ (↑g⁻¹ (↑f x))) = ↑f x
⊢ ↑τ x = ↑f⁻¹ (↑g (↑τ (↑g⁻¹ (↑f x))))
[PROOFSTEP]
rw [h, inv_apply_self, (hd1 x).resolve_left hxσ]
[GOAL]
case intro.intro.intro.refine'_2.inl.refine_1
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxσ : ↑σ x ≠ x
⊢ ¬↑(f * σ * f⁻¹) (↑f x) = ↑f x
[PROOFSTEP]
rwa [mul_apply, mul_apply, inv_apply_self, apply_eq_iff_eq]
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxσ : ↑σ x ≠ x
⊢ ↑{ val := ↑(σ * τ) x,
property :=
(_ :
↑(Equiv.refl α) ↑{ val := ↑(σ * τ) x, property := (_ : ↑(σ * τ) x ∈ support (σ * τ)) } ∈
↑(support σ) ∪ ↑(support τ)) } ∈
↑(support σ)
[PROOFSTEP]
rwa [Subtype.coe_mk, Perm.mul_apply, (hd1 x).resolve_left hxσ, mem_coe, apply_mem_support, mem_support]
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxσ : ↑σ x ≠ x
⊢ ↑{ val := x, property := (_ : ↑(Equiv.refl α) ↑{ val := x, property := hx } ∈ ↑(support σ) ∪ ↑(support τ)) } ∈
↑(support σ)
[PROOFSTEP]
rwa [Subtype.coe_mk, mem_coe, mem_support]
[GOAL]
case intro.intro.intro.refine'_2.inr
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxτ : x ∈ ↑(support τ)
⊢ ↑(↑(Set.union (_ : ↑(support (f * σ * f⁻¹)) ⊓ ↑(support (g * τ * g⁻¹)) ≤ ⊥)).symm
(Sum.map (↑(subtypeEquiv f (_ : ∀ (a : α), a ∈ ↑(support σ) ↔ ↑f a ∈ ↑(support (f * σ * f⁻¹)))))
(↑(subtypeEquiv g (_ : ∀ (a : α), a ∈ ↑(support τ) ↔ ↑g a ∈ ↑(support (g * τ * g⁻¹)))))
(↑(Set.union (_ : ↑(support σ) ⊓ ↑(support τ) ≤ ⊥))
{ val := ↑(σ * τ) x,
property :=
(_ :
↑(Equiv.refl α) ↑{ val := ↑(σ * τ) x, property := (_ : ↑(σ * τ) x ∈ support (σ * τ)) } ∈
↑(support σ) ∪ ↑(support τ)) }))) =
↑(f * σ * f⁻¹ * (g * τ * g⁻¹))
↑(↑(Set.union (_ : ↑(support (f * σ * f⁻¹)) ⊓ ↑(support (g * τ * g⁻¹)) ≤ ⊥)).symm
(Sum.map (↑(subtypeEquiv f (_ : ∀ (a : α), a ∈ ↑(support σ) ↔ ↑f a ∈ ↑(support (f * σ * f⁻¹)))))
(↑(subtypeEquiv g (_ : ∀ (a : α), a ∈ ↑(support τ) ↔ ↑g a ∈ ↑(support (g * τ * g⁻¹)))))
(↑(Set.union (_ : ↑(support σ) ⊓ ↑(support τ) ≤ ⊥))
{ val := x,
property := (_ : ↑(Equiv.refl α) ↑{ val := x, property := hx } ∈ ↑(support σ) ∪ ↑(support τ)) })))
[PROOFSTEP]
rw [mem_coe, ← apply_mem_support, mem_support] at hxτ
[GOAL]
case intro.intro.intro.refine'_2.inr
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxτ : ↑τ (↑τ x) ≠ ↑τ x
⊢ ↑(↑(Set.union (_ : ↑(support (f * σ * f⁻¹)) ⊓ ↑(support (g * τ * g⁻¹)) ≤ ⊥)).symm
(Sum.map (↑(subtypeEquiv f (_ : ∀ (a : α), a ∈ ↑(support σ) ↔ ↑f a ∈ ↑(support (f * σ * f⁻¹)))))
(↑(subtypeEquiv g (_ : ∀ (a : α), a ∈ ↑(support τ) ↔ ↑g a ∈ ↑(support (g * τ * g⁻¹)))))
(↑(Set.union (_ : ↑(support σ) ⊓ ↑(support τ) ≤ ⊥))
{ val := ↑(σ * τ) x,
property :=
(_ :
↑(Equiv.refl α) ↑{ val := ↑(σ * τ) x, property := (_ : ↑(σ * τ) x ∈ support (σ * τ)) } ∈
↑(support σ) ∪ ↑(support τ)) }))) =
↑(f * σ * f⁻¹ * (g * τ * g⁻¹))
↑(↑(Set.union (_ : ↑(support (f * σ * f⁻¹)) ⊓ ↑(support (g * τ * g⁻¹)) ≤ ⊥)).symm
(Sum.map (↑(subtypeEquiv f (_ : ∀ (a : α), a ∈ ↑(support σ) ↔ ↑f a ∈ ↑(support (f * σ * f⁻¹)))))
(↑(subtypeEquiv g (_ : ∀ (a : α), a ∈ ↑(support τ) ↔ ↑g a ∈ ↑(support (g * τ * g⁻¹)))))
(↑(Set.union (_ : ↑(support σ) ⊓ ↑(support τ) ≤ ⊥))
{ val := x,
property := (_ : ↑(Equiv.refl α) ↑{ val := x, property := hx } ∈ ↑(support σ) ∪ ↑(support τ)) })))
[PROOFSTEP]
rw [Set.union_apply_right hd1''.le_bot _, Set.union_apply_right hd1''.le_bot _]
[GOAL]
case intro.intro.intro.refine'_2.inr
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxτ : ↑τ (↑τ x) ≠ ↑τ x
⊢ ↑(↑(Set.union (_ : ↑(support (f * σ * f⁻¹)) ⊓ ↑(support (g * τ * g⁻¹)) ≤ ⊥)).symm
(Sum.map (↑(subtypeEquiv f (_ : ∀ (a : α), a ∈ ↑(support σ) ↔ ↑f a ∈ ↑(support (f * σ * f⁻¹)))))
(↑(subtypeEquiv g (_ : ∀ (a : α), a ∈ ↑(support τ) ↔ ↑g a ∈ ↑(support (g * τ * g⁻¹)))))
(Sum.inr
{
val :=
↑{ val := ↑(σ * τ) x,
property :=
(_ :
↑(Equiv.refl α) ↑{ val := ↑(σ * τ) x, property := (_ : ↑(σ * τ) x ∈ support (σ * τ)) } ∈
↑(support σ) ∪ ↑(support τ)) },
property := ?m.3185057 }))) =
↑(f * σ * f⁻¹ * (g * τ * g⁻¹))
↑(↑(Set.union (_ : ↑(support (f * σ * f⁻¹)) ⊓ ↑(support (g * τ * g⁻¹)) ≤ ⊥)).symm
(Sum.map (↑(subtypeEquiv f (_ : ∀ (a : α), a ∈ ↑(support σ) ↔ ↑f a ∈ ↑(support (f * σ * f⁻¹)))))
(↑(subtypeEquiv g (_ : ∀ (a : α), a ∈ ↑(support τ) ↔ ↑g a ∈ ↑(support (g * τ * g⁻¹)))))
(Sum.inr
{
val :=
↑{ val := x,
property := (_ : ↑(Equiv.refl α) ↑{ val := x, property := hx } ∈ ↑(support σ) ∪ ↑(support τ)) },
property := ?m.3185166 })))
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxτ : ↑τ (↑τ x) ≠ ↑τ x
⊢ ↑{ val := ↑(σ * τ) x,
property :=
(_ :
↑(Equiv.refl α) ↑{ val := ↑(σ * τ) x, property := (_ : ↑(σ * τ) x ∈ support (σ * τ)) } ∈
↑(support σ) ∪ ↑(support τ)) } ∈
↑(support τ)
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxτ : ↑τ (↑τ x) ≠ ↑τ x
⊢ ↑{ val := x, property := (_ : ↑(Equiv.refl α) ↑{ val := x, property := hx } ∈ ↑(support σ) ∪ ↑(support τ)) } ∈
↑(support τ)
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxτ : ↑τ (↑τ x) ≠ ↑τ x
⊢ ↑{ val := ↑(σ * τ) x,
property :=
(_ :
↑(Equiv.refl α) ↑{ val := ↑(σ * τ) x, property := (_ : ↑(σ * τ) x ∈ support (σ * τ)) } ∈
↑(support σ) ∪ ↑(support τ)) } ∈
↑(support τ)
[PROOFSTEP]
simp only [subtypeEquiv_apply, Perm.coe_mul, Sum.map_inr, comp_apply, Set.union_symm_apply_right, Subtype.coe_mk,
apply_eq_iff_eq]
[GOAL]
case intro.intro.intro.refine'_2.inr
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxτ : ↑τ (↑τ x) ≠ ↑τ x
⊢ ↑g (↑σ (↑τ x)) = ↑f (↑σ (↑f⁻¹ (↑g (↑τ (↑g⁻¹ (↑g x))))))
[PROOFSTEP]
have h := (hd2 (g (τ x))).resolve_right ?_
[GOAL]
case intro.intro.intro.refine'_2.inr.refine_2
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxτ : ↑τ (↑τ x) ≠ ↑τ x
h : ↑(f * σ * f⁻¹) (↑g (↑τ x)) = ↑g (↑τ x)
⊢ ↑g (↑σ (↑τ x)) = ↑f (↑σ (↑f⁻¹ (↑g (↑τ (↑g⁻¹ (↑g x))))))
[PROOFSTEP]
rw [mul_apply, mul_apply] at h
[GOAL]
case intro.intro.intro.refine'_2.inr.refine_2
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxτ : ↑τ (↑τ x) ≠ ↑τ x
h : ↑f (↑σ (↑f⁻¹ (↑g (↑τ x)))) = ↑g (↑τ x)
⊢ ↑g (↑σ (↑τ x)) = ↑f (↑σ (↑f⁻¹ (↑g (↑τ (↑g⁻¹ (↑g x))))))
[PROOFSTEP]
rw [inv_apply_self, h, (hd1 (τ x)).resolve_right hxτ]
[GOAL]
case intro.intro.intro.refine'_2.inr.refine_1
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxτ : ↑τ (↑τ x) ≠ ↑τ x
⊢ ¬↑(g * τ * g⁻¹) (↑g (↑τ x)) = ↑g (↑τ x)
[PROOFSTEP]
rwa [mul_apply, mul_apply, inv_apply_self, apply_eq_iff_eq]
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxτ : ↑τ (↑τ x) ≠ ↑τ x
⊢ ↑{ val := ↑(σ * τ) x,
property :=
(_ :
↑(Equiv.refl α) ↑{ val := ↑(σ * τ) x, property := (_ : ↑(σ * τ) x ∈ support (σ * τ)) } ∈
↑(support σ) ∪ ↑(support τ)) } ∈
↑(support τ)
[PROOFSTEP]
rwa [Subtype.coe_mk, Perm.mul_apply, (hd1 (τ x)).resolve_right hxτ, mem_coe, mem_support]
[GOAL]
ι : Type u_1
α✝ : Type u_2
β : Type u_3
inst✝² : DecidableEq α✝
inst✝¹ : Fintype α✝
σ✝ τ✝ : Perm α✝
α : Type u_4
inst✝ : Finite α
σ τ : Perm α
hd1 : Disjoint σ τ
val✝ : Fintype α
f : Perm α
hc1 : IsConj σ (f * σ * f⁻¹)
g : Perm α
hc2 : IsConj τ (g * τ * g⁻¹)
hd2 : Disjoint (f * σ * f⁻¹) (g * τ * g⁻¹)
hd1' : ↑(support (σ * τ)) = ↑(support σ) ∪ ↑(support τ)
hd2' : ↑(support (f * σ * f⁻¹ * (g * τ * g⁻¹))) = ↑(support (f * σ * f⁻¹)) ∪ ↑(support (g * τ * g⁻¹))
hd1'' : _root_.Disjoint ↑(support σ) ↑(support τ)
hd2'' : _root_.Disjoint ↑(support (f * σ * f⁻¹)) ↑(support (g * τ * g⁻¹))
x : α
hx : x ∈ ↑(support (σ * τ))
hxτ : ↑τ (↑τ x) ≠ ↑τ x
⊢ ↑{ val := x, property := (_ : ↑(Equiv.refl α) ↑{ val := x, property := hx } ∈ ↑(support σ) ∪ ↑(support τ)) } ∈
↑(support τ)
[PROOFSTEP]
rwa [Subtype.coe_mk, mem_coe, ← apply_mem_support, mem_support]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Fintype α
σ✝ τ : Perm α
inst✝ : Fintype α
σ : Perm α
h : σ ≠ 1
⊢ card (filter (fun x => ↑σ x = x) univ) < Fintype.card α - 1
[PROOFSTEP]
rw [lt_tsub_iff_left, ← lt_tsub_iff_right, ← Finset.card_compl, Finset.compl_filter]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² : DecidableEq α
inst✝¹ : Fintype α
σ✝ τ : Perm α
inst✝ : Fintype α
σ : Perm α
h : σ ≠ 1
⊢ 1 < card (filter (fun x => ¬↑σ x = x) univ)
[PROOFSTEP]
exact one_lt_card_support_of_ne_one h
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ inst✝ : DecidableEq α
l : List α
h : List.Nodup l
⊢ IsCycleOn (List.formPerm l) {a | a ∈ l}
[PROOFSTEP]
refine' ⟨l.formPerm.bijOn fun _ => List.formPerm_mem_iff_mem, fun a ha b hb => _⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ inst✝ : DecidableEq α
l : List α
h : List.Nodup l
a : α
ha : a ∈ {a | a ∈ l}
b : α
hb : b ∈ {a | a ∈ l}
⊢ SameCycle (List.formPerm l) a b
[PROOFSTEP]
rw [Set.mem_setOf, ← List.indexOf_lt_length] at ha hb
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ inst✝ : DecidableEq α
l : List α
h : List.Nodup l
a : α
ha✝ : a ∈ l
ha : List.indexOf a l < List.length l
b : α
hb✝ : b ∈ l
hb : List.indexOf b l < List.length l
⊢ SameCycle (List.formPerm l) a b
[PROOFSTEP]
rw [← List.indexOf_get ha, ← List.indexOf_get hb]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ inst✝ : DecidableEq α
l : List α
h : List.Nodup l
a : α
ha✝ : a ∈ l
ha : List.indexOf a l < List.length l
b : α
hb✝ : b ∈ l
hb : List.indexOf b l < List.length l
⊢ SameCycle (List.formPerm l) (List.get l { val := List.indexOf a l, isLt := ha })
(List.get l { val := List.indexOf b l, isLt := hb })
[PROOFSTEP]
refine' ⟨l.indexOf b - l.indexOf a, _⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ inst✝ : DecidableEq α
l : List α
h : List.Nodup l
a : α
ha✝ : a ∈ l
ha : List.indexOf a l < List.length l
b : α
hb✝ : b ∈ l
hb : List.indexOf b l < List.length l
⊢ ↑(List.formPerm l ^ (↑(List.indexOf b l) - ↑(List.indexOf a l)))
(List.get l { val := List.indexOf a l, isLt := ha }) =
List.get l { val := List.indexOf b l, isLt := hb }
[PROOFSTEP]
simp only [sub_eq_neg_add, zpow_add, zpow_neg, Equiv.Perm.inv_eq_iff_eq, zpow_ofNat, Equiv.Perm.coe_mul, ←
List.nthLe_eq, List.formPerm_pow_apply_nthLe _ h, Function.comp]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝¹ inst✝ : DecidableEq α
l : List α
h : List.Nodup l
a : α
ha✝ : a ∈ l
ha : List.indexOf a l < List.length l
b : α
hb✝ : b ∈ l
hb : List.indexOf b l < List.length l
⊢ List.nthLe l ((List.indexOf a l + List.indexOf b l) % List.length l)
(_ : (List.indexOf a l + List.indexOf b l) % List.length l < List.length l) =
List.nthLe l ((List.indexOf b l + List.indexOf a l) % List.length l)
(_ : (List.indexOf b l + List.indexOf a l) % List.length l < List.length l)
[PROOFSTEP]
rw [add_comm]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
n : ℤ
x✝ : ↑(Equiv.addLeft 1) n ≠ n
⊢ ↑(Equiv.addLeft 1 ^ n) 0 = n
[PROOFSTEP]
simp
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
n : ℤ
x✝ : ↑(Equiv.addRight 1) n ≠ n
⊢ ↑(Equiv.addRight 1 ^ n) 0 = n
[PROOFSTEP]
simp
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² inst✝¹ : DecidableEq α
inst✝ : Fintype α
s : Finset α
⊢ ∃ f, IsCycleOn f ↑s ∧ support f ⊆ s
[PROOFSTEP]
refine' ⟨s.toList.formPerm, _, fun x hx => by simpa using List.mem_of_formPerm_apply_ne _ _ (Perm.mem_support.1 hx)⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² inst✝¹ : DecidableEq α
inst✝ : Fintype α
s : Finset α
x : α
hx : x ∈ support (List.formPerm (toList s))
⊢ x ∈ s
[PROOFSTEP]
simpa using List.mem_of_formPerm_apply_ne _ _ (Perm.mem_support.1 hx)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² inst✝¹ : DecidableEq α
inst✝ : Fintype α
s : Finset α
⊢ IsCycleOn (List.formPerm (toList s)) ↑s
[PROOFSTEP]
convert s.nodup_toList.isCycleOn_formPerm
[GOAL]
case h.e'_3
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝² inst✝¹ : DecidableEq α
inst✝ : Fintype α
s : Finset α
⊢ ↑s = {a | a ∈ toList s}
[PROOFSTEP]
simp
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Set α
hs : Set.Countable s
⊢ ∃ f, IsCycleOn f s ∧ {x | ↑f x ≠ x} ⊆ s
[PROOFSTEP]
classical
obtain hs' | hs' := s.finite_or_infinite
· refine' ⟨hs'.toFinset.toList.formPerm, _, fun x hx => by simpa using List.mem_of_formPerm_apply_ne _ _ hx⟩
convert hs'.toFinset.nodup_toList.isCycleOn_formPerm
simp
haveI := hs.to_subtype
haveI := hs'.to_subtype
obtain ⟨f⟩ : Nonempty (ℤ ≃ s) := inferInstance
refine'
⟨(Equiv.addRight 1).extendDomain f, _, fun x hx =>
of_not_not fun h => hx <| Perm.extendDomain_apply_not_subtype _ _ h⟩
convert Int.addRight_one_isCycle.isCycleOn.extendDomain f
rw [Set.image_comp, Equiv.image_eq_preimage]
ext
simp
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Set α
hs : Set.Countable s
⊢ ∃ f, IsCycleOn f s ∧ {x | ↑f x ≠ x} ⊆ s
[PROOFSTEP]
obtain hs' | hs' := s.finite_or_infinite
[GOAL]
case inl
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Set α
hs : Set.Countable s
hs' : Set.Finite s
⊢ ∃ f, IsCycleOn f s ∧ {x | ↑f x ≠ x} ⊆ s
[PROOFSTEP]
refine' ⟨hs'.toFinset.toList.formPerm, _, fun x hx => by simpa using List.mem_of_formPerm_apply_ne _ _ hx⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Set α
hs : Set.Countable s
hs' : Set.Finite s
x : α
hx : x ∈ {x | ↑(List.formPerm (toList (Set.Finite.toFinset hs'))) x ≠ x}
⊢ x ∈ s
[PROOFSTEP]
simpa using List.mem_of_formPerm_apply_ne _ _ hx
[GOAL]
case inl
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Set α
hs : Set.Countable s
hs' : Set.Finite s
⊢ IsCycleOn (List.formPerm (toList (Set.Finite.toFinset hs'))) s
[PROOFSTEP]
convert hs'.toFinset.nodup_toList.isCycleOn_formPerm
[GOAL]
case h.e'_3
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Set α
hs : Set.Countable s
hs' : Set.Finite s
⊢ s = {a | a ∈ toList (Set.Finite.toFinset hs')}
[PROOFSTEP]
simp
[GOAL]
case inr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Set α
hs : Set.Countable s
hs' : Set.Infinite s
⊢ ∃ f, IsCycleOn f s ∧ {x | ↑f x ≠ x} ⊆ s
[PROOFSTEP]
haveI := hs.to_subtype
[GOAL]
case inr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Set α
hs : Set.Countable s
hs' : Set.Infinite s
this : Countable ↑s
⊢ ∃ f, IsCycleOn f s ∧ {x | ↑f x ≠ x} ⊆ s
[PROOFSTEP]
haveI := hs'.to_subtype
[GOAL]
case inr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Set α
hs : Set.Countable s
hs' : Set.Infinite s
this✝ : Countable ↑s
this : Infinite ↑s
⊢ ∃ f, IsCycleOn f s ∧ {x | ↑f x ≠ x} ⊆ s
[PROOFSTEP]
obtain ⟨f⟩ : Nonempty (ℤ ≃ s) := inferInstance
[GOAL]
case inr.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f✝ : Perm α
s : Set α
hs : Set.Countable s
hs' : Set.Infinite s
this✝ : Countable ↑s
this : Infinite ↑s
f : ℤ ≃ ↑s
⊢ ∃ f, IsCycleOn f s ∧ {x | ↑f x ≠ x} ⊆ s
[PROOFSTEP]
refine'
⟨(Equiv.addRight 1).extendDomain f, _, fun x hx =>
of_not_not fun h => hx <| Perm.extendDomain_apply_not_subtype _ _ h⟩
[GOAL]
case inr.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f✝ : Perm α
s : Set α
hs : Set.Countable s
hs' : Set.Infinite s
this✝ : Countable ↑s
this : Infinite ↑s
f : ℤ ≃ ↑s
⊢ IsCycleOn (extendDomain (Equiv.addRight 1) f) s
[PROOFSTEP]
convert Int.addRight_one_isCycle.isCycleOn.extendDomain f
[GOAL]
case h.e'_3
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f✝ : Perm α
s : Set α
hs : Set.Countable s
hs' : Set.Infinite s
this✝ : Countable ↑s
this : Infinite ↑s
f : ℤ ≃ ↑s
⊢ s = Subtype.val ∘ ↑f '' {x | ↑(Equiv.addRight 1) x ≠ x}
[PROOFSTEP]
rw [Set.image_comp, Equiv.image_eq_preimage]
[GOAL]
case h.e'_3
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f✝ : Perm α
s : Set α
hs : Set.Countable s
hs' : Set.Infinite s
this✝ : Countable ↑s
this : Infinite ↑s
f : ℤ ≃ ↑s
⊢ s = Subtype.val '' (↑f.symm ⁻¹' {x | ↑(Equiv.addRight 1) x ≠ x})
[PROOFSTEP]
ext
[GOAL]
case h.e'_3.h
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f✝ : Perm α
s : Set α
hs : Set.Countable s
hs' : Set.Infinite s
this✝ : Countable ↑s
this : Infinite ↑s
f : ℤ ≃ ↑s
x✝ : α
⊢ x✝ ∈ s ↔ x✝ ∈ Subtype.val '' (↑f.symm ⁻¹' {x | ↑(Equiv.addRight 1) x ≠ x})
[PROOFSTEP]
simp
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Set α
hf : IsCycleOn f s
⊢ s ×ˢ s = ⋃ (n : ℤ), (fun a => (a, ↑(f ^ n) a)) '' s
[PROOFSTEP]
ext ⟨a, b⟩
[GOAL]
case h.mk
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Set α
hf : IsCycleOn f s
a b : α
⊢ (a, b) ∈ s ×ˢ s ↔ (a, b) ∈ ⋃ (n : ℤ), (fun a => (a, ↑(f ^ n) a)) '' s
[PROOFSTEP]
simp only [Set.mem_prod, Set.mem_iUnion, Set.mem_image]
[GOAL]
case h.mk
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Set α
hf : IsCycleOn f s
a b : α
⊢ a ∈ s ∧ b ∈ s ↔ ∃ i x, x ∈ s ∧ (x, ↑(f ^ i) x) = (a, b)
[PROOFSTEP]
refine' ⟨fun hx => _, _⟩
[GOAL]
case h.mk.refine'_1
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Set α
hf : IsCycleOn f s
a b : α
hx : a ∈ s ∧ b ∈ s
⊢ ∃ i x, x ∈ s ∧ (x, ↑(f ^ i) x) = (a, b)
[PROOFSTEP]
obtain ⟨n, rfl⟩ := hf.2 hx.1 hx.2
[GOAL]
case h.mk.refine'_1.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Set α
hf : IsCycleOn f s
a : α
n : ℤ
hx : a ∈ s ∧ ↑(f ^ n) a ∈ s
⊢ ∃ i x, x ∈ s ∧ (x, ↑(f ^ i) x) = (a, ↑(f ^ n) a)
[PROOFSTEP]
exact ⟨_, _, hx.1, rfl⟩
[GOAL]
case h.mk.refine'_2
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Set α
hf : IsCycleOn f s
a b : α
⊢ (∃ i x, x ∈ s ∧ (x, ↑(f ^ i) x) = (a, b)) → a ∈ s ∧ b ∈ s
[PROOFSTEP]
rintro ⟨n, a, ha, ⟨⟩⟩
[GOAL]
case h.mk.refine'_2.intro.intro.intro.refl
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Set α
hf : IsCycleOn f s
a : α
n : ℤ
ha : a ∈ s
⊢ a ∈ s ∧ ↑(f ^ n) a ∈ s
[PROOFSTEP]
exact ⟨ha, (hf.1.perm_zpow _).mapsTo ha⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Finset α
hf : IsCycleOn f ↑s
⊢ Set.PairwiseDisjoint ↑(range (card s)) fun k =>
map
{ toFun := fun i => (i, ↑(f ^ k) i),
inj' :=
(_ :
∀ (i j : α),
(fun i => (i, ↑(f ^ k) i)) i = (fun i => (i, ↑(f ^ k) i)) j →
((fun i => (i, ↑(f ^ k) i)) i).fst = ((fun i => (i, ↑(f ^ k) i)) j).fst) }
s
[PROOFSTEP]
obtain hs | _ := (s : Set α).subsingleton_or_nontrivial
[GOAL]
case inl
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Finset α
hf : IsCycleOn f ↑s
hs : Set.Subsingleton ↑s
⊢ Set.PairwiseDisjoint ↑(range (card s)) fun k =>
map
{ toFun := fun i => (i, ↑(f ^ k) i),
inj' :=
(_ :
∀ (i j : α),
(fun i => (i, ↑(f ^ k) i)) i = (fun i => (i, ↑(f ^ k) i)) j →
((fun i => (i, ↑(f ^ k) i)) i).fst = ((fun i => (i, ↑(f ^ k) i)) j).fst) }
s
[PROOFSTEP]
refine' Set.Subsingleton.pairwise _ _
[GOAL]
case inl
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Finset α
hf : IsCycleOn f ↑s
hs : Set.Subsingleton ↑s
⊢ Set.Subsingleton ↑(range (card s))
[PROOFSTEP]
simp_rw [Set.Subsingleton, mem_coe, ← card_le_one] at hs ⊢
[GOAL]
case inl
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Finset α
hf : IsCycleOn f ↑s
hs : card s ≤ 1
⊢ card (range (card s)) ≤ 1
[PROOFSTEP]
rwa [card_range]
[GOAL]
case inr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Finset α
hf : IsCycleOn f ↑s
h✝ : Set.Nontrivial ↑s
⊢ Set.PairwiseDisjoint ↑(range (card s)) fun k =>
map
{ toFun := fun i => (i, ↑(f ^ k) i),
inj' :=
(_ :
∀ (i j : α),
(fun i => (i, ↑(f ^ k) i)) i = (fun i => (i, ↑(f ^ k) i)) j →
((fun i => (i, ↑(f ^ k) i)) i).fst = ((fun i => (i, ↑(f ^ k) i)) j).fst) }
s
[PROOFSTEP]
classical
rintro m hm n hn hmn
simp only [disjoint_left, Function.onFun, mem_map, Function.Embedding.coeFn_mk, exists_prop, not_exists, not_and,
forall_exists_index, and_imp, Prod.forall, Prod.mk.inj_iff]
rintro _ _ _ - rfl rfl a ha rfl h
rw [hf.pow_apply_eq_pow_apply ha] at h
rw [mem_coe, mem_range] at hm hn
exact hmn.symm (h.eq_of_lt_of_lt hn hm)
[GOAL]
case inr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Finset α
hf : IsCycleOn f ↑s
h✝ : Set.Nontrivial ↑s
⊢ Set.PairwiseDisjoint ↑(range (card s)) fun k =>
map
{ toFun := fun i => (i, ↑(f ^ k) i),
inj' :=
(_ :
∀ (i j : α),
(fun i => (i, ↑(f ^ k) i)) i = (fun i => (i, ↑(f ^ k) i)) j →
((fun i => (i, ↑(f ^ k) i)) i).fst = ((fun i => (i, ↑(f ^ k) i)) j).fst) }
s
[PROOFSTEP]
rintro m hm n hn hmn
[GOAL]
case inr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Finset α
hf : IsCycleOn f ↑s
h✝ : Set.Nontrivial ↑s
m : ℕ
hm : m ∈ ↑(range (card s))
n : ℕ
hn : n ∈ ↑(range (card s))
hmn : m ≠ n
⊢ (_root_.Disjoint on fun k =>
map
{ toFun := fun i => (i, ↑(f ^ k) i),
inj' :=
(_ :
∀ (i j : α),
(fun i => (i, ↑(f ^ k) i)) i = (fun i => (i, ↑(f ^ k) i)) j →
((fun i => (i, ↑(f ^ k) i)) i).fst = ((fun i => (i, ↑(f ^ k) i)) j).fst) }
s)
m n
[PROOFSTEP]
simp only [disjoint_left, Function.onFun, mem_map, Function.Embedding.coeFn_mk, exists_prop, not_exists, not_and,
forall_exists_index, and_imp, Prod.forall, Prod.mk.inj_iff]
[GOAL]
case inr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Finset α
hf : IsCycleOn f ↑s
h✝ : Set.Nontrivial ↑s
m : ℕ
hm : m ∈ ↑(range (card s))
n : ℕ
hn : n ∈ ↑(range (card s))
hmn : m ≠ n
⊢ ∀ (a b x : α), x ∈ s → x = a → ↑(f ^ m) x = b → ∀ (x : α), x ∈ s → x = a → ¬↑(f ^ n) x = b
[PROOFSTEP]
rintro _ _ _ - rfl rfl a ha rfl h
[GOAL]
case inr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Finset α
hf : IsCycleOn f ↑s
h✝ : Set.Nontrivial ↑s
m : ℕ
hm : m ∈ ↑(range (card s))
n : ℕ
hn : n ∈ ↑(range (card s))
hmn : m ≠ n
a : α
ha : a ∈ s
h : ↑(f ^ n) a = ↑(f ^ m) a
⊢ False
[PROOFSTEP]
rw [hf.pow_apply_eq_pow_apply ha] at h
[GOAL]
case inr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Finset α
hf : IsCycleOn f ↑s
h✝ : Set.Nontrivial ↑s
m : ℕ
hm : m ∈ ↑(range (card s))
n : ℕ
hn : n ∈ ↑(range (card s))
hmn : m ≠ n
a : α
ha : a ∈ s
h : n ≡ m [MOD card s]
⊢ False
[PROOFSTEP]
rw [mem_coe, mem_range] at hm hn
[GOAL]
case inr
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Finset α
hf : IsCycleOn f ↑s
h✝ : Set.Nontrivial ↑s
m : ℕ
hm : m < card s
n : ℕ
hn : n < card s
hmn : m ≠ n
a : α
ha : a ∈ s
h : n ≡ m [MOD card s]
⊢ False
[PROOFSTEP]
exact hmn.symm (h.eq_of_lt_of_lt hn hm)
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Finset α
hf : IsCycleOn f ↑s
⊢ s ×ˢ s =
disjiUnion (range (card s))
(fun k =>
map
{ toFun := fun i => (i, ↑(f ^ k) i),
inj' :=
(_ :
∀ (i j : α),
(fun i => (i, ↑(f ^ k) i)) i = (fun i => (i, ↑(f ^ k) i)) j →
((fun i => (i, ↑(f ^ k) i)) i).fst = ((fun i => (i, ↑(f ^ k) i)) j).fst) }
s)
(_ :
Set.PairwiseDisjoint ↑(range (card s)) fun k =>
map
{ toFun := fun i => (i, ↑(f ^ k) i),
inj' :=
(_ :
∀ (i j : α),
(fun i => (i, ↑(f ^ k) i)) i = (fun i => (i, ↑(f ^ k) i)) j →
((fun i => (i, ↑(f ^ k) i)) i).fst = ((fun i => (i, ↑(f ^ k) i)) j).fst) }
s)
[PROOFSTEP]
ext ⟨a, b⟩
[GOAL]
case a.mk
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Finset α
hf : IsCycleOn f ↑s
a b : α
⊢ (a, b) ∈ s ×ˢ s ↔
(a, b) ∈
disjiUnion (range (card s))
(fun k =>
map
{ toFun := fun i => (i, ↑(f ^ k) i),
inj' :=
(_ :
∀ (i j : α),
(fun i => (i, ↑(f ^ k) i)) i = (fun i => (i, ↑(f ^ k) i)) j →
((fun i => (i, ↑(f ^ k) i)) i).fst = ((fun i => (i, ↑(f ^ k) i)) j).fst) }
s)
(_ :
Set.PairwiseDisjoint ↑(range (card s)) fun k =>
map
{ toFun := fun i => (i, ↑(f ^ k) i),
inj' :=
(_ :
∀ (i j : α),
(fun i => (i, ↑(f ^ k) i)) i = (fun i => (i, ↑(f ^ k) i)) j →
((fun i => (i, ↑(f ^ k) i)) i).fst = ((fun i => (i, ↑(f ^ k) i)) j).fst) }
s)
[PROOFSTEP]
simp only [mem_product, Equiv.Perm.coe_pow, mem_disjiUnion, mem_range, mem_map, Function.Embedding.coeFn_mk,
Prod.mk.inj_iff, exists_prop]
[GOAL]
case a.mk
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Finset α
hf : IsCycleOn f ↑s
a b : α
⊢ a ∈ s ∧ b ∈ s ↔ ∃ a_1, a_1 < card s ∧ ∃ a_2, a_2 ∈ s ∧ a_2 = a ∧ (↑f)^[a_1] a_2 = b
[PROOFSTEP]
refine' ⟨fun hx => _, _⟩
[GOAL]
case a.mk.refine'_1
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Finset α
hf : IsCycleOn f ↑s
a b : α
hx : a ∈ s ∧ b ∈ s
⊢ ∃ a_1, a_1 < card s ∧ ∃ a_2, a_2 ∈ s ∧ a_2 = a ∧ (↑f)^[a_1] a_2 = b
[PROOFSTEP]
obtain ⟨n, hn, rfl⟩ := hf.exists_pow_eq hx.1 hx.2
[GOAL]
case a.mk.refine'_1.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Finset α
hf : IsCycleOn f ↑s
a : α
n : ℕ
hn : n < card s
hx : a ∈ s ∧ ↑(f ^ n) a ∈ s
⊢ ∃ a_1, a_1 < card s ∧ ∃ a_2, a_2 ∈ s ∧ a_2 = a ∧ (↑f)^[a_1] a_2 = ↑(f ^ n) a
[PROOFSTEP]
exact ⟨n, hn, a, hx.1, rfl, by rw [f.iterate_eq_pow]⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Finset α
hf : IsCycleOn f ↑s
a : α
n : ℕ
hn : n < card s
hx : a ∈ s ∧ ↑(f ^ n) a ∈ s
⊢ (↑f)^[n] a = ↑(f ^ n) a
[PROOFSTEP]
rw [f.iterate_eq_pow]
[GOAL]
case a.mk.refine'_2
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Finset α
hf : IsCycleOn f ↑s
a b : α
⊢ (∃ a_1, a_1 < card s ∧ ∃ a_2, a_2 ∈ s ∧ a_2 = a ∧ (↑f)^[a_1] a_2 = b) → a ∈ s ∧ b ∈ s
[PROOFSTEP]
rintro ⟨n, -, a, ha, rfl, rfl⟩
[GOAL]
case a.mk.refine'_2.intro.intro.intro.intro.intro
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝ : DecidableEq α
f : Perm α
s : Finset α
hf : IsCycleOn f ↑s
n : ℕ
a : α
ha : a ∈ s
⊢ a ∈ s ∧ (↑f)^[n] a ∈ s
[PROOFSTEP]
exact ⟨ha, (hf.1.iterate _).mapsTo ha⟩
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝³ : DecidableEq α
inst✝² : Semiring α
inst✝¹ : AddCommMonoid β
inst✝ : Module α β
s : Finset ι
σ : Perm ι
hσ : IsCycleOn σ ↑s
f : ι → α
g : ι → β
⊢ (∑ i in s, f i) • ∑ i in s, g i = ∑ k in range (card s), ∑ i in s, f i • g (↑(σ ^ k) i)
[PROOFSTEP]
simp_rw [sum_smul_sum, product_self_eq_disjUnion_perm hσ, sum_disjiUnion, sum_map]
[GOAL]
ι : Type u_1
α : Type u_2
β : Type u_3
inst✝³ : DecidableEq α
inst✝² : Semiring α
inst✝¹ : AddCommMonoid β
inst✝ : Module α β
s : Finset ι
σ : Perm ι
hσ : IsCycleOn σ ↑s
f : ι → α
g : ι → β
⊢ ∑ x in range (card s),
∑ x_1 in s,
f
(↑{ toFun := fun i => (i, ↑(σ ^ x) i),
inj' :=
(_ :
∀ (i j : ι),
(fun i => (i, ↑(σ ^ x) i)) i = (fun i => (i, ↑(σ ^ x) i)) j →
((fun i => (i, ↑(σ ^ x) i)) i).fst = ((fun i => (i, ↑(σ ^ x) i)) j).fst) }
x_1).fst •
g
(↑{ toFun := fun i => (i, ↑(σ ^ x) i),
inj' :=
(_ :
∀ (i j : ι),
(fun i => (i, ↑(σ ^ x) i)) i = (fun i => (i, ↑(σ ^ x) i)) j →
((fun i => (i, ↑(σ ^ x) i)) i).fst = ((fun i => (i, ↑(σ ^ x) i)) j).fst) }
x_1).snd =
∑ x in range (card s), ∑ x_1 in s, f x_1 • g (↑(σ ^ x) x_1)
[PROOFSTEP]
rfl
|
(* TLC in Coq
*
* Module: tlc.component.perfect_link_3
* Purpose: Contains the local specification of the perfect link PL_3 property.
*)
Require Import mathcomp.ssreflect.eqtype.
Require Import mathcomp.ssreflect.seq.
Require Import mathcomp.ssreflect.ssrbool.
Require Import mathcomp.ssreflect.ssreflect.
Require Import mathcomp.ssreflect.ssrnat.
Require Import tlc.component.component.
Require Import tlc.component.perfect_link.
Require Import tlc.logic.all_logic.
Require Import tlc.semantics.all_semantics.
Require Import tlc.syntax.all_syntax.
Require Import tlc.utility.all_utility.
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
(* No forge
* If a node n delivers a message m with sender n', then m was previously sent
* to n by node n'.
*)
Theorem PL_3 Delta : Context Delta [::] ||- perfect_link, {-A
forall: forall: forall: (* n, n', m *)
$$2 \in UCorrect /\ $$1 \in UCorrect ->
on $$2, event[]<- CPLDeliver ' $$1 ' $$0 <~
on $$1, event[]-> CPLSend ' $$2 ' $$0
-}.
Proof.
dforall n; dforall n'; dforall m; dif; dsplitp.
(* By OI' *)
dhave {-A
on n, event[]<- CPLDeliver ' n' ' m <~
on n, CPLDeliver ' n' ' m \in Fois /\ self-event
-}.
{
duse DPOI'; dforallp n; dforallp {-t CPLDeliver ' n' ' m -}.
eapply DSCut; first (by repeat dclear; apply DTL123 with
(A := {-A self-event /\ on n, CPLDeliver ' n' ' m \in Fois -}));
dtsubstposp.
eapply DSCut; first (by repeat dclear; apply DTAndComm with
(A1 := {-A self-event -})
(A2 := {-A on n, CPLDeliver ' n' ' m \in Fois -}));
dtsubstp_l.
by eapply DSCut; first (by repeat dclear; apply DTAndAssoc with
(A1 := {-A Fn = n -})
(A2 := {-A CPLDeliver ' n' ' m \in Fois -})
(A3 := {-A self-event -}));
dtsubstp_l.
}
(* By InvL *)
dhave {-A
on n, CPLDeliver ' n' ' m \in Fois /\ self-event =>>
exists: (* c *) on n, event[0]<- CSLDeliver ' n' ' ($$0, m)
-}.
{
repeat dclear.
eapply DSCut; first by apply DPInvL with
(A := {-A
on n, CPLDeliver ' n' ' m \in Fois ->
exists: (* c *) on n, event[0]<- CSLDeliver ' n' ' ($$0, m)
-});
[by dautoclosed | by repeat constructor].
(* request *)
difp.
{
dforall e; dif; dsplitp; dswap; dsimplp.
dcase {-t ? e -}; dexistsp e_m; dexistsp e_n'; dtgenp;
dtsubstep_l; dswap; dclear; dsimplp.
dcase {-t ? Fs ' ? Fn -}; dexistsp s_r; dexistsp s_c; dtgenp;
dtsubstep_l; dswap; dclear; dsimplp.
dtinjectionp; repeat dsplitp; do 2 dclear.
dif; dsplitp; dclear; dswap.
by dtgenp; dtsubstep_l; dpmembernilp.
}
(* indication *)
difp.
{
dforall i; dforall e; dif; dsplitp; dswap; dsimplp.
dcase {-t (? i, ? e) -}; dexistsp e_m; dexistsp e_c; dexistsp e_n.
dtinjectionp; dsplitp; do 2 (dtgenp; dswap).
dxchg 1 2; dtsubstep_l; dsimplp.
dswap; dxchg 1 3; dtsubstep_l; dautoeq; dswap; dclear.
dswap; dtsubstep_l.
dswap; dxchg 1 2; dtsubstep_l; dsimplp; dswap; dclear.
dcase {-t ? Fs ' ? Fn -}; dexistsp s_r; dexistsp s_c; dtgenp;
dtsubstep_l; dswap; dclear; dsimplp.
dcase {-t FCount ' (? e_n, ? e_c) ' ? s_r == 0 -}; dorp; dtgenp;
dtsubstep_l; dswap; dclear; dsimplp;
dtinjectionp; repeat dsplitp;
do 2 dclear; dtgenp;
dif; dsplitp.
- dexists e_c; dsplit; first (by dassumption); dclear.
dswap; dtsubstep_l; dswap; dclear.
by dpmembersingletonp; dtinjectionp; repeat (dsplitp; dswap);
repeat (dtgenp; dtsubste_l; dautoeq; dclear).
- by dclear; dswap; dtsubstep_l; dpmembernilp.
}
(* periodic *)
difp.
{
dif; dsplitp; dswap; dsimplp.
dtinjectionp; repeat dsplitp; do 2 dclear.
dif; dsplitp; dclear.
by dswap; dtgenp; dtsubstep_l; dpmembernilp.
}
dtmergeentailsifp.
eapply DSCut; first (by repeat dclear; apply DTAndComm with
(A1 := {-A self-event -})
(A2 := {-A on n, CPLDeliver ' n' ' m \in Fois -}));
dtsubstp_l.
by eapply DSCut; first (by repeat dclear; apply DTAndAssoc with
(A1 := {-A Fn = n -})
(A2 := {-A CPLDeliver ' n' ' m \in Fois -})
(A3 := {-A self-event -}));
dtsubstp_l.
}
(* By lemma 99 on (1) and (2) *)
(* NOTE: Rewriting is easier. *)
dtsubstposp.
(* By rule OR' *)
dhave {-A
forall: (* c *)
on n', event[0]-> CSLSend ' n ' ($$0, m) <~
on n', (0, CSLSend ' n ' ($$0, m)) \in Fors /\ self-event
-}.
{
dforall c.
duse DPOR'; dforallp n'; dforallp {-t 0 -}; dforallp {-t CSLSend ' n ' (c, m) -}.
eapply DSCut; first (by repeat dclear; apply DTL123 with
(A := {-A self-event /\ on n', (0, CSLSend ' n ' (c, m)) \in Fors -}));
dtsubstposp.
eapply DSCut; first (by repeat dclear; apply DTAndComm with
(A1 := {-A self-event -})
(A2 := {-A on n', (0, CSLSend ' n ' (c, m)) \in Fors -}));
dtsubstp_l.
by eapply DSCut; first (by repeat dclear; apply DTAndAssoc with
(A1 := {-A Fn = n' -})
(A2 := {-A (0, CSLSend ' n ' (c, m)) \in Fors -})
(A3 := {-A self-event -}));
dtsubstp_l.
}
(* By rule InvL *)
dhave {-A
forall: (* c *)
on n', (0, CSLSend ' n ' ($$0, m)) \in Fors /\ self-event =>>
on n', event[]-> CPLSend ' n ' m
-}.
{
repeat dclear.
dforall c.
eapply DSCut; first by apply DPInvL with
(A := {-A
on n', (0, CSLSend ' n ' (c, m)) \in Fors ->
on n', event[]-> CPLSend ' n ' m
-});
[by dautoclosed | by repeat constructor].
(* request *)
difp.
{
dforall e; dif; dsplitp; dswap; dsimplp.
dcase {-t ? e -}; dexistsp e_m; dexistsp e_n'; dtgenp;
dtsubstep_l; dsimplp;
dswap; dxchg 1 2; dtsubstep_l; dswap; dclear; dswap.
dcase {-t ? Fs ' ? Fn -}; dexistsp s_r; dexistsp s_c; dtgenp;
dtsubstep_l; dswap; dclear; dsimplp.
dtinjectionp; repeat dsplitp; dclear; dswap; dclear.
dif; dsplitp; dsplit; first (by dassumption); dclear.
dswap; dtgenp; dtsubstep_l; dswap; dclear.
by dpmembersingletonp; dtinjectionp; repeat (dsplitp; dswap);
do 2 (dtgenp; dtsubste_l; dautoeq; dclear; dclear).
}
(* indication *)
difp.
{
dforall i; dforall e; dif; dsplitp; dswap; dsimplp.
dcase {-t (? i, ? e) -}; dexistsp e_m; dexistsp e_c; dexistsp e_n; dtgenp;
dtsubstep_l; dswap; dclear; dsimplp.
dcase {-t ? Fs ' ? Fn -}; dexistsp s_r; dexistsp s_c; dtgenp;
dtsubstep_l; dswap; dclear; dsimplp.
dcase {-t FCount ' (? e_n, ? e_c) ' ? s_r == 0 -}; dorp; dtgenp;
dtsubstep_l; dswap; dclear; dsimplp;
dtinjectionp; repeat dsplitp;
dclear; dswap; dclear; dtgenp; dtsubste_l; dclear;
dif; dsplitp; dclear;
by dpmembernilp.
}
(* periodic *)
difp.
{
dif; dsplitp; dswap; dsimplp.
dtinjectionp; repeat dsplitp; dclear; dswap; dclear.
dif; dsplitp; dclear.
by dswap; dtgenp; dtsubstep_l; dpmembernilp.
}
dtmergeentailsifp.
eapply DSCut; first (by repeat dclear; apply DTAndComm with
(A1 := {-A self-event -})
(A2 := {-A on n', (0, CSLSend ' n ' (c, m)) \in Fors -}));
dtsubstp_l.
by eapply DSCut; first (by repeat dclear; apply DTAndAssoc with
(A1 := {-A Fn = n' -})
(A2 := {-A (0, CSLSend ' n ' (c, m)) \in Fors -})
(A3 := {-A self-event -}));
dtsubstp_l.
}
(* By lemma 99 on (1) and (2) *)
(* NOTE: Rewriting is easier. *)
dtsubstposp.
(* By lemma 88 on (3), SL_2', and (6) *)
duse PL_SL_2.
dxchg 1 2; dtsubstposp.
dswap; dtsubstposp.
eapply DSCut; first (by repeat dclear; apply DTL83_1 with
(A := {-A on n', event[]-> CPLSend ' n ' m -}));
dtsubstp_r.
eapply DSCut; first (by repeat dclear; apply DTL127_3 with
(A := {-A on n', event[]-> CPLSend ' n ' m -}));
dtsubstp_r.
eapply DSCut; first (by repeat dclear; apply DTL83_1 with
(A := {-A exists: on n', event[]-> CPLSend ' n ' m -}));
dtsubstp_r.
by eapply DSCut; first (by repeat dclear; apply DTExistsConstant with
(A := {-A on n', event[]-> CPLSend ' n ' m -}); first by dautoclosed);
dtsubstp_r.
Qed.
|
theory Chapter5
imports Main
begin
theorem "\<exists>S. S \<notin> range (f :: 'a \<Rightarrow> 'a set)"
proof
let ?S = "{x. x \<notin> f x}"
show "?S \<notin> range f"
proof
assume "?S \<in> range f"
then obtain y where "?S = f y" ..
then show False
proof (rule equalityCE)
assume "y \<in> f y"
assume "y \<in> ?S"
then have "y \<notin> f y" ..
with \<open>y \<in> f y\<close> show ?thesis by contradiction
next
assume "y \<notin> ?S"
assume "y \<notin> f y"
then have "y \<in> ?S" ..
with \<open>y \<notin> ?S\<close> show ?thesis by contradiction
qed
qed
qed
(* sseefried: After much rewriting and searching online
(https://isabelle.in.tum.de/library/HOL/HOL-Isar_Examples/Cantor.html)
I've rewritten then proof so that it makes a whole lot more sense to me
*)
lemma "\<not> surj (f :: 'a \<Rightarrow> 'a set)"
proof
assume 0: "surj f"
from 0 have 1: "\<forall>A. \<exists>a. A = f a" by (simp add: surj_def)
from 1 have 2: "\<exists>a. { x. x \<notin> f x } = f a" by blast
then obtain a where "{x. x \<notin> f x } = f a" by blast
then show False
proof (rule equalityCE)
assume "a \<in> f a"
assume "a \<in> { x. x \<notin> f x }"
then have "a \<notin> f a" ..
with \<open>a \<in> f a\<close> show ?thesis by contradiction
next
assume "a \<notin> { x. x \<notin> f x }"
assume "a \<notin> f a"
then have "a \<in> { x. x \<notin> f x } " ..
with \<open>a \<notin> { x. x \<notin> f x }\<close> show ?thesis by contradiction
qed
qed
(* Using much shorthand *)
lemma
fixes f :: "'a \<Rightarrow> 'a set"
assumes s: "surj f"
shows "False"
proof -
have "\<exists> a. {x. x \<notin> f x} = f a" using s
by (auto simp: surj_def)
thus "False" by blast
qed
lemma
fixes a b :: int
assumes "b dvd (a + b)"
shows "b dvd a"
proof -
{ fix k
assume 1: "a + b = b*k"
have "\<exists>k'. a = b * k'"
proof
show "a = b*(k-1)" using 1 by (simp add: algebra_simps)
qed}
then show ?thesis using assms by (auto simp add: dvd_def)
qed
lemma "length (tl xs) = length xs - 1"
proof (cases xs)
case Nil
thus ?thesis by simp
next
case (Cons y ys)
thus ?thesis by simp
qed
lemma "\<Sum>{ 0..n::nat} = n*(n+1) div 2"
proof (induction n)
case 0
show ?case by simp
next
case (Suc n)
thus ?case by simp
qed
inductive ev :: "nat \<Rightarrow> bool" where
ev0: "ev 0"
| evSS: "ev n \<Longrightarrow> ev (Suc (Suc n))"
fun evn :: "nat \<Rightarrow> bool" where
"evn 0 = True"
| "evn (Suc 0) = False"
| "evn (Suc (Suc n)) = evn n"
lemma "ev n \<Longrightarrow> ev (n - 2)"
proof -
assume "ev n"
thus "ev (n - 2)"
proof cases
case ev0
thus "ev (n - 2)" by (simp add: ev.ev0)
next
case (evSS k)
thus "ev (n - 2)" by (simp add: ev.evSS)
qed
qed
lemma "ev n \<Longrightarrow> n = 0 \<or> (\<exists>k. n = Suc (Suc k) \<and> ev k)"
proof (induction n rule: ev.induct)
case ev0
thus ?case by blast
next
case evSS
thus ?case by blast
qed
end
|
section \<open> Design Healthiness Conditions \<close>
theory utp_des_healths
imports utp_des_core
utp_des_laws
begin
subsection \<open> H1: No observation is allowed before initiation \<close>
definition H1 :: "('\<alpha>, '\<beta>) des_rel \<Rightarrow> ('\<alpha>, '\<beta>) des_rel" where
[pred, rel]: "H1(P) = (ok\<^sup>< \<longrightarrow> P)"
expr_ctr H1
lemma H1_idem:
"H1 (H1 P) = H1(P)"
by (pred_auto)
lemma H1_monotone:
"P \<sqsubseteq> Q \<Longrightarrow> H1(P) \<sqsubseteq> H1(Q)"
by (pred_auto)
lemma H1_Continuous: "Continuous H1"
by (pred_auto)
lemma H1_below_top:
"H1(P) \<sqsubseteq> \<top>\<^sub>D"
by (pred_auto)
lemma H1_design_skip:
"H1(II) = II\<^sub>D"
by (pred_auto)
lemma H1_cond: "H1(P \<lhd> b \<rhd> Q) = H1(P) \<lhd> b \<rhd> H1(Q)"
by (pred_auto)
lemma H1_conj: "H1(P \<and> Q) = (H1(P) \<and> H1(Q))"
by (pred_auto)
lemma H1_disj: "H1(P \<or> Q) = (H1(P) \<or> H1(Q))"
by (pred_auto)
lemma design_export_H1: "(P \<turnstile> Q) = (P \<turnstile> H1(Q))"
by (pred_auto)
text \<open> The H1 algebraic laws are valid only when $\alpha(R)$ is homogeneous. This should maybe be
generalised. \<close>
theorem H1_algebraic_intro:
assumes
"(true\<^sub>h ;; R) = true\<^sub>h"
"(II\<^sub>D ;; R) = R"
shows "R is H1"
proof -
have "R = (II\<^sub>D ;; R)" by (simp add: assms(2))
also have "... = (H1(II) ;; R)"
by (simp add: H1_design_skip)
also have "... = ((ok\<^sup>< \<longrightarrow> II) ;; R)"
by (simp add: H1_def)
also have "... = (((\<not> ok\<^sup><) ;; R) \<or> R)"
by (pred_auto)
also have "... = ((((\<not> ok\<^sup><) ;; true\<^sub>h) ;; R) \<or> R)"
by (pred_auto)
also have "... = (((\<not> (ok\<^sup><)) ;; true\<^sub>h) \<or> R)"
by (metis assms(1) seqr_assoc)
also have "... = (ok\<^sup>< \<longrightarrow> R)"
by (pred_auto)
finally show ?thesis by (metis H1_def Healthy_def')
qed
lemma nok_not_false:
"(\<not> ok\<^sup><) \<noteq> false"
by (pred_auto)
theorem H1_left_zero:
assumes "P is H1"
shows "(true ;; P) = true"
proof -
from assms have "(true ;; P) = true ;; (ok\<^sup>< \<longrightarrow> P)"
by (simp add: H1_def Healthy_def')
(* The next step ensures we get the right alphabet for true by copying it *)
also from assms have "... = (true ;; ((\<not> ok\<^sup><) \<or> P))" (is "_ = (?true ;; _)")
by (pred_auto; blast)
also from assms have "... = ((?true ;; (\<not> ok\<^sup><)) \<or> (?true ;; P))"
by pred_auto
also from assms have "... = (true \<or> (true ;; P))"
by pred_auto
finally show ?thesis
by pred_auto
qed
theorem H1_left_unit:
fixes P :: "('\<alpha>, '\<beta>) des_rel"
assumes "P is H1"
shows "(II\<^sub>D ;; P) = P"
proof -
have "(II\<^sub>D ;; P) = ((ok\<^sup>< \<longrightarrow> II) ;; P)"
by (metis H1_def H1_design_skip)
also have "... = (((\<not> ok\<^sup><) ;; P) \<or> P)"
by (pred_auto)
also from assms have "... = ((((\<not> ok\<^sup><) ;; true\<^sub>h) ;; P) \<or> P)"
by (pred_auto)
also have "... = (((\<not> ok\<^sup><) ;; (true\<^sub>h ;; P)) \<or> P)"
by (simp add: seqr_assoc)
also from assms have "... = ((ok\<^sup><) \<longrightarrow> P)"
proof -
have "((\<not> (ok\<^sup><)) ;; (true\<^sub>h ;; P)) = ((\<not> (ok\<^sup><)) ;; true\<^sub>h)"
using assms
by (simp add: H1_left_zero, pred_auto)
also have "... = (\<not> (ok\<^sup><))"
by pred_auto
finally show ?thesis
by pred_auto
qed
finally show ?thesis using assms
by (simp add: H1_def Healthy_def')
qed
theorem H1_algebraic:
"P is H1 \<longleftrightarrow> (true\<^sub>h ;; P) = true\<^sub>h \<and> (II\<^sub>D ;; P) = P"
using H1_algebraic_intro H1_left_unit H1_left_zero by metis
theorem H1_nok_left_zero:
fixes P :: "'\<alpha> des_hrel"
assumes "P is H1"
shows "((\<not> ok\<^sup><) ;; P) = (\<not> ok\<^sup><)"
proof -
have "((\<not> ok\<^sup><) ;; P) = (((\<not> ok\<^sup><) ;; true\<^sub>h) ;; P)"
by pred_auto
also have "... = ((\<not> ok\<^sup><) ;; true\<^sub>h)"
by (metis H1_left_zero assms seqr_assoc)
also have "... = (\<not> (ok\<^sup><))"
by pred_auto
finally show ?thesis .
qed
lemma H1_design:
"H1(P \<turnstile> Q) = (P \<turnstile> Q)"
by (pred_auto)
lemma H1_rdesign:
"H1(P \<turnstile>\<^sub>r Q) = (P \<turnstile>\<^sub>r Q)"
by (pred_auto)
lemma H1_choice_closed [closure]:
"\<lbrakk> P is H1; Q is H1 \<rbrakk> \<Longrightarrow> P \<sqinter> Q is H1"
by (metis H1_disj Healthy_if Healthy_intro disj_pred_def)
lemma H1_inf_closed [closure]:
"\<lbrakk> P is H1; Q is H1 \<rbrakk> \<Longrightarrow> P \<squnion> Q is H1"
by (metis H1_conj Healthy_def' conj_pred_def)
lemma H1_UINF:
assumes "A \<noteq> {}"
shows "H1(\<Sqinter> i \<in> A. P(i)) = (\<Sqinter> i \<in> A. H1(P(i)))"
using assms by (pred_auto)
lemma H1_Sup:
assumes "A \<noteq> {}" "\<forall> P \<in> A. P is H1"
shows "(\<Sqinter> A) is H1"
proof -
from assms(2) have "H1 ` A = A"
by (auto simp add: Healthy_def rev_image_eqI)
with H1_UINF[of A id, OF assms(1)] show ?thesis
by (simp add: Healthy_def)
qed
lemma H1_USUP:
shows "H1(\<Squnion> i \<in> A. P(i)) = (\<Squnion> i \<in> A. H1(P(i)))"
by (pred_auto)
lemma H1_Inf [closure]:
assumes "\<forall> P \<in> A. P is H1"
shows "(\<Squnion> A) is H1"
proof -
from assms have "H1 ` A = A"
by (auto simp add: Healthy_def rev_image_eqI)
then show ?thesis
apply (simp add: Healthy_def)
by (metis H1_USUP image_image)
qed
(*
lemma msubst_H1: "(\<And>x. P x is H1) \<Longrightarrow> P x\<lbrakk>x\<rightarrow>v\<rbrakk> is H1"
by (rel_auto)
*)
subsection \<open> H2: A specification cannot require non-termination \<close>
definition J :: "'\<alpha> des_hrel" where
[pred]: "J = ((ok\<^sup>< \<longrightarrow> ok\<^sup>>) \<and> II \<up> more\<^sub>L\<^sup>2)\<^sub>e"
definition H2 where
[pred]: "H2 (P) \<equiv> P ;; J"
expr_ctr H2
lemma J_split:
shows "(P ;; J) = (P\<^sup>f \<or> (P\<^sup>t \<and> ok\<^sup>>))"
proof -
have "(P ;; J) = (P ;; ((ok\<^sup>< \<longrightarrow> ok\<^sup>>) \<and> II \<up> more\<^sub>L\<^sup>2))\<^sub>e"
by (simp add: H2_def J_def design_def, pred_auto)
also have "... = (P ;; ((ok\<^sup>< \<longrightarrow> (ok\<^sup>< \<and> ok\<^sup>>)) \<and> II \<up> more\<^sub>L\<^sup>2))\<^sub>e"
by (pred_auto)
also have "... = ((P ;; (\<not> ok\<^sup>< \<and> II \<up> more\<^sub>L\<^sup>2)) \<or> (P ;; (ok\<^sup>< \<and> (II \<up> more\<^sub>L\<^sup>2 \<and> ok\<^sup>>))))"
by (pred_auto)
also have "... = (P\<^sup>f \<or> (P\<^sup>t \<and> ok\<^sup>>))"
proof -
have "(P ;; (\<not> ok\<^sup>< \<and> II \<up> more\<^sub>L\<^sup>2)) = P\<^sup>f"
proof -
have "(P ;; (\<not> ok\<^sup>< \<and> II \<up> more\<^sub>L\<^sup>2)) = ((P \<and> \<not> ok\<^sup>>) ;; II \<up> more\<^sub>L\<^sup>2)"
by (pred_auto)
also have "... = (\<exists>ok\<^sup>> \<Zspot> (P \<and> ok\<^sup>> = False)\<^sub>e)"
by pred_auto
also have "... = P\<^sup>f"
by pred_auto
finally show ?thesis .
qed
moreover have "(P ;; (ok\<^sup>< \<and> (II \<up> more\<^sub>L\<^sup>2 \<and> ok\<^sup>>))) = (P\<^sup>t \<and> ok\<^sup>>)"
proof -
have "(P ;; (ok\<^sup>< \<and> (II \<up> more\<^sub>L\<^sup>2 \<and> ok\<^sup>>))) = (P ;; (ok\<^sup>< \<and> II))"
by (pred_auto)
also have "... = (P\<^sup>t \<and> ok\<^sup>>)"
by (pred_auto)
finally show ?thesis .
qed
ultimately show ?thesis
by simp
qed
finally show ?thesis .
qed
lemma H2_split:
shows "H2(P) = (P\<^sup>f \<or> (P\<^sup>t \<and> ok\<^sup>>))"
by (simp add: H2_def J_split)
theorem H2_equivalence:
"P is H2 \<longleftrightarrow> `(P\<^sup>f \<longrightarrow> P\<^sup>t)`"
by (pred_auto, (metis (full_types))+)
(*
proof -
have "(P = (P ;; J)) \<longleftrightarrow> (P = (P\<^sup>f \<or> (P\<^sup>t \<and> ok\<^sup>>)))"
by (simp add: J_split)
also have "... \<longleftrightarrow> `\<lbrakk>(P \<longleftrightarrow> P\<^sup>f \<or> P\<^sup>t \<and> (ok\<^sup>>)\<^sub>e)\<^sup>f \<and> (P \<longleftrightarrow> P\<^sup>f \<or> P\<^sup>t \<and> (ok\<^sup>>)\<^sub>e)\<rbrakk>\<^sub>P`"
by rel_auto
also have "... = `\<lbrakk>(P\<^sup>f \<longleftrightarrow> P\<^sup>f) \<and> (P\<^sup>t \<longleftrightarrow> P\<^sup>f \<or> P\<^sup>t)\<rbrakk>\<^sub>P`"
apply pred_auto
by metis+
also have "... = `\<lbrakk>P\<^sup>t \<longleftrightarrow> (P\<^sup>f \<or> P\<^sup>t)\<rbrakk>\<^sub>P`"
by (pred_auto)
also have "... = `P\<^sup>f \<longrightarrow> P\<^sup>t`"
by (pred_auto)
finally show ?thesis
using H2_def Healthy_def'
by (metis (no_types, lifting) SEXP_def conj_refine_left iff_pred_def pred_ba.boolean_algebra.conj_one_right pred_ba.inf_le2 pred_ba.sup.absorb2 pred_ba.sup.orderE pred_impl_laws(5) pred_set rel_eq_iff taut_def true_false_pred_expr(1))
qed
*)
lemma H2_equiv:
"P is H2 \<longleftrightarrow> P\<^sup>t \<sqsubseteq> P\<^sup>f"
by (simp add: H2_equivalence pred_refine_iff, expr_simp)
lemma H2_design:
assumes "$ok\<^sup>> \<sharp> P" "$ok\<^sup>> \<sharp> Q"
shows "H2(P \<turnstile> Q) = P \<turnstile> Q"
using assms
by (simp add: H2_split design_def usubst unrest, pred_auto)
lemma H2_rdesign:
"H2(P \<turnstile>\<^sub>r Q) = P \<turnstile>\<^sub>r Q"
by (simp add: H2_design unrest rdesign_def)
theorem J_idem:
"(J ;; J) = J"
by (pred_auto)
theorem H2_idem:
"H2(H2(P)) = H2(P)"
by (metis H2_def J_idem seqr_assoc)
(*
theorem H2_Continuous: "Continuous H2"
by (rel_auto)
*)
theorem H2_not_okay: "H2 (\<not>ok\<^sup><) = (\<not>ok\<^sup><)"
proof -
have "H2 (\<not>ok\<^sup><) = ((\<not>ok\<^sup><)\<^sup>f \<or> ((\<not>ok\<^sup><)\<^sup>t \<and> ok\<^sup>>))"
by (simp add: H2_split)
also have "... = (\<not> ok\<^sup>< \<or> (\<not>ok\<^sup><) \<and> ok\<^sup>>)"
by (pred_auto)
also have "... = (\<not> ok\<^sup><)"
by (pred_auto)
finally show ?thesis .
qed
lemma H2_true: "H2(true) = true"
by (pred_auto)
lemma H2_choice_closed [closure]:
"\<lbrakk> P is H2; Q is H2 \<rbrakk> \<Longrightarrow> P \<sqinter> Q is H2"
by (metis H2_def Healthy_def' disj_pred_def seqr_or_distl)
lemma H2_inf_closed [closure]:
assumes "P is H2" "Q is H2"
shows "P \<squnion> Q is H2"
proof -
have "P \<squnion> Q = (P\<^sup>f \<or> P\<^sup>t \<and> ok\<^sup>>) \<squnion> (Q\<^sup>f \<or> Q\<^sup>t \<and> ok\<^sup>>)"
by (metis H2_def Healthy_def J_split assms(1) assms(2))
moreover have "H2(...) = ..."
by (simp add: H2_split usubst, pred_auto)
ultimately show ?thesis
by (simp add: Healthy_def)
qed
lemma H2_USUP:
shows "H2(\<Sqinter> i \<in> A. P(i)) = (\<Sqinter> i \<in> A. H2(P(i)))"
by (pred_auto)
theorem H1_H2_commute:
"H1 (H2 P) = H2 (H1 P)"
proof -
have "H2 (H1 P) = ((ok\<^sup>< \<longrightarrow> P) ;; J)"
by (simp add: H1_def H2_def)
also have "... = ((\<not> ok\<^sup>< \<or> P) ;; J)"
by (pred_auto)
also have "... = (((\<not> ok\<^sup><) ;; J) \<or> (P ;; J))"
by (pred_auto)
also have "... = ((H2 (\<not> ok\<^sup><)) \<or> H2(P))"
by (simp add: H2_def)
also have "... = ((\<not> ok\<^sup><) \<or> H2(P))"
by (pred_auto)
also have "... = H1(H2(P))"
by (pred_auto)
finally show ?thesis by simp
qed
subsection \<open> Designs as $H1$-$H2$ predicates \<close>
abbreviation H1_H2 :: "('\<alpha>, '\<beta>) des_rel \<Rightarrow> ('\<alpha>, '\<beta>) des_rel" ("\<^bold>H") where
"H1_H2 P \<equiv> H1 (H2 P)"
lemma H1_H2_comp: "\<^bold>H = H1 \<circ> H2"
by (auto)
theorem H1_H2_eq_design:
"\<^bold>H(P) = (\<not> P\<^sup>f) \<turnstile> P\<^sup>t"
proof -
have "\<^bold>H(P) = (ok\<^sup>< \<longrightarrow> H2(P))"
by (simp add: H1_def)
also have "... = (ok\<^sup>< \<longrightarrow> (P\<^sup>f \<or> (P\<^sup>t \<and> ok\<^sup>>)))\<^sub>e"
by (simp add:H2_split, pred_auto)
also have "... = (ok\<^sup>< \<and> (\<not> P\<^sup>f) \<longrightarrow> ok\<^sup>> \<and> ok\<^sup>< \<and> P\<^sup>t)\<^sub>e"
by (pred_auto)
also have "... = (\<not> P\<^sup>f) \<turnstile> P\<^sup>t"
by (pred_auto)
finally show ?thesis .
qed
theorem H1_H2_is_design:
assumes "P is H1" "P is H2"
shows "P = (\<not> P\<^sup>f) \<turnstile> P\<^sup>t"
using assms by (metis H1_H2_eq_design Healthy_def)
(*
lemma aext_arestr' [alpha]:
fixes P :: "'a \<leftrightarrow> 'b"
assumes "$a \<sharp> P"
shows "(P \<down> a) \<up> a = P"
apply rel_auto
by (rel_simp, metis assms lens_override_def)
*)
theorem H1_H2_eq_rdesign:
"\<^bold>H(P) = pre\<^sub>D(P) \<turnstile>\<^sub>r post\<^sub>D(P)"
proof -
have "\<^bold>H(P) = (ok\<^sup>< \<longrightarrow> H2(P))"
by (simp add: H1_def Healthy_def')
also have "... = (ok\<^sup>< \<longrightarrow> (P\<^sup>f \<or> (P\<^sup>t \<and> ok\<^sup>>)))"
by (simp add: H2_split)
also have "... = (ok\<^sup>< \<and> (\<not> P\<^sup>f) \<longrightarrow> ok\<^sup>> \<and> P\<^sup>t)"
by (pred_auto)
also have "... = (ok\<^sup>< \<and> (\<not> P\<^sup>f) \<longrightarrow> ok\<^sup>> \<and> ok\<^sup>< \<and> P\<^sup>t)"
by (pred_auto)
also have "... = ((ok\<^sup>< \<and> (pre\<^sub>D(P) \<up> more\<^sub>L\<^sup>2)) \<longrightarrow> ok\<^sup>> \<and> ok\<^sup>< \<and> (post\<^sub>D(P) \<up> more\<^sub>L\<^sup>2))"
by (simp add: ok_post ok_pre )
also have "... = (ok\<^sup>< \<and> (pre\<^sub>D(P) \<up> more\<^sub>L\<^sup>2) \<longrightarrow> ok\<^sup>> \<and> (post\<^sub>D(P)\<up> more\<^sub>L\<^sup>2))\<^sub>e"
by (pred_auto)
also have "... = pre\<^sub>D(P) \<turnstile>\<^sub>r post\<^sub>D(P)"
by (simp add: rdesign_def design_def)
finally show ?thesis .
qed
theorem H1_H2_is_rdesign:
assumes "P is H1" "P is H2"
shows "P = pre\<^sub>D(P) \<turnstile>\<^sub>r post\<^sub>D(P)"
by (metis H1_H2_eq_rdesign Healthy_def assms(1) assms(2))
thm H1_H2_eq_rdesign
thm rdesign_refinement
lemma H1_H2_refinement:
assumes "P is \<^bold>H" "Q is \<^bold>H"
shows "P \<sqsubseteq> Q \<longleftrightarrow> (`pre\<^sub>D(P) \<longrightarrow> pre\<^sub>D(Q)` \<and> `pre\<^sub>D(P) \<and> post\<^sub>D(Q) \<longrightarrow> post\<^sub>D(P)`)"
using assms
apply (simp only:rdesign_refinement[symmetric])
by (metis H1_H2_eq_rdesign Healthy_if)
lemma H1_H2_refines:
assumes "P is \<^bold>H" "Q is \<^bold>H" "P \<sqsubseteq> Q"
shows "pre\<^sub>D(Q) \<sqsubseteq> pre\<^sub>D(P)" "post\<^sub>D(P) \<sqsubseteq> (pre\<^sub>D(P) \<and> post\<^sub>D(Q))"
apply (metis assms(3) conj_pred_def design_pre_choice ref_lattice.inf.absorb_iff2 ref_lattice.le_iff_sup)
apply (metis assms(3) design_post_choice pred_ba.inf_le2 pred_ba.le_supI1 ref_lattice.inf.absorb_iff2)
done
lemma H1_H2_idempotent: "\<^bold>H (\<^bold>H P) = \<^bold>H P"
by (simp add: H1_H2_commute H1_idem H2_idem)
lemma H1_H2_Idempotent [closure]: "Idempotent \<^bold>H"
by (simp add: Idempotent_def H1_H2_idempotent)
(*
lemma H1_H2_monotonic [closure]: "Monotone \<^bold>H"
by (simp add: H1_monotone H2_def mono_def seqr_mono)
lemma H1_H2_Continuous [closure]: "Continuous \<^bold>H"
by (simp add: Continuous_comp H1_Continuous H1_H2_comp H2_Continuous)
*)
lemma H1_H2_false: "\<^bold>H false = \<top>\<^sub>D"
by (pred_auto)
lemma H1_H2_true: "\<^bold>H true = \<bottom>\<^sub>D"
by (pred_auto)
lemma design_is_H1_H2 [closure]:
"\<lbrakk> $ok\<^sup>> \<sharp> P; $ok\<^sup>> \<sharp> Q \<rbrakk> \<Longrightarrow> (P \<turnstile> Q) is \<^bold>H"
by (simp add: H1_design H2_design Healthy_def')
lemma rdesign_is_H1_H2 [closure]:
"(P \<turnstile>\<^sub>r Q) is \<^bold>H"
by (simp add: Healthy_def H1_rdesign H2_rdesign)
lemma top_d_is_H1_H2 [closure]: "\<top>\<^sub>D is \<^bold>H"
by (simp add: rdesign_is_H1_H2 top_d_ndes_def)
lemma bot_d_is_H1_H2 [closure]: "\<bottom>\<^sub>D is \<^bold>H"
by (metis bot_d_true rdesign_is_H1_H2 true_is_rdesign)
lemma seq_r_H1_H2_closed [closure]:
assumes "P is \<^bold>H" "Q is \<^bold>H"
shows "(P ;; Q) is \<^bold>H"
proof -
obtain P\<^sub>1 P\<^sub>2 where "P = P\<^sub>1 \<turnstile>\<^sub>r P\<^sub>2"
by (metis H1_H2_commute H1_H2_is_rdesign H2_idem Healthy_def assms(1))
moreover obtain Q\<^sub>1 Q\<^sub>2 where "Q = Q\<^sub>1 \<turnstile>\<^sub>r Q\<^sub>2"
by (metis H1_H2_commute H1_H2_is_rdesign H2_idem Healthy_def assms(2))
moreover have "((P\<^sub>1 \<turnstile>\<^sub>r P\<^sub>2) ;; (Q\<^sub>1 \<turnstile>\<^sub>r Q\<^sub>2)) is \<^bold>H"
by (simp add: rdesign_composition rdesign_is_H1_H2)
ultimately show ?thesis by simp
qed
lemma H1_H2_left_unit: "P is \<^bold>H \<Longrightarrow> II\<^sub>D ;; P = P"
by (metis H1_H2_eq_rdesign Healthy_def' rdesign_left_unit)
thm design_is_H1_H2
lemma UINF_H1_H2_closed [closure]:
assumes "A \<noteq> {}" "\<forall> P \<in> A. P is \<^bold>H"
shows "(\<Sqinter> A) is H1_H2"
proof -
from assms have A: "A = H1_H2 ` A"
by (auto simp add: Healthy_def rev_image_eqI)
then have "\<Sqinter> (...) = (\<Sqinter> P \<in> A. (\<not> P\<^sup>f) \<turnstile> P\<^sup>t)"
by (simp add:H1_H2_eq_design)
also have "... = (\<Squnion> P \<in> A. \<not> P\<^sup>f) \<turnstile> (\<Sqinter> P \<in> A. P\<^sup>t)"
by (simp add: design_UINF_mem assms)
also have "... is H1_H2"
proof -
have "$ok\<^sup>> \<sharp> (\<Squnion>P\<in>A. \<not> P\<lbrakk>False/ok\<^sup>>\<rbrakk>)"
"$ok\<^sup>> \<sharp> (\<Sqinter>P \<in> A. P\<^sup>t)"
by (pred_auto)+
then show ?thesis
by (simp add: design_is_H1_H2)
qed
ultimately show ?thesis using A by auto
qed
definition design_inf :: "('\<alpha>, '\<beta>) des_rel set \<Rightarrow> ('\<alpha>, '\<beta>) des_rel" ("\<Sqinter>\<^sub>D_" [900] 900) where
"\<Sqinter>\<^sub>D A = (if (A = {}) then \<top>\<^sub>D else \<Sqinter> A)"
abbreviation design_sup :: "('\<alpha>, '\<beta>) des_rel set \<Rightarrow> ('\<alpha>, '\<beta>) des_rel" ("\<Squnion>\<^sub>D_" [900] 900) where
"\<Squnion>\<^sub>D A \<equiv> \<Squnion> A"
lemma design_inf_H1_H2_closed:
assumes "\<forall> P \<in> A. P is \<^bold>H"
shows "(\<Sqinter>\<^sub>D A) is \<^bold>H"
using assms
by (auto simp add: design_inf_def closure)
lemma design_sup_empty [simp]: "\<Sqinter>\<^sub>D {} = \<top>\<^sub>D"
by (simp add: design_inf_def)
lemma design_sup_non_empty [simp]: "A \<noteq> {} \<Longrightarrow> \<Sqinter>\<^sub>D A = \<Sqinter> A"
by (simp add: design_inf_def)
thm design_is_H1_H2
lemma USUP_mem_H1_H2_closed:
assumes "\<And> i. i \<in> A \<Longrightarrow> P i is \<^bold>H"
shows "(\<Squnion> i\<in>A. P i) is \<^bold>H"
proof -
from assms have "(\<Squnion> i\<in>A. P i) = (\<Squnion> i\<in>A. \<^bold>H(P i))"
by (simp add:Healthy_def)
also have "... = (\<Squnion> i\<in>A. (\<not> (P i)\<^sup>f) \<turnstile> (P i)\<^sup>t)"
by (simp add:H1_H2_eq_design)
also have "... = (\<Sqinter> i\<in>A. \<not> (P i)\<^sup>f) \<turnstile> (\<Squnion> i\<in>A. (\<not> (@(P i))\<^sup>f \<longrightarrow> (@(P i))\<^sup>t)\<^sub>e)"
by (simp add: design_USUP_mem, pred_auto)
also have "... is \<^bold>H"
proof -
have "$ok\<^sup>> \<sharp> (\<Sqinter> i\<in>A. \<not> (P i)\<^sup>f)"
"$ok\<^sup>> \<sharp> (\<Squnion> i\<in>A. (\<not> (@(P i))\<^sup>f \<longrightarrow> (@(P i))\<^sup>t)\<^sub>e)"
by pred_auto+
then show ?thesis
using design_is_H1_H2 by blast
qed
ultimately show ?thesis by auto
qed
lemma USUP_ind_H1_H2_closed:
assumes "\<And> i. P i is \<^bold>H"
shows "(\<Squnion> i. P i) is \<^bold>H"
using assms USUP_mem_H1_H2_closed[of UNIV P] by simp
lemma Inf_H1_H2_closed:
assumes "\<forall> P \<in> A. P is \<^bold>H"
shows "(\<Squnion> A) is \<^bold>H"
proof -
from assms have A: "A = \<^bold>H ` A"
by (auto simp add: Healthy_def rev_image_eqI)
also have "(\<Squnion> ...) = (\<Squnion> P \<in> A. \<^bold>H(P))"
by auto
also have B: "... = (\<Squnion> P \<in> A. (\<not> P\<^sup>f) \<turnstile> P\<^sup>t)"
by (simp add:H1_H2_eq_design)
then have C: "... = (\<Sqinter> P \<in> A. \<not> P\<^sup>f) \<turnstile> (\<Squnion> P \<in> A. (\<not> P\<^sup>f \<longrightarrow> P\<^sup>t)\<^sub>e)"
by (simp add: design_USUP_mem, pred_auto)
then have "... is \<^bold>H"
proof -
have "$ok\<^sup>> \<sharp> (\<Sqinter>P\<in>A. \<not> P\<lbrakk>False/ok\<^sup>>\<rbrakk>)"
"$ok\<^sup>> \<sharp> \<Squnion>\<^sub>D((\<lambda>P. (\<not> P\<lbrakk>False/ok\<^sup>>\<rbrakk> \<longrightarrow> P\<lbrakk>True/ok\<^sup>>\<rbrakk>)\<^sub>e) ` A)"
by (pred_auto)+
then show ?thesis
using design_is_H1_H2 by auto
qed
ultimately show ?thesis using A B C by auto
qed
lemma rdesign_ref_monos:
assumes "P is \<^bold>H" "Q is \<^bold>H" "P \<sqsubseteq> Q"
shows "pre\<^sub>D(Q) \<sqsubseteq> pre\<^sub>D(P)" "post\<^sub>D(P) \<sqsubseteq> (pre\<^sub>D(P) \<and> post\<^sub>D(Q))"
proof -
have r: "P \<sqsubseteq> Q \<longleftrightarrow> (`pre\<^sub>D(P) \<longrightarrow> pre\<^sub>D(Q)` \<and> `pre\<^sub>D(P) \<and> post\<^sub>D(Q) \<longrightarrow> post\<^sub>D(P)`)"
using assms(3) design_refine_thms(1) design_refine_thms(2) by blast
from r assms show "pre\<^sub>D(Q) \<sqsubseteq> pre\<^sub>D(P)"
using H1_H2_refines(1) by blast
from r assms show "post\<^sub>D(P) \<sqsubseteq> (pre\<^sub>D(P) \<and> post\<^sub>D(Q))"
using H1_H2_refines(2) by blast
qed
subsection \<open> H3: The design assumption is a precondition \<close>
definition H3 :: "('\<alpha>, '\<beta>) des_rel \<Rightarrow> ('\<alpha>, '\<beta>) des_rel" where
[pred]: "H3 (P) \<equiv> P ;; II\<^sub>D"
theorem H3_idem:
"H3(H3(P)) = H3(P)"
by (metis H3_def design_skip_idem seqr_assoc)
theorem H3_mono:
"P \<sqsubseteq> Q \<Longrightarrow> H3(P) \<sqsubseteq> H3(Q)"
by (simp add: H3_def seqr_mono)
(*
theorem H3_Monotonic:
"Monotonic H3"
by (simp add: H3_mono mono_def)
theorem H3_Continuous: "Continuous H3"
by (rel_auto)
*)
theorem design_condition_is_H3:
assumes "out\<alpha> \<sharp> p"
shows "(p \<turnstile> Q) is H3"
proof -
have "((p \<turnstile> Q) ;; II\<^sub>D) = (\<not> ((\<not> p) ;; true)) \<turnstile> (Q\<^sup>t ;; II\<lbrakk>True/ok\<^sup><\<rbrakk>)"
by (simp add: skip_d_alt_def design_composition_subst unrest assms)
also have "... = p \<turnstile> (Q\<^sup>t ;; II\<lbrakk>True/ok\<^sup><\<rbrakk>)"
using assms precond_equiv seqr_true_lemma
by metis
also have "... = p \<turnstile> Q"
by (pred_auto)
finally show ?thesis
by (simp add: H3_def Healthy_def')
qed
theorem rdesign_H3_iff_pre:
"P \<turnstile>\<^sub>r Q is H3 \<longleftrightarrow> P = (P ;; true)"
proof -
have "(P \<turnstile>\<^sub>r Q) ;; II\<^sub>D = (P \<turnstile>\<^sub>r Q) ;; (true \<turnstile>\<^sub>r II)"
by (simp add: skip_d_def)
also have "... = (\<not> ((\<not> P) ;; true) \<and> \<not> (Q ;; (\<not> true))) \<turnstile>\<^sub>r (Q ;; II)"
by (simp add: rdesign_composition)
also have "... = (\<not> ((\<not> P) ;; true) \<and> \<not> (Q ;; (\<not> true))) \<turnstile>\<^sub>r Q"
by (pred_auto)
also have "... = (\<not> ((\<not> P) ;; true)) \<turnstile>\<^sub>r Q"
by (pred_auto)
finally have "P \<turnstile>\<^sub>r Q is H3 \<longleftrightarrow> P \<turnstile>\<^sub>r Q = (\<not> ((\<not> P) ;; true)) \<turnstile>\<^sub>r Q"
by (metis H3_def Healthy_def')
also have "... \<longleftrightarrow> P = (\<not> ((\<not> P) ;; true))"
by (metis rdesign_pre)
also have "... \<longleftrightarrow> P = (P ;; true)"
by (simp add: seqr_true_lemma)
finally show ?thesis .
qed
theorem design_H3_iff_pre:
assumes "$ok\<^sup>< \<sharp> P" "$ok\<^sup>> \<sharp> P" "$ok\<^sup>< \<sharp> Q" "$ok\<^sup>> \<sharp> Q"
shows "P \<turnstile> Q is H3 \<longleftrightarrow> P = (P ;; true)"
proof -
have "P \<turnstile> Q = (P \<down> more\<^sub>L\<^sup>2) \<turnstile>\<^sub>r (Q \<down> more\<^sub>L\<^sup>2)"
by (simp add: assms rdesign_def lift_desr_inv)
moreover hence "(P \<down> more\<^sub>L\<^sup>2) \<turnstile>\<^sub>r (Q \<down> more\<^sub>L\<^sup>2) is H3 \<longleftrightarrow> (P \<down> more\<^sub>L\<^sup>2) = ((P \<down> more\<^sub>L\<^sup>2) ;; true)"
using rdesign_H3_iff_pre by blast
ultimately show ?thesis
by (metis assms(1,2) design_condition_is_H3 lift_desr_inv unrest_out_des_lift utp_rel_laws.precond_equiv)
qed
theorem H1_H3_commute:
"H1 (H3 P) = H3 (H1 P)"
by (pred_auto)
lemma skip_d_absorb_J_1:
"(II\<^sub>D ;; J) = II\<^sub>D"
by (metis H2_def H2_rdesign skip_d_def)
lemma skip_d_absorb_J_2:
"(J ;; II\<^sub>D) = II\<^sub>D"
proof -
have "(J ;; II\<^sub>D) = ((ok\<^sup>< \<longrightarrow> ok\<^sup>>) \<and> II \<up> more\<^sub>L\<^sup>2)\<^sub>e ;; (true \<turnstile> II)"
by (simp add: J_def skip_d_alt_def)
also have "... = ((((ok\<^sup>< \<longrightarrow> ok\<^sup>>)\<^sub>e \<and> II \<up> more\<^sub>L\<^sup>2)\<lbrakk>False/ok\<^sup>>\<rbrakk> ;; (true \<turnstile> II)\<lbrakk>False/ok\<^sup><\<rbrakk>)
\<or> (((ok\<^sup>< \<longrightarrow> ok\<^sup>>)\<^sub>e \<and> II \<up> more\<^sub>L\<^sup>2)\<lbrakk>True/ok\<^sup>>\<rbrakk> ;; (true \<turnstile> II)\<lbrakk>True/ok\<^sup><\<rbrakk>))"
by (pred_auto)
also have "... = ((\<not>ok\<^sup>< \<and> II \<up> more\<^sub>L\<^sup>2 ;; true) \<or> (II \<up> more\<^sub>L\<^sup>2 ;; ok\<^sup>> \<and> II \<up> more\<^sub>L\<^sup>2))"
by (pred_auto)
also have "... = II\<^sub>D"
by (pred_auto)
finally show ?thesis .
qed
lemma H2_H3_absorb:
"H2 (H3 P) = H3 P"
by (metis H2_def H3_def seqr_assoc skip_d_absorb_J_1)
lemma H3_H2_absorb:
"H3 (H2 P) = H3 P"
by (metis H2_def H3_def seqr_assoc skip_d_absorb_J_2)
theorem H2_H3_commute:
"H2 (H3 P) = H3 (H2 P)"
by (simp add: H2_H3_absorb H3_H2_absorb)
theorem H3_design_pre:
assumes "$ok\<^sup>< \<sharp> p" "out\<alpha> \<sharp> p" "$ok\<^sup>< \<sharp> Q" "$ok\<^sup>> \<sharp> Q"
shows "H3(p \<turnstile> Q) = p \<turnstile> Q"
using assms
using Healthy_def design_condition_is_H3 by auto
theorem H3_rdesign_pre:
assumes "out\<alpha> \<sharp> p"
shows "H3(p \<turnstile>\<^sub>r Q) = p \<turnstile>\<^sub>r Q"
using assms
by (simp add: H3_def)
theorem H3_ndesign: "H3(p \<turnstile>\<^sub>n Q) = (p \<turnstile>\<^sub>n Q)"
by pred_auto
theorem ndesign_is_H3 [closure]: "p \<turnstile>\<^sub>n Q is H3"
by (simp add: H3_ndesign Healthy_def)
(*
lemma msubst_pre_H3: "(\<And>x. P x is H3) \<Longrightarrow> P x\<lbrakk>x\<rightarrow>\<lceil>v\<rceil>\<^sub><\<rbrakk> is H3"
by (rel_auto)
*)
subsection \<open> Normal Designs as $H1$-$H3$ predicates \<close>
text \<open> A normal design~\cite{Guttman2010} refers only to initial state variables in the precondition. \<close>
abbreviation H1_H3 :: "('\<alpha>, '\<beta>) des_rel \<Rightarrow> ('\<alpha>, '\<beta>) des_rel" ("\<^bold>N") where
"H1_H3 p \<equiv> H1 (H3 p)"
lemma H1_H3_comp: "H1_H3 = H1 \<circ> H3"
by (auto)
theorem H1_H3_is_design:
assumes "P is H1" "P is H3"
shows "P = (\<not> P\<^sup>f) \<turnstile> P\<^sup>t"
by (metis H1_H2_eq_design H2_H3_absorb Healthy_def' assms(1) assms(2))
theorem H1_H3_is_rdesign:
assumes "P is H1" "P is H3"
shows "P = pre\<^sub>D(P) \<turnstile>\<^sub>r post\<^sub>D(P)"
by (metis H1_H2_is_rdesign H2_H3_absorb Healthy_def' assms)
theorem H1_H3_is_normal_design:
assumes "P is H1" "P is H3"
shows "P = (pre\<^sub>D(P))\<^sub>< \<turnstile>\<^sub>n post\<^sub>D(P)"
by (metis H1_H3_is_rdesign SEXP_def assms drop_pre_inv rdesign_H3_iff_pre utp_rel.postcond_equiv)
lemma H1_H3_idempotent: "\<^bold>N (\<^bold>N P) = \<^bold>N P"
by (simp add: H1_H3_commute H1_idem H3_idem)
lemma H1_H3_Idempotent [closure]: "Idempotent \<^bold>N"
by (simp add: Idempotent_def H1_H3_idempotent)
(*
lemma H1_H3_monotonic [closure]: "Monotonic \<^bold>N"
by (simp add: H1_monotone H3_mono mono_def)
lemma H1_H3_Continuous [closure]: "Continuous \<^bold>N"
by (simp add: Continuous_comp H1_Continuous H1_H3_comp H3_Continuous)
*)
lemma H1_H3_false: "\<^bold>N false = \<top>\<^sub>D"
by (pred_auto)
lemma H1_H3_true: "\<^bold>N true = \<bottom>\<^sub>D"
by (pred_auto)
lemma H1_H3_intro:
assumes "P is \<^bold>H" "out\<alpha> \<sharp> pre\<^sub>D(P)"
shows "P is \<^bold>N"
by (metis H1_H2_eq_rdesign H1_rdesign H3_rdesign_pre Healthy_def' assms)
lemma H1_H3_left_unit: "P is \<^bold>N \<Longrightarrow> II\<^sub>D ;; P = P"
by (metis H1_H2_left_unit H1_H3_commute H2_H3_absorb H3_idem Healthy_def)
lemma H1_H3_right_unit: "P is \<^bold>N \<Longrightarrow> P ;; II\<^sub>D = P"
by (metis H1_H3_commute H3_def H3_idem Healthy_def)
lemma H1_H3_top_left: "P is \<^bold>N \<Longrightarrow> \<top>\<^sub>D ;; P = \<top>\<^sub>D"
by (metis H1_H2_eq_design H2_H3_absorb Healthy_if design_top_left_zero)
lemma H1_H3_bot_left: "P is \<^bold>N \<Longrightarrow> \<bottom>\<^sub>D ;; P = \<bottom>\<^sub>D"
by (metis H1_idem H1_left_zero Healthy_def bot_d_true)
lemma H1_H3_impl_H2 [closure]: "P is \<^bold>N \<Longrightarrow> P is \<^bold>H"
by (metis H1_H2_commute H1_idem H2_H3_absorb Healthy_def')
lemma H1_H3_eq_design_d_comp: "\<^bold>N(P) = ((\<not> P\<^sup>f) \<turnstile> P\<^sup>t) ;; II\<^sub>D"
by (metis H1_H2_eq_design H1_H3_commute H3_H2_absorb H3_def)
lemma H1_H3_eq_design: "\<^bold>N(P) = (\<not> (P\<^sup>f ;; true)) \<turnstile> P\<^sup>t"
apply (simp add: H1_H3_eq_design_d_comp skip_d_alt_def)
apply (subst design_composition_subst)
by pred_auto+
lemma H3_unrest_out_alpha_nok [unrest]:
assumes "P is \<^bold>N"
shows "out\<alpha> \<sharp> P\<^sup>f"
proof -
have "P = (\<not> (P\<^sup>f ;; true)) \<turnstile> P\<^sup>t"
by (metis H1_H3_eq_design Healthy_def assms)
also have "out\<alpha> \<sharp> (...\<^sup>f)"
by (simp add: design_def usubst unrest, pred_auto)
ultimately show ?thesis by auto
qed
lemma H3_unrest_out_alpha [unrest]: "P is \<^bold>N \<Longrightarrow> out\<alpha> \<sharp> pre\<^sub>D(P)"
by (metis H1_H3_commute H1_H3_is_rdesign H1_idem Healthy_def' precond_equiv rdesign_H3_iff_pre)
lemma ndesign_H1_H3 [closure]: "p \<turnstile>\<^sub>n Q is \<^bold>N"
by (simp add: H1_rdesign H3_def Healthy_def', pred_auto)
lemma ndesign_form: "P is \<^bold>N \<Longrightarrow> ((pre\<^sub>D(P))\<^sub>< \<turnstile>\<^sub>n post\<^sub>D(P)) = P"
by (metis H1_H3_is_normal_design H1_H3_right_unit H3_def Healthy_def)
lemma des_bot_H1_H3 [closure]: "\<bottom>\<^sub>D is \<^bold>N"
by (metis H1_design H3_def Healthy_def' design_false_pre design_true_left_zero skip_d_alt_def bot_d_def)
lemma des_top_is_H1_H3 [closure]: "\<top>\<^sub>D is \<^bold>N"
by (metis ndesign_H1_H3 ndesign_miracle)
lemma skip_d_is_H1_H3 [closure]: "II\<^sub>D is \<^bold>N"
by (simp add: ndesign_H1_H3 skip_d_ndes_def)
lemma seq_r_H1_H3_closed [closure]:
assumes "P is \<^bold>N" "Q is \<^bold>N"
shows "(P ;; Q) is \<^bold>N"
by (metis (no_types) H1_H2_eq_design H1_H3_eq_design_d_comp H1_H3_impl_H2 Healthy_def assms(1) assms(2) seq_r_H1_H2_closed seqr_assoc)
lemma dcond_H1_H2_closed [closure]:
assumes "P is \<^bold>N" "Q is \<^bold>N"
shows "(P \<triangleleft> b \<triangleright>\<^sub>D Q) is \<^bold>N"
by (metis assms ndesign_H1_H3 ndesign_dcond ndesign_form)
lemma inf_H1_H2_closed [closure]:
assumes "P is \<^bold>N" "Q is \<^bold>N"
shows "(P \<sqinter> Q) is \<^bold>N"
proof -
obtain P\<^sub>1 P\<^sub>2 Q\<^sub>1 Q\<^sub>2 where P:"P = (P\<^sub>1 \<turnstile>\<^sub>n P\<^sub>2)" and Q:"Q = (Q\<^sub>1 \<turnstile>\<^sub>n Q\<^sub>2)"
by (metis assms ndesign_form)
have "(P\<^sub>1 \<turnstile>\<^sub>n P\<^sub>2) \<sqinter> (Q\<^sub>1 \<turnstile>\<^sub>n Q\<^sub>2) = (P\<^sub>1 \<and> Q\<^sub>1) \<turnstile>\<^sub>n (P\<^sub>2 \<or> Q\<^sub>2)"
by (simp add: ndesign_choice)
moreover have "... is \<^bold>N"
by (simp add: ndesign_H1_H3)
ultimately show ?thesis by (simp add: P Q)
qed
lemma sup_H1_H2_closed [closure]:
assumes "P is \<^bold>N" "Q is \<^bold>N"
shows "(P \<squnion> Q) is \<^bold>N"
proof -
obtain P\<^sub>1 P\<^sub>2 Q\<^sub>1 Q\<^sub>2 where P:"P = (P\<^sub>1 \<turnstile>\<^sub>n P\<^sub>2)" and Q:"Q = (Q\<^sub>1 \<turnstile>\<^sub>n Q\<^sub>2)"
by (metis assms ndesign_form)
have "(P\<^sub>1 \<turnstile>\<^sub>n P\<^sub>2) \<squnion> (Q\<^sub>1 \<turnstile>\<^sub>n Q\<^sub>2) = (P\<^sub>1 \<or> Q\<^sub>1) \<turnstile>\<^sub>n ((P\<^sub>1\<^sup>< \<longrightarrow> P\<^sub>2) \<and> (Q\<^sub>1\<^sup>< \<longrightarrow> Q\<^sub>2))"
by (simp add: ndesign_inf)
moreover have "... is \<^bold>N"
by (simp add: ndesign_H1_H3)
ultimately show ?thesis by (simp add: P Q)
qed
lemma ndes_seqr_miracle:
assumes "P is \<^bold>N"
shows "P ;; \<top>\<^sub>D = (pre\<^sub>D P)\<^sub>< \<turnstile>\<^sub>n false"
proof -
have "P ;; \<top>\<^sub>D = ((pre\<^sub>D(P))\<^sub>< \<turnstile>\<^sub>n post\<^sub>D(P)) ;; (True \<turnstile>\<^sub>n false)"
by (simp add: assms ndesign_form ndesign_miracle)
also have "... = (pre\<^sub>D P)\<^sub>< \<turnstile>\<^sub>n false"
by (simp add: ndesign_composition_wlp wp)
finally show ?thesis .
qed
lemma ndes_seqr_abort:
assumes "P is \<^bold>N"
shows "P ;; \<bottom>\<^sub>D = ((pre\<^sub>D P)\<^sub>< \<and> post\<^sub>D P wlp False) \<turnstile>\<^sub>n false"
proof -
have "P ;; \<bottom>\<^sub>D = ((pre\<^sub>D(P))\<^sub>< \<turnstile>\<^sub>n post\<^sub>D(P)) ;; (False \<turnstile>\<^sub>n false)"
by (simp add: assms bot_d_true ndesign_false_pre ndesign_form)
also have "... = ((pre\<^sub>D P)\<^sub>< \<and> post\<^sub>D P wlp False) \<turnstile>\<^sub>n false"
by (simp add: ndesign_composition_wlp)
finally show ?thesis .
qed
lemma USUP_ind_H1_H3_closed [closure]:
"\<lbrakk> \<And> i. P i is \<^bold>N \<rbrakk> \<Longrightarrow> (\<Squnion> i. P i) is \<^bold>N"
by (rule H1_H3_intro, simp_all add: H1_H3_impl_H2 USUP_ind_H1_H2_closed preD_USUP_ind unrest)
(*
lemma msubst_pre_H1_H3 [closure]: "(\<And>x. P x is \<^bold>N) \<Longrightarrow> P x\<lbrakk>x\<rightarrow>\<lceil>v\<rceil>\<^sub><\<rbrakk> is \<^bold>N"
by (metis H1_H3_right_unit H3_def Healthy_if Healthy_intro msubst_H1 msubst_pre_H3)
*)
subsection \<open> H4: Feasibility \<close>
definition H4 :: "('\<alpha>, '\<beta>) des_rel \<Rightarrow> ('\<alpha>, '\<beta>) des_rel" where
[pred]: "H4(P) = ((P;;true) \<longrightarrow> P)"
theorem H4_idem:
"H4(H4(P)) = H4(P)"
by (pred_auto)
lemma is_H4_alt_def:
"P is H4 \<longleftrightarrow> (P ;; true) = true"
by (pred_auto, blast)
end
|
\<^marker>\<open>creator "Kevin Kappelmann"\<close>
subsubsection \<open>Galois Concepts\<close>
theory Transport_Natural_Functors_Galois
imports
Transport_Natural_Functors_Base
begin
context transport_natural_functor
begin
lemma half_galois_prop_leftI:
assumes "((\<le>\<^bsub>L1\<^esub>) \<^sub>h\<unlhd> (\<le>\<^bsub>R1\<^esub>)) l1 r1"
and "((\<le>\<^bsub>L2\<^esub>) \<^sub>h\<unlhd> (\<le>\<^bsub>R2\<^esub>)) l2 r2"
and "((\<le>\<^bsub>L3\<^esub>) \<^sub>h\<unlhd> (\<le>\<^bsub>R3\<^esub>)) l3 r3"
shows "((\<le>\<^bsub>L\<^esub>) \<^sub>h\<unlhd> (\<le>\<^bsub>R\<^esub>)) l r"
apply (rule half_galois_prop_leftI)
apply (unfold left_rel_eq_Frel right_rel_eq_Frel left_eq_Fmap right_eq_Fmap)
apply (subst (asm) in_codom_Frel_eq_Fpred_in_codom)
apply (erule FpredE)
apply (unfold Frel_Fmap_eqs)
apply (rule Frel_mono_strong,
assumption;
rule t1.half_galois_prop_leftD t2.half_galois_prop_leftD
t3.half_galois_prop_leftD,
rule assms,
assumption+)
done
interpretation flip_inv : transport_natural_functor "(\<ge>\<^bsub>R1\<^esub>)" "(\<ge>\<^bsub>L1\<^esub>)" r1 l1
"(\<ge>\<^bsub>R2\<^esub>)" "(\<ge>\<^bsub>L2\<^esub>)" r2 l2 "(\<ge>\<^bsub>R3\<^esub>)" "(\<ge>\<^bsub>L3\<^esub>)" r3 l3
rewrites "flip_inv.R \<equiv> (\<ge>\<^bsub>L\<^esub>)"
and "flip_inv.L \<equiv> (\<ge>\<^bsub>R\<^esub>)"
and "\<And>R S f g. (R\<inverse> \<^sub>h\<unlhd> S\<inverse>) f g \<equiv> (S \<unlhd>\<^sub>h R) g f"
by (simp_all only: flip_inv_left_eq_ge_right flip_inv_right_eq_ge_left
galois_prop.half_galois_prop_left_rel_inv_iff_half_galois_prop_right)
lemma half_galois_prop_rightI:
assumes "((\<le>\<^bsub>L1\<^esub>) \<unlhd>\<^sub>h (\<le>\<^bsub>R1\<^esub>)) l1 r1"
and "((\<le>\<^bsub>L2\<^esub>) \<unlhd>\<^sub>h (\<le>\<^bsub>R2\<^esub>)) l2 r2"
and "((\<le>\<^bsub>L3\<^esub>) \<unlhd>\<^sub>h (\<le>\<^bsub>R3\<^esub>)) l3 r3"
shows "((\<le>\<^bsub>L\<^esub>) \<unlhd>\<^sub>h (\<le>\<^bsub>R\<^esub>)) l r"
using assms by (intro flip_inv.half_galois_prop_leftI)
corollary galois_propI:
assumes "((\<le>\<^bsub>L1\<^esub>) \<unlhd> (\<le>\<^bsub>R1\<^esub>)) l1 r1"
and "((\<le>\<^bsub>L2\<^esub>) \<unlhd> (\<le>\<^bsub>R2\<^esub>)) l2 r2"
and "((\<le>\<^bsub>L3\<^esub>) \<unlhd> (\<le>\<^bsub>R3\<^esub>)) l3 r3"
shows "((\<le>\<^bsub>L\<^esub>) \<unlhd> (\<le>\<^bsub>R\<^esub>)) l r"
using assms by (elim galois_prop.galois_propE)
(intro galois_propI half_galois_prop_leftI half_galois_prop_rightI)
interpretation flip :
transport_natural_functor R1 L1 r1 l1 R2 L2 r2 l2 R3 L3 r3 l3 .
corollary galois_connectionI:
assumes "((\<le>\<^bsub>L1\<^esub>) \<stileturn> (\<le>\<^bsub>R1\<^esub>)) l1 r1"
and "((\<le>\<^bsub>L2\<^esub>) \<stileturn> (\<le>\<^bsub>R2\<^esub>)) l2 r2"
and "((\<le>\<^bsub>L3\<^esub>) \<stileturn> (\<le>\<^bsub>R3\<^esub>)) l3 r3"
shows "((\<le>\<^bsub>L\<^esub>) \<stileturn> (\<le>\<^bsub>R\<^esub>)) l r"
using assms by (elim galois.galois_connectionE) (intro
galois_connectionI galois_propI mono_wrt_rel_leftI flip.mono_wrt_rel_leftI)
corollary galois_equivalenceI:
assumes "((\<le>\<^bsub>L1\<^esub>) \<equiv>\<^sub>G (\<le>\<^bsub>R1\<^esub>)) l1 r1"
and "((\<le>\<^bsub>L2\<^esub>) \<equiv>\<^sub>G (\<le>\<^bsub>R2\<^esub>)) l2 r2"
and "((\<le>\<^bsub>L3\<^esub>) \<equiv>\<^sub>G (\<le>\<^bsub>R3\<^esub>)) l3 r3"
shows "((\<le>\<^bsub>L\<^esub>) \<equiv>\<^sub>G (\<le>\<^bsub>R\<^esub>)) l r"
using assms by (elim galois.galois_equivalenceE flip.t1.galois_connectionE
flip.t2.galois_connectionE flip.t3.galois_connectionE)
(intro galois_equivalenceI galois_connectionI flip.galois_propI)
end
end
|
# Unit 00 - Brief Review of Vectors, Planes, and Optimization
using LinearAlgebra, Distributions
## Homework 0
### 4. Points and Vectors
x = [0.4, 0.3]
y = [-0.15, 0.2]
nx = norm(x)
ny = norm(y)
sqrt(0.4^2+0.3^2)
sqrt((-0.15)^2+0.2^2)
dotxy = dot(x,y)
0.4*-0.15+0.3*0.2
α = acos(0)
3.14/2
using LinearAlgebra
a = [4,1]
b = [2,3]
normC = dot(a,b)/norm(b)
c = (dot(a,b)/norm(b)^2) * b
### 7. Univariate Gaussians
#### Probability
# Direct approach
X = Normal(1,sqrt(2))
P = cdf(X,2) - cdf(X,0.5)
# Using Standard Normals
Z = Normal(0,1)
ZlBound = (0.5-1)/sqrt(2)
ZuBound = (2-1)/sqrt(2)
P = cdf(Z,ZuBound) - cdf(Z,ZlBound)
### 8. (Optional Ungraded Warmup) 1D Optimization via Calculus
using SymPy,Plots
x = symbols("x")
f = (1/3)* x^3 - x^2 - 3*x + 10
df = diff(f,x)
critPoints = solve(df,x)
df2 = diff(df,x)
df2_x1 = subs(df2, x => critPoints[1])
df2_x2 = subs(df2, x => critPoints[2])
f_x1 = subs(f, x => critPoints[1])
f_x2 = subs(f, x => critPoints[2])
f_m4 = subs(f, x => -4)
f_4 = subs(f, x => 4)
# or, more simply...
f(critPoints[1])
f(critPoints[2])
f(-4)
f(4)
plot(f,-4,4)
plot(-exp(-x))
plot(x^0.7)
### 9. Gradients and Optimization
surface((x,y) -> x^2+y^2)
using Plots
x=-10:0.1:10
y=-10:0.1:10
f2(x,y) = x^2+y^2
plot(x,y,f2,st=:surface,camera=(45,45))
### 10. Matrices and Vectors
A = [1 2 3; 4 5 6; 1 2 1]
B = [2 1 0; 1 4 4; 5 6 4]
rank(A)
rank(B)
### 12. Linear Independence, Subspaces and Dimension
A = [1 3; 2 6]
B = [1 2; 2 1]
C = [1 1 0; 0 1 1; 0 0 1]
D = [2 -1 -1; -1 2 -1; -1 -1 2]
rank(A)
rank(B)
rank(C)
rank(D)
### 13. Determinant
A = [1 2 3; 4 5 6; 1 2 1]
det(A)
det(A')
|
/**
* TuningPotential.cc
* Computes tuning potential for all regions
* @ param1:
*/
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <unistd.h>
#include <algorithm>
#include <numeric>
#include <boost/format.hpp>
#include <vector>
#include <list>
#include <map>
#include <iomanip>
#include "../include/TuningPotential.h"
#include "../include/ProcessingIntensity.h"
#include "../../common_incl/helper.h"
using namespace std;
using namespace cube;
using namespace services;
using namespace boost;
/**
* @Brief: Computes and detect dynamism for all significant regions
* @param phase_node
* @param cnodes list of significant call nodes
* @param rgion_names list of significant region names
* @param in_cube name of the cube file
* @param threshold Threshold of Dynamism depending on avg of phase
* @return
*/
list< SignificantRegion* >
ComputeIntraPhaseTP( Cnode* phase_node,
vector< Cnode* >& cnodes,
vector< string >& region_names,
Cube* in_cube ) {
vector< Cnode* > sig_nodes;
list< SignificantRegion* > sig_region_list;
const vector< Process* >& processes = in_cube->get_procv();
Metric* met_any = in_cube->get_met( "time" );
for( const auto& cnode : cnodes )
{
string c_name = cnode->get_callee()->get_name();
for( const auto& region : region_names )
{
if( strcasecmp( region.c_str(), c_name.c_str() ) == 0 )
sig_nodes.push_back( cnode );
}
}
//double avg_phase_transfer_intnsty = getPhaseNodeAvgProcIntnsty( phase_node, in_cube, processes[0] );
vector< Cnode* > variant_nodes;
for( const auto& sig_node : sig_nodes )
{
Region *region = sig_node->get_callee();
Value* met_tau_val = in_cube->get_sev_adv( met_any,
CUBE_CALCULATE_INCLUSIVE,
sig_node,
CUBE_CALCULATE_EXCLUSIVE,
processes[ 0 ],
CUBE_CALCULATE_INCLUSIVE );
if( met_tau_val->myDataType() != CUBE_DATA_TYPE_TAU_ATOMIC )
{
std::cout << "Please instrument the application with CUBE_TUPLE profiling format( Intra-phase )" << endl;
return sig_region_list;
}
/* Casting from Value to TauAtomicValue */
TauAtomicValue* tau_atomic_tuple = ( TauAtomicValue* ) met_tau_val;
string stat_tuple = tau_atomic_tuple->getString();
vector< string > tau_atomic_val = ValueParser( stat_tuple );
double stand_deviation = tau_atomic_val.at( 4 ) == "-nan" ? 0.0 : stod( tau_atomic_val.at( 4 ) );
uint64_t N = stod( tau_atomic_val.at( 0 ) );
double mean = stod( tau_atomic_val.at( 3 ) );
double minValue = tau_atomic_tuple->getMinValue().getDouble();
double maxValue = tau_atomic_tuple->getMaxValue().getDouble();
if ( N != 0 )
{
double phasetime = getPhaseNodeTime( phase_node, in_cube, met_any, processes[ 0 ] );
/*std::cout << "REGION NAME: " << sig_node->get_callee()->get_name() << endl;
std::cout << "Exec_time: " << mean * N << endl;
std::cout << "Exec_time of Phase: " << phasetime << endl;*/
double dyn_avg_phase = ( mean ) * N / getPhaseNodeTime( phase_node, in_cube, met_any, processes[ 0 ] ) * 100; // weight
double dev_perc_reg = 0.0;
if ( mean != 0.0 )
{
dev_perc_reg = ( stand_deviation / mean ) * 100 ; // coefficient of variation OR degree of spreadness
}
double dev_perc_phase = ( stand_deviation / getPhaseNodeAvgValue( phase_node, in_cube, met_any, processes[ 0 ] ) ) * 100;
DynamismMetric dyn_ti = DynamismMetric( met_any->get_uniq_name(), minValue, maxValue, ( mean ) * N, dev_perc_reg, dev_perc_phase, dyn_avg_phase );
vector< DynamismMetric > dyn_metrics;
dyn_metrics.push_back( dyn_ti );
double avg_compute_intensity = getProcessingIntensity( sig_node, in_cube );
if( avg_compute_intensity != -1 )
{
double avg_phase_compute_intensity = getPhaseNodeAvgProcIntnsty( phase_node, in_cube, processes[ 0 ] );
double variation_compute_intensity = ( avg_compute_intensity / avg_phase_compute_intensity ) * 100;
std::string str = "Transfer Intensity";
DynamismMetric dyn_t_i = DynamismMetric( str, 0.0, 0.0, 0.0, 0.0, 0.0, variation_compute_intensity );
dyn_metrics.push_back( dyn_t_i );
}
else
{
std::cout << " Please run the application with PAPI Metric plugin to get intensity information" << endl;
std::string str = "Transfer Intensity";
DynamismMetric dyn_t_i = DynamismMetric( str, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 );
dyn_metrics.push_back( dyn_t_i );
}
if( !dyn_metrics.empty() )
{
SignificantRegion* sig_region = new SignificantRegion;
sig_region->name = region->get_name();
//sig_region->source_location = region->get_mod();
//sig_region->line_no = region->get_begn_ln();
sig_region->granularity = computeGranularity( sig_node, in_cube );
sig_region->dynamism_metrics.assign( dyn_metrics.begin(), dyn_metrics.end() );
sig_region_list.push_back( sig_region );
variant_nodes.push_back( sig_node );
}
}
}
if ( !variant_nodes.empty() )
{
printPotentialResults( sig_region_list );
}
else
{
std::cout << endl << " There is no intra-phase dynamism" << endl;
}
return sig_region_list;
}
/**
*
* @Brief: Print the tuning potential results
* @param
* @s_regions: pointer to dnyamism metric
* @size: no of significant regions
* @no_m: # of metrices
*/
void
printPotentialResults( list< SignificantRegion* >& regions )
{
std::cout << "Significant region information\n";
std::cout << "==============================" << endl;
std::cout << format( "%-28s %-15s %-12s %-15s %-15s %-15s %-15s\n" )
% "Region name" % "Min(t)" % "Max(t)" % "Time" % "Time Dev.(%Reg)" % "Ops/L3miss" % "Weight(%Phase)" ;
for ( const auto& region : regions )
{
if ( region->dynamism_metrics.size() > 0 )
{
std::cout << format( "%-25s %8.3f %8.3f %8.3f %5.1f %7.0f %5.0f \n" ) %
region->name.substr( 0, 25 ) %
region->dynamism_metrics[ 0 ].min %
region->dynamism_metrics[ 0 ].max %
region->dynamism_metrics[ 0 ].execTime %
region->dynamism_metrics[ 0 ].dev_perc_reg %
region->dynamism_metrics[ 1 ].dyn_perc_phase %
region->dynamism_metrics[ 0 ].dyn_perc_phase;
}
}
}
/**
* @brief Computes and detect dynamism across all phases
* @param phase_node
* @param in_cube name of the cube file
* @param threshold Threshold of Dynamism
* @return
*/
PhaseRegion*
ComputeInterPhaseTP( Cnode* phase_node,
Cube* in_cube,
double threshold )
{
Metric* met_t = in_cube->get_met( "time" );
const vector< Process* >& processes = in_cube->get_procv();
Value* complex_value = in_cube->get_sev_adv( met_t,
CUBE_CALCULATE_INCLUSIVE,
phase_node,
CUBE_CALCULATE_EXCLUSIVE,
processes[ 0 ],
CUBE_CALCULATE_INCLUSIVE );
if( complex_value->myDataType() != CUBE_DATA_TYPE_TAU_ATOMIC )
{
std::cout << "Please instrument the application with CUBE_TUPLE profiling format( Inter-phase ) " << endl;
return NULL;
}
/* Casting from Value to TauAtomicValue */
TauAtomicValue* tau_atomic_tuple = ( TauAtomicValue* )complex_value;
vector< string > tau_atomic_val = ValueParser( tau_atomic_tuple->getString() );
double standard_deviation = stod( tau_atomic_val.at( 4 ) );
double mean = stod( tau_atomic_val.at( 3 ) );
double minValue = tau_atomic_tuple->getMinValue().getDouble();
double maxValue = tau_atomic_tuple->getMaxValue().getDouble();
uint64_t N = stod( tau_atomic_val.at( 0 ) );
if( std::isnan( standard_deviation ) )
standard_deviation = 0.0;
double variation_percentage = ( ( maxValue - minValue ) / mean ) * 100;
double dev_percentage = ( standard_deviation / mean ) * 100;
std::cout << endl << "Phase information" << endl;
std::cout << "=================" << endl;
std::cout << format( "%-20s %-20s %-20s %-20s %-20s %-20s \n" )
% "Min" % "Max" % "Mean"% "Time"% "Dev.(% Phase)" % "Dyn.(% Phase)";
std::cout << format( "%-20s %-20s %-20s %-20s %-20s %-20s \n" ) %
minValue % maxValue % mean % ( N * mean ) % dev_percentage % variation_percentage;
PhaseRegion* phase = new PhaseRegion;
phase->name = phase_node->get_callee()->get_name();
phase->granularity = computeGranularity( phase_node, in_cube );
phase->min = minValue;
phase->max = maxValue;
phase->mean = mean;
phase->absTime = N * mean;
phase->dev_perc = dev_percentage;
phase->var_perc = variation_percentage;
phase->has_dynamism = variation_percentage > threshold;
return phase;
}
/**
* @brief Get the avaergae value of phase node
* @param pnode
* @param input
* @param met_any
* @param proc
* @return
*/
double
getPhaseNodeAvgValue( Cnode* pnode,
Cube * input,
Metric* met_any,
Process* proc )
{
Value* complex_value = input->get_sev_adv( met_any,
CUBE_CALCULATE_INCLUSIVE,
pnode,
CUBE_CALCULATE_EXCLUSIVE,
proc,
CUBE_CALCULATE_INCLUSIVE );
/* Casting from Value to TauAtomicValue */
TauAtomicValue* tau_atomic_tuple = ( TauAtomicValue* )complex_value;
vector< string > tau_atomic_val = ValueParser( tau_atomic_tuple->getString() );
double average = stod( tau_atomic_val.at( 3 ) );
return average;
}
/**
* @brief Get the absolute value of phase node
* @param pnode
* @param input
* @param met_any
* @param proc
* @return
*/
double
getPhaseNodeTime( Cnode* pnode,
Cube* input,
Metric* met_any,
Process* proc )
{
Value* complex_value = input->get_sev_adv( met_any,
CUBE_CALCULATE_INCLUSIVE,
pnode,
CUBE_CALCULATE_EXCLUSIVE,
proc,
CUBE_CALCULATE_INCLUSIVE );
/* Casting from Value to TauAtomicValue */
TauAtomicValue* tau_atomic_tuple = ( TauAtomicValue* )complex_value;
vector< string > tau_atomic_val = ValueParser( tau_atomic_tuple->getString() );
double average = stod( tau_atomic_val.at( 3 ) );
uint64_t N = stod( tau_atomic_val.at( 0 ) );
return average * N;
}
|
open import SystemT
open import Data.List using ([])
module Examples where
-- λ x . x
ex1 : [] ⊢ base ⟶ base
ex1 = lam (var i0)
-- λ x . λ y . y
ex2 : [] ⊢ base ⟶ base ⟶ base
ex2 = lam (lam (var i0))
-- λ x . λ y . x
ex3 : [] ⊢ base ⟶ base ⟶ base
ex3 = lam (lam (var (iS i0)))
|
open import Agda.Builtin.Equality
open import Agda.Builtin.Nat
data D (A : Set) : Set → Set₁ where
c₁ : {B : Set} → D A B
c₂ : D A A
record P {A B : Set} (p : D A B) : Set₁ where
constructor c
field
d : D A B
Q : {A B₁ B₂ C : Set} {x : D A (B₁ → C)} {y : D A B₂} →
P x → P y → B₁ ≡ B₂ → Nat
Q (c c₁) _ refl = 0
Q _ (c c₁) refl = 1
Q _ _ _ = 2
module _ {A B C : Set} where
checkQ₀ : {x : D A (B → C)} {y : D A B} (px : P x) (py : P y) →
Q {x = x} {y = y} (c c₁) py refl ≡ 0
checkQ₀ _ _ = refl
checkQ₁ : {x : D (A → B) (A → B)} {y : D (A → B) A} (px : P x) (py : P y) →
Q {x = x} {y = y} (c c₂) (c c₁) refl ≡ 1
checkQ₁ _ _ = refl
checkQ₂ : {x : D (A → B) (A → B)} {y : D (A → B) (A → B)} (px : P x) (py : P y) (eq : A ≡ (A → B)) →
Q {x = x} {y = y} (c c₂) (c c₂) eq ≡ 2
checkQ₂ _ _ _ = refl
R : {A B₁ B₂ C : Set} {x : D A (B₁ → C)} {y : D A B₂} →
P x → P y → B₁ ≡ B₂ → Nat
R (c c₂) _ refl = 0
R _ (c c₂) refl = 1
R _ _ _ = 2
module _ {A B C : Set} where
checkR₀ : ∀ {B C} {x : D (B → C) (B → C)} {y : D (B → C) B} (px : P x) (py : P y) →
R {x = x} {y = y} (c c₂) py refl ≡ 0
checkR₀ _ _ = refl
checkR₁ : ∀ {A B} {x : D A (A → B)} {y : D A A} (px : P x) (py : P y) →
R {x = x} {y = y} (c c₁) (c c₂) refl ≡ 1
checkR₁ _ _ = refl
checkR₂ : ∀ {A B C} {x : D A (B → C)} {y : D A B} (px : P x) (py : P y) →
R {x = x} {y = y} (c c₁) (c c₁) refl ≡ 2
checkR₂ _ _ = refl
|
function title = p01_title ( )
%*****************************************************************************80
%
%% P01_TITLE returns the name of problem p01.
%
% Licensing:
%
% This code is distributed under the GNU LGPL license.
%
% Modified:
%
% 04 August 2012
%
% Author:
%
% John Burkardt
%
% Parameters:
%
% Output, string TITLE, the title of the problem.
%
title = 'Oscillatory';
return
end
|
lemma poly_IVT: "a < b \<Longrightarrow> poly p a * poly p b < 0 \<Longrightarrow> \<exists>x>a. x < b \<and> poly p x = 0" for p :: "real poly"
|
[STATEMENT]
lemma segments_0 [simp]: "segments 0 = {}"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. segments 0 = {}
[PROOF STEP]
by (simp add: segments_def)
|
# ---------- Program Mode Controls ---------------
saving_data = True
auto_mount_usb = True
enable_servo = True
Simulate = False
# -- End --- Program Mode Controls ---------------
if not Simulate:
import Adafruit_BBIO.GPIO as GPIO
import Adafruit_BBIO.ADC as ADC
import Adafruit_BBIO.PWM as PWM
import datetime
import numpy as np
import os
import time
from SBE_functions import *
SimulationCheck(Simulate) # passes simulation status on to the function module
'''
data_row : row of data to be saved to a csv, format:
unix time (converted to PST tho), potentiometer [0-1.0],ultrasonic [mm],target_RH [mm],error[mm],P_term,I_term,D_term,Servo output angle [degrees]
'''
data_row = []
data_array = [] # list of data rows, each row is saved at the measurement frequency, once per period
usb_path = "/media/usb/"
now = datetime.datetime.now()
red_pin = "P9_41"
r_led = False
if Simulate == False:
GPIO.setup(red_pin, GPIO.OUT)
record_sw_pin = "P9_15"
if not Simulate:
GPIO.setup(record_sw_pin, GPIO.IN)
print("ADC setup...")
if not Simulate: time.sleep(15) # attempt to solve bootup problem
poten_pin = "P9_33"
poten_value = 0 # input range 0 - 1.0
try:
if not Simulate: ADC.setup()
except:
e = sys.exc_info()[0]
print("ERROR: ",e)
print("retrying...")
# try again
time.sleep(15) # attempt to solve bootup problem
ADC.setup()
timer_1hz = datetime.datetime.now()
timer_led = datetime.datetime.now()
epoch = datetime.datetime.utcfromtimestamp(0) # 1970 UNIX time
Control_ON = False
blink_count = 0 # counter for led indicator
# ------------- Timing setup ------------
control_freq = 100 # hz (actually means it will record a bit slower than this due to checking time without interrupts)
control_freq_micros = 1.0/control_freq*1000*1000 # number of microseconds before data grab
control_timer = datetime.datetime.now()
# --- End ----- Timing setup ------------
timer_program = datetime.datetime.now()
# ------------- Serial reading setup ------------
if not Simulate:
time.sleep(15) # attempt to solve bootup problem
ser = setupSerial()
sen_gain = 0.003384*25.4 # converts sensor reading to mm
gained_val = 0.0 # sensor reading in mm
# --- End ----- Serial reading setup ------------
watch_dog_01_count = 0 # counter for csv saving timeout
# ---------------- Mounting USB drive ----------
mounted_successfully = False
unmounted_successfully = True
failed_mount = False
mount_timer = datetime.datetime.now()
if not Simulate and auto_mount_usb and not os.path.isfile('/media/usb/important_text.txt'):
mount_check = os.system('sudo mount /dev/sda1 /media/usb')
while True:
if mount_check == 0:
mounted_successfully = True
print('usb mounted')
break
elif (datetime.datetime.now()-mount_timer).seconds > 15:
print('failed to mount')
failed_mount = True
break
# ------ End ----- Mounting USB drive ----------
# ------------- Servo output setup -------------
# 1-HK 15138, 2-HS-815BB (ball tilt servo), 3-DS3218mg (wing)"soft" limits, 4-Moth servo
Servo_Type = 4
duty_min, duty_max = servo_parameters(Servo_Type) # parameters for various kroova servos stored in the function
duty_span = duty_max - duty_min
servo_pin = "P8_13"
if not Simulate and enable_servo: PWM.start(servo_pin, (duty_max-duty_min)/2.0+duty_min, 60)
control_servo_angle = 90 # initial servo output angle
# --- End ----- Servo output setup ------------
# ------------- CONTROL VARIABLES setup ------------
path_to_params_file = '/home/debian/Desktop/Kroova_SBE/SBE_control_params.csv'
params = np.genfromtxt(path_to_params_file,delimiter=",")
target_RH, P_gain, I_gain, D_gain, servo_control_offset, US_rolling_avg_window, US_max_thresh, US_min_thresh, servo_max, servo_min = params[1]
# target RH in mm
# P gain
# I gain
# D gain
# servo control angle offset in degrees
# Length of rolling average window on US sensor
# max valid mm -- based on blade rider foil and mounting setup as of 6/11/18
# min valid mm -- based on blade rider foil and mounting setup as of 6/11/18
# max servo angle based on mechanical limits as of 6/11/18
# min servo angle based on mechanical limits as of 6/11/18
US_input_array = []
averaged_US_input = 200 # some initial
I_max = 10 # based on full range of flap motion being ~ 25
error = 0
last_error = 0 # for storing errors from previous loop
sum_error = 0 # integral term of error
# last_derivate_error = 0
# rolling_avg_D_errors = [0]*70 # 50 seems good
# --- End ----- CONTROL VARIABLES setup ------------
# csv parameters check in
parameters_check_timer = datetime.datetime.now()
parameters_check_freq = 3 # seconds not hz
while True:
if Simulate: print('Running...')
# recording running switch
if not Simulate and GPIO.input(record_sw_pin): Control_ON = True
elif Simulate: Control_ON = True
else: Control_ON = False
if (datetime.datetime.now() - parameters_check_timer).seconds >= parameters_check_freq:
parameters_check_timer = datetime.datetime.now()
params = np.genfromtxt(path_to_params_file,delimiter=",")
target_RH, P_gain, I_gain, D_gain, servo_control_offset, US_rolling_avg_window, US_max_thresh, US_min_thresh, servo_max, servo_min = params[1]
# -------- Ultrasonic serial reading --------
# reading at full speed seems to minimize error values
if not Simulate: rval = ToughSonicRead(ser)
else: rval = SimulateToughSonic()
if US_min_thresh < rval*sen_gain < US_max_thresh:
gained_val = rval * sen_gain # sensor reading in mm
elif rval*sen_gain > US_max_thresh and abs(averaged_US_input-rval*sen_gain) < 200: # this allows the max thresh to be higher if the avg values are high
gained_val = rval * sen_gain # sensor reading in mm
# else gained val doesn't update and is equal to the last reading
else:
gained_val = 0 # heavy handed way of defaulting bad/weird readings to result in max lift
# --End -- Ultrasonic serial reading --------
if not Control_ON and not Simulate:
## -------------- LED state indicator -----------
if (datetime.datetime.now() - timer_1hz).seconds >= 1:
timer_1hz = datetime.datetime.now() # resets the timer
r_led = not r_led
## --- End ------ LED state indicator -----------
# --------------- Saving csv data file ------------
# save any data that may have come from a stopped recording session
if len(data_array) > 500 and saving_data:
print("saving after recording stop")
now = datetime.datetime.now()
f_name = (usb_path+"Moth_Data_" + str(now.year)+"-"+str(now.month)+"-"+str(now.day)
+"_"+str(now.hour)+"h"+str(now.minute)+"m"+str(now.second)+"s")
print(f_name)
data_array = np.asarray(data_array)
np.savetxt((f_name+".csv"),data_array,delimiter=",")
watch_dog_01 = datetime.datetime.now()
while not os.path.isfile(f_name+".csv"):
if (datetime.datetime.now() - watch_dog_01).seconds > 5:
print("ERROR in watch_dog_01")
watch_dog_01 = datetime.datetime.now()
watch_dog_01_count += 1 # increment the error flag count
data_array = [] # reset the data array now that it's been saved
# ---------------- Unmounting USB drive ----------
mount_timer = datetime.datetime.now()
if auto_mount_usb and os.path.isfile('/media/usb/important_text.txt'):
unmounted_successfully = False
mount_check = os.system('sudo umount /media/usb')
while True:
if mount_check == 0:
unmounted_successfully = True
break
elif (datetime.datetime.now()-mount_timer).seconds > 15:
failed_mount = True
print('failed to unmount')
break
# ------ End ----- Unmounting USB drive ----------
# ------ End ----- Saving csv data file ------------
elif Control_ON:
# ---------------- Mounting USB drive ----------
if not Simulate and auto_mount_usb and not os.path.isfile('/media/usb/important_text.txt') and not failed_mount:
mount_timer = datetime.datetime.now()
mounted_successfully = False
mount_check = os.system('sudo mount /dev/sda1 /media/usb')
while True:
if mount_check == 0:
mounted_successfully = True
break
elif (datetime.datetime.now()-mount_timer).seconds > 15: # not sure this is written correctly...
failed_mount = True
print('failed to mount')
break
# ------ End ----- Mounting USB drive ----------
## -------------- LED state indicator -----------
if blink_count == 0 and (datetime.datetime.now() - timer_led).microseconds/1000 >= 600 :
timer_led = datetime.datetime.now() # resets the timer
blink_count += 1
r_led = False
elif blink_count > 0 and (datetime.datetime.now() - timer_led).microseconds/1000 >= 200 :
timer_led = datetime.datetime.now() # resets the timer
blink_count += 1
r_led = not r_led
if blink_count >= 5: blink_count = 0
## --- End ------ LED state indicator -----------
# ------------- Log and control at specified interval ----------------
if (datetime.datetime.now() - control_timer).microseconds >= control_freq_micros:
control_timer = datetime.datetime.now() # resets the timer
# ---------------- CONTROLS SECTION -----------------------------
US_input_array.append(gained_val)
if len(US_input_array) >= US_rolling_avg_window:
US_input_array.pop(0)
averaged_US_input = sum(US_input_array)/len(US_input_array)
gained_val = averaged_US_input # averaged US input
error = int(gained_val)-target_RH
P_term = error*P_gain
# second part may be unnecessary thresholding, but the goal is to fix weird capsize I term skews
if ((servo_min < control_servo_angle < servo_max) and (-I_max < sum_error*I_gain < I_max)): sum_error = error + sum_error
else: sum_error = sum_error
I_term = sum_error*I_gain
# rolling_avg_D_errors.append(error)
# rolling_avg_D_errors.pop(0)
# D_term = (error - float(sum(rolling_avg_D_errors))/len(rolling_avg_D_errors))*D_gain
D_term = (error - last_error)*D_gain
# update error terms
last_error = error
control_servo_angle = P_term + I_term + D_term + servo_control_offset # control equation
# threshold servo commands in case of errors
if control_servo_angle > servo_max: control_servo_angle = servo_max
elif control_servo_angle < servo_min: control_servo_angle = servo_min
duty = float(control_servo_angle)
duty = ((duty / 180) * duty_span + duty_min)
if not Simulate and enable_servo: PWM.set_duty_cycle(servo_pin, duty)
# ------- END -------- CONTROLS SECTION -------------------------------
# -------------------- LOGGING SECTION -------------------------------
data_row = []
unix_time_stamp = ((datetime.datetime.now()-epoch)-datetime.timedelta(hours=7)).total_seconds()
if not Simulate:
data_row.append(unix_time_stamp)
poten_value = ADC.read(poten_pin)
poten_value = ADC.read(poten_pin) # read twice due to possible known ADC driver bug
data_row.append(poten_value)
data_row.append(gained_val)
# new values
data_row.append(target_RH)
data_row.append(error)
data_row.append(P_term)
data_row.append(I_term)
data_row.append(D_term)
data_row.append(control_servo_angle)
if saving_data: data_array.append(data_row)
# ------- END -------- LOGGING SECTION -------------------------------
# ---- End ---- Sensor readings at specified interval ----------------
# --------------- Saving csv data file ------------
# save any data that may have come from a stopped recording session
if not Simulate and len(data_array) > 200000 and saving_data: # roughly 33 minutes of data if recording at 100 hz
print("saving after 200000 row limit")
now = datetime.datetime.now()
f_name = (usb_path+"Moth_Data_" + str(now.year)+"-"+str(now.month)+"-"+str(now.day)
+"_"+str(now.hour)+"h"+str(now.minute)+"m"+str(now.second)+"s")
print(f_name)
data_array = np.asarray(data_array)
np.savetxt((f_name+".csv"),data_array,delimiter=",")
watch_dog_01 = datetime.datetime.now()
while not os.path.isfile(f_name+".csv"):
if (datetime.datetime.now() - watch_dog_01).seconds > 5:
print("ERROR in watch_dog_01")
watch_dog_01 = datetime.datetime.now()
watch_dog_01_count += 1 # increment the error flag count
data_array = [] # reset the data array now that it's been saved
# ------ End ----- Saving csv data file ------------
# --------------- Outputs ----------------
if not Simulate:
if r_led: GPIO.output(red_pin,GPIO.HIGH)#print("red on")
else: GPIO.output(red_pin,GPIO.LOW)#print("red off")
# ------ End ---- Outputs --------------
# clean up
if not Simulate:
ser.close()
PWM.stop(servo_pin)
PWM.cleanup()
|
(10
* 15)
foo <- function(arg =
10) {
arg
}
(foo
(10,
20))
if(1
+ 2) 3
for (x in 1
:10) 20
while(1
+ 3) break
|
#ifndef BOOST_STATECHART_DETAIL_STATE_BASE_HPP_INCLUDED
#define BOOST_STATECHART_DETAIL_STATE_BASE_HPP_INCLUDED
//////////////////////////////////////////////////////////////////////////////
// Copyright 2002-2008 Andreas Huber Doenni
// Distributed under the Boost Software License, Version 1.0. (See accompany-
// ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//////////////////////////////////////////////////////////////////////////////
#include <boost/statechart/result.hpp>
#include <boost/statechart/event.hpp>
#include <boost/statechart/detail/counted_base.hpp>
#include <boost/intrusive_ptr.hpp>
#include <boost/noncopyable.hpp>
#include <boost/assert.hpp>
#include <boost/config.hpp> // BOOST_MSVC
#include <boost/detail/workaround.hpp>
#include <boost/detail/allocator_utilities.hpp>
#ifdef BOOST_MSVC
# pragma warning( push )
# pragma warning( disable: 4702 ) // unreachable code (in release mode only)
#endif
#include <list>
#ifdef BOOST_MSVC
# pragma warning( pop )
#endif
namespace boost
{
namespace statechart
{
namespace detail
{
template< class Allocator, class RttiPolicy >
class leaf_state;
template< class Allocator, class RttiPolicy >
class node_state_base;
typedef unsigned char orthogonal_position_type;
//////////////////////////////////////////////////////////////////////////////
template< class Allocator, class RttiPolicy >
class state_base :
#ifndef NDEBUG
noncopyable,
#endif
public RttiPolicy::template rtti_base_type<
// Derived class objects will be created, handled and destroyed by exactly
// one thread --> locking is not necessary
counted_base< false > >
{
typedef typename RttiPolicy::template rtti_base_type<
counted_base< false > > base_type;
public:
//////////////////////////////////////////////////////////////////////////
void exit() {}
virtual const state_base * outer_state_ptr() const = 0;
protected:
//////////////////////////////////////////////////////////////////////////
state_base( typename RttiPolicy::id_provider_type idProvider ) :
base_type( idProvider ),
deferredEvents_( false )
{
}
#if BOOST_WORKAROUND( __GNUC__, BOOST_TESTED_AT( 4 ) )
// We make the destructor virtual for GCC because with this compiler there
// is currently no way to disable the "has virtual functions but
// non-virtual destructor" warning on a class by class basis. Although it
// can be done on the compiler command line with -Wno-non-virtual-dtor,
// this is undesirable as this would also suppress legitimate warnings for
// types that are not states.
virtual ~state_base() {}
#else
// This destructor is not virtual for performance reasons. The library
// ensures that a state object is never deleted through a state_base
// pointer but only through a pointer to the most-derived type.
~state_base() {}
#endif
protected:
//////////////////////////////////////////////////////////////////////////
// The following declarations should be private.
// They are only protected because many compilers lack template friends.
//////////////////////////////////////////////////////////////////////////
void defer_event()
{
deferredEvents_ = true;
}
bool deferred_events() const
{
return deferredEvents_;
}
template< class Context >
void set_context( orthogonal_position_type position, Context * pContext )
{
pContext->add_inner_state( position, this );
}
public:
//////////////////////////////////////////////////////////////////////////
// The following declarations should be private.
// They are only public because many compilers lack template friends.
//////////////////////////////////////////////////////////////////////////
virtual detail::reaction_result react_impl(
const event_base & evt,
typename RttiPolicy::id_type eventType ) = 0;
typedef intrusive_ptr< node_state_base< Allocator, RttiPolicy > >
node_state_base_ptr_type;
typedef intrusive_ptr< leaf_state< Allocator, RttiPolicy > >
leaf_state_ptr_type;
typedef std::list<
leaf_state_ptr_type,
typename boost::detail::allocator::rebind_to<
Allocator, leaf_state_ptr_type >::type
> state_list_type;
virtual void remove_from_state_list(
typename state_list_type::iterator & statesEnd,
node_state_base_ptr_type & pOutermostUnstableState,
bool performFullExit ) = 0;
private:
//////////////////////////////////////////////////////////////////////////
bool deferredEvents_;
};
#ifdef BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP
} // namespace detail
} // namespace statechart
#endif
template< class Allocator, class RttiPolicy >
inline void intrusive_ptr_add_ref(
const ::boost::statechart::detail::state_base< Allocator, RttiPolicy > * pBase )
{
pBase->add_ref();
}
template< class Allocator, class RttiPolicy >
inline void intrusive_ptr_release(
const ::boost::statechart::detail::state_base< Allocator, RttiPolicy > * pBase )
{
if ( pBase->release() )
{
// The state_base destructor is *not* virtual for performance reasons
// but intrusive_ptr< state_base > objects are nevertheless used to point
// to states. This assert ensures that such a pointer is never the last
// one referencing a state object.
BOOST_ASSERT( false );
}
}
#ifndef BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP
} // namespace detail
} // namespace statechart
#endif
} // namespace boost
#endif
|
# This file was generated, do not modify it.
using Pkg # hideall
Pkg.activate("_literate/A-ensembles-3/Project.toml")
Pkg.update()
macro OUTPUT()
return isdefined(Main, :Franklin) ? Franklin.OUT_PATH[] : "/tmp/"
end;
using MLJ
using PyPlot
ioff() # hide
import Statistics
Xs = source()
ys = source()
DecisionTreeRegressor = @load DecisionTreeRegressor pkg=DecisionTree
atom = DecisionTreeRegressor()
machines = (machine(atom, Xs, ys) for i in 1:100)
Statistics.mean(v...) = mean(v)
Statistics.mean(v::AbstractVector{<:AbstractNode}) = node(mean, v...)
yhat = mean([predict(m, Xs) for m in machines]);
surrogate = Deterministic()
mach = machine(surrogate, Xs, ys; predict=yhat)
@from_network mach begin
mutable struct OneHundredModels
atom=atom
end
end
one_hundred_models = OneHundredModels()
X, y = @load_boston;
r = range(atom,
:min_samples_split,
lower=2,
upper=100, scale=:log)
mach = machine(atom, X, y)
figure()
curve = learning_curve!(mach,
range=r,
measure=mav,
resampling=CV(nfolds=9),
verbosity=0)
plot(curve.parameter_values, curve.measurements)
xlabel(curve.parameter_name)
savefig(joinpath(@OUTPUT, "e1.svg")) # hide
r = range(one_hundred_models,
:(atom.min_samples_split),
lower=2,
upper=100, scale=:log)
mach = machine(one_hundred_models, X, y)
figure()
curve = learning_curve!(mach,
range=r,
measure=mav,
resampling=CV(nfolds=9),
verbosity=0)
plot(curve.parameter_values, curve.measurements)
xlabel(curve.parameter_name)
savefig(joinpath(@OUTPUT, "e2.svg")) # hide
PyPlot.close_figs() # hide
|
The 1082 IMX is an absolutely perfect sidedrifting rod for those faster seams just loaded with steelhead.
With a bit faster action than the 1141, this IMX was created with steelhead in mind. It is extremely light weight which keeps your boat guests from fatiguing on the river. The 1082S is a rod that I highly recommend if you are fishing with new-ish people because the ultra sensitive IMX graphite allows you to them to easily feel the difference between a tick on a rock and the soft, tender bite of a steelhead. The shorter length is ideal for boat fishing as it helps when trying to bring a hot fish to the boat, the last thing you want to worry about is where you need to stand in the boat or how you’re going to bring a fish all the way to the surface with your arm trying to hold the rod tip up. Pricing at $395 retail to truly enhance your sensitivity, the same dimensions also comes in a GL2 for just $220 if you are targeting kings or larger salmon.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.