text
stringlengths 0
3.34M
|
---|
module Basic where
open import Prelude
data List (A : Set) : Set
data List A where
nil : List A
cons : A -> List A -> List A
append : {A : Set} -> List A -> List A -> List A
append nil ys = ys
append (cons x xs) ys = cons x (append xs ys)
record Equiv {A : Set} (R : A -> A -> Set) : Set
record Equiv {A} R where
constructor equiv
field
ref : (x : A) -> R x x
sym : (x : A) (y : A) -> R x y -> R y x
trans : {x y z : A} -> R x y -> R y z -> R x z
open Equiv
trans1 : {A : Set}{R : A -> A -> Set}{x y z : A} -> Equiv R -> R x y -> R y z -> R x z
trans1 eq p q = trans eq p q
postulate
symId : {A : Set} (x y : A) -> x == y -> y == x
transId : {A : Set} {x y z : A} -> x == y -> y == z -> x == z
equivId : {A : Set} -> Equiv {A} (\x y -> x == y)
equivId {A} = equiv (\x -> refl) symId (\ x y z -> transId)
record Sigma (A : Set) (B : A -> Set) : Set
record Sigma A B where
constructor pair
field fst : A
snd : B fst
record True : Set
record True where
constructor tt
|
(*
* Copyright 2014, NICTA
*
* This software may be distributed and modified according to the terms of
* the BSD 2-Clause license. Note that NO WARRANTY is provided.
* See "LICENSE_BSD2.txt" for details.
*
* @TAG(NICTA_BSD)
*)
(*
* This file introduces an experimental "distinct" command that takes
* a list of 'n' terms, and generates O(n^2) lemmas for you to prove
* that the 'n' terms are all distinct. These proofs can typically be
* carried out by an "apply auto" command, giving you O(n^2)
* distinctness theorems relatively easily. These new theorems can then
* be thrown into a simpset to avoid having to constantly unfold
* definitions merely to prove distinctness.
*
* This may significantly simplify certain proofs where inequality of
* defined terms is frequently relied upon.
*
* The "distinct" command is not really scalable, due to its O(n^2)
* proof terms generated. If we wanted to use this in a larger example,
* we would probably want a "ordered" command, which forces you to show
* that 'n' terms have some ordering, and then automatically derive the
* O(n^2) possible proof terms on-the-fly in a simproc (possibly using
* Isabelle's existing "order_tac").
*)
theory Distinct_Cmd
imports Main
keywords "distinct" :: thy_goal
begin
ML {*
local
(*
* Process a parsed binding, converting it from raw tokens (which
* can't be passed into Local_Theory.note) into its semantic meaning
* (which can).
*)
fun process_binding lthy binding =
apsnd (map (Attrib.check_src lthy)) binding
(* Parse the parameters to "distinct". *)
val distinct_parser =
(Scan.optional (Parse_Spec.opt_thm_name ":") Binding.empty_atts
-- Scan.repeat1 Parse.term)
(* Generate a prop of the form "a ~= b". *)
fun mk_inequality_pair a b =
HOLogic.mk_eq (a, b)
|> HOLogic.mk_not
|> HOLogic.mk_Trueprop
(* Generate O(n^2) distinctness goals. *)
fun gen_distinct_goals terms =
map_product
(fn a => fn b =>
if a = b then NONE
else SOME (mk_inequality_pair a b))
terms terms
|> map_filter I
|> map (fn t => (t, []))
(* Given a list of terms, coerce them all into the same type. *)
fun coerce_terms_to_same_type lthy terms =
HOLogic.mk_list dummyT terms
|> Syntax.check_term lthy
|> HOLogic.dest_list
(* We save the theorems to the context afterwards. *)
fun after_qed thm_name thms lthy =
Local_Theory.note (thm_name, (flat thms)) lthy |> snd
in
val _ =
Outer_Syntax.local_theory_to_proof @{command_keyword "distinct"}
"prove distinctness of a list of terms"
(distinct_parser
>> (fn (thm_name, terms) => fn lthy =>
Proof.theorem NONE (after_qed (process_binding lthy thm_name)) [
map (Syntax.parse_term lthy) terms
|> coerce_terms_to_same_type lthy
|> gen_distinct_goals
] lthy
))
end
*}
(* Test. *)
context
fixes A :: nat
fixes B :: nat
fixes C :: nat
assumes x: "A = 1 \<and> B = 2 \<and> C = 3"
begin
distinct A B C "5" "6" "2 + 11"
by (auto simp: x)
end
end
|
! =============================================================================
!
!> \file
!> \brief Contains the Attribute object setter methods
!> \author CMJ (XCP-3; LANL)
!
! =============================================================================
! =============================================================================
!
!> \fn setConstructed
!> \brief Sets the construction state of the object
!
! ARGUMENTS:
!> \param[inout] this The Attribute (or child of) object
!> \param[in ] flag The new value of the construction flag
!
! =============================================================================
subroutine setConstructed(this, flag)
implicit none
class(Attribute), intent(inout):: this
logical, intent(in ):: flag
this%b_constructed = flag
return
end subroutine setConstructed
! =============================================================================
!
!> \fn setName
!> \brief Sets the name of the object
!
!> Sets the name of the Attribute (or child of) object.
!
! ARGUMENTS:
!> \param[inout] this the attribute (or child of) object
!> \param[in ] name name assigned to the object
!
! =============================================================================
subroutine setName(this, name)
implicit none
class(Attribute), intent(inout):: this
character(:), intent(in ), allocatable:: name
this%b_name = trim(adjustl(name))
return
end subroutine setName
! =============================================================================
!
!> \fn setDescription
!> \brief Sets the description of the Attribute (or child of) object
!
! ARGUMENTS:
!> \param[inout] this The attribute (or child of) object
!> \param[in ] description Description of the object
!
! =============================================================================
subroutine setDescription(this, description)
implicit none
class(Attribute), intent(inout):: this
character(:), intent(in ), allocatable:: description
this%b_description = trim(adjustl(description))
return
end subroutine setDescription
! =============================================================================
!
!> \fn setLogger
!> \brief Sets the Attribute (or child of) object's Logger
!
! ARGUMENTS:
!> \param[inout] this The attribute (or child of) object
!> \param[in ] logger The new Logger object
!
! =============================================================================
subroutine setLogger(this, logger)
use Loggers, only: IOLogger => Logger
implicit none
class(Attribute), intent(inout):: this
class(IOLogger), intent(in ), target:: logger
this%b_log => logger
return
end subroutine setLogger
|
= = Regular season = =
|
classdef MimRemapBlue < MimGuiPlugin
% MimRemapBlue. Gui Plugin for setting paint colour
%
% You should not use this class within your own code. It is intended to
% be used by the gui of the TD MIM Toolkit.
%
% MimRemapBlue is a Gui Plugin for the MIM Toolkit.
%
%
% Licence
% -------
% Part of the TD MIM Toolkit. https://github.com/tomdoel
% Author: Tom Doel, Copyright Tom Doel 2014. www.tomdoel.com
% Distributed under the MIT licence. Please see website for details.
%
properties
ButtonText = 'Right upper'
SelectedText = 'Right upper'
ToolTip = 'Marks airway as right upper'
Category = 'Airway label'
Visibility = 'Dataset'
Mode = 'Edit'
HidePluginInDisplay = false
PTKVersion = '1'
ButtonWidth = 5
ButtonHeight = 1
Icon = 'paint.png'
IconColour = GemMarkerPoint.DefaultColours{1}
Location = 31
end
methods (Static)
function RunGuiPlugin(gui_app)
gui_app.ImagePanel.PaintBrushColour = 1;
end
function enabled = IsEnabled(gui_app)
enabled = gui_app.IsDatasetLoaded && gui_app.ImagePanel.OverlayImage.ImageExists && ...
isequal(gui_app.ImagePanel.SelectedControl, 'Map');
end
function is_selected = IsSelected(gui_app)
is_selected = gui_app.ImagePanel.PaintBrushColour == 1;
end
end
end |
lemma pred_less_const[measurable (raw generic)]: assumes f: "f \<in> measurable M N" and c: "{..< c} \<in> sets N" shows "pred M (\<lambda>x. f x < c)" |
(*
Title: Strong-Security
Authors: Sylvia Grewe, Alexander Lux, Heiko Mantel, Jens Sauer
*)
theory Type_System_example
imports Type_System Expr Domain_example
begin
--"When interpreting, we have to instantiate the type for domains."
--"As an example, we take a type containing 'low' and 'high' as domains."
consts DA :: "('id,Dom) DomainAssignment"
consts BMap :: "'val \<Rightarrow> bool"
abbreviation d_indistinguishable' :: "('id,'val) Expr \<Rightarrow> Dom
\<Rightarrow> ('id,'val) Expr \<Rightarrow> bool"
( "(_ \<equiv>\<^bsub>_\<^esub> _)" )
where
"e1 \<equiv>\<^bsub>d\<^esub> e2
\<equiv> Strongly_Secure_Programs.d_indistinguishable ExprEval DA d e1 e2"
abbreviation relatedbyUSdB' :: "(('id,'val) Expr, 'id) MWLfCom list
\<Rightarrow> Dom \<Rightarrow> (('id,'val) Expr, 'id) MWLfCom list \<Rightarrow> bool" (infixr "\<approx>\<^bsub>_\<^esub>" 65)
where "V \<approx>\<^bsub>d\<^esub> V' \<equiv> (V,V') \<in> Strong_Security.USdB
(MWLf_semantics.MWLfSteps_det ExprEval BMap) DA d"
-- "Security typing rules for expressions - will be part of a side condition"
inductive
ExprSecTyping :: "('id, 'val) Expr \<Rightarrow> Dom set \<Rightarrow> bool"
("\<turnstile>\<^bsub>\<E>\<^esub> _ : _")
where
Consts: "\<turnstile>\<^bsub>\<E>\<^esub> (Const v) : {d}" |
Vars: "\<turnstile>\<^bsub>\<E>\<^esub> (Var x) : {DA x}" |
Ops: "\<forall>i < length arglist. \<turnstile>\<^bsub>\<E>\<^esub> (arglist!i) : (dl!i)
\<Longrightarrow> \<turnstile>\<^bsub>\<E>\<^esub> (Op f arglist) : (\<Union>{d. (\<exists>i < length arglist. d = (dl!i))})"
definition synAssignSC :: "'id \<Rightarrow> ('id, 'val) Expr \<Rightarrow> bool"
where
"synAssignSC x e \<equiv> \<exists>D. (\<turnstile>\<^bsub>\<E>\<^esub> e : D \<and> (\<forall>d \<in> D. (d \<le> DA x)))"
definition synWhileSC :: "('id, 'val) Expr \<Rightarrow> bool"
where
"synWhileSC e \<equiv> \<exists>D. (\<turnstile>\<^bsub>\<E>\<^esub> e : D \<and> (\<forall>d\<in>D. \<forall>d'. d \<le> d'))"
definition synIfSC :: "('id, 'val) Expr \<Rightarrow> (('id, 'val) Expr, 'id) MWLfCom
\<Rightarrow> (('id, 'val) Expr, 'id) MWLfCom \<Rightarrow> bool"
where
"synIfSC e c1 c2 \<equiv>
\<forall>d. (\<not> (e \<equiv>\<^bsub>d\<^esub> e) \<longrightarrow> [c1] \<approx>\<^bsub>d\<^esub> [c2])"
lemma ExprTypable_with_smallerD_implies_d_indistinguishable:
"\<lbrakk> \<turnstile>\<^bsub>\<E>\<^esub> e : D'; \<forall>d' \<in> D'. d' \<le> d \<rbrakk> \<Longrightarrow> e \<equiv>\<^bsub>d\<^esub> e"
proof (induct rule: ExprSecTyping.induct,
simp_all add: Strongly_Secure_Programs.d_indistinguishable_def
Strong_Security.d_equal_def, auto)
fix dl and arglist::"(('id, 'val) Expr) list" and f::"'val list \<Rightarrow> 'val"
and m1::"('id,'val) State" and m2::"('id,'val) State"
assume main: "\<forall>i < length arglist. \<turnstile>\<^bsub>\<E>\<^esub> arglist!i : dl!i \<and>
((\<forall>d' \<in> (dl!i). d' \<le> d) \<longrightarrow>
(\<forall>m m'. (\<forall>x. DA x \<le> d \<longrightarrow> m x = m' x)
\<longrightarrow> ExprEval (arglist!i) m = ExprEval (arglist!i) m'))"
assume smaller: "\<forall>D. (\<exists>i < length arglist. D = (dl!i))
\<longrightarrow> (\<forall>d'\<in>D. d' \<le> d)"
assume eqstate: "\<forall>x. DA x \<le> d \<longrightarrow> m1 x = m2 x"
from smaller have irangesubst:
"\<forall>i < length arglist. \<forall>d' \<in> (dl!i). d' \<le> d"
by auto
with eqstate main have
"\<forall>i < length arglist. ExprEval (arglist!i) m1
= ExprEval (arglist!i) m2"
by force
hence substmap: "(ExprEvalL arglist m1) = (ExprEvalL arglist m2)"
by (induct arglist, auto, force)
show "f (ExprEvalL arglist m1) = f (ExprEvalL arglist m2)"
by (subst substmap, auto)
qed
interpretation Type_System_example: Type_System ExprEval BMap DA
synAssignSC synWhileSC synIfSC
by (unfold_locales, simp add: synAssignSC_def,
metis ExprTypable_with_smallerD_implies_d_indistinguishable,
simp add: synWhileSC_def,
metis ExprTypable_with_smallerD_implies_d_indistinguishable,
simp add: synIfSC_def, metis)
end
|
[STATEMENT]
lemma True
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. True
[PROOF STEP]
nitpick[satisfy, card c = 1, card e = 1, card w = 1]
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. True
[PROOF STEP]
oops \<comment> \<open> one-world model found \<close> |
/-
Copyright (c) 2022 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
! This file was ported from Lean 3 source module analysis.complex.removable_singularity
! leanprover-community/mathlib commit f2ce6086713c78a7f880485f7917ea547a215982
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Analysis.Calculus.FderivAnalytic
import Mathbin.Analysis.Asymptotics.SpecificAsymptotics
import Mathbin.Analysis.Complex.CauchyIntegral
/-!
# Removable singularity theorem
In this file we prove Riemann's removable singularity theorem: if `f : ℂ → E` is complex
differentiable in a punctured neighborhood of a point `c` and is bounded in a punctured neighborhood
of `c` (or, more generally, $f(z) - f(c)=o((z-c)^{-1})$), then it has a limit at `c` and the
function `function.update f c (lim (𝓝[≠] c) f)` is complex differentiable in a neighborhood of `c`.
-/
open TopologicalSpace Metric Set Filter Asymptotics Function
open Topology Filter NNReal Real
universe u
variable {E : Type u} [NormedAddCommGroup E] [NormedSpace ℂ E] [CompleteSpace E]
namespace Complex
/-- **Removable singularity** theorem, weak version. If `f : ℂ → E` is differentiable in a punctured
neighborhood of a point and is continuous at this point, then it is analytic at this point. -/
theorem analyticAt_of_differentiable_on_punctured_nhds_of_continuousAt {f : ℂ → E} {c : ℂ}
(hd : ∀ᶠ z in 𝓝[≠] c, DifferentiableAt ℂ f z) (hc : ContinuousAt f c) : AnalyticAt ℂ f c :=
by
rcases(nhdsWithin_hasBasis nhds_basis_closed_ball _).mem_iff.1 hd with ⟨R, hR0, hRs⟩
lift R to ℝ≥0 using hR0.le
replace hc : ContinuousOn f (closed_ball c R)
· refine' fun z hz => ContinuousAt.continuousWithinAt _
rcases eq_or_ne z c with (rfl | hne)
exacts[hc, (hRs ⟨hz, hne⟩).ContinuousAt]
exact
(has_fpower_series_on_ball_of_differentiable_off_countable (countable_singleton c) hc
(fun z hz => hRs (diff_subset_diff_left ball_subset_closed_ball hz)) hR0).AnalyticAt
#align complex.analytic_at_of_differentiable_on_punctured_nhds_of_continuous_at Complex.analyticAt_of_differentiable_on_punctured_nhds_of_continuousAt
theorem differentiableOn_compl_singleton_and_continuousAt_iff {f : ℂ → E} {s : Set ℂ} {c : ℂ}
(hs : s ∈ 𝓝 c) : DifferentiableOn ℂ f (s \ {c}) ∧ ContinuousAt f c ↔ DifferentiableOn ℂ f s :=
by
refine' ⟨_, fun hd => ⟨hd.mono (diff_subset _ _), (hd.DifferentiableAt hs).ContinuousAt⟩⟩
rintro ⟨hd, hc⟩ x hx
rcases eq_or_ne x c with (rfl | hne)
· refine'
(analytic_at_of_differentiable_on_punctured_nhds_of_continuous_at _
hc).DifferentiableAt.DifferentiableWithinAt
refine' eventually_nhdsWithin_iff.2 ((eventually_mem_nhds.2 hs).mono fun z hz hzx => _)
exact hd.differentiable_at (inter_mem hz (is_open_ne.mem_nhds hzx))
·
simpa only [DifferentiableWithinAt, HasFderivWithinAt, hne.nhds_within_diff_singleton] using
hd x ⟨hx, hne⟩
#align complex.differentiable_on_compl_singleton_and_continuous_at_iff Complex.differentiableOn_compl_singleton_and_continuousAt_iff
theorem differentiableOn_dslope {f : ℂ → E} {s : Set ℂ} {c : ℂ} (hc : s ∈ 𝓝 c) :
DifferentiableOn ℂ (dslope f c) s ↔ DifferentiableOn ℂ f s :=
⟨fun h => h.of_dslope, fun h =>
(differentiableOn_compl_singleton_and_continuousAt_iff hc).mp <|
⟨Iff.mpr (differentiableOn_dslope_of_nmem fun h => h.2 rfl) (h.mono <| diff_subset _ _),
continuousAt_dslope_same.2 <| h.DifferentiableAt hc⟩⟩
#align complex.differentiable_on_dslope Complex.differentiableOn_dslope
/-- **Removable singularity** theorem: if `s` is a neighborhood of `c : ℂ`, a function `f : ℂ → E`
is complex differentiable on `s \ {c}`, and $f(z) - f(c)=o((z-c)^{-1})$, then `f` redefined to be
equal to `lim (𝓝[≠] c) f` at `c` is complex differentiable on `s`. -/
theorem differentiableOn_update_limUnder_of_isOCat {f : ℂ → E} {s : Set ℂ} {c : ℂ} (hc : s ∈ 𝓝 c)
(hd : DifferentiableOn ℂ f (s \ {c}))
(ho : (fun z => f z - f c) =o[𝓝[≠] c] fun z => (z - c)⁻¹) :
DifferentiableOn ℂ (update f c (limUnder (𝓝[≠] c) f)) s :=
by
set F : ℂ → E := fun z => (z - c) • f z with hF
suffices DifferentiableOn ℂ F (s \ {c}) ∧ ContinuousAt F c
by
rw [differentiable_on_compl_singleton_and_continuous_at_iff hc, ← differentiable_on_dslope hc,
dslope_sub_smul] at this <;>
try infer_instance
have hc : tendsto f (𝓝[≠] c) (𝓝 (deriv F c)) :=
continuous_at_update_same.mp (this.continuous_on.continuous_at hc)
rwa [hc.lim_eq]
refine' ⟨(differentiable_on_id.sub_const _).smul hd, _⟩
rw [← continuousWithinAt_compl_self]
have H := ho.tendsto_inv_smul_nhds_zero
have H' : tendsto (fun z => (z - c) • f c) (𝓝[≠] c) (𝓝 (F c)) :=
(continuous_within_at_id.tendsto.sub tendsto_const_nhds).smul tendsto_const_nhds
simpa [← smul_add, ContinuousWithinAt] using H.add H'
#align complex.differentiable_on_update_lim_of_is_o Complex.differentiableOn_update_limUnder_of_isOCat
/-- **Removable singularity** theorem: if `s` is a punctured neighborhood of `c : ℂ`, a function
`f : ℂ → E` is complex differentiable on `s`, and $f(z) - f(c)=o((z-c)^{-1})$, then `f` redefined to
be equal to `lim (𝓝[≠] c) f` at `c` is complex differentiable on `{c} ∪ s`. -/
theorem differentiableOn_update_limUnder_insert_of_isOCat {f : ℂ → E} {s : Set ℂ} {c : ℂ}
(hc : s ∈ 𝓝[≠] c) (hd : DifferentiableOn ℂ f s)
(ho : (fun z => f z - f c) =o[𝓝[≠] c] fun z => (z - c)⁻¹) :
DifferentiableOn ℂ (update f c (limUnder (𝓝[≠] c) f)) (insert c s) :=
differentiableOn_update_limUnder_of_isOCat (insert_mem_nhds_iff.2 hc)
(hd.mono fun z hz => hz.1.resolve_left hz.2) ho
#align complex.differentiable_on_update_lim_insert_of_is_o Complex.differentiableOn_update_limUnder_insert_of_isOCat
/-- **Removable singularity** theorem: if `s` is a neighborhood of `c : ℂ`, a function `f : ℂ → E`
is complex differentiable and is bounded on `s \ {c}`, then `f` redefined to be equal to
`lim (𝓝[≠] c) f` at `c` is complex differentiable on `s`. -/
theorem differentiableOn_update_limUnder_of_bddAbove {f : ℂ → E} {s : Set ℂ} {c : ℂ} (hc : s ∈ 𝓝 c)
(hd : DifferentiableOn ℂ f (s \ {c})) (hb : BddAbove (norm ∘ f '' (s \ {c}))) :
DifferentiableOn ℂ (update f c (limUnder (𝓝[≠] c) f)) s :=
differentiableOn_update_limUnder_of_isOCat hc hd <|
IsBoundedUnder.isOCat_sub_self_inv <|
let ⟨C, hC⟩ := hb
⟨C + ‖f c‖,
eventually_map.2 <|
mem_nhdsWithin_iff_exists_mem_nhds_inter.2
⟨s, hc, fun z hz => norm_sub_le_of_le (hC <| mem_image_of_mem _ hz) le_rfl⟩⟩
#align complex.differentiable_on_update_lim_of_bdd_above Complex.differentiableOn_update_limUnder_of_bddAbove
/-- **Removable singularity** theorem: if a function `f : ℂ → E` is complex differentiable on a
punctured neighborhood of `c` and $f(z) - f(c)=o((z-c)^{-1})$, then `f` has a limit at `c`. -/
theorem tendsto_limUnder_of_differentiable_on_punctured_nhds_of_isOCat {f : ℂ → E} {c : ℂ}
(hd : ∀ᶠ z in 𝓝[≠] c, DifferentiableAt ℂ f z)
(ho : (fun z => f z - f c) =o[𝓝[≠] c] fun z => (z - c)⁻¹) :
Tendsto f (𝓝[≠] c) (𝓝 <| limUnder (𝓝[≠] c) f) :=
by
rw [eventually_nhdsWithin_iff] at hd
have : DifferentiableOn ℂ f ({ z | z ≠ c → DifferentiableAt ℂ f z } \ {c}) := fun z hz =>
(hz.1 hz.2).DifferentiableWithinAt
have H := differentiable_on_update_lim_of_is_o hd this ho
exact continuousAt_update_same.1 (H.differentiable_at hd).ContinuousAt
#align complex.tendsto_lim_of_differentiable_on_punctured_nhds_of_is_o Complex.tendsto_limUnder_of_differentiable_on_punctured_nhds_of_isOCat
/-- **Removable singularity** theorem: if a function `f : ℂ → E` is complex differentiable and
bounded on a punctured neighborhood of `c`, then `f` has a limit at `c`. -/
theorem tendsto_limUnder_of_differentiable_on_punctured_nhds_of_bounded_under {f : ℂ → E} {c : ℂ}
(hd : ∀ᶠ z in 𝓝[≠] c, DifferentiableAt ℂ f z)
(hb : IsBoundedUnder (· ≤ ·) (𝓝[≠] c) fun z => ‖f z - f c‖) :
Tendsto f (𝓝[≠] c) (𝓝 <| limUnder (𝓝[≠] c) f) :=
tendsto_limUnder_of_differentiable_on_punctured_nhds_of_isOCat hd hb.isOCat_sub_self_inv
#align complex.tendsto_lim_of_differentiable_on_punctured_nhds_of_bounded_under Complex.tendsto_limUnder_of_differentiable_on_punctured_nhds_of_bounded_under
/-- The Cauchy formula for the derivative of a holomorphic function. -/
theorem two_pi_i_inv_smul_circleIntegral_sub_sq_inv_smul_of_differentiable {U : Set ℂ}
(hU : IsOpen U) {c w₀ : ℂ} {R : ℝ} {f : ℂ → E} (hc : closedBall c R ⊆ U)
(hf : DifferentiableOn ℂ f U) (hw₀ : w₀ ∈ ball c R) :
((2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), ((z - w₀) ^ 2)⁻¹ • f z) = deriv f w₀ :=
by
-- We apply the removable singularity theorem and the Cauchy formula to `dslope f w₀`
have hR : 0 < R := not_le.mp (ball_eq_empty.not.mp (nonempty_of_mem hw₀).ne_empty)
have hf' : DifferentiableOn ℂ (dslope f w₀) U :=
(differentiable_on_dslope (hU.mem_nhds ((ball_subset_closed_ball.trans hc) hw₀))).mpr hf
have h0 := (hf'.diff_cont_on_cl_ball hc).two_pi_i_inv_smul_circleIntegral_sub_inv_smul hw₀
rw [← dslope_same, ← h0]
congr 1
trans ∮ z in C(c, R), ((z - w₀) ^ 2)⁻¹ • (f z - f w₀)
· have h1 : ContinuousOn (fun z : ℂ => ((z - w₀) ^ 2)⁻¹) (sphere c R) :=
by
refine' ((continuous_id'.sub continuous_const).pow 2).ContinuousOn.inv₀ fun w hw h => _
exact sphere_disjoint_ball.ne_of_mem hw hw₀ (sub_eq_zero.mp (sq_eq_zero_iff.mp h))
have h2 : CircleIntegrable (fun z : ℂ => ((z - w₀) ^ 2)⁻¹ • f z) c R :=
by
refine' ContinuousOn.circleIntegrable (pos_of_mem_ball hw₀).le _
exact h1.smul (hf.continuous_on.mono (sphere_subset_closed_ball.trans hc))
have h3 : CircleIntegrable (fun z : ℂ => ((z - w₀) ^ 2)⁻¹ • f w₀) c R :=
ContinuousOn.circleIntegrable (pos_of_mem_ball hw₀).le (h1.smul continuousOn_const)
have h4 : (∮ z : ℂ in C(c, R), ((z - w₀) ^ 2)⁻¹) = 0 := by
simpa using circleIntegral.integral_sub_zpow_of_ne (by decide : (-2 : ℤ) ≠ -1) c w₀ R
simp only [smul_sub, circleIntegral.integral_sub h2 h3, h4, circleIntegral.integral_smul_const,
zero_smul, sub_zero]
· refine' circleIntegral.integral_congr (pos_of_mem_ball hw₀).le fun z hz => _
simp only [dslope_of_ne, metric.sphere_disjoint_ball.ne_of_mem hz hw₀, slope, ← smul_assoc, sq,
mul_inv, Ne.def, not_false_iff, vsub_eq_sub, Algebra.id.smul_eq_mul]
#align complex.two_pi_I_inv_smul_circle_integral_sub_sq_inv_smul_of_differentiable Complex.two_pi_i_inv_smul_circleIntegral_sub_sq_inv_smul_of_differentiable
end Complex
|
Ask yourself whether the person you’re dealing with has a problem that is solved by the solution you offer. If they don’t – you simply won’t sell anything.
That’s why many great sales starts with generating inbound marketing leads. If you create content marketing programs and drive traffic to websites where you can measure how long somebody spends reading your materials or downloading your white papers you’ve at least confirmed some level of interest.
If you have a product, knowing who the “typical buyer” by department or title is helps you greatly because you can quickly get to somebody likely to be familiar with the space in which you’re selling.
If you generate outbound email campaigns to groups of potential buyers you can use SalesLoft or tools like Yesware and ToutApp to track whether people opened your emails, clicked on your links, downloaded your documents, etc.
The other obvious area in determining interested parties is to find referrals from trusted sources. That’s why companies partner with vendors with complementary service offerings.
Let me make it simple: If you can’t identify a problem that a prospect has that you can quantifiably solve you won’t sell anything.
(1) Note the similarities to What problem are you solving? and Focus on the job, not the customer type.
(2) This is the beauty of freemium models. You create the customers’ problem by making them hit the paywall, and your conversion data tells you if the problem is serious enough that customers will pay to solve it. |
There are many lecture halls on campus, but the largest and most frequently used ones are:Image(Lecture hall in Campus.jpg, right, thumbnail, 400 Lecture Hall in Campus, by Users/JASH)
Peter A. Rock Hall formerly known as 194 Chemistry
179 Chemistry
176 Everson
1213 Gallagher
1001 Giedt
3 Kleiber
1227 Haring
2205 Haring
100 Hunt
55 Roessler
66 Roessler primary lecture hall for lower division physics lectures.
123 Sciences Lecture Hall primary lecture hall for the Chemistry CHE 2 series.
1100 Social Science
1322 Storer
2 Wellman
198 Young
To get information on the sizes of each hall, and what AV equipment is in each hall, see the http://registrar.ucdavis.edu/schedule/html/sum_display.cfm classroom summary.
Some of these halls are great places to watch a movie with your friends.
See also Campus Buildings.
|
import category_theory.colimit_lemmas
import .definitions
universes v u
open category_theory
open category_theory.category
local notation f ` ∘ `:80 g:80 := g ≫ f
namespace homotopy_theory.cofibrations
open category_theory.has_initial_object category_theory.preserves_initial_object
open category_theory.preserves_coproducts
open homotopy_theory.cylinder
open I_category
variables {C : Type u} [category.{v} C] [has_initial_object.{v} C]
[has_coproducts.{v} C] [I_category.{v} C]
def Ii_initial : Is_initial_object.{v} (I.obj ∅ : C) :=
Is_initial_object_of_Is_initial_object
has_initial_object.initial_object.is_initial_object
def I_preserves_coproducts : preserves_coproducts (I : C ↝ C) :=
⟨λ a₀ a₁ b f₀ f₁ copr,
let po : Is_pushout (! a₀) (! a₁) f₀ f₁ :=
Is_pushout_of_Is_coproduct_of_Is_initial copr
has_initial_object.initial_object.is_initial_object in
Is_coproduct_of_Is_pushout_of_Is_initial
(I_preserves_pushout_by_cof (all_objects_cofibrant.cofibrant a₀) po) Ii_initial⟩
def I_of_coprod_is_coproduct {a₀ a₁ : C} :
Is_coproduct (I &> (i₀ : a₀ ⟶ a₀ ⊔ a₁)) (I &> (i₁ : a₁ ⟶ a₀ ⊔ a₁)) :=
let ⟨f⟩ := I_preserves_coproducts in
f (has_coproducts.coproduct.{v} a₀ a₁).is_coproduct
lemma I_preserves_cofibrations {a b : C} {j : a ⟶ b} (hj : is_cof j) : is_cof (I.map j) :=
begin
convert cof_comp _ (relative_cylinder j hj),
exact (Is_pushout.induced_commutes₁ _ _ _ _).symm,
exact precofibration_category.pushout_is_cof (pushout.is_pushout _) (cof_coprod hj hj)
end
end homotopy_theory.cofibrations
|
function xhpf = HPF(u)
%
%
persistent prevX
persistent prevU
persistent dt tau
persistent firstRun
if isempty(firstRun)
prevX = 0;
prevU = 0;
dt = 0.01;
tau = 0.0233;
firstRun = 1;
end
alpha = tau / (tau + dt);
xhpf = alpha*prevX + alpha*(u - prevU);
prevX = xhpf;
prevU = u; |
[STATEMENT]
lemma conj_idem [simp]: "((P::'\<alpha> upred) \<and> P) = P"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (P \<and> P) = P
[PROOF STEP]
by (pred_auto) |
------------------------------------------------------------------------
-- The Agda standard library
--
-- A different interface to the Kleene lists, designed to mimic
-- Data.List.
------------------------------------------------------------------------
{-# OPTIONS --without-K --safe #-}
module Data.List.Kleene.AsList where
open import Level as Level using (Level)
private
variable
a b c : Level
A : Set a
B : Set b
C : Set c
import Data.List.Kleene.Base as Kleene
------------------------------------------------------------------------
-- Here we import half of the functions from Data.KleeneList: the half
-- for possibly-empty lists.
open import Data.List.Kleene.Base public
using ([])
renaming
( _* to List
; foldr* to foldr
; foldl* to foldl
; _++*_ to _++_
; map* to map
; mapMaybe* to mapMaybe
; pure* to pure
; _<*>*_ to _<*>_
; _>>=*_ to _>>=_
; mapAccumˡ* to mapAccumˡ
; mapAccumʳ* to mapAccumʳ
; _[_]* to _[_]
; applyUpTo* to applyUpTo
; upTo* to upTo
; zipWith* to zipWith
; unzipWith* to unzipWith
; partitionSumsWith* to partitionSumsWith
; reverse* to reverse
)
------------------------------------------------------------------------
-- A pattern which mimics Data.List._∷_
infixr 5 _∷_
pattern _∷_ x xs = Kleene.∹ x Kleene.& xs
------------------------------------------------------------------------
-- The following functions change the type of the list (from ⁺ to * or vice
-- versa) in Data.KleeneList, so we reimplement them here to keep the
-- type the same.
scanr : (A → B → B) → B → List A → List B
scanr f b xs = Kleene.∹ Kleene.scanr* f b xs
scanl : (B → A → B) → B → List A → List B
scanl f b xs = Kleene.∹ Kleene.scanl* f b xs
tails : List A → List (List A)
tails xs = foldr (λ x xs → (Kleene.∹ x) ∷ xs) ([] ∷ []) (Kleene.tails* xs)
|
/-
Copyright (c) 2020 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
! This file was ported from Lean 3 source module data.prod.pprod
! leanprover-community/mathlib commit c4658a649d216f57e99621708b09dcb3dcccbd23
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathlib.Logic.Basic
/-!
# Extra facts about `pprod`
-/
open Function
variable {α β γ δ : Sort _}
namespace PProd
@[simp]
theorem mk.eta {p : PProd α β} : PProd.mk p.1 p.2 = p :=
PProd.casesOn p fun _ _ ↦ rfl
#align pprod.mk.eta PProd.mk.eta
@[simp]
theorem «forall» {p : PProd α β → Prop} : (∀ x, p x) ↔ ∀ a b, p ⟨a, b⟩ :=
⟨fun h a b ↦ h ⟨a, b⟩, fun h ⟨a, b⟩ ↦ h a b⟩
#align pprod.forall PProd.forall
@[simp]
theorem «exists» {p : PProd α β → Prop} : (∃ x, p x) ↔ ∃ a b, p ⟨a, b⟩ :=
⟨fun ⟨⟨a, b⟩, h⟩ ↦ ⟨a, b, h⟩, fun ⟨a, b, h⟩ ↦ ⟨⟨a, b⟩, h⟩⟩
#align pprod.exists PProd.exists
theorem forall' {p : α → β → Prop} : (∀ x : PProd α β, p x.1 x.2) ↔ ∀ a b, p a b :=
PProd.forall
#align pprod.forall' PProd.forall'
theorem exists' {p : α → β → Prop} : (∃ x : PProd α β, p x.1 x.2) ↔ ∃ a b, p a b :=
PProd.exists
#align pprod.exists' PProd.exists'
end PProd
theorem Function.Injective.pprod_map {f : α → β} {g : γ → δ} (hf : Injective f) (hg : Injective g) :
Injective (fun x ↦ ⟨f x.1, g x.2⟩ : PProd α γ → PProd β δ) := fun _ _ h ↦
have A := congr_arg PProd.fst h
have B := congr_arg PProd.snd h
congr_arg₂ PProd.mk (hf A) (hg B)
#align function.injective.pprod_map Function.Injective.pprod_map
|
module Cats.Category.Discrete {li} (I : Set li) where
open import Data.Unit using (⊤)
open import Level
open import Cats.Category.Base
open import Cats.Functor using (Functor)
Obj : Set li
Obj = I
data _⇒_ : Obj → Obj → Set where
id : ∀ {A} → A ⇒ A
_∘_ : ∀ {A B C} → B ⇒ C → A ⇒ B → A ⇒ C
id ∘ id = id
Discrete : Category li zero zero
Discrete = record
{ Obj = Obj
; _⇒_ = _⇒_
; _≈_ = λ _ _ → ⊤
; id = id
; _∘_ = _∘_
; equiv = _
; ∘-resp = _
; id-r = _
; id-l = _
; assoc = _
}
functor : ∀ {lo la l≈} {C : Category lo la l≈}
→ (I → Category.Obj C)
→ Functor Discrete C
functor {C = C} f = record
{ fobj = f
; fmap = λ { id → C.id }
; fmap-resp = λ { {_} {_} {id} {id} _ → C.≈.refl }
; fmap-id = C.≈.refl
; fmap-∘ = λ { {f = id} {id} → C.id-l }
}
where
module C = Category C
|
[STATEMENT]
lemma set_integrableI_nonneg:
fixes f :: "'a \<Rightarrow> real"
assumes "set_borel_measurable M A f"
assumes "AE x in M. x \<in> A \<longrightarrow> 0 \<le> f x" "(\<integral>\<^sup>+x\<in>A. f x \<partial>M) < \<infinity>"
shows "set_integrable M A f"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. set_integrable M A f
[PROOF STEP]
unfolding set_integrable_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. integrable M (\<lambda>x. indicat_real A x *\<^sub>R f x)
[PROOF STEP]
proof (rule integrableI_nonneg)
[PROOF STATE]
proof (state)
goal (3 subgoals):
1. (\<lambda>x. indicat_real A x *\<^sub>R f x) \<in> borel_measurable M
2. AE x in M. 0 \<le> indicat_real A x *\<^sub>R f x
3. \<integral>\<^sup>+ x. ennreal (indicat_real A x *\<^sub>R f x) \<partial>M < \<infinity>
[PROOF STEP]
from assms
[PROOF STATE]
proof (chain)
picking this:
set_borel_measurable M A f
AE x\<in>A in M. 0 \<le> f x
\<integral>\<^sup>+x\<in>A. ennreal (f x)\<partial>M < \<infinity>
[PROOF STEP]
show "(\<lambda>x. indicator A x *\<^sub>R f x) \<in> borel_measurable M"
[PROOF STATE]
proof (prove)
using this:
set_borel_measurable M A f
AE x\<in>A in M. 0 \<le> f x
\<integral>\<^sup>+x\<in>A. ennreal (f x)\<partial>M < \<infinity>
goal (1 subgoal):
1. (\<lambda>x. indicat_real A x *\<^sub>R f x) \<in> borel_measurable M
[PROOF STEP]
by (simp add: set_borel_measurable_def)
[PROOF STATE]
proof (state)
this:
(\<lambda>x. indicat_real A x *\<^sub>R f x) \<in> borel_measurable M
goal (2 subgoals):
1. AE x in M. 0 \<le> indicat_real A x *\<^sub>R f x
2. \<integral>\<^sup>+ x. ennreal (indicat_real A x *\<^sub>R f x) \<partial>M < \<infinity>
[PROOF STEP]
from assms(2)
[PROOF STATE]
proof (chain)
picking this:
AE x\<in>A in M. 0 \<le> f x
[PROOF STEP]
show "AE x in M. 0 \<le> indicat_real A x *\<^sub>R f x"
[PROOF STATE]
proof (prove)
using this:
AE x\<in>A in M. 0 \<le> f x
goal (1 subgoal):
1. AE x in M. 0 \<le> indicat_real A x *\<^sub>R f x
[PROOF STEP]
by eventually_elim (auto simp: indicator_def)
[PROOF STATE]
proof (state)
this:
AE x in M. 0 \<le> indicat_real A x *\<^sub>R f x
goal (1 subgoal):
1. \<integral>\<^sup>+ x. ennreal (indicat_real A x *\<^sub>R f x) \<partial>M < \<infinity>
[PROOF STEP]
have "(\<integral>\<^sup>+x. ennreal (indicator A x *\<^sub>R f x) \<partial>M) = (\<integral>\<^sup>+x\<in>A. f x \<partial>M)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<integral>\<^sup>+ x. ennreal (indicat_real A x *\<^sub>R f x) \<partial>M = \<integral>\<^sup>+x\<in>A. ennreal (f x)\<partial>M
[PROOF STEP]
by (intro nn_integral_cong) (auto simp: indicator_def)
[PROOF STATE]
proof (state)
this:
\<integral>\<^sup>+ x. ennreal (indicat_real A x *\<^sub>R f x) \<partial>M = \<integral>\<^sup>+x\<in>A. ennreal (f x)\<partial>M
goal (1 subgoal):
1. \<integral>\<^sup>+ x. ennreal (indicat_real A x *\<^sub>R f x) \<partial>M < \<infinity>
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
\<integral>\<^sup>+ x. ennreal (indicat_real A x *\<^sub>R f x) \<partial>M = \<integral>\<^sup>+x\<in>A. ennreal (f x)\<partial>M
goal (1 subgoal):
1. \<integral>\<^sup>+ x. ennreal (indicat_real A x *\<^sub>R f x) \<partial>M < \<infinity>
[PROOF STEP]
have "\<dots> < \<infinity>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<integral>\<^sup>+x\<in>A. ennreal (f x)\<partial>M < \<infinity>
[PROOF STEP]
by fact
[PROOF STATE]
proof (state)
this:
\<integral>\<^sup>+x\<in>A. ennreal (f x)\<partial>M < \<infinity>
goal (1 subgoal):
1. \<integral>\<^sup>+ x. ennreal (indicat_real A x *\<^sub>R f x) \<partial>M < \<infinity>
[PROOF STEP]
finally
[PROOF STATE]
proof (chain)
picking this:
\<integral>\<^sup>+ x. ennreal (indicat_real A x *\<^sub>R f x) \<partial>M < \<infinity>
[PROOF STEP]
show "(\<integral>\<^sup>+x. ennreal (indicator A x *\<^sub>R f x) \<partial>M) < \<infinity>"
[PROOF STATE]
proof (prove)
using this:
\<integral>\<^sup>+ x. ennreal (indicat_real A x *\<^sub>R f x) \<partial>M < \<infinity>
goal (1 subgoal):
1. \<integral>\<^sup>+ x. ennreal (indicat_real A x *\<^sub>R f x) \<partial>M < \<infinity>
[PROOF STEP]
.
[PROOF STATE]
proof (state)
this:
\<integral>\<^sup>+ x. ennreal (indicat_real A x *\<^sub>R f x) \<partial>M < \<infinity>
goal:
No subgoals!
[PROOF STEP]
qed |
function test_memory_data_layer(backend::Backend, T, eps)
println("-- Testing Memory Data Layer on $(typeof(backend)){$T}...")
############################################################
# Prepare Data for Testing
############################################################
batch_size = 6
tensor_dim = abs(rand(Int)) % 6 + 1
data_dim = tuple(rand(1:6, tensor_dim)...)
println(" > $data_dim")
data = rand(T, data_dim..., 9)
mean_data = rand(T, data_dim..., 1)
mean_blob = make_blob(backend, mean_data)
############################################################
# Setup
############################################################
# batch size is determined by
layer = MemoryDataLayer(data = Array[data], tops = [:data], batch_size=batch_size,
transformers=[(:data, DataTransformers.SubMean(mean_blob=mean_blob))])
state = setup(backend, layer, Blob[], Blob[])
data_idx = map(x->1:x, data_dim)
layer_data = Array{eltype(data)}(tuple(data_dim..., batch_size))
data_aug = cat(tensor_dim+1, data, data)
data_aug .-= mean_data
forward(backend, state, Blob[])
copy!(layer_data, state.blobs[1])
@test all(-eps .< layer_data - data_aug[data_idx..., 1:1+batch_size-1] .< eps)
@test state.epoch == 0
forward(backend, state, Blob[])
copy!(layer_data, state.blobs[1])
@test all(-eps .< layer_data - data_aug[data_idx..., batch_size+1:2batch_size] .< eps)
@test state.epoch == 1
forward(backend, state, Blob[])
copy!(layer_data, state.blobs[1])
@test all(-eps .< layer_data - data_aug[data_idx..., 2batch_size+1:3batch_size] .< eps)
@test state.epoch == 2
shutdown(backend, state)
end
function test_memory_data_layer(backend::Backend)
test_memory_data_layer(backend, Float32, 1e-5)
test_memory_data_layer(backend, Float64, 1e-10)
end
if test_cpu
test_memory_data_layer(backend_cpu)
end
if test_gpu
test_memory_data_layer(backend_gpu)
end
|
open import Agda.Builtin.Equality
postulate
foo : (A : Set) → A ≡ A
helper : {W : Set} (A : Set) → W → W ≡ A → (A → Set) → Set
helper A w refl f = f w
bar : (A : Set) → A → Set
bar A a = let A≡A = foo A in helper A a (foo A) {!!} -- A≡A : A ≡ A
baz : (A : Set) → A → Set
baz A a = let A≡A = foo A in helper A a (foo A) λ a' → {!!} -- A≡A : a ≡ a
f : (A : Set) → A → Set → Set
f A x = let y = x in λ B → {!!} -- y : x
|
data Nat : Set where
Zero : Nat
Suc : Nat → Nat
{-# COMPILE AGDA2HS Nat #-}
Nat' = Nat
{-# COMPILE AGDA2HS Nat' #-}
myNat : Nat'
myNat = Suc (Suc Zero)
{-# COMPILE AGDA2HS myNat #-}
data List (a : Set) : Set where
Nil : List a
Cons : a → List a → List a
{-# COMPILE AGDA2HS List #-}
List' : Set → Set
List' a = List a
{-# COMPILE AGDA2HS List' #-}
NatList = List Nat
{-# COMPILE AGDA2HS NatList #-}
myListFun : List' Nat' → NatList
myListFun Nil = Nil
myListFun (Cons x xs) = Cons x (myListFun xs)
{-# COMPILE AGDA2HS myListFun #-}
ListList : Set → Set
ListList a = List (List a)
{-# COMPILE AGDA2HS ListList #-}
flatten : ∀ {a} → ListList a → List a
flatten Nil = Nil
flatten (Cons Nil xss) = flatten xss
flatten (Cons (Cons x xs) xss) = Cons x (flatten (Cons xs xss))
{-# COMPILE AGDA2HS flatten #-}
|
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "PETDynamicView.h"
#include "mitkWorkbenchUtil.h"
#include "mitkAterialInputFunctionGenerator.h"
#include "mitkOneTissueCompartmentModelFactory.h"
#include "mitkOneTissueCompartmentModelParameterizer.h"
#include "mitkExtendedOneTissueCompartmentModelFactory.h"
#include "mitkExtendedOneTissueCompartmentModelParameterizer.h"
#include "mitkTwoTissueCompartmentFDGModelFactory.h"
#include "mitkTwoTissueCompartmentFDGModelParameterizer.h"
#include "mitkTwoTissueCompartmentModelFactory.h"
#include "mitkTwoTissueCompartmentModelParameterizer.h"
#include "mitkNumericTwoTissueCompartmentModelFactory.h"
#include "mitkNumericTwoTissueCompartmentModelParameterizer.h"
#include <mitkNodePredicateAnd.h>
#include <mitkNodePredicateNot.h>
#include <mitkNodePredicateProperty.h>
#include <mitkNodePredicateDataType.h>
#include <mitkNodePredicateOr.h>
#include <mitkPixelBasedParameterFitImageGenerator.h>
#include <mitkROIBasedParameterFitImageGenerator.h>
#include <mitkLevenbergMarquardtModelFitFunctor.h>
#include <mitkSumOfSquaredDifferencesFitCostFunction.h>
#include <mitkSquaredDifferencesFitCostFunction.h>
#include <mitkChiSquareFitCostFunction.h>
#include <mitkReducedChiSquareFitCostFunction.h>
#include <mitkSimpleBarrierConstraintChecker.h>
#include <mitkModelFitResultHelper.h>
#include <mitkImageTimeSelector.h>
#include <mitkMaskedDynamicImageStatisticsGenerator.h>
#include <mitkExtractTimeGrid.h>
#include <mitkInitialParameterizationDelegateBase.h>
#include <QMessageBox>
#include <QThreadPool>
#include <QmitkDataStorageComboBox.h>
#include <QFileDialog>
#include <boost/tokenizer.hpp>
// Includes for image casting between ITK and MITK
#include <mitkImage.h>
#include "mitkImageCast.h"
#include "mitkITKImageImport.h"
#include <itkImage.h>
#include <itkImageRegionIterator.h>
#include <iostream>
const std::string PETDynamicView::VIEW_ID = "org.mitk.gui.qt.pharmacokinetics.pet";
inline double convertToDouble(const std::string& data)
{
std::istringstream stepStream(data);
double value = 0.0;
stepStream >> value;
return value;
}
void PETDynamicView::SetFocus()
{
m_Controls.btnModelling->setFocus();
}
void PETDynamicView::CreateQtPartControl(QWidget* parent)
{
m_Controls.setupUi(parent);
m_Controls.btnModelling->setEnabled(false);
m_Controls.errorMessageLabel->hide();
this->InitModelComboBox();
connect(m_Controls.btnModelling, SIGNAL(clicked()), this, SLOT(OnModellingButtonClicked()));
connect(m_Controls.comboModel, SIGNAL(currentIndexChanged(int)), this, SLOT(OnModellSet(int)));
connect(m_Controls.radioPixelBased, SIGNAL(toggled(bool)), this, SLOT(UpdateGUIControls()));
//AIF setting
m_Controls.groupAIF->hide();
m_Controls.btnAIFFile->setEnabled(false);
m_Controls.btnAIFFile->setEnabled(false);
m_Controls.radioAIFImage->setChecked(true);
m_Controls.comboAIFMask->SetDataStorage(this->GetDataStorage());
m_Controls.comboAIFMask->SetPredicate(m_IsMaskPredicate);
m_Controls.comboAIFMask->setVisible(true);
m_Controls.comboAIFMask->setEnabled(true);
m_Controls.comboAIFImage->SetDataStorage(this->GetDataStorage());
m_Controls.comboAIFImage->SetPredicate(m_IsNoMaskImagePredicate);
m_Controls.comboAIFImage->setEnabled(false);
m_Controls.checkDedicatedAIFImage->setEnabled(true);
m_Controls.HCLSpinBox->setValue(0.0);
connect(m_Controls.radioAIFImage, SIGNAL(toggled(bool)), m_Controls.comboAIFMask,
SLOT(setVisible(bool)));
connect(m_Controls.radioAIFImage, SIGNAL(toggled(bool)), m_Controls.labelAIFMask,
SLOT(setVisible(bool)));
connect(m_Controls.radioAIFImage, SIGNAL(toggled(bool)), m_Controls.checkDedicatedAIFImage,
SLOT(setVisible(bool)));
connect(m_Controls.radioAIFImage, SIGNAL(toggled(bool)), m_Controls.comboAIFMask,
SLOT(setEnabled(bool)));
connect(m_Controls.radioAIFImage, SIGNAL(toggled(bool)), m_Controls.checkDedicatedAIFImage,
SLOT(setEnabled(bool)));
connect(m_Controls.radioAIFImage, SIGNAL(toggled(bool)), m_Controls.checkDedicatedAIFImage,
SLOT(setVisible(bool)));
connect(m_Controls.radioAIFImage, SIGNAL(toggled(bool)), m_Controls.comboAIFImage,
SLOT(setVisible(bool)));
connect(m_Controls.checkDedicatedAIFImage, SIGNAL(toggled(bool)), m_Controls.comboAIFImage,
SLOT(setEnabled(bool)));
connect(m_Controls.radioAIFImage, SIGNAL(toggled(bool)), this, SLOT(UpdateGUIControls()));
connect(m_Controls.radioAIFFile, SIGNAL(toggled(bool)), m_Controls.btnAIFFile,
SLOT(setEnabled(bool)));
connect(m_Controls.radioAIFFile, SIGNAL(toggled(bool)), m_Controls.aifFilePath,
SLOT(setEnabled(bool)));
connect(m_Controls.radioAIFFile, SIGNAL(toggled(bool)), this, SLOT(UpdateGUIControls()));
connect(m_Controls.btnAIFFile, SIGNAL(clicked()), this, SLOT(LoadAIFfromFile()));
//Model fit configuration
m_Controls.groupBox_FitConfiguration->hide();
m_Controls.checkBox_Constraints->setEnabled(false);
m_Controls.constraintManager->setEnabled(false);
m_Controls.initialValuesManager->setEnabled(false);
m_Controls.initialValuesManager->setDataStorage(this->GetDataStorage());
connect(m_Controls.radioButton_StartParameters, SIGNAL(toggled(bool)), this,
SLOT(UpdateGUIControls()));
connect(m_Controls.checkBox_Constraints, SIGNAL(toggled(bool)), this,
SLOT(UpdateGUIControls()));
connect(m_Controls.initialValuesManager, SIGNAL(initialValuesChanged(void)), this, SLOT(UpdateGUIControls()));
connect(m_Controls.radioButton_StartParameters, SIGNAL(toggled(bool)),
m_Controls.initialValuesManager,
SLOT(setEnabled(bool)));
connect(m_Controls.checkBox_Constraints, SIGNAL(toggled(bool)), m_Controls.constraintManager,
SLOT(setEnabled(bool)));
connect(m_Controls.checkBox_Constraints, SIGNAL(toggled(bool)), m_Controls.constraintManager,
SLOT(setVisible(bool)));
UpdateGUIControls();
}
void PETDynamicView::UpdateGUIControls()
{
m_Controls.lineFitName->setPlaceholderText(QString::fromStdString(this->GetDefaultFitName()));
m_Controls.lineFitName->setEnabled(!m_FittingInProgress);
m_Controls.checkBox_Constraints->setEnabled(m_modelConstraints.IsNotNull());
bool is1TCMFactory = dynamic_cast<mitk::OneTissueCompartmentModelFactory*>
(m_selectedModelFactory.GetPointer()) != nullptr;
bool isExt1TCMFactory = dynamic_cast<mitk::ExtendedOneTissueCompartmentModelFactory*>
(m_selectedModelFactory.GetPointer()) != nullptr;
bool isFDGCMFactory = dynamic_cast<mitk::TwoTissueCompartmentFDGModelFactory*>
(m_selectedModelFactory.GetPointer()) != nullptr;
bool is2TCMFactory = dynamic_cast<mitk::TwoTissueCompartmentModelFactory*>
(m_selectedModelFactory.GetPointer()) != nullptr ||
dynamic_cast<mitk::NumericTwoTissueCompartmentModelFactory*>
(m_selectedModelFactory.GetPointer()) != nullptr;
m_Controls.groupAIF->setVisible(is1TCMFactory || isExt1TCMFactory || isFDGCMFactory || is2TCMFactory);
m_Controls.groupBox_FitConfiguration->setVisible(m_selectedModelFactory);
m_Controls.groupBox->setEnabled(!m_FittingInProgress);
m_Controls.comboModel->setEnabled(!m_FittingInProgress);
m_Controls.groupAIF->setEnabled(!m_FittingInProgress);
m_Controls.groupBox_FitConfiguration->setEnabled(!m_FittingInProgress);
m_Controls.radioROIbased->setEnabled(m_selectedMask.IsNotNull());
m_Controls.btnModelling->setEnabled(m_selectedImage.IsNotNull()
&& m_selectedModelFactory.IsNotNull() && !m_FittingInProgress && CheckModelSettings());
}
//void PETDynamicView::OnModelSettingChanged()
//{
// bool ok = m_selectedImage.IsNotNull() && m_selectedModelFactory.IsNotNull() && !m_FittingInProgress && CheckModelSettings();
// m_Controls.btnModelling->setEnabled(ok);
//}
void PETDynamicView::OnModellSet(int index)
{
m_selectedModelFactory = nullptr;
if (index > 0)
{
if (static_cast<ModelFactoryStackType::size_type>(index) <= m_FactoryStack.size() )
{
m_selectedModelFactory = m_FactoryStack[index - 1];
}
else
{
MITK_WARN << "Invalid model index. Index outside of the factory stack. Factory stack size: "<< m_FactoryStack.size() << "; invalid index: "<< index;
}
}
if (m_selectedModelFactory)
{
this->m_modelConstraints = dynamic_cast<mitk::SimpleBarrierConstraintChecker*>
(m_selectedModelFactory->CreateDefaultConstraints().GetPointer());
m_Controls.initialValuesManager->setInitialValues(m_selectedModelFactory->GetParameterNames(),
m_selectedModelFactory->GetDefaultInitialParameterization());
if (this->m_modelConstraints.IsNull())
{
this->m_modelConstraints = mitk::SimpleBarrierConstraintChecker::New();
}
m_Controls.constraintManager->setChecker(this->m_modelConstraints,
this->m_selectedModelFactory->GetParameterNames());
}
m_Controls.checkBox_Constraints->setEnabled(m_modelConstraints.IsNotNull());
UpdateGUIControls();
}
std::string PETDynamicView::GetFitName() const
{
std::string fitName = m_Controls.lineFitName->text().toStdString();
if (fitName.empty())
{
fitName = m_Controls.lineFitName->placeholderText().toStdString();
}
return fitName;
}
std::string PETDynamicView::GetDefaultFitName() const
{
std::string defaultName = "undefined model";
if (this->m_selectedModelFactory.IsNotNull())
{
defaultName = this->m_selectedModelFactory->GetClassID();
}
if (this->m_Controls.radioPixelBased->isChecked())
{
defaultName += "_pixel";
}
else
{
defaultName += "_roi";
}
return defaultName;
}
void PETDynamicView::OnModellingButtonClicked()
{
//check if all static parameters set
if (m_selectedModelFactory.IsNotNull() && CheckModelSettings())
{
mitk::ParameterFitImageGeneratorBase::Pointer generator = nullptr;
mitk::modelFit::ModelFitInfo::Pointer fitSession = nullptr;
bool isOTCFactory = dynamic_cast<mitk::OneTissueCompartmentModelFactory*>
(m_selectedModelFactory.GetPointer()) != nullptr;
bool isextOTCFactory = dynamic_cast<mitk::ExtendedOneTissueCompartmentModelFactory*>
(m_selectedModelFactory.GetPointer()) != nullptr;
bool isFDGFactory = dynamic_cast<mitk::TwoTissueCompartmentFDGModelFactory*>
(m_selectedModelFactory.GetPointer()) != nullptr;
bool isTTCFactory = dynamic_cast<mitk::TwoTissueCompartmentModelFactory*>
(m_selectedModelFactory.GetPointer()) != nullptr;
bool isNumTTCFactory = dynamic_cast<mitk::NumericTwoTissueCompartmentModelFactory*>
(m_selectedModelFactory.GetPointer()) != nullptr;
if (isOTCFactory)
{
if (this->m_Controls.radioPixelBased->isChecked())
{
GenerateModelFit_PixelBased<mitk::OneTissueCompartmentModelParameterizer>(fitSession, generator);
}
else
{
GenerateModelFit_ROIBased<mitk::OneTissueCompartmentModelParameterizer>(fitSession, generator);
}
}
else if (isextOTCFactory)
{
if (this->m_Controls.radioPixelBased->isChecked())
{
GenerateModelFit_PixelBased<mitk::ExtendedOneTissueCompartmentModelParameterizer>(fitSession, generator);
}
else
{
GenerateModelFit_ROIBased<mitk::ExtendedOneTissueCompartmentModelParameterizer>(fitSession, generator);
}
}
else if (isFDGFactory)
{
if (this->m_Controls.radioPixelBased->isChecked())
{
GenerateModelFit_PixelBased<mitk::TwoTissueCompartmentFDGModelParameterizer>(fitSession, generator);
}
else
{
GenerateModelFit_ROIBased<mitk::TwoTissueCompartmentFDGModelParameterizer>(fitSession, generator);
}
}
else if (isTTCFactory)
{
if (this->m_Controls.radioPixelBased->isChecked())
{
GenerateModelFit_PixelBased<mitk::TwoTissueCompartmentModelParameterizer>(fitSession, generator);
}
else
{
GenerateModelFit_ROIBased<mitk::TwoTissueCompartmentModelParameterizer>(fitSession, generator);
}
}
else if (isNumTTCFactory)
{
if (this->m_Controls.radioPixelBased->isChecked())
{
GenerateModelFit_PixelBased<mitk::NumericTwoTissueCompartmentModelParameterizer>(fitSession,
generator);
}
else
{
GenerateModelFit_ROIBased<mitk::NumericTwoTissueCompartmentModelParameterizer>(fitSession,
generator);
}
}
//add other models with else if
if (generator.IsNotNull() && fitSession.IsNotNull())
{
m_FittingInProgress = true;
DoFit(fitSession, generator);
}
else
{
QMessageBox box;
box.setText("Fitting error!");
box.setInformativeText("Could not establish fitting job. Error when setting ab generator, model parameterizer or session info.");
box.setStandardButtons(QMessageBox::Ok);
box.setDefaultButton(QMessageBox::Ok);
box.setIcon(QMessageBox::Warning);
box.exec();
}
}
else
{
QMessageBox box;
box.setText("Static parameters for model are not set!");
box.setInformativeText("Some static parameters, that are needed for calculation are not set and equal to zero. Modeling not possible");
box.setStandardButtons(QMessageBox::Ok);
box.setDefaultButton(QMessageBox::Ok);
box.setIcon(QMessageBox::Warning);
box.exec();
}
}
void PETDynamicView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*source*/,
const QList<mitk::DataNode::Pointer>& selectedNodes)
{
m_selectedMaskNode = nullptr;
m_selectedMask = nullptr;
m_Controls.errorMessageLabel->setText("");
m_Controls.masklabel->setText("No (valid) mask selected.");
m_Controls.timeserieslabel->setText("No (valid) series selected.");
QList<mitk::DataNode::Pointer> nodes = selectedNodes;
if (nodes.size() > 0 && this->m_IsNoMaskImagePredicate->CheckNode(nodes.front()))
{
this->m_selectedNode = nodes.front();
auto selectedImage = dynamic_cast<mitk::Image*>(this->m_selectedNode->GetData());
m_Controls.timeserieslabel->setText((this->m_selectedNode->GetName()).c_str());
if (selectedImage != this->m_selectedImage)
{
if (selectedImage)
{
this->m_Controls.initialValuesManager->setReferenceImageGeometry(selectedImage->GetGeometry());
}
else
{
this->m_Controls.initialValuesManager->setReferenceImageGeometry(nullptr);
}
}
this->m_selectedImage = selectedImage;
nodes.pop_front();
}
else
{
this->m_selectedNode = nullptr;
this->m_selectedImage = nullptr;
this->m_Controls.initialValuesManager->setReferenceImageGeometry(nullptr);
}
if (nodes.size() > 0 && this->m_IsMaskPredicate->CheckNode(nodes.front()))
{
this->m_selectedMaskNode = nodes.front();
this->m_selectedMask = dynamic_cast<mitk::Image*>(this->m_selectedMaskNode->GetData());
if (this->m_selectedMask->GetTimeSteps() > 1)
{
MITK_INFO <<
"Selected mask has multiple timesteps. Only use first timestep to mask model fit. Mask name: " <<
m_selectedMaskNode->GetName();
mitk::ImageTimeSelector::Pointer maskedImageTimeSelector = mitk::ImageTimeSelector::New();
maskedImageTimeSelector->SetInput(this->m_selectedMask);
maskedImageTimeSelector->SetTimeNr(0);
maskedImageTimeSelector->UpdateLargestPossibleRegion();
this->m_selectedMask = maskedImageTimeSelector->GetOutput();
}
m_Controls.masklabel->setText((this->m_selectedMaskNode->GetName()).c_str());
}
if (m_selectedMask.IsNull())
{
this->m_Controls.radioPixelBased->setChecked(true);
}
m_Controls.errorMessageLabel->show();
UpdateGUIControls();
}
bool PETDynamicView::CheckModelSettings() const
{
bool ok = true;
//check wether any model is set at all. Otherwise exit with false
if (m_selectedModelFactory.IsNotNull())
{
bool isOTCFactory = dynamic_cast<mitk::OneTissueCompartmentModelFactory*>
(m_selectedModelFactory.GetPointer()) != nullptr;
bool isextOTCFactory = dynamic_cast<mitk::ExtendedOneTissueCompartmentModelFactory*>
(m_selectedModelFactory.GetPointer()) != nullptr;
bool isFDGFactory = dynamic_cast<mitk::TwoTissueCompartmentFDGModelFactory*>
(m_selectedModelFactory.GetPointer()) != nullptr;
bool isTTCFactory = dynamic_cast<mitk::TwoTissueCompartmentModelFactory*>
(m_selectedModelFactory.GetPointer()) != nullptr;
bool isNumTTCFactory = dynamic_cast<mitk::NumericTwoTissueCompartmentModelFactory*>
(m_selectedModelFactory.GetPointer()) != nullptr;
if (isOTCFactory || isextOTCFactory || isFDGFactory || isTTCFactory || isNumTTCFactory)
{
if (this->m_Controls.radioAIFImage->isChecked())
{
ok = ok && m_Controls.comboAIFMask->GetSelectedNode().IsNotNull();
if (this->m_Controls.checkDedicatedAIFImage->isChecked())
{
ok = ok && m_Controls.comboAIFImage->GetSelectedNode().IsNotNull();
}
}
else if (this->m_Controls.radioAIFFile->isChecked())
{
ok = ok && (this->AIFinputGrid.size() != 0) && (this->AIFinputFunction.size() != 0);
}
else
{
ok = false;
}
}
//add other models as else if and check wether all needed static parameters are set
else
{
ok = false;
}
if (this->m_Controls.radioButton_StartParameters->isChecked() && !this->m_Controls.initialValuesManager->hasValidInitialValues())
{
std::string warning = "Warning. Invalid start parameters. At least one parameter as an invalid image setting as source.";
MITK_ERROR << warning;
m_Controls.infoBox->append(QString("<font color='red'><b>") + QString::fromStdString(warning) + QString("</b></font>"));
ok = false;
};
}
else
{
ok = false;
}
return ok;
}
void PETDynamicView::ConfigureInitialParametersOfParameterizer(mitk::ModelParameterizerBase*
parameterizer) const
{
if (m_Controls.radioButton_StartParameters->isChecked())
{
//use user defined initial parameters
mitk::InitialParameterizationDelegateBase::Pointer paramDelegate = m_Controls.initialValuesManager->getInitialParametrizationDelegate();
parameterizer->SetInitialParameterizationDelegate(paramDelegate);
}
}
template <typename TParameterizer>
void PETDynamicView::GenerateModelFit_PixelBased(
mitk::modelFit::ModelFitInfo::Pointer& modelFitInfo,
mitk::ParameterFitImageGeneratorBase::Pointer& generator)
{
mitk::PixelBasedParameterFitImageGenerator::Pointer fitGenerator =
mitk::PixelBasedParameterFitImageGenerator::New();
typename TParameterizer::Pointer modelParameterizer =
TParameterizer::New();
mitk::AIFBasedModelBase::AterialInputFunctionType aif;
mitk::AIFBasedModelBase::TimeGridType aifTimeGrid;
GetAIF(aif, aifTimeGrid);
//Model configuration (static parameters) can be done now
modelParameterizer->SetAIF(aif);
modelParameterizer->SetAIFTimeGrid(aifTimeGrid);
this->ConfigureInitialParametersOfParameterizer(modelParameterizer);
//Specify fitting strategy and criterion parameters
mitk::ModelFitFunctorBase::Pointer fitFunctor = CreateDefaultFitFunctor(modelParameterizer);
//Parametrize fit generator
fitGenerator->SetModelParameterizer(modelParameterizer);
std::string roiUID = "";
if (m_selectedMask.IsNotNull())
{
fitGenerator->SetMask(m_selectedMask);
roiUID = m_selectedMask->GetUID();
}
fitGenerator->SetDynamicImage(this->m_selectedImage);
fitGenerator->SetFitFunctor(fitFunctor);
generator = fitGenerator.GetPointer();
//Create model info
modelFitInfo = mitk::modelFit::CreateFitInfoFromModelParameterizer(modelParameterizer,
m_selectedNode->GetData(), mitk::ModelFitConstants::FIT_TYPE_VALUE_PIXELBASED(), this->GetFitName(), roiUID);
mitk::ScalarListLookupTable::ValueType infoSignal;
for (mitk::AIFBasedModelBase::AterialInputFunctionType::const_iterator pos = aif.begin();
pos != aif.end(); ++pos)
{
infoSignal.push_back(*pos);
}
modelFitInfo->inputData.SetTableValue("AIF", infoSignal);
}
template <typename TParameterizer>
void PETDynamicView::GenerateModelFit_ROIBased(
mitk::modelFit::ModelFitInfo::Pointer& modelFitInfo,
mitk::ParameterFitImageGeneratorBase::Pointer& generator)
{
mitk::ROIBasedParameterFitImageGenerator::Pointer fitGenerator =
mitk::ROIBasedParameterFitImageGenerator::New();
typename TParameterizer::Pointer modelParameterizer =
TParameterizer::New();
//Compute AIF
mitk::AterialInputFunctionGenerator::Pointer aifGenerator =
mitk::AterialInputFunctionGenerator::New();
aifGenerator->SetDynamicImage(this->m_selectedImage);
aifGenerator->SetMask(this->m_selectedAIFMask);
mitk::AIFBasedModelBase::AterialInputFunctionType aif = aifGenerator->GetAterialInputFunction();
mitk::AIFBasedModelBase::TimeGridType aifTimeGrid = aifGenerator->GetAterialInputFunctionTimeGrid();
//Model configuration (static parameters) can be done now
modelParameterizer->SetAIF(aif);
modelParameterizer->SetAIFTimeGrid(aifTimeGrid);
this->ConfigureInitialParametersOfParameterizer(modelParameterizer);
//Compute ROI signal
mitk::MaskedDynamicImageStatisticsGenerator::Pointer signalGenerator =
mitk::MaskedDynamicImageStatisticsGenerator::New();
signalGenerator->SetMask(m_selectedMask);
signalGenerator->SetDynamicImage(m_selectedImage);
signalGenerator->Generate();
mitk::MaskedDynamicImageStatisticsGenerator::ResultType roiSignal = signalGenerator->GetMean();
//Specify fitting strategy and criterion parameters
mitk::ModelFitFunctorBase::Pointer fitFunctor = CreateDefaultFitFunctor(modelParameterizer);
//Parametrize fit generator
fitGenerator->SetModelParameterizer(modelParameterizer);
fitGenerator->SetMask(m_selectedMask);
fitGenerator->SetFitFunctor(fitFunctor);
fitGenerator->SetSignal(roiSignal);
fitGenerator->SetTimeGrid(mitk::ExtractTimeGrid(m_selectedImage));
generator = fitGenerator.GetPointer();
std::string roiUID = "";
if (m_selectedMask.IsNotNull())
{
roiUID = m_selectedMask->GetUID();
}
//Create model info
modelFitInfo = mitk::modelFit::CreateFitInfoFromModelParameterizer(modelParameterizer,
m_selectedNode->GetData(), mitk::ModelFitConstants::FIT_TYPE_VALUE_ROIBASED(), this->GetFitName(), roiUID);
mitk::ScalarListLookupTable::ValueType infoSignal;
for (mitk::MaskedDynamicImageStatisticsGenerator::ResultType::const_iterator pos =
roiSignal.begin(); pos != roiSignal.end(); ++pos)
{
infoSignal.push_back(*pos);
}
modelFitInfo->inputData.SetTableValue("ROI", infoSignal);
infoSignal.clear();
for (mitk::AIFBasedModelBase::AterialInputFunctionType::const_iterator pos = aif.begin();
pos != aif.end(); ++pos)
{
infoSignal.push_back(*pos);
}
modelFitInfo->inputData.SetTableValue("AIF", infoSignal);
}
void PETDynamicView::DoFit(const mitk::modelFit::ModelFitInfo* fitSession,
mitk::ParameterFitImageGeneratorBase* generator)
{
std::stringstream message;
message << "<font color='green'>" << "Fitting Data Set . . ." << "</font>";
m_Controls.errorMessageLabel->setText(message.str().c_str());
m_Controls.errorMessageLabel->show();
/////////////////////////
//create job and put it into the thread pool
ParameterFitBackgroundJob* pJob = new ParameterFitBackgroundJob(generator, fitSession,
this->m_selectedNode);
pJob->setAutoDelete(true);
connect(pJob, SIGNAL(Error(QString)), this, SLOT(OnJobError(QString)));
connect(pJob, SIGNAL(Finished()), this, SLOT(OnJobFinished()));
connect(pJob, SIGNAL(ResultsAreAvailable(mitk::modelFit::ModelFitResultNodeVectorType,
const ParameterFitBackgroundJob*)), this,
SLOT(OnJobResultsAreAvailable(mitk::modelFit::ModelFitResultNodeVectorType,
const ParameterFitBackgroundJob*)), Qt::BlockingQueuedConnection);
connect(pJob, SIGNAL(JobProgress(double)), this, SLOT(OnJobProgress(double)));
connect(pJob, SIGNAL(JobStatusChanged(QString)), this, SLOT(OnJobStatusChanged(QString)));
QThreadPool* threadPool = QThreadPool::globalInstance();
threadPool->start(pJob);
}
PETDynamicView::PETDynamicView() : m_FittingInProgress(false)
{
m_selectedImage = nullptr;
m_selectedMask = nullptr;
mitk::ModelFactoryBase::Pointer factory =
mitk::OneTissueCompartmentModelFactory::New().GetPointer();
m_FactoryStack.push_back(factory);
factory = mitk::ExtendedOneTissueCompartmentModelFactory::New().GetPointer();
m_FactoryStack.push_back(factory);
factory = mitk::TwoTissueCompartmentModelFactory::New().GetPointer();
m_FactoryStack.push_back(factory);
factory = mitk::TwoTissueCompartmentFDGModelFactory::New().GetPointer();
m_FactoryStack.push_back(factory);
factory = mitk::NumericTwoTissueCompartmentModelFactory::New().GetPointer();
m_FactoryStack.push_back(factory);
mitk::NodePredicateDataType::Pointer isLabelSet = mitk::NodePredicateDataType::New("LabelSetImage");
mitk::NodePredicateDataType::Pointer isImage = mitk::NodePredicateDataType::New("Image");
mitk::NodePredicateProperty::Pointer isBinary = mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(true));
mitk::NodePredicateAnd::Pointer isLegacyMask = mitk::NodePredicateAnd::New(isImage, isBinary);
mitk::NodePredicateOr::Pointer isMask = mitk::NodePredicateOr::New(isLegacyMask, isLabelSet);
mitk::NodePredicateAnd::Pointer isNoMask = mitk::NodePredicateAnd::New(isImage, mitk::NodePredicateNot::New(isMask));
this->m_IsMaskPredicate = mitk::NodePredicateAnd::New(isMask, mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))).GetPointer();
this->m_IsNoMaskImagePredicate = mitk::NodePredicateAnd::New(isNoMask, mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))).GetPointer();
}
void PETDynamicView::OnJobFinished()
{
this->m_Controls.infoBox->append(QString("Fitting finished"));
this->m_FittingInProgress = false;
};
void PETDynamicView::OnJobError(QString err)
{
MITK_ERROR << err.toStdString().c_str();
m_Controls.infoBox->append(QString("<font color='red'><b>") + err + QString("</b></font>"));
};
void PETDynamicView::OnJobResultsAreAvailable(mitk::modelFit::ModelFitResultNodeVectorType results,
const ParameterFitBackgroundJob* pJob)
{
//Store the resulting parameter fit image via convenience helper function in data storage
//(handles the correct generation of the nodes and their properties)
mitk::modelFit::StoreResultsInDataStorage(this->GetDataStorage(), results, pJob->GetParentNode());
m_Controls.errorMessageLabel->setText("");
m_Controls.errorMessageLabel->hide();
};
void PETDynamicView::OnJobProgress(double progress)
{
QString report = QString("Progress. ") + QString::number(progress);
this->m_Controls.infoBox->append(report);
};
void PETDynamicView::OnJobStatusChanged(QString info)
{
this->m_Controls.infoBox->append(info);
}
void PETDynamicView::InitModelComboBox() const
{
this->m_Controls.comboModel->clear();
this->m_Controls.comboModel->addItem(tr("No model selected"));
for (ModelFactoryStackType::const_iterator pos = m_FactoryStack.begin();
pos != m_FactoryStack.end(); ++pos)
{
this->m_Controls.comboModel->addItem(QString::fromStdString((*pos)->GetClassID()));
}
this->m_Controls.comboModel->setCurrentIndex(0);
};
mitk::ModelFitFunctorBase::Pointer PETDynamicView::CreateDefaultFitFunctor(
const mitk::ModelParameterizerBase* parameterizer) const
{
mitk::LevenbergMarquardtModelFitFunctor::Pointer fitFunctor =
mitk::LevenbergMarquardtModelFitFunctor::New();
mitk::SumOfSquaredDifferencesFitCostFunction::Pointer evaluation =
mitk::SumOfSquaredDifferencesFitCostFunction::New();
fitFunctor->RegisterEvaluationParameter("sum_diff^2", evaluation);
mitk::ChiSquareFitCostFunction::Pointer chi2 =
mitk::ChiSquareFitCostFunction::New();
fitFunctor->RegisterEvaluationParameter("Chi^2", chi2);
mitk::ReducedChiSquareFitCostFunction::Pointer redchi2 =
mitk::ReducedChiSquareFitCostFunction::New();
fitFunctor->RegisterEvaluationParameter("redChi^2", redchi2);
if (m_Controls.checkBox_Constraints->isChecked())
{
fitFunctor->SetConstraintChecker(m_modelConstraints);
}
mitk::ModelBase::Pointer refModel = parameterizer->GenerateParameterizedModel();
::itk::LevenbergMarquardtOptimizer::ScalesType scales;
scales.SetSize(refModel->GetNumberOfParameters());
scales.Fill(1.0);
fitFunctor->SetScales(scales);
return fitFunctor.GetPointer();
}
void PETDynamicView::GetAIF(mitk::AIFBasedModelBase::AterialInputFunctionType& aif,
mitk::AIFBasedModelBase::AterialInputFunctionType& aifTimeGrid)
{
if (this->m_Controls.radioAIFFile->isChecked())
{
aif.clear();
aifTimeGrid.clear();
aif.SetSize(AIFinputFunction.size());
aifTimeGrid.SetSize(AIFinputGrid.size());
aif.fill(0.0);
aifTimeGrid.fill(0.0);
itk::Array<double>::iterator aifPos = aif.begin();
for (std::vector<double>::const_iterator pos = AIFinputFunction.begin();
pos != AIFinputFunction.end(); ++pos, ++aifPos)
{
*aifPos = *pos;
}
itk::Array<double>::iterator gridPos = aifTimeGrid.begin();
for (std::vector<double>::const_iterator pos = AIFinputGrid.begin(); pos != AIFinputGrid.end();
++pos, ++gridPos)
{
*gridPos = *pos;
}
}
else if (this->m_Controls.radioAIFImage->isChecked())
{
aif.clear();
aifTimeGrid.clear();
mitk::AterialInputFunctionGenerator::Pointer aifGenerator =
mitk::AterialInputFunctionGenerator::New();
//Hematocrit level
aifGenerator->SetHCL(this->m_Controls.HCLSpinBox->value());
//mask settings
this->m_selectedAIFMaskNode = m_Controls.comboAIFMask->GetSelectedNode();
this->m_selectedAIFMask = dynamic_cast<mitk::Image*>(this->m_selectedAIFMaskNode->GetData());
if (this->m_selectedAIFMask->GetTimeSteps() > 1)
{
MITK_INFO <<
"Selected AIF mask has multiple timesteps. Only use first timestep to mask model fit. AIF Mask name: "
<<
m_selectedAIFMaskNode->GetName() ;
mitk::ImageTimeSelector::Pointer maskedImageTimeSelector = mitk::ImageTimeSelector::New();
maskedImageTimeSelector->SetInput(this->m_selectedAIFMask);
maskedImageTimeSelector->SetTimeNr(0);
maskedImageTimeSelector->UpdateLargestPossibleRegion();
this->m_selectedAIFMask = maskedImageTimeSelector->GetOutput();
}
if (this->m_selectedAIFMask.IsNotNull())
{
aifGenerator->SetMask(this->m_selectedAIFMask);
}
//image settings
if (this->m_Controls.checkDedicatedAIFImage->isChecked())
{
this->m_selectedAIFImageNode = m_Controls.comboAIFImage->GetSelectedNode();
this->m_selectedAIFImage = dynamic_cast<mitk::Image*>(this->m_selectedAIFImageNode->GetData());
}
else
{
this->m_selectedAIFImageNode = m_selectedNode;
this->m_selectedAIFImage = m_selectedImage;
}
aifGenerator->SetDynamicImage(this->m_selectedAIFImage);
aif = aifGenerator->GetAterialInputFunction();
aifTimeGrid = aifGenerator->GetAterialInputFunctionTimeGrid();
}
else
{
mitkThrow() << "Cannot generate AIF. View is in a invalide state. No AIF mode selected.";
}
}
void PETDynamicView::LoadAIFfromFile()
{
QFileDialog dialog;
dialog.setNameFilter(tr("Images (*.csv"));
QString fileName = dialog.getOpenFileName();
m_Controls.aifFilePath->setText(fileName);
std::string m_aifFilePath = fileName.toStdString();
//Read Input
typedef boost::tokenizer< boost::escaped_list_separator<char> > Tokenizer;
/////////////////////////////////////////////////////////////////////////////////////////////////
//AIF Data
std::ifstream in1(m_aifFilePath.c_str());
if (!in1.is_open())
{
m_Controls.errorMessageLabel->setText("Could not open AIF File!");
}
std::vector< std::string > vec1;
std::string line1;
while (getline(in1, line1))
{
Tokenizer tok(line1);
vec1.assign(tok.begin(), tok.end());
// if (vec1.size() < 3) continue;
this->AIFinputGrid.push_back(convertToDouble(vec1[0]));
this->AIFinputFunction.push_back(convertToDouble(vec1[1]));
}
}
|
Full of the true , the <unk> Hippocrene ,
|
[STATEMENT]
lemma comp_eqI:
assumes "t \<lesssim> v" and "u = v \\ t"
shows "t \<cdot> u = v"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. t \<cdot> u = v
[PROOF STEP]
by (metis assms prfx_decomp) |
export
AdadeltaOptimizer,
AdagradDAOptimizer,
AdagradOptimizer,
AdamOptimizer,
GradientDescentOptimizer,
RMSPropOptimizer,
minimize,
ScipyOptimizerInterface,
ScipyOptimizerMinimize,
BFGS!,
CustomOptimizer,
newton_raphson,
newton_raphson_with_grad,
NonlinearConstrainedProblem,
Optimize!,
optimize
#### Section 1: TensorFlow Optimizers ####
@doc raw"""
AdamOptimizer(learning_rate=1e-3;kwargs...)
Constructs an ADAM optimizer.
# Example
```julia
learning_rate = 1e-3
opt = AdamOptimizer(learning_rate).minimize(loss)
sess = Session(); init(sess)
for i = 1:1000
_, l = run(sess, [opt, loss])
@info "Iteration $i, loss = $l")
end
```
# Dynamical Learning Rate
We can also use dynamical learning rate. For example, if we want to use a learning rate
$l_t = \frac{1}{1+t}$, we have
```julia
learning_rate = placeholder(1.0)
opt = AdamOptimizer(learning_rate).minimize(loss)
sess = Session(); init(sess)
for i = 1:1000
_, l = run(sess, [opt, loss], lr = 1/(1+i))
@info "Iteration $i, loss = $l")
end
```
The usage of other optimizers such as [`GradientDescentOptimizer`](@ref), [`AdadeltaOptimizer`](@ref), and so on
is similar: we can just replace `AdamOptimizer` with the corresponding ones.
"""
function AdamOptimizer(learning_rate=1e-3;kwargs...)
return tf.train.AdamOptimizer(;learning_rate=learning_rate,kwargs...)
end
"""
AdadeltaOptimizer(learning_rate=1e-3;kwargs...)
See [`AdamOptimizer`](@ref) for descriptions.
"""
function AdadeltaOptimizer(learning_rate=1e-3;kwargs...)
return tf.train.AdadeltaOptimizer(;learning_rate=learning_rate,kwargs...)
end
"""
AdagradDAOptimizer(learning_rate=1e-3; global_step, kwargs...)
See [`AdamOptimizer`](@ref) for descriptions.
"""
function AdagradDAOptimizer(learning_rate=1e-3; global_step, kwargs...)
return tf.train.AdagradDAOptimizer(learning_rate, global_step;kwargs...)
end
"""
AdagradOptimizer(learning_rate=1e-3;kwargs...)
See [`AdamOptimizer`](@ref) for descriptions.
"""
function AdagradOptimizer(learning_rate=1e-3;kwargs...)
return tf.train.AdagradOptimizer(learning_rate;kwargs...)
end
"""
GradientDescentOptimizer(learning_rate=1e-3;kwargs...)
See [`AdamOptimizer`](@ref) for descriptions.
"""
function GradientDescentOptimizer(learning_rate=1e-3;kwargs...)
return tf.train.GradientDescentOptimizer(learning_rate;kwargs...)
end
"""
RMSPropOptimizer(learning_rate=1e-3;kwargs...)
See [`AdamOptimizer`](@ref) for descriptions.
"""
function RMSPropOptimizer(learning_rate=1e-3;kwargs...)
return tf.train.RMSPropOptimizer(learning_rate;kwargs...)
end
function minimize(o::PyObject, loss::PyObject; kwargs...)
o.minimize(loss;kwargs...)
end
"""
ScipyOptimizerInterface(loss; method="L-BFGS-B", options=Dict("maxiter"=> 15000, "ftol"=>1e-12, "gtol"=>1e-12), kwargs...)
A simple interface for Scipy Optimizer. See also [`ScipyOptimizerMinimize`](@ref) and [`BFGS!`](@ref).
"""
ScipyOptimizerInterface(loss; method="L-BFGS-B", options=Dict("maxiter"=> 15000, "ftol"=>1e-12, "gtol"=>1e-12), kwargs...) =
tf.contrib.opt.ScipyOptimizerInterface(loss; method = method, options=options, kwargs...)
"""
ScipyOptimizerMinimize(sess::PyObject, opt::PyObject; kwargs...)
Minimizes a scalar Tensor. Variables subject to optimization are updated in-place at the end of optimization.
Note that this method does not just return a minimization Op, unlike `minimize`; instead it actually performs minimization by executing commands to control a Session
https://www.tensorflow.org/api_docs/python/tf/contrib/opt/ScipyOptimizerInterface. See also [`ScipyOptimizerInterface`](@ref) and [`BFGS!`](@ref).
- feed_dict: A feed dict to be passed to calls to session.run.
- fetches: A list of Tensors to fetch and supply to loss_callback as positional arguments.
- step_callback: A function to be called at each optimization step; arguments are the current values of all optimization variables packed into a single vector.
- loss_callback: A function to be called every time the loss and gradients are computed, with evaluated fetches supplied as positional arguments.
- run_kwargs: kwargs to pass to session.run.
"""
function ScipyOptimizerMinimize(sess::PyObject, opt::PyObject; kwargs...)
opt.minimize(sess;kwargs...)
end
@doc raw"""
CustomOptimizer(opt::Function, name::String)
creates a custom optimizer with struct name `name`. For example, we can integrate `Optim.jl` with `ADCME` by
constructing a new optimizer
```julia
CustomOptimizer("Con") do f, df, c, dc, x0, x_L, x_U
opt = Opt(:LD_MMA, length(x0))
bd = zeros(length(x0)); bd[end-1:end] = [-Inf, 0.0]
opt.lower_bounds = bd
opt.xtol_rel = 1e-4
opt.min_objective = (x,g)->(g[:]= df(x); return f(x)[1])
inequality_constraint!(opt, (x,g)->( g[:]= dc(x);c(x)[1]), 1e-8)
(minf,minx,ret) = NLopt.optimize(opt, x0)
minx
end
```
Here
∘ `f`: a function that returns $f(x)$
∘ `df`: a function that returns $\nabla f(x)$
∘ `c`: a function that returns the constraints $c(x)$
∘ `dc`: a function that returns $\nabla c(x)$
∘ `x0`: initial guess
∘ `nineq`: number of inequality constraints
∘ `neq`: number of equality constraints
∘ `x_L`: lower bounds of optimizable variables
∘ `x_U`: upper bounds of optimizable variables
Then we can create an optimizer with
```
opt = Con(loss, inequalities=[c1], equalities=[c2])
```
To trigger the optimization, use
```
minimize(opt, sess)
```
Note thanks to the global variable scope of Julia, `step_callback`, `optimizer_kwargs` can actually
be passed from Julia environment directly.
"""
function CustomOptimizer(opt::Function)
name = "CustomOptimizer_"*randstring(16)
name = Symbol(name)
@eval begin
@pydef mutable struct $name <: tf.contrib.opt.ExternalOptimizerInterface
function _minimize(self; initial_val, loss_grad_func, equality_funcs,
equality_grad_funcs, inequality_funcs, inequality_grad_funcs,
packed_bounds, step_callback, optimizer_kwargs)
local x_L, x_U
x0 = initial_val # rename
nineq, neq = length(inequality_funcs), length(equality_funcs)
printstyled("[CustomOptimizer] Number of inequalities constraints = $nineq, Number of equality constraints = $neq\n", color=:blue)
nvar = Int64(sum([prod(self._vars[i].get_shape().as_list()) for i = 1:length(self._vars)]))
printstyled("[CustomOptimizer] Total number of variables = $nvar\n", color=:blue)
if isnothing(packed_bounds)
printstyled("[CustomOptimizer] No bounds provided, use (-∞, +∞) as default; or you need to provide bounds in the function CustomOptimizer\n", color=:blue)
x_L = -Inf*ones(nvar); x_U = Inf*ones(nvar)
else
x_L = vcat([x[1] for x in packed_bounds]...)
x_U = vcat([x[2] for x in packed_bounds]...)
end
ncon = nineq + neq
f(x) = loss_grad_func(x)[1]
df(x) = loss_grad_func(x)[2]
function c(x)
inequalities = vcat([inequality_funcs[i](x) for i = 1:nineq]...)
equalities = vcat([equality_funcs[i](x) for i=1:neq]...)
return Array{eltype(initial_val)}([inequalities;equalities])
end
function dc(x)
inequalities = [inequality_grad_funcs[i](x) for i = 1:nineq]
equalities = [equality_grad_funcs[i](x) for i=1:neq]
values = zeros(eltype(initial_val),nvar, ncon)
for idc = 1:nineq
values[:,idc] = inequalities[idc][1]
end
for idc = 1:neq
values[:,idc+nineq] = equalities[idc][1]
end
return values[:]
end
$opt(f, df, c, dc, x0, x_L, x_U)
end
end
return $name
end
end
@doc raw"""
BFGS!(sess::PyObject, loss::PyObject, max_iter::Int64=15000;
vars::Array{PyObject}=PyObject[], callback::Union{Function, Nothing}=nothing, method::String = "L-BFGS-B", kwargs...)
`BFGS!` is a simplified interface for **L-BFGS-B** optimizer. See also [`ScipyOptimizerInterface`](@ref).
`callback` is a callback function with signature
```julia
callback(vs::Array, iter::Int64, loss::Float64)
```
`vars` is an array consisting of tensors and its values will be the input to `vs`.
# Example 1
```julia
a = Variable(1.0)
loss = (a - 10.0)^2
sess = Session(); init(sess)
BFGS!(sess, loss)
```
# Example 2
```julia
θ1 = Variable(1.0)
θ2 = Variable(1.0)
loss = (θ1-1)^2 + (θ2-2)^2
cb = (vs, iter, loss)->begin
printstyled("[#iter $iter] θ1=$(vs[1]), θ2=$(vs[2]), loss=$loss\n", color=:green)
end
sess = Session(); init(sess)
cb(run(sess, [θ1, θ2]), 0, run(sess, loss))
BFGS!(sess, loss, 100; vars=[θ1, θ2], callback=cb)
```
# Example 3
Use `bounds` to specify upper and lower bound of a variable.
```julia
x = Variable(2.0)
loss = x^2
sess = Session(); init(sess)
BFGS!(sess, loss, bounds=Dict(x=>[1.0,3.0]))
```
!!! note
Users can also use other scipy optimization algorithm by providing `method` keyword arguments. For example, you can use the BFGS optimizer
```julia
BFGS!(sess, loss, method = "BFGS")
```
"""->
function BFGS!(sess::PyObject, loss::PyObject, max_iter::Int64=15000;
vars::Array{PyObject}=PyObject[], callback::Union{Function, Nothing}=nothing,
method::String = "L-BFGS-B", kwargs...)
__cnt = 0
__loss = 0
__var = nothing
out = []
function print_loss(l, vs...)
if !isnothing(callback); __var = vs; end
if mod(__cnt,1)==0
println("iter $__cnt, current loss=",l)
end
__loss = l
__cnt += 1
end
__iter = 0
function step_callback(rk)
if mod(__iter,1)==0
println("================ STEP $__iter ===============")
end
if !isnothing(callback)
callback(__var, __iter, __loss)
end
push!(out, __loss)
__iter += 1
end
kwargs = Dict(kwargs)
if haskey(kwargs, :bounds)
kwargs[:var_to_bounds] = kwargs[:bounds]
delete!(kwargs, :bounds)
end
feed_dict = nothing
if haskey(kwargs, :feed_dict)
feed_dict = kwargs[:feed_dict]
delete!(kwargs, :feed_dict)
end
if haskey(kwargs, :var_to_bounds)
desc = "`bounds` or `var_to_bounds` keywords of `BFGS!` only accepts dictionaries whose keys are Variables"
for (k,v) in kwargs[:var_to_bounds]
if !(hasproperty(k, "trainable"))
error("The tensor $k does not have property `trainable`, indicating it is not a `Variable`. $desc\n")
end
if !k.trainable
@warn("The variable $k is not trainable, ignoring the bounds")
end
end
end
opt = ScipyOptimizerInterface(loss, method=method,options=Dict("maxiter"=> max_iter, "ftol"=>1e-12, "gtol"=>1e-12); kwargs...)
@info "Optimization starts..."
ScipyOptimizerMinimize(sess, opt,
loss_callback=print_loss, step_callback=step_callback,
fetches=[loss, vars...],
feed_dict = feed_dict)
out
end
"""
BFGS!(value_and_gradients_function::Function, initial_position::Union{PyObject, Array{Float64}}, max_iter::Int64=50, args...;kwargs...)
Applies the BFGS optimizer to `value_and_gradients_function`
"""
function BFGS!(value_and_gradients_function::Function,
initial_position::Union{PyObject, Array{Float64}}, max_iter::Int64=50, args...;kwargs...)
tfp.optimizer.bfgs_minimize(value_and_gradients_function,
initial_position=initial_position, args...;max_iterations=max_iter, kwargs...)[5]
end
struct NRResult
x::Union{PyObject, Array{Float64}} # final solution
res::Union{PyObject, Array{Float64, 1}} # residual
u::Union{PyObject, Array{Float64, 2}} # solution history
converged::Union{PyObject, Bool} # whether it converges
iter::Union{PyObject, Int64} # number of iterations
end
function Base.:run(sess::PyObject, nr::NRResult)
NRResult(run(sess, [nr.x, nr.res, nr.u, nr.converged, nr.iter])...)
end
function backtracking(compute_gradient::Function , u::PyObject)
f0, r0, _, δ0 = compute_gradient(u)
df0 = -sum(r0.*δ0)
c1 = options.newton_raphson.linesearch_options.c1
ρ_hi = options.newton_raphson.linesearch_options.ρ_hi
ρ_lo = options.newton_raphson.linesearch_options.ρ_lo
iterations = options.newton_raphson.linesearch_options.iterations
maxstep = options.newton_raphson.linesearch_options.maxstep
αinitial = options.newton_raphson.linesearch_options.αinitial
@assert !isnothing(f0)
@assert ρ_lo < ρ_hi
@assert iterations > 0
function condition(i, ta_α, ta_f)
f = read(ta_f, i)
α = read(ta_α, i)
tf.logical_and(f > f0 + c1 * α * df0, i<=iterations)
end
function body(i, ta_α, ta_f)
α_1 = read(ta_α, i-1)
α_2 = read(ta_α, i)
d = 1/(α_1^2*α_2^2*(α_2-α_1))
f = read(ta_f, i)
a = (α_1^2*(f - f0 - df0*α_2) - α_2^2*(df0 - f0 - df0*α_1))*d
b = (-α_1^3*(f - f0 - df0*α_2) + α_2^3*(df0 - f0 - df0*α_1))*d
α_tmp = tf.cond(abs(a)<1e-10,
()->df0/(2b),
()->begin
d = max(b^2-3a*df0, constant(0.0))
(-b + sqrt(d))/(3a)
end)
α_2 = tf.cond(tf.math.is_nan(α_tmp),
()->α_2*ρ_hi,
()->begin
α_tmp = min(α_tmp, α_2*ρ_hi)
α_2 = max(α_tmp, α_2*ρ_lo)
end)
fnew, _, _, _ = compute_gradient(u - α_2*δ0)
ta_f = write(ta_f, i+1, fnew)
ta_α = write(ta_α, i+1, α_2)
i+1, ta_α, ta_f
end
ta_α = TensorArray(iterations)
ta_α = write(ta_α, 1, constant(αinitial))
ta_α = write(ta_α, 2, constant(αinitial))
ta_f = TensorArray(iterations)
ta_f = write(ta_f, 1, constant(0.0))
ta_f = write(ta_f, 2, f0)
i = constant(2, dtype=Int32)
iter, out_α, out_f = while_loop(condition, body, [i, ta_α, ta_f]; back_prop=false)
α = read(out_α, iter)
return α
end
"""
newton_raphson(func::Function,
u0::Union{Array,PyObject},
θ::Union{Missing,PyObject, Array{<:Real}}=missing,
args::PyObject...) where T<:Real
Newton Raphson solver for solving a nonlinear equation.
∘ `func` has the signature
- `func(θ::Union{Missing,PyObject}, u::PyObject)->(r::PyObject, A::Union{PyObject,SparseTensor})` (if `linesearch` is off)
- `func(θ::Union{Missing,PyObject}, u::PyObject)->(fval::PyObject, r::PyObject, A::Union{PyObject,SparseTensor})` (if `linesearch` is on)
where `r` is the residual and `A` is the Jacobian matrix; in the case where `linesearch` is on, the function value `fval` must also be supplied.
∘ `θ` are external parameters.
∘ `u0` is the initial guess for `u`
∘ `args`: additional inputs to the func function
∘ `kwargs`: keyword arguments to `func`
The solution can be configured via `ADCME.options.newton_raphson`
- `max_iter`: maximum number of iterations (default=100)
- `rtol`: relative tolerance for termination (default=1e-12)
- `tol`: absolute tolerance for termination (default=1e-12)
- `LM`: a float number, Levenberg-Marquardt modification ``x^{k+1} = x^k - (J^k + \\mu^k)^{-1}g^k`` (default=0.0)
- `linesearch`: whether linesearch is used (default=false)
Currently, the backtracing algorithm is implemented.
The parameters for `linesearch` are supplied via `options.newton_raphson.linesearch_options`
- `c1`: stop criterion, ``f(x^k) < f(0) + \\alpha c_1 f'(0)``
- `ρ_hi`: the new step size ``\\alpha_1\\leq \\rho_{hi}\\alpha_0``
- `ρ_lo`: the new step size ``\\alpha_1\\geq \\rho_{lo}\\alpha_0``
- `iterations`: maximum number of iterations for linesearch
- `maxstep`: maximum allowable steps
- `αinitial`: initial guess for the step size ``\\alpha``
"""
function newton_raphson(func::Function,
u0::Union{Array,PyObject},
θ::Union{Missing,PyObject, Array{<:Real}}=missing,
args::PyObject...; kwargs...) where T<:Real
f = (θ, u)->func(θ, u, args...; kwargs...)
if length(size(u0))!=1
error("ADCME: Initial guess must be a vector")
end
if length(u0)===nothing
error("ADCME: The length of the initial guess must be determined at compilation.")
end
u = convert_to_tensor(u0)
max_iter = options.newton_raphson.max_iter
verbose = options.newton_raphson.verbose
oprtol = options.newton_raphson.rtol
optol = options.newton_raphson.tol
LM = options.newton_raphson.LM
linesearch = options.newton_raphson.linesearch
function condition(i, ta_r, ta_u)
if verbose; @info "(2/4)Parsing Condition..."; end
if_else(tf.math.logical_and(tf.equal(i,2), tf.less(i, max_iter+1)),
constant(true),
()->begin
tol = read(ta_r, i-1)
rel_tol = read(ta_r, i-2)
if verbose
op = tf.print("Newton iteration ", i-2, ": r (abs) =", tol, " r (rel) =", rel_tol, summarize=-1)
tol = bind(tol, op)
end
return tf.math.logical_and(
tf.math.logical_and(tol>=optol, rel_tol>=oprtol),
i<=max_iter
)
end
)
end
function body(i, ta_r, ta_u)
local δ, val, r_
if verbose; @info "(3/4)Parsing Main Loop..."; end
u_ = read(ta_u, i-1)
function compute_gradients(x)
val = nothing
out = f(θ, x)
if length(out)==2
r_, J = out
else
val, r_, J = out
end
if LM>0.0 # Levenberg-Marquardt
μ = LM
μ = convert_to_tensor(μ)
δ = (J + μ*spdiag(size(J,1)))\r_
else
δ = J\r_
end
return val, r_, J, δ
end
if linesearch
if verbose; @info "Perform Linesearch..."; end
step_size = backtracking(compute_gradients, u_)
else
step_size = 1.0
end
val, r_, _, δ = compute_gradients(u_)
ta_r = write(ta_r, i, norm(r_))
δ = step_size * δ
new_u = u_ - δ
if verbose && linesearch
op = tf.print("Current Step Size = ", step_size)
new_u = bind(new_u, op)
end
ta_u = write(ta_u, i, new_u)
i+1, ta_r, ta_u
end
if verbose; @info "(1/4)Intializing TensorArray..."; end
out = f(θ, u)
r0 = length(out)==2 ? out[1] : out[2]
tol0 = norm(r0)
if verbose
op = tf.print("Newton-Raphson with absolute tolerance = $optol and relative tolerance = $oprtol")
tol0 = bind(tol0, op)
end
ta_r = TensorArray(max_iter)
ta_u = TensorArray(max_iter)
ta_u = write(ta_u, 1, u)
ta_r = write(ta_r, 1, tol0)
i = constant(2, dtype=Int32)
i_, ta_r_, ta_u_ = while_loop(condition, body, [i, ta_r, ta_u], back_prop=false)
r_out, u_out = stack(ta_r_), stack(ta_u_)
if verbose; @info "(4/4)Postprocessing Results..."; end
sol = if_else(
tf.less(tol0,optol),
u,
u_out[i_-1]
)
res = if_else(
tf.less(tol0,optol),
reshape(tol0, 1),
tf.slice(r_out, [1],[i_-2])
)
u_his = if_else(
tf.less(tol0,optol),
reshape(u, 1, length(u)),
tf.slice(u_out, [0; 0], [i_-2; length(u)])
)
iter = if_else(
tf.less(tol0,optol),
constant(1),
cast(Int64,i_)-2
)
converged = if_else(
tf.less(i_, max_iter),
constant(true),
constant(false)
)
# it makes no sense to take the gradients
sol = stop_gradient(sol)
res = stop_gradient(res)
NRResult(sol, res, u_his', converged, iter)
end
"""
newton_raphson_with_grad(f::Function,
u0::Union{Array,PyObject},
θ::Union{Missing,PyObject, Array{<:Real}}=missing,
args::PyObject...) where T<:Real
Differentiable Newton-Raphson algorithm. See [`newton_raphson`](@ref).
Use `ADCME.options.newton_raphson` to supply options.
# Example
```julia
function f(θ, x)
x^3 - θ, 3spdiag(x^2)
end
θ = constant([2. .^3;3. ^3; 4. ^3])
x = newton_raphson_with_grad(f, constant(ones(3)), θ)
run(sess, x)≈[2.;3.;4.]
run(sess, gradients(sum(x), θ))
```
"""
function newton_raphson_with_grad(func::Function,
u0::Union{Array,PyObject},
θ::Union{Missing,PyObject, Array{<:Real}}=missing,
args::PyObject...; kwargs...) where T<:Real
f = ( θ, u, args...) -> func(θ, u, args...; kwargs...)
function forward(θ, args...)
nr = newton_raphson(f, u0, θ, args...)
return nr.x
end
function backward(dy, x, θ, xargs...)
θ = copy(θ)
args = [copy(z) for z in xargs]
r, A = f(θ, x, args...)
dy = tf.convert_to_tensor(dy)
g = independent(A'\dy)
s = sum(r*g)
gs = [-gradients(s, z) for z in args]
if length(args)==0
-gradients(s, θ)
else
-gradients(s, θ), gs...
end
end
if !isa(θ, PyObject)
@warn("θ is not a PyObject, no gradients is available")
return forward(θ, args...)
end
fn = register(forward, backward)
return fn(θ, args...)
end
@doc raw"""
NonlinearConstrainedProblem(f::Function, L::Function, θ::PyObject, u0::Union{PyObject, Array{Float64}}; options::Union{Dict{String, T}, Missing}=missing) where T<:Integer
Computes the gradients ``\frac{\partial L}{\partial \theta}``
```math
\min \ L(u) \quad \mathrm{s.t.} \ F(\theta, u) = 0
```
`u0` is the initial guess for the numerical solution `u`, see [`newton_raphson`](@ref).
Caveats:
Assume `r, A = f(θ, u)` and `θ` are the unknown parameters,
`gradients(r, θ)` must be defined (backprop works properly)
Returns:
It returns a tuple (`L`: loss, `C`: constraints, and `Graidents`)
```math
\left(L(u), u, \frac{\partial L}{\partial θ}\right)
```
# Example
We want to solve the following constrained optimization problem
$$\begin{aligned}\min_\theta &\; L(u) = (u-1)^3\\ \text{s.t.} &\; u^3 + u = \theta\end{aligned}$$
The solution is $\theta = 2$. The Julia code is
```julia
function f(θ, u)
u^3 + u - θ, spdiag(3u^2+1)
end
function L(u)
sum((u-1)^2)
end
pl = Variable(ones(1))
l, θ, dldθ = NonlinearConstrainedProblem(f, L, pl, ones(1))
```
We can coupled it with a mathematical optimizer
```julia
using Optim
sess = Session(); init(sess)
BFGS!(sess, l, dldθ, pl)
```
"""
function NonlinearConstrainedProblem(f::Function, L::Function, θ::Union{Array{Float64,1},PyObject},
u0::Union{PyObject, Array{Float64}}) where T<:Real
θ = convert_to_tensor(θ)
nr = newton_raphson(f, u0, θ)
r, A = f(θ, nr.x)
l = L(nr.x)
top_grad = tf.convert_to_tensor(gradients(l, nr.x))
A = A'
g = A\top_grad
g = independent(g) # preventing gradients backprop
l, nr.x, tf.convert_to_tensor(-gradients(sum(r*g), θ))
end
@doc raw"""
BFGS!(sess::PyObject, loss::PyObject, grads::Union{Array{T},Nothing,PyObject},
vars::Union{Array{PyObject},PyObject}; kwargs...) where T<:Union{Nothing, PyObject}
Running BFGS algorithm
``\min_{\texttt{vars}} \texttt{loss}(\texttt{vars})``
The gradients `grads` must be provided. Typically, `grads[i] = gradients(loss, vars[i])`.
`grads[i]` can exist on different devices (GPU or CPU).
# Example 1
```julia
import Optim # required
a = Variable(0.0)
loss = (a-1)^2
g = gradients(loss, a)
sess = Session(); init(sess)
BFGS!(sess, loss, g, a)
```
# Example 2
```julia
import Optim # required
a = Variable(0.0)
loss = (a^2+a-1)^2
g = gradients(loss, a)
sess = Session(); init(sess)
cb = (vs, iter, loss)->begin
printstyled("[#iter $iter] a = $vs, loss=$loss\n", color=:green)
end
BFGS!(sess, loss, g, a; callback = cb)
```
"""
function BFGS!(sess::PyObject, loss::PyObject, grads::Union{Array{T},Nothing,PyObject},
vars::Union{Array{PyObject},PyObject}; kwargs...) where T<:Union{Nothing, PyObject}
Optimize!(sess, loss; vars=vars, grads = grads, kwargs...)
end
"""
Optimize!(sess::PyObject, loss::PyObject, max_iter::Int64 = 15000;
vars::Union{Array{PyObject},PyObject, Missing} = missing,
grads::Union{Array{T},Nothing,PyObject, Missing} = missing,
optimizer = missing,
callback::Union{Function, Missing}=missing,
x_tol::Union{Missing, Float64} = missing,
f_tol::Union{Missing, Float64} = missing,
g_tol::Union{Missing, Float64} = missing, kwargs...) where T<:Union{Nothing, PyObject}
An interface for using optimizers in the Optim package or custom optimizers.
- `sess`: a session;
- `loss`: a loss function;
- `max_iter`: maximum number of max_iterations;
- `vars`, `grads`: optimizable variables and gradients
- `optimizer`: Optim optimizers (default: LBFGS)
- `callback`: callback after each linesearch completion (NOT one step in the linesearch)
Other arguments are passed to Options in Optim optimizers.
We can also construct a custom optimizer. For example, to construct an optimizer out of Ipopt:
```julia
import Ipopt
x = Variable(rand(2))
loss = (1-x[1])^2 + 100(x[2]-x[1]^2)^2
function opt(f, g, fg, x0, kwargs...)
prob = createProblem(2, -100ones(2), 100ones(2), 0, Float64[], Float64[], 0, 0,
f, (x,g)->nothing, (x,G)->g(G, x), (x, mode, rows, cols, values)->nothing, nothing)
prob.x = x0
Ipopt.addOption(prob, "hessian_approximation", "limited-memory")
status = Ipopt.solveProblem(prob)
println(Ipopt.ApplicationReturnStatus[status])
println(prob.x)
Ipopt.freeProblem(prob)
nothing
end
sess = Session(); init(sess)
Optimize!(sess, loss, optimizer = opt)
```
"""
function Optimize!(sess::PyObject, loss::PyObject, max_iter::Int64 = 15000;
vars::Union{Array{PyObject},PyObject, Missing} = missing,
grads::Union{Array{T},Nothing,PyObject, Missing} = missing,
optimizer = missing,
callback::Union{Function, Missing}=missing,
x_tol::Union{Missing, Float64} = missing,
f_tol::Union{Missing, Float64} = missing,
g_tol::Union{Missing, Float64} = missing,
return_feval_loss::Bool = false, kwargs...) where T<:Union{Nothing, PyObject}
vars = coalesce(vars, get_collection())
grads = coalesce(grads, gradients(loss, vars))
if isa(vars, PyObject); vars = [vars]; end
if isa(grads, PyObject); grads = [grads]; end
if length(grads)!=length(vars); error("ADCME: length of grads and vars do not match"); end
if !all(is_variable.(vars))
error("ADCME: the input `vars` should be trainable variables")
end
idx = ones(Bool, length(grads))
pynothing = pytypeof(PyObject(nothing))
for i = 1:length(grads)
if isnothing(grads[i]) || pytypeof(grads[i])==pynothing
idx[i] = false
end
end
grads = grads[idx]
vars = vars[idx]
sizes = []
for v in vars
push!(sizes, size(v))
end
grds = vcat([tf.reshape(g, (-1,)) for g in grads]...)
vs = vcat([tf.reshape(v, (-1,)) for v in vars]...); x0 = run(sess, vs)
pl = placeholder(x0)
n = 0
assign_ops = PyObject[]
for (k,v) in enumerate(vars)
vnew = tf.reshape(pl[n+1:n+prod(sizes[k])], sizes[k])
vnew = cast(vnew, get_dtype(pl))
push!(assign_ops, assign(v, vnew))
n += prod(sizes[k])
end
__loss = 0.0
__losses = Float64[]
__feval_loss = Float64[]
__iter = 0
__value = nothing
__ls_iter = 0
function f(x)
run(sess, assign_ops, pl=>x)
__loss = run(sess, loss)
__ls_iter += 1
push!(__feval_loss, __loss)
options.training.verbose && (println("iter $__ls_iter, current loss = $__loss"))
return __loss
end
function g!(G, x)
run(sess, assign_ops, pl=>x)
G[:] = run(sess, grds)
__value = x
end
function fg(G, x)
run(sess, assign_ops, pl=>x)
__loss, G[:] = run(sess, [loss, grds])
__ls_iter += 1
__value = x
return __loss
end
if isa(optimizer, Function)
if length(kwargs)>0
kwargs_ = copy(kwargs)
else
kwargs_ = Dict{Symbol, Any}()
end
kwargs_[:max_iter] = max_iter
__losses = optimizer(f, g!, fg, x0; kwargs_...)
if return_feval_loss
__losses = (__losses, __feval_loss)
end
return __losses
end
if !isdefined(Main, :Optim)
error("Package Optim.jl must be imported in the main module using `import Optim` or `using Optim`")
end
function callback1(x)
@info x.iteration, x.value
__iter = x.iteration
__loss = x.value
push!(__losses, __loss)
if options.training.verbose
println("================== STEP $__iter ==================")
end
if !ismissing(callback)
callback(__value, __iter, __loss)
end
false
end
method = coalesce(optimizer, Main.Optim.LBFGS())
@info "Optimization starts..."
res = Main.Optim.optimize(f, g!, x0, method, Main.Optim.Options(
; store_trace = false,
show_trace = false,
callback=callback1,
iterations = max_iter,
x_tol = coalesce(x_tol, 1e-12),
f_tol = coalesce(f_tol, 1e-12),
g_tol = coalesce(g_tol, 1e-12),
kwargs...))
if return_feval_loss
__losses = (__losses, __feval_loss)
end
return __losses
end |
"""
julia_worker_regex
Regex for parsing the output printed by Julia worker processes.
"""
const julia_worker_regex = r"julia_worker:([\d]*?)#([\w\d.]*?)\n"
"""
parse_julia_worker_output_to_hosts_and_ports(; regex = julia_worker_regex)
Parse the output printed by Julia workers and return a list of hosts and
ports.
## Example
```jldoctest; setup = :(using ExistingProcessManagers; using Distributed)
julia> worker_output = \"""
julia_worker:9960#192.168.1.151
julia_worker:9962#192.168.1.153
julia_worker:9964#192.168.1.155
julia_worker:9966#192.168.1.157
julia_worker:9968#192.168.1.159
\""";
julia> hosts_and_ports = parse_julia_worker_output_to_hosts_and_ports(worker_output);
```
Now you can do either of the following two options, which are equivalent:
Option 1:
```julia
julia> addprocs(ExistingProcessManager(hosts_and_ports))
```
Option 2:
```julia
julia> addprocs_existing(hosts_and_ports)
```
"""
@inline function parse_julia_worker_output_to_hosts_and_ports(worker_ouput::AbstractString;
regex = julia_worker_regex)
occurrences = findall(regex, worker_ouput)
num_occurences = length(occurrences)
hosts_and_ports = Vector{Tuple{String, Int}}(undef, num_occurences)
for i in 1:num_occurences
occurrence = occurrences[i]
m = match(regex, worker_ouput[occurrence])
host = convert(String, m[2])::String
port_string = m[1]
port = parse(Int, port_string)::Int
host_and_port = (host, port)
hosts_and_ports[i] = host_and_port
end
unique!(hosts_and_ports)
return hosts_and_ports
end
|
/* Copyright (c) 2011-2014 ETH Zürich. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of ETH Zürich nor the names of other contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ETH
* ZURICH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define BOOST_TEST_DYN_LINK
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test.hpp>
#include "InfoElement.h"
#include "InfoModel.h"
BOOST_AUTO_TEST_SUITE(Basics)
BOOST_AUTO_TEST_CASE(InfoModel) {
libfc::InfoModel& m = libfc::InfoModel::instance();
// we're going to do default info model stuff
m.defaultIPFIX();
// make sure we only have one instance
libfc::InfoModel& mcheck = libfc::InfoModel::instance();
BOOST_CHECK_EQUAL(&m, &mcheck);
// check a few IEs that should be there
BOOST_CHECK_EQUAL(m.lookupIE("octetDeltaCount")->number(), 1);
BOOST_CHECK_EQUAL(m.lookupIE("octetDeltaCount")->pen(), 0U);
BOOST_CHECK_EQUAL(m.lookupIE("octetDeltaCount")->len(), 8);
// check an IE that shouldn't
BOOST_CHECK_EQUAL(m.lookupIE("thisIsNotAnInformationElement"), (void *)0);
}
BOOST_AUTO_TEST_CASE(InfoElement01) {
libfc::InfoModel& m = libfc::InfoModel::instance();
m.defaultIPFIX();
const libfc::InfoElement* e = m.lookupIE("octetDeltaCount");
BOOST_REQUIRE(e != 0);
BOOST_CHECK_EQUAL(e->toIESpec(), "octetDeltaCount(1)<unsigned64>[8]");
}
BOOST_AUTO_TEST_SUITE_END()
|
[GOAL]
⊢ ConcreteCategory HeytAlgCat
[PROOFSTEP]
dsimp [HeytAlgCat]
[GOAL]
⊢ ConcreteCategory (Bundled HeytingAlgebra)
[PROOFSTEP]
infer_instance
-- Porting note: No idea why it does not find this instance...
[GOAL]
α β : HeytAlgCat
e : ↑α ≃o ↑β
⊢ {
toLatticeHom :=
{ toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) },
map_inf' := (_ : ∀ (a b : ↑α), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) },
map_bot' := (_ : ↑e ⊥ = ⊥), map_himp' := (_ : ∀ (a b : ↑α), ↑e (a ⇨ b) = ↑e a ⇨ ↑e b) } ≫
{
toLatticeHom :=
{
toSupHom :=
{ toFun := ↑(OrderIso.symm e),
map_sup' :=
(_ : ∀ (a b : ↑β), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) },
map_inf' := (_ : ∀ (a b : ↑β), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) },
map_bot' := (_ : ↑(OrderIso.symm e) ⊥ = ⊥),
map_himp' := (_ : ∀ (a b : ↑β), ↑(OrderIso.symm e) (a ⇨ b) = ↑(OrderIso.symm e) a ⇨ ↑(OrderIso.symm e) b) } =
𝟙 α
[PROOFSTEP]
ext
[GOAL]
case w
α β : HeytAlgCat
e : ↑α ≃o ↑β
x✝ : (forget HeytAlgCat).obj α
⊢ ↑({
toLatticeHom :=
{ toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) },
map_inf' := (_ : ∀ (a b : ↑α), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) },
map_bot' := (_ : ↑e ⊥ = ⊥), map_himp' := (_ : ∀ (a b : ↑α), ↑e (a ⇨ b) = ↑e a ⇨ ↑e b) } ≫
{
toLatticeHom :=
{
toSupHom :=
{ toFun := ↑(OrderIso.symm e),
map_sup' :=
(_ : ∀ (a b : ↑β), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) },
map_inf' :=
(_ : ∀ (a b : ↑β), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) },
map_bot' := (_ : ↑(OrderIso.symm e) ⊥ = ⊥),
map_himp' := (_ : ∀ (a b : ↑β), ↑(OrderIso.symm e) (a ⇨ b) = ↑(OrderIso.symm e) a ⇨ ↑(OrderIso.symm e) b) })
x✝ =
↑(𝟙 α) x✝
[PROOFSTEP]
exact e.symm_apply_apply _
[GOAL]
α β : HeytAlgCat
e : ↑α ≃o ↑β
⊢ {
toLatticeHom :=
{
toSupHom :=
{ toFun := ↑(OrderIso.symm e),
map_sup' :=
(_ : ∀ (a b : ↑β), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) },
map_inf' := (_ : ∀ (a b : ↑β), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) },
map_bot' := (_ : ↑(OrderIso.symm e) ⊥ = ⊥),
map_himp' := (_ : ∀ (a b : ↑β), ↑(OrderIso.symm e) (a ⇨ b) = ↑(OrderIso.symm e) a ⇨ ↑(OrderIso.symm e) b) } ≫
{
toLatticeHom :=
{ toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) },
map_inf' := (_ : ∀ (a b : ↑α), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) },
map_bot' := (_ : ↑e ⊥ = ⊥), map_himp' := (_ : ∀ (a b : ↑α), ↑e (a ⇨ b) = ↑e a ⇨ ↑e b) } =
𝟙 β
[PROOFSTEP]
ext
[GOAL]
case w
α β : HeytAlgCat
e : ↑α ≃o ↑β
x✝ : (forget HeytAlgCat).obj β
⊢ ↑({
toLatticeHom :=
{
toSupHom :=
{ toFun := ↑(OrderIso.symm e),
map_sup' :=
(_ : ∀ (a b : ↑β), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) },
map_inf' :=
(_ : ∀ (a b : ↑β), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) },
map_bot' := (_ : ↑(OrderIso.symm e) ⊥ = ⊥),
map_himp' :=
(_ : ∀ (a b : ↑β), ↑(OrderIso.symm e) (a ⇨ b) = ↑(OrderIso.symm e) a ⇨ ↑(OrderIso.symm e) b) } ≫
{
toLatticeHom :=
{ toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) },
map_inf' := (_ : ∀ (a b : ↑α), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) },
map_bot' := (_ : ↑e ⊥ = ⊥), map_himp' := (_ : ∀ (a b : ↑α), ↑e (a ⇨ b) = ↑e a ⇨ ↑e b) })
x✝ =
↑(𝟙 β) x✝
[PROOFSTEP]
exact e.apply_symm_apply _
|
import number_theory.padics.padic_integers
--OUTPUT 1
theorem p_adic_units (p : ℕ) [hp : prime p] (x : ℕ) : coprime x p → is_unit (x : ℤ_[p]) :=
begin
assume h1 : coprime x p,
have h2 : ∀ y : ℤ_[p], (norm_int p y = 1) ↔ is_unit (y : ℤ_[p]), from by auto [norm_int_one],
have h3 : ¬ (is_unit (x : ℤ_[p])), from by auto [norm_int_lt_one],
show false, from by auto [h2, h3, h1, norm_int_eq_one],
end
--OUTPUT 2
theorem padic_units (p : ℕ) [hp : prime p] (x : ℕ) (hx : gcd x p = 1) : is_unit (x : ℤ/p) :=
begin
have h1 : ¬ is_unit (x : ℤ/p), from by auto [hx, nat.gcd_dvd_right, nat.gcd_dvd_left, nat.gcd_eq_left],
have h2 : ¬ (↑x : ℤ/p) = 1, from by auto [is_unit.def, h1],
have h3 : ¬ (↑x : ℤ/p) = 0, from by auto [is_unit.def, h1],
have h4 : (↑x : ℤ/p) ≠ 0, from by auto [h3],
have h5 : (↑x : ℤ/p) ≠ 1, from by auto [h2],
have h6 : (↑x : ℤ/p) ≠ 0 ∧ (↑x : ℤ/p) ≠ 1, from by auto [h4, h5],
have h7 : ¬ (↑x : ℤ/p) = 0 ∧ ¬ (↑x : ℤ/p) = 1, from by auto [h6],
have h8 : ¬ (↑x : ℤ/p) = 0 ∨ ¬ (↑x : ℤ/p) = 1, from by auto [h7],
have h9 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h8],
have h10 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h9],
have h11 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h10],
have h12 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h11],
have h13 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h12],
have h14 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h13],
have h15 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h14],
have h16 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h15],
have h17 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h16],
have h18 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h17],
have h19 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h18],
have h20 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h19],
have h21 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h20],
have h22 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h21],
have h23 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h22],
have h24 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h23],
have h25 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h24],
have h26 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h25],
have h27 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h26],
have h28 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h27],
have h29 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h28],
have h30 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h29],
have h31 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h30],
have h32 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h31],
have h33 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h32],
have h34 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h33],
have h35 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h34],
have h36 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h35],
have h37 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h36],
have h38 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h37],
have h39 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h38],
have h40 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h39],
have h41 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h40],
have h42 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h41],
have h43 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h42],
have h44 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h43],
have h45 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h44],
have h46 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h45],
have h47 : (↑x : ℤ/p) ≠ 0 ∨ (↑x : ℤ/p) ≠ 1, from by auto [h46],
end --Needs more than 2000 tokens!
--OUTPUT 3
theorem p_adic_units {p : ℕ} (h : prime p) (x : ℕ) (h2 : gcd x p = 1) : is_unit (x : ℤ_[p]) :=
begin
have h3 : (x : ℤ_[p]) ≠ 0, from by auto [h2, gcd_eq_zero_iff],
have h4 : (x : ℤ_[p]) ≠ 1, from by auto [h2, gcd_eq_one_iff],
have h5 : (x : ℤ_[p]) ≠ -1, from by auto [h2, gcd_eq_neg_one_iff],
have h6 : (x : ℤ_[p]) ≠ (p : ℤ_[p]), from by auto [h, prime.not_dvd_one],
have h7 : (x : ℤ_[p]) ≠ (-p : ℤ_[p]), from by auto [h, prime.not_dvd_one],
have h8 : (x : ℤ_[p]) ≠ (p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h9 : (x : ℤ_[p]) ≠ (-p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h10 : (x : ℤ_[p]) ≠ (p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h11 : (x : ℤ_[p]) ≠ (-p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h12 : (x : ℤ_[p]) ≠ (p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h13 : (x : ℤ_[p]) ≠ (-p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h14 : (x : ℤ_[p]) ≠ (p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h15 : (x : ℤ_[p]) ≠ (-p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h16 : (x : ℤ_[p]) ≠ (p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h17 : (x : ℤ_[p]) ≠ (-p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h18 : (x : ℤ_[p]) ≠ (p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h19 : (x : ℤ_[p]) ≠ (-p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h20 : (x : ℤ_[p]) ≠ (p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h21 : (x : ℤ_[p]) ≠ (-p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h22 : (x : ℤ_[p]) ≠ (p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h23 : (x : ℤ_[p]) ≠ (-p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h24 : (x : ℤ_[p]) ≠ (p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h25 : (x : ℤ_[p]) ≠ (-p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h26 : (x : ℤ_[p]) ≠ (p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h27 : (x : ℤ_[p]) ≠ (-p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h28 : (x : ℤ_[p]) ≠ (p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h29 : (x : ℤ_[p]) ≠ (-p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h30 : (x : ℤ_[p]) ≠ (p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h31 : (x : ℤ_[p]) ≠ (-p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h32 : (x : ℤ_[p]) ≠ (p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h33 : (x : ℤ_[p]) ≠ (-p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h34 : (x : ℤ_[p]) ≠ (p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h35 : (x : ℤ_[p]) ≠ (-p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h36 : (x : ℤ_[p]) ≠ (p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h37 : (x : ℤ_[p]) ≠ (-p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h38 : (x : ℤ_[p]) ≠ (p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h39 : (x : ℤ_[p]) ≠ (-p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h40 : (x : ℤ_[p]) ≠ (p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h41 : (x : ℤ_[p]) ≠ (-p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h42 : (x : ℤ_[p]) ≠ (p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h43 : (x : ℤ_[p]) ≠ (-p : ℤ_[p])⁻¹, from by auto [h, prime.not_dvd_one],
have h44 : (x : ℤ_[p]) ≠ (p :
end --Needs more than 2000 tokens!
--OUTPUT 4
theorem p_adic_units (p : ℕ) (x : ℕ) (h : gcd x p = 1) : is_unit (p_adic_int p x) :=
begin
have h1 : (p_adic_int p x) ≠ 0, from by auto [p_adic_int.ne_zero],
have h2 : (p_adic_int p x) ≠ 1, from by auto [p_adic_int.ne_one],
have h3 : (p_adic_int p x) ≠ -1, from by auto [p_adic_int.ne_neg_one],
have h4 : (p_adic_int p x) ≠ -(p_adic_int p x), from by auto [p_adic_int.ne_neg],
have h5 : (p_adic_int p x) ≠ (p_adic_int p x), from by auto [p_adic_int.ne_self],
have h6 : (p_adic_int p x) ≠ -(1 : p_adic_int p), from by auto [p_adic_int.ne_neg],
have h7 : (p_adic_int p x) ≠ (1 : p_adic_int p), from by auto [p_adic_int.ne_one],
have h8 : (p_adic_int p x) ≠ -1, from by auto [p_adic_int.ne_neg_one],
have h9 : (p_adic_int p x) ≠ 0, from by auto [p_adic_int.ne_zero],
have h10 : (p_adic_int p x) ≠ -(p_adic_int p x), from by auto [p_adic_int.ne_neg],
have h11 : (p_adic_int p x) ≠ (p_adic_int p x), from by auto [p_adic_int.ne_self],
have h12 : (p_adic_int p x) ≠ -(1 : p_adic_int p), from by auto [p_adic_int.ne_neg],
have h13 : (p_adic_int p x) ≠ (1 : p_adic_int p), from by auto [p_adic_int.ne_one],
have h14 : (p_adic_int p x) ≠ -1, from by auto [p_adic_int.ne_neg_one],
have h15 : (p_adic_int p x) ≠ 0, from by auto [p_adic_int.ne_zero],
have h16 : (p_adic_int p x) ≠ -(p_adic_int p x), from by auto [p_adic_int.ne_neg],
have h17 : (p_adic_int p x) ≠ (p_adic_int p x), from by auto [p_adic_int.ne_self],
have h18 : (p_adic_int p x) ≠ -(1 : p_adic_int p), from by auto [p_adic_int.ne_neg],
have h19 : (p_adic_int p x) ≠ (1 : p_adic_int p), from by auto [p_adic_int.ne_one],
have h20 : (p_adic_int p x) ≠ -1, from by auto [p_adic_int.ne_neg_one],
have h21 : (p_adic_int p x) ≠ 0, from by auto [p_adic_int.ne_zero],
have h22 : (p_adic_int p x) ≠ -(p_adic_int p x), from by auto [p_adic_int.ne_neg],
have h23 : (p_adic_int p x) ≠ (p_adic_int p x), from by auto [p_adic_int.ne_self],
have h24 : (p_adic_int p x) ≠ -(1 : p_adic_int p), from by auto [p_adic_int.ne_neg],
have h25 : (p_adic_int p x) ≠ (1 : p_adic_int p), from by auto [p_adic_int.ne_one],
have h26 : (p_adic_int p x) ≠ -1, from by auto [p_adic_int.ne_neg_one],
have h27 : (p_adic_int p x) ≠ 0, from by auto [p_adic_int.ne_zero],
have h28 : (p_adic_int p x) ≠ -(p_adic_int p x), from by auto [p_adic_int.ne_neg],
have h29 : (p_adic_int p x) ≠ (p_adic_int p x), from by auto [p_adic_int.ne_self],
have h30 : (p_adic_int p x) ≠ -(1 : p_adic_int p), from by auto [p_adic_int.ne_neg],
have h31 : (p_adic_int p x) ≠ (1 : p_adic_int p), from by auto [p_adic_int.ne_one],
have h32 : (p_adic_int p x) ≠ -1, from by auto [p_adic_int.ne_neg_one],
have h33 : (p_adic_int p x) ≠ 0, from by auto [p_adic_int.ne_zero],
have h34 : (p_adic_int p x) ≠ -(p_adic_int p x), from by auto [p_adic_int.ne_neg],
have h35 : (p_adic_int p x) ≠ (p_adic_int p x), from by auto [p_adic_int.ne_self],
have h36 : (p_adic_int p x) ≠ -(1 : p_adic_int p), from by auto [p_adic_int.ne_neg],
have h37 : (p_adic_int p x) ≠ (1 : p_adic_int p), from by auto [p_adic_int.ne_one],
have h38 : (p_adic_int p x) ≠ -1, from by auto [p_adic_int.ne_neg_one],
have h39 : (p_adic_int p x) ≠ 0, from by auto [p_adic_int.ne_zero],
have h40 : (p_adic_int p x) ≠ -(p_adic_int p x), from by auto [p_adic_int.ne_neg],
have h41 : (p_adic_int p x) ≠ (p_adic_int p x), from by auto [p_adic_int.ne_self],
have h42 : (p_adic_int p x) ≠ -(1 : p_adic_int p), from by auto [p_adic_int.ne_neg],
have h43 : (p_adic_int p x) ≠ (1 : p_adic_int p), from by auto [p_adic_int.ne_one],
have h44 : (p_adic_int p x) ≠ -1, from by auto [p_adic_int.ne_neg_one],
have h45 : (p_adic_int p x) ≠ 0, from by auto [p_adic_int.ne_zero],
have h46 : (p_adic_int p x) ≠ -(p_adic_int p x), from by auto [p_adic_int.ne_neg],
have h47 : (p_adic_int p x) ≠ (p_adic_int p x), from by auto [p_adic_int.ne_self],
have h48 : (p_adic_int p x) ≠ -(1 : p_adic_int p), from by auto [p_adic_int.ne_neg],
have h49 : (p_adic_int p x) ≠ (1 : p_adic_int p), from by auto [p_adic_int.ne_one],
have h50 : (p_adic_int p x) ≠ -1, from by auto [p_adic_int.ne_neg_one],
have h51 : (p_adic_int p x) ≠ 0, from by auto
end --Needs more than 2000 tokens!
--OUTPUT 5
theorem p_adic_units {p : ℕ} (hp : prime p) (x : ℕ) (hx : nat.coprime x p) : nat.units (p_adic_int p) x :=
begin
have h1 : ∀ a : ℕ, ∀ b : ℕ, ∀ c : ℕ, a ∣ b → a ∣ (b * c), from by auto [dvd_mul_of_dvd_left],
have h2 : ∀ a : ℕ, ∀ b : ℕ, ∀ c : ℕ, a ∣ b → a ∣ (c * b), from by auto [dvd_mul_of_dvd_right],
have h3 : ∀ a : ℕ, ∀ b : ℕ, ∀ c : ℕ, a ∣ b → a ∣ (b + c), from by auto [dvd_add],
have h4 : ∀ a : ℕ, ∀ b : ℕ, ∀ c : ℕ, a ∣ b → a ∣ (c + b), from by auto [dvd_add],
have h5 : ∀ a : ℕ, ∀ b : ℕ, ∀ c : ℕ, a ∣ b → a ∣ (b - c), from by auto [dvd_sub],
have h6 : ∀ a : ℕ, ∀ b : ℕ, ∀ c : ℕ, a ∣ b → a ∣ (c - b), from by auto [dvd_sub],
have h7 : ∀ a : ℕ, ∀ b : ℕ, ∀ c : ℕ, a ∣ b → a ∣ (b / c), from by auto [dvd_div_of_dvd_mul],
have h8 : ∀ a : ℕ, ∀ b : ℕ, ∀ c : ℕ, a ∣ b → a ∣ (c / b), from by auto [dvd_div_of_dvd_mul],
have h9 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b + a), from by auto [dvd_add],
have h10 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (a + b), from by auto [dvd_add],
have h11 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b - a), from by auto [dvd_sub],
have h12 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (a - b), from by auto [dvd_sub],
have h13 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b / a), from by auto [dvd_div_of_dvd_mul],
have h14 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (a / b), from by auto [dvd_div_of_dvd_mul],
have h15 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b * a), from by auto [dvd_mul_of_dvd_left],
have h16 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (a * b), from by auto [dvd_mul_of_dvd_right],
have h17 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ b, from by auto [dvd_refl],
have h18 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b * b), from by auto [dvd_mul_of_dvd_left],
have h19 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b * b), from by auto [dvd_mul_of_dvd_right],
have h20 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b * b), from by auto [dvd_mul_of_dvd_left],
have h21 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b * b), from by auto [dvd_mul_of_dvd_right],
have h22 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b * b), from by auto [dvd_mul_of_dvd_left],
have h23 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b * b), from by auto [dvd_mul_of_dvd_right],
have h24 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b * b), from by auto [dvd_mul_of_dvd_left],
have h25 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b * b), from by auto [dvd_mul_of_dvd_right],
have h26 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b * b), from by auto [dvd_mul_of_dvd_left],
have h27 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b * b), from by auto [dvd_mul_of_dvd_right],
have h28 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b * b), from by auto [dvd_mul_of_dvd_left],
have h29 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b * b), from by auto [dvd_mul_of_dvd_right],
have h30 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b * b), from by auto [dvd_mul_of_dvd_left],
have h31 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b * b), from by auto [dvd_mul_of_dvd_right],
have h32 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b * b), from by auto [dvd_mul_of_dvd_left],
have h33 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b * b), from by auto [dvd_mul_of_dvd_right],
have h34 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b * b), from by auto [dvd_mul_of_dvd_left],
have h35 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b * b), from by auto [dvd_mul_of_dvd_right],
have h36 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b * b), from by auto [dvd_mul_of_dvd_left],
have h37 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b * b), from by auto [dvd_mul_of_dvd_right],
have h38 : ∀ a : ℕ, ∀ b : ℕ, a ∣ b → a ∣ (b *
end --Needs more than 2000 tokens!
--OUTPUT 6
theorem p_adic_units {p : ℕ} (hp : prime p) (x : ℕ) (hx : nat.gcd x p = 1) : (∃ y : ℕ, y * x = 1) :=
begin
have h1 : (∃ y : ℕ, y * x = 1) ↔ (∃ y : ℕ, y * x = 1 mod p),
{
split,
{
assume h2,
cases h2 with y h3,
existsi y,
rw h3,
rw nat.mod_one,
simp,
},
{
assume h2,
cases h2 with y h3,
existsi y,
rw h3,
rw nat.mod_eq_of_lt,
apply nat.lt_succ_self,
},
},
have h2 : (∃ y : ℕ, y * x = 1 mod p) ↔ (∃ y : ℕ, y * x = 1 mod p ∧ y < p),
{
split,
{
assume h3,
cases h3 with y h4,
existsi y,
split,
{
exact h4,
},
{
apply nat.lt_succ_self,
},
},
{
assume h3,
cases h3 with y h4,
existsi y,
exact h4.left,
},
},
have h3 : (∃ y : ℕ, y * x = 1 mod p ∧ y < p) ↔ (∃ y : ℕ, y * x = 1 mod p ∧ y < p ∧ y ≠ 0),
{
split,
{
assume h4,
cases h4 with y h5,
existsi y,
split,
{
exact h5.left,
},
{
split,
{
exact h5.right,
},
{
intro h6,
rw h6 at h5.left,
rw nat.mod_zero at h5.left,
apply nat.eq_zero_of_mul_eq_zero_right hp.pos h5.left.symm,
},
},
},
{
assume h4,
cases h4 with y h5,
existsi y,
split,
{
exact h5.left,
},
{
exact h5.right.left,
},
},
},
have h4 : (∃ y : ℕ, y * x = 1 mod p ∧ y < p ∧ y ≠ 0) ↔ (∃ y : ℕ, y * x = 1 mod p ∧ y < p ∧ y ≠ 0 ∧ y ≠ p),
{
split,
{
assume h5,
cases h5 with y h6,
existsi y,
split,
{
exact h6.left,
},
{
split,
{
exact h6.right.left,
},
{
split,
{
exact h6.right.right,
},
{
intro h7,
rw h7 at h6.right.left,
apply nat.not_lt_of_ge h6.right.left,
apply nat.le_succ_self,
},
},
},
},
{
assume h5,
cases h5 with y h6,
existsi y,
split,
{
exact h6.left,
},
{
split,
{
exact h6.right.left.left,
},
{
exact h6.right.left.right,
},
},
},
},
have h5 : (∃ y : ℕ, y * x = 1 mod p ∧ y < p ∧ y ≠ 0 ∧ y ≠ p) ↔ (∃ y : ℕ, y * x = 1 mod p ∧ y < p ∧ y ≠ 0 ∧ y ≠ p ∧ y ≠ 1),
{
split,
{
assume h6,
cases h6 with y h7,
existsi y,
split,
{
exact h7.left,
},
{
split,
{
exact h7.right.left.left,
},
{
split,
{
exact h7.right.left.right,
},
{
split,
{
exact h7.right.right,
},
{
intro h8,
rw h8 at h7.left,
rw nat.mod_one at h7.left,
apply nat.eq_zero_of_mul_eq_zero_right hp.pos h7.left.symm,
},
},
},
},
},
{
assume h6,
cases h6 with y h7,
existsi y,
split,
{
exact h7.left,
},
{
split,
{
exact h7.right.left.left.left,
},
{
split,
{
exact h7.right.left.left.right,
},
{
exact h7.right.left.right,
},
},
},
},
},
have h6 : (∃ y : ℕ, y * x = 1 mod p ∧ y < p ∧ y ≠ 0 ∧ y ≠ p ∧ y ≠ 1) ↔ (∃ y : ℕ, y * x = 1 mod p ∧ y < p ∧ y ≠ 0 ∧ y ≠ p ∧ y ≠ 1 ∧ y ≠ 2),
{
split,
{
assume h7,
cases h7 with y h8,
existsi y,
split,
{
exact h8.left,
},
{
split,
{
exact h8.right.left.left.left,
},
{
split,
{
exact h8.right.left.left.right,
},
{
split,
{
exact h8.right.left.right,
},
{
split,
{
exact h8.right.right,
},
{
intro h9,
rw h9 at h8.left,
rw nat.mod_two at h8.left,
apply nat.eq_zero_of_mul_eq_zero_right hp.pos h8.left.symm,
},
},
},
},
},
},
{
assume h7,
cases h7 with y h8,
existsi y,
split,
{
exact h8.left,
},
{
split,
{
exact h8.right.left.left.left.left,
},
{
split,
{
exact h8.right.left.left.left.right,
},
{
split,
{
exact h8.right.left.left.right,
},
{
split,
{
exact h8.right.left.right,
},
{
exact h8.right.right,
},
},
},
},
},
},
},
have h7 : (∃ y : ℕ, y * x = 1 mod p ∧ y < p ∧ y ≠ 0 ∧ y ≠ p ∧ y ≠ 1 ∧ y ≠ 2) ↔ (∃ y : ℕ, y * x = 1 mod p ∧ y < p ∧ y ≠ 0 ∧ y ≠ p ∧ y ≠ 1 ∧ y ≠ 2 ∧
end --Needs more than 2000 tokens!
/- FEW SHOT PROMPTS TO CODEX(START)
/--`theorem`
Power Set is Closed under Intersection
Let $S$ be a set.
Let $\powerset S$ be the power set of $S$.
Then:
:$\forall A, B \in \powerset S: A \cap B \in \powerset S$
`proof`
Let $A, B \in \powerset S$.
Then by the definition of power set, $A \subseteq S$ and $B \subseteq S$.
From Intersection is Subset we have that $A \cap B \subseteq A$.
It follows from Subset Relation is Transitive that $A \cap B \subseteq S$.
Thus $A \cap B \in \powerset S$ and closure is proved.
{{qed}}
-/
theorem power_set_intersection_closed {α : Type*} (S : set α) : ∀ A B ∈ 𝒫 S, (A ∩ B) ∈ 𝒫 S :=
begin
assume (A : set α) (hA : A ∈ 𝒫 S) (B : set α) (hB : B ∈ 𝒫 S),
have h1 : (A ⊆ S) ∧ (B ⊆ S), from by auto [set.subset_of_mem_powerset, set.subset_of_mem_powerset],
have h2 : (A ∩ B) ⊆ A, from by auto [set.inter_subset_left],
have h3 : (A ∩ B) ⊆ S, from by auto [set.subset.trans],
show (A ∩ B) ∈ 𝒫 S, from by auto [set.mem_powerset],
end
/--`theorem`
Square of Sum
:$\forall x, y \in \R: \paren {x + y}^2 = x^2 + 2 x y + y^2$
`proof`
Follows from the distribution of multiplication over addition:
{{begin-eqn}}
{{eqn | l = \left({x + y}\right)^2
| r = \left({x + y}\right) \cdot \left({x + y}\right)
}}
{{eqn | r = x \cdot \left({x + y}\right) + y \cdot \left({x + y}\right)
| c = Real Multiplication Distributes over Addition
}}
{{eqn | r = x \cdot x + x \cdot y + y \cdot x + y \cdot y
| c = Real Multiplication Distributes over Addition
}}
{{eqn | r = x^2 + 2xy + y^2
| c =
}}
{{end-eqn}}
{{qed}}
-/
theorem square_of_sum (x y : ℝ) : (x + y)^2 = (x^2 + 2*x*y + y^2) :=
begin
calc (x + y)^2 = (x+y)*(x+y) : by auto [sq]
... = x*(x+y) + y*(x+y) : by auto [add_mul]
... = x*x + x*y + y*x + y*y : by auto [mul_comm, add_mul] using [ring]
... = x^2 + 2*x*y + y^2 : by auto [sq, mul_comm] using [ring]
end
/--`theorem`
Identity of Group is Unique
Let $\struct {G, \circ}$ be a group. Then there is a unique identity element $e \in G$.
`proof`
From Group has Latin Square Property, there exists a unique $x \in G$ such that:
:$a x = b$
and there exists a unique $y \in G$ such that:
:$y a = b$
Setting $b = a$, this becomes:
There exists a unique $x \in G$ such that:
:$a x = a$
and there exists a unique $y \in G$ such that:
:$y a = a$
These $x$ and $y$ are both $e$, by definition of identity element.
{{qed}}
-/
theorem group_identity_unique {G : Type*} [group G] : ∃! e : G, ∀ a : G, e * a = a ∧ a * e = a :=
begin
have h1 : ∀ a b : G, ∃! x : G, a * x = b, from by auto using [use (a⁻¹ * b)],
have h2 : ∀ a b : G, ∃! y : G, y * a = b, from by auto using [use b * a⁻¹],
have h3 : ∀ a : G, ∃! x : G, a * x = a, from by auto [h1],
have h4 : ∀ a : G, ∃! y : G, y * a = a, from by auto [h2],
have h5 : ∀ a : G, classical.some (h3 a).exists = (1 : G), from by auto [exists_unique.unique, h3, classical.some_spec, exists_unique.exists, mul_one],
have h6 : ∀ a : G, classical.some (h4 a).exists = (1 : G), from by auto [exists_unique.unique, h4, classical.some_spec, exists_unique.exists, one_mul],
show ∃! e : G, ∀ a : G, e * a = a ∧ a * e = a, from by auto [h3, h4, exists_unique.unique, classical.some_spec, exists_unique.exists] using [use (1 : G)],
end
/--`theorem`
p-adic units
Given a prime number $p$ and a natural number $x$, if $x$ is coprime to $p$, then $x$ is a unit in the $p$-adic integers.
`proof`
Let us prove the contrapositive, that is, is $x$ is not a unit of $\mathbb{Z}_p$, then $x$ is not coprime to $p$.
We know that any element of $\mathbb{Z}_p$ is a unit if and only if it has norm 1, thus $\Vert x \Vert \neq 1$. Also, since every element of $\mathbb{Z}_p$ must have norm less than or equal to 1, we conclude that $\Vert x \Vert < 1$.
But this must imply that $p | x$.
This completes our proof.
QED
-/
theorem
FEW SHOT PROMPTS TO CODEX(END)-/
|
/-
Copyright (c) 2022 Sina Hazratpour. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
----------------
# Definitions, Lemmas, and Theorems .
Sina Hazratpour
Introduction to Proof
MATH 301, Johns Hopkins University, Fall 2022
-/
import ..prooflab
import lectures.lec0_intro
set_option pp.beta true
set_option pp.generalized_field_notation false
-- set_option pp.all true
/-
In this lesson, we learn how to define stuff in Lean. We also learn to state and use lemmas and theorems in Lean to prove some basic arithmetic equalities in combination with the tactics `refl`, `exact`, `rw`, and `change` we learned in the previous lesson.
-/
namespace PROOFS
/-! ## Definitions, Lemmas, Theorems -/
section
/-
We can __define__ new stuff in Lean: A __definition__ assigns an expression to a keyword and puts it in the environment.
def keyword : type := expression
In below, we define `foo` as the natural number `5`.
-/
def foo : nat := 5
#check foo
#print foo
#check foo + 7
/-
We can similarly state a __lemma__ or a __theorem__. A lemma or a theorem is written the same way as `example` except that we give name to our lemmas and theorems for further use.
- A genral __term style__ form of a `lemma` or a `theorem` is as follows:
lemma name_of_lemma (context_of_our_assumptions) :
statement_of_lemma
:= proof_of_lemma
- A general form of a `lemma` in __tactic style__:
lemma name_of_lemma (context_of_our_assumptions) :
statement_we_wanna_prove :=
begin
tactic_1 [...],
tactic_2 [...],
⋮
tactic_n [...],
end
For instance, in below, we have a __term-style__ of the lemma `bar`:
- `bar` is the __name_of_lemma__ which we can invoke later.
- `(m n : ℤ)` is th __context__ of the lemma: these are the parameters which are used in the statement of the lemma. Think of context as a way of telling to Lean "let x, y, z, and n be natural numbers".
- `2 + n + m = n + 2 + m` is the __statement__ of the lemma: i.e. the thing we want to prove. The statement is usually a proposition which makes sense only in a given context. For instance, the contexts
` m : ℕ `, and ` m n : ℕ ` would not work. Try!
-/
lemma bar (m n : ℤ) :
2 + n - m = n + 2 - m :=
congr_arg (λ x, x - m) (add_comm 2 n) -- you do not need to understand this proof now
#check bar
#check (bar 2 : ∀ (n : ℤ), 2 + n - 2 = n + 2 - 2)
#check (bar 2 5 : 2 + 5 - 2 = 5 + 2 - 2)
/- In below,
-`flt` is the __name_of_theorem__ which we can invoke later.
- `(x y z n : ℕ)` is th __context__ of the theorem:
- `n > 2 → x * y * z ≠ 0 → x^n + y^n ≠ z^n` is the __statement__ of the theorem:
-`sorry` is a way of telling Lean that we are going to supply a __proof__ later.
-/
theorem flt (x y z n : ℕ) :
n > 2 → x * y * z ≠ 0 → x^n + y^n ≠ z^n :=
sorry
theorem goldbach : ∀ n, 2 < n → n % 2 = 0 →
∃ p q : ℕ, p.prime ∧ q.prime ∧ n = p + q :=
sorry
/-
If we do not want to refer to the result we are proving we can simply declare it as `example`. It works the same way as theorem declaration, but without a name.
-/
example :
2 + 3 = 5 :=
rfl
end --end of the section
/-
Here we are going to a state a lemma which says that equality in a type `X` is symmetric, i.e. if `x = y` in X then `y = x`. We are going to call this lemma `symme_of_eq`, but you could as well chosen a different name.
Here's a proof of the lemma `symm_of_eq` (symmetry of equality) for any type `X` in the tactic style.
-/
lemma symm_of_eq {X : Type} (x y : X) (h₁ : x = y) :
y = x :=
begin
rw h₁,
end
/-
Here's a proof of the lemma `trans_of_eq` (transitivity of equality) for any type `X` in the tactic style.
-/
lemma trans_of_eq {X : Type} (x y z : X) (h₁ : x = y) (h₂ : y = z) :
x = z :=
begin
rw h₁,
rw h₂,
end
/-! ### Using definitions, lemmas, theorems -/
/-
We prove the lemma `bar` above, and we would like to use it to prove
`2 + n - 1 = n + 2 - 1` :=
which is a special case of `bar` when `m =1`. We do this by the expression `bar 1 n`.
-/
example (n : ℤ) :
2 + n - 1 = n + 2 - 1 :=
bar 1 n
#check eq.symm -- a lemma in lean library
example (m n : ℕ) (e : m^2 = n) :
n = m^2 :=
begin
exact (eq.symm e), -- here's how we use the lemma `eq.symm`.
end
#check eq.subst
example (m n : ℕ) (h : n + 1 = 7) (e : m = n) : m + 1 = 7 :=
begin
exact eq.subst (eq.symm e) h,
end
#check (zero_mul : ∀ x : ℝ, 0 * x = 0) -- this lemma says that for all real numbers `x`, multiplying `x` by zero on the left yields zero.
example (x y : ℕ) (h₁ : x = 0) (h₂ : y = 0) :
x * y = 0 :=
begin
rw h₁, -- we substitute `0` for `x` in the goal
rw h₂, -- we substitute `0` for `y` in the goal
exact zero_mul 0, -- we apply lemma `zero_mul` to `0` to prove that `0 * 0 = 0`.
end
-- another proof of the same statement
example (x y : ℕ) (h₁ : x = 0) (h₂ : y = 0) :
x * y = 0 :=
begin
rw h₂,
exact zero_mul y, -- this time we apply lemma `zero_mul` to `y`, to prove that `0 * y = 0`.
end
-- yet another proof of the same statement
example (x y : ℕ) (h₁ : x = 0) (h₂ : y = 0) :
x * y = 0 :=
begin
rw h₁,
rw h₂,
exact mul_zero 0, -- `mul_zero` isntead of `zero_mul`.
end
/-
remember the example below from previos lecture? we had the problem of applying `rw` directly to `h₁` (since `x + 0` is not a subexpression of the goal), so we applied the tactic `change`. But we could also use the lemma `add_zero : ∀ (a : ℕ), a + 0 = a` to first repalce `x + 0` by `x` in hypothesis `h₁` to obtain a new `h₁ : x = y`, and then replace `x` by `y` in the goal using `rw h₁`. The new goal is now `y = z`. Finally, we finish the proof by copying `h₂`.
-/
example (x y z : ℕ)
(h₁ : x + 0 = y) (h₂ : y = z) : x = z :=
begin
-- rw h, -- fails because rw works up to syntactic equality
rw add_zero at h₁, -- would also work; note that the proof of `add_zero` is `refl`.
rw h₁, -- now it works
exact h₂,
end
-- maybe seach_library or suggest?
lemma add_sub_left (x y z : ℕ) :
x + y - x = y :=
begin
rw add_comm,
-- seach_library
-- suggest
exact nat.add_sub_cancel y x,
end
#lint
example (x y z : ℕ) :
x + y - x = y :=
begin
rw add_comm,
refine nat.add_sub_cancel _ _, -- use show_term to get the exact term
end
/-
In the following exercises, we will use the following two lemmas:
` mul_assoc a b c : a * b * c = a * (b * c) `
` mul_comm a b : a * b = b * a `
Hence the command
`rw mul_assoc a b c`,
will replace `a * b * c` by `a * (b * c)` in the current goal.
In order to replace backward, we use
` rw ← mul_assoc a b c`,
replacing `a * ( b * c )` by `a * b * c` in the current goal.
-/
example (a b c : ℝ) :
(a * b) * c = b * (a * c) :=
begin
rw mul_comm a b,
rw mul_assoc b a c,
end
example (a b c : ℝ) : a * (b * c) = b * (a * c) :=
begin
rw ← mul_assoc a b c,
nth_rewrite 1 mul_comm,
rw mul_assoc,
end
/-
Now let's return to the preceding example to experiment with what happens if we don't give arguments to `mul_assoc` or `mul_comm`. For instance, you can start the next proof with
`rw ← mul_assoc`,
Try to figure out what happens.
-/
example (a b c : ℝ) :
a * (b * c) = b * (a * c) :=
begin
rw ← mul_assoc,
nth_rewrite 1 mul_comm,
rw mul_assoc,
end
example (a b c : ℝ) :
a * (b * c) = b * (a * c) :=
begin
rw mul_comm,
rw mul_assoc,
nth_rewrite 1 mul_comm,
end
/- We can also perform _rewriting in an assumption_ of the local context, using for instance
`rw mul_comm a b at h`,
in order to replace `a * b` by `b * a` in assumption `h`.
The next example will use a third lemma:
`two_mul a : 2 * a = a + a`
-/
example (a b c d : ℝ) (h₁ : c = d * a + b) (h₂ : b = a * d) : c = 2 * a * d :=
begin
rw h₂ at h₁,
rw mul_comm at h₁,
rw ← two_mul (a * d) at h₁,
rw ← mul_assoc at h₁,
exact h₁,
end
end PROOFS |
#define BOOST_TEST_MODULE "dsn::countof"
#include <dsnutil/countof.h>
#include <iostream>
#include <boost/test/unit_test.hpp>
// test countof for foo[known_size]
BOOST_AUTO_TEST_CASE(basic_countof)
{
const size_t size{ 3 };
int foo[size] = { 1, 2, 3 };
BOOST_CHECK(dsn::countof(foo) == size);
}
// test countof for foo[]
BOOST_AUTO_TEST_CASE(deduced_countof)
{
const size_t size{ 3 };
int foo[] = { 1, 2, 3 };
BOOST_CHECK(dsn::countof(foo) == size);
}
|
-- ch1 ex.1.23
import Statistics.Distribution.Normal
import qualified Statistics.Distribution as S
normalD :: NormalDistribution
normalD = normalDistr mean stdD
where
mean = 75
stdD = 20
main :: IO ()
main = do
-- ratio greater than 95 sec:
putStrLn $ "the ratio of longer than 95 second: "
++ show (S.complCumulative normalD 95)
putStrLn $ "Between 35 sec and 115 sec: "
++ show ((S.complCumulative normalD 35) - (S.complCumulative normalD 115))
putStrLn $ "more than 2 min: "
++ show (S.complCumulative normalD 120)
|
import util.data.nat
open nat (hiding zero_le)
open list
def fin_interleave (n : ℕ) (i : ℕ) : fin (succ n) :=
⟨i % succ n,mod_lt _ (succ_le_succ $ nat.zero_le _)⟩
theorem inf_repeat_fin_inter {n : ℕ} : ∀ x i, ∃ j, fin_interleave n (i+j) = x :=
begin
intro x,
cases x with x H,
intro i,
existsi x + succ n - (i % succ n),
tactic.swap,
unfold fin_interleave,
have h : i % succ n ≤ succ n,
{ apply nat.le_of_lt (mod_lt _ _),
apply succ_le_succ, apply nat.zero_le },
apply fin.eq_of_veq, unfold fin.val ,
rw [nat.add_sub_assoc h,add_comm x,← add_assoc,mod_add,@mod_add i],
rw [← @mod_add' (i % succ n),← nat.add_sub_assoc h],
rw [nat.add_sub_cancel_left, nat.mod_self',nat.zero_add,mod_mod,mod_of_lt],
apply H,
end
|
lemma coeffs_1_eq [simp, code abstract]: "coeffs 1 = [1]" |
Data from Gunston , Tupolev Aircraft since 1922
|
State Before: x : ℝ
h : x ≠ -1
⊢ HasDerivWithinAt arcsin (1 / sqrt (1 - x ^ 2)) (Ici x) x State After: case inl
h : 1 ≠ -1
⊢ HasDerivWithinAt arcsin (1 / sqrt (1 - 1 ^ 2)) (Ici 1) 1
case inr
x : ℝ
h : x ≠ -1
h' : x ≠ 1
⊢ HasDerivWithinAt arcsin (1 / sqrt (1 - x ^ 2)) (Ici x) x Tactic: rcases eq_or_ne x 1 with (rfl | h') State Before: case inl
h : 1 ≠ -1
⊢ HasDerivWithinAt arcsin (1 / sqrt (1 - 1 ^ 2)) (Ici 1) 1 State After: no goals Tactic: convert (hasDerivWithinAt_const (1 : ℝ) _ (π / 2)).congr _ _ <;>
simp (config := { contextual := true }) [arcsin_of_one_le] State Before: case inr
x : ℝ
h : x ≠ -1
h' : x ≠ 1
⊢ HasDerivWithinAt arcsin (1 / sqrt (1 - x ^ 2)) (Ici x) x State After: no goals Tactic: exact (hasDerivAt_arcsin h h').hasDerivWithinAt |
[STATEMENT]
lemma dynT_subcls:
"\<lbrakk> a' \<noteq> Null; G,h\<turnstile>a'::\<preceq> Class C; dynT = fst (the (h (the_Addr a')));
is_class G dynT; ws_prog G \<rbrakk> \<Longrightarrow> G\<turnstile>dynT \<preceq>C C"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>a' \<noteq> Null; G,h \<turnstile> a' ::\<preceq> Class C; dynT = cname_of h a'; is_class G dynT; ws_prog G\<rbrakk> \<Longrightarrow> G \<turnstile> dynT \<preceq>C C
[PROOF STEP]
apply (case_tac "C = Object")
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<lbrakk>a' \<noteq> Null; G,h \<turnstile> a' ::\<preceq> Class C; dynT = cname_of h a'; is_class G dynT; ws_prog G; C = Object\<rbrakk> \<Longrightarrow> G \<turnstile> dynT \<preceq>C C
2. \<lbrakk>a' \<noteq> Null; G,h \<turnstile> a' ::\<preceq> Class C; dynT = cname_of h a'; is_class G dynT; ws_prog G; C \<noteq> Object\<rbrakk> \<Longrightarrow> G \<turnstile> dynT \<preceq>C C
[PROOF STEP]
apply (simp, rule subcls_C_Object, assumption+)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>a' \<noteq> Null; G,h \<turnstile> a' ::\<preceq> Class C; dynT = cname_of h a'; is_class G dynT; ws_prog G; C \<noteq> Object\<rbrakk> \<Longrightarrow> G \<turnstile> dynT \<preceq>C C
[PROOF STEP]
apply simp
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>a' \<noteq> Null; G,h \<turnstile> a' ::\<preceq> Class C; dynT = cname_of h a'; is_class G (cname_of h a'); ws_prog G; C \<noteq> Object\<rbrakk> \<Longrightarrow> G \<turnstile> cname_of h a' \<preceq>C C
[PROOF STEP]
apply (frule non_np_objD, auto)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
[STATEMENT]
lemma insert_slot_rl2:
assumes "PROP P \<Longrightarrow> PROP (CONSTRAINT_SLOT S) \<Longrightarrow> PROP Q"
shows "PROP (CONSTRAINT_SLOT (PROP S &&& PROP P)) \<Longrightarrow> PROP Q"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. CONSTRAINT_SLOT (PROP S &&& PROP P) \<Longrightarrow> PROP Q
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>PROP P; CONSTRAINT_SLOT PROP S\<rbrakk> \<Longrightarrow> PROP Q
goal (1 subgoal):
1. CONSTRAINT_SLOT (PROP S &&& PROP P) \<Longrightarrow> PROP Q
[PROOF STEP]
unfolding CONSTRAINT_SLOT_def conjunction_def
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>PROP P; PROP S\<rbrakk> \<Longrightarrow> PROP Q
goal (1 subgoal):
1. (\<And>C. (\<lbrakk>PROP S; PROP P\<rbrakk> \<Longrightarrow> PROP C) \<Longrightarrow> PROP C) \<Longrightarrow> PROP Q
[PROOF STEP]
. |
(*
Copyright 2018
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.
*)
theory atomic_int64_test_and_set_mem
imports spinlock
begin
text \<open>Up to two locales per function in the binary.\<close>
locale atomic_int64_test_and_set_function = spinlock_context +
fixes rsp\<^sub>0 rbp\<^sub>0 a atomic_int64_test_and_set_ret :: \<open>64 word\<close>
and v\<^sub>0 :: \<open>8 word\<close>
and blocks :: \<open>(nat \<times> 64 word \<times> nat) set\<close>
assumes seps: \<open>seps blocks\<close>
and masters:
\<open>master blocks (a, 1) 0\<close>
\<open>master blocks (rsp\<^sub>0-16, 8) 1\<close>
\<open>master blocks (rsp\<^sub>0, 8) 2\<close>
and ret_address: \<open>outside atomic_int64_test_and_set_ret 11 44\<close> \<comment> \<open>Only works for non-recursive functions.\<close>
begin
text \<open>
The Floyd invariant expresses for some locations properties that are invariably true.
Simply expresses that a byte in the memory remains untouched.
\<close>
definition pp_\<Theta> :: floyd_invar where
\<open>pp_\<Theta> \<equiv> [
\<comment> \<open>precondition\<close>
boffset+11 \<mapsto> \<lambda>\<sigma>. regs \<sigma> rsp = rsp\<^sub>0
\<and> regs \<sigma> rbp = rbp\<^sub>0
\<and> \<sigma> \<turnstile> *[rsp\<^sub>0,8] = boffset+atomic_int64_test_and_set_ret
\<and> \<sigma> \<turnstile> *[a,1] = v\<^sub>0,
boffset+31 \<mapsto> \<lambda>\<sigma>. regs \<sigma> rsp = rsp\<^sub>0-8
\<and> regs \<sigma> rbp = rsp\<^sub>0-8
\<and> \<sigma> \<turnstile> *[rsp\<^sub>0,8] = boffset+atomic_int64_test_and_set_ret
\<and> \<sigma> \<turnstile> *[a,1] = v\<^sub>0,
\<comment> \<open>postcondition\<close>
boffset+atomic_int64_test_and_set_ret \<mapsto> \<lambda>\<sigma>. \<sigma> \<turnstile> *[a,1] = v\<^sub>0
\<and> regs \<sigma> rsp = rsp\<^sub>0+8
\<^cancel>\<open>\<and> regs \<sigma> rbp = rbp\<^sub>0\<close> \<comment> \<open>TODO: work in flow-through of rbp0 as necessary (such as when pushed, etc.)\<close>
]\<close>
text \<open>Adding some rules to the simplifier to simplify proofs.\<close>
schematic_goal pp_\<Theta>_zero[simp]:
\<open>pp_\<Theta> boffset = ?x\<close>
unfolding pp_\<Theta>_def
by simp
schematic_goal pp_\<Theta>_numeral_l[simp]:
\<open>pp_\<Theta> (n + boffset) = ?x\<close>
unfolding pp_\<Theta>_def
by simp
schematic_goal pp_\<Theta>_numeral_r[simp]:
\<open>pp_\<Theta> (boffset + n) = ?x\<close>
unfolding pp_\<Theta>_def
by simp
lemma rewrite_atomic_int64_test_and_set_mem:
\<open>is_std_invar atomic_int64_test_and_set_ret (floyd.invar atomic_int64_test_and_set_ret pp_\<Theta>)\<close>
text \<open>Boilerplate code to start the VCG\<close>
apply (rule floyd_invarI)
apply (rewrite at \<open>floyd_vcs atomic_int64_test_and_set_ret \<hole> _\<close> pp_\<Theta>_def)
apply (intro floyd_vcsI)
text \<open>Subgoal for rip = boffset+11\<close>
subgoal premises prems for \<sigma>
text \<open>Insert relevant knowledge\<close>
apply (insert prems seps ret_address)
text \<open>Apply VCG/symb.\ execution\<close>
apply (restart_symbolic_execution?, (symbolic_execution masters: masters)+, (finish_symbolic_execution masters: masters)?)+
done
text \<open>Subgoal for rip = boffset+31\<close>
subgoal premises prems for \<sigma>
text \<open>Insert relevant knowledge\<close>
apply (insert prems seps ret_address)
text \<open>Apply VCG/symb.\ execution\<close>
apply (restart_symbolic_execution?, (symbolic_execution masters: masters)+, (finish_symbolic_execution masters: masters)?)+
done
text \<open>Trivial ending subgoal.\<close>
subgoal
by simp
done
end
end
|
module SHE-Prelude where
record Functor (T : Set -> Set) : Set1 where
field
-- OPERATIONS ----------------------------------------------
map : forall {X Y} -> (X -> Y) -> T X -> T Y
record Applicative (T : Set -> Set) : Set1 where
field
-- OPERATIONS ----------------------------------------------
pure : forall {X} -> X -> T X
_<*>_ : forall {X Y} -> T (X -> Y) -> T X -> T Y
data Zero : Set where
magic : forall {l}{A : Set l} -> Zero -> A
magic ()
record One : Set where
constructor <>
open One public
{-# COMPILED_DATA One () () #-}
|
[STATEMENT]
lemma sinks_aux_single_dom:
"sinks_aux I D {u} xs = insert u (sinks I D u xs)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. sinks_aux I D {u} xs = insert u (sinks I D u xs)
[PROOF STEP]
by (induction xs rule: rev_induct, simp_all add: insert_commute) |
lemma fract_poly_eq_iff [simp]: "fract_poly p = fract_poly q \<longleftrightarrow> p = q" |
[STATEMENT]
lemma qTerm_templateInduct[case_names Var Op Abs]:
fixes X :: "('index,'bindex,'varSort,'var,'opSym)qTerm"
and A :: "('index,'bindex,'varSort,'var,'opSym)qAbs"
and phi phiAbs and rel
assumes
REL: "\<And> X Y. (X,Y) \<in> rel \<Longrightarrow> qSkel Y = qSkel X" and
Var: "\<And> xs x. phi (qVar xs x)" and
Op: "\<And> delta inp binp. \<lbrakk>liftAll phi inp; liftAll phiAbs binp\<rbrakk>
\<Longrightarrow> phi (qOp delta inp binp)" and
Abs: "\<And> xs x X. (\<And> Y. (X,Y) \<in> rel \<Longrightarrow> phi Y) \<Longrightarrow> phiAbs (qAbs xs x X)"
shows "phi X \<and> phiAbs A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. phi X \<and> phiAbs A
[PROOF STEP]
proof-
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. phi X \<and> phiAbs A
[PROOF STEP]
{
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. phi X \<and> phiAbs A
[PROOF STEP]
fix T
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. phi X \<and> phiAbs A
[PROOF STEP]
have "\<forall> X A. (T = qSkel X \<longrightarrow> phi X) \<and> (T = qSkelAbs A \<longrightarrow> phiAbs A)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>X A. (T = qSkel X \<longrightarrow> phi X) \<and> (T = qSkelAbs A \<longrightarrow> phiAbs A)
[PROOF STEP]
proof(induct rule: treeLess_induct)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>T'. (\<And>T. (T, T') \<in> treeLess \<Longrightarrow> \<forall>X A. (T = qSkel X \<longrightarrow> phi X) \<and> (T = qSkelAbs A \<longrightarrow> phiAbs A)) \<Longrightarrow> \<forall>X A. (T' = qSkel X \<longrightarrow> phi X) \<and> (T' = qSkelAbs A \<longrightarrow> phiAbs A)
[PROOF STEP]
case (1 T')
[PROOF STATE]
proof (state)
this:
(?T, T') \<in> treeLess \<Longrightarrow> \<forall>X A. (?T = qSkel X \<longrightarrow> phi X) \<and> (?T = qSkelAbs A \<longrightarrow> phiAbs A)
goal (1 subgoal):
1. \<And>T'. (\<And>T. (T, T') \<in> treeLess \<Longrightarrow> \<forall>X A. (T = qSkel X \<longrightarrow> phi X) \<and> (T = qSkelAbs A \<longrightarrow> phiAbs A)) \<Longrightarrow> \<forall>X A. (T' = qSkel X \<longrightarrow> phi X) \<and> (T' = qSkelAbs A \<longrightarrow> phiAbs A)
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>X A. (T' = qSkel X \<longrightarrow> phi X) \<and> (T' = qSkelAbs A \<longrightarrow> phiAbs A)
[PROOF STEP]
apply safe
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>X A. T' = qSkel X \<Longrightarrow> phi X
2. \<And>X A. T' = qSkelAbs A \<Longrightarrow> phiAbs A
[PROOF STEP]
subgoal for X _
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. T' = qSkel X \<Longrightarrow> phi X
[PROOF STEP]
using assms 1
[PROOF STATE]
proof (prove)
using this:
(?X, ?Y) \<in> rel \<Longrightarrow> qSkel ?Y = qSkel ?X
phi (qVar ?xs ?x)
\<lbrakk>liftAll phi ?inp; liftAll phiAbs ?binp\<rbrakk> \<Longrightarrow> phi (qOp ?delta ?inp ?binp)
(\<And>Y. (?X, Y) \<in> rel \<Longrightarrow> phi Y) \<Longrightarrow> phiAbs (qAbs ?xs ?x ?X)
(?T, T') \<in> treeLess \<Longrightarrow> \<forall>X A. (?T = qSkel X \<longrightarrow> phi X) \<and> (?T = qSkelAbs A \<longrightarrow> phiAbs A)
goal (1 subgoal):
1. T' = qSkel X \<Longrightarrow> phi X
[PROOF STEP]
unfolding treeLess_def liftAll_def
[PROOF STATE]
proof (prove)
using this:
(?X, ?Y) \<in> rel \<Longrightarrow> qSkel ?Y = qSkel ?X
phi (qVar ?xs ?x)
\<lbrakk>\<forall>i v. ?inp i = Some v \<longrightarrow> phi v; \<forall>i v. ?binp i = Some v \<longrightarrow> phiAbs v\<rbrakk> \<Longrightarrow> phi (qOp ?delta ?inp ?binp)
(\<And>Y. (?X, Y) \<in> rel \<Longrightarrow> phi Y) \<Longrightarrow> phiAbs (qAbs ?xs ?x ?X)
(?T, T') \<in> {(T, T'). \<exists>inp binp i j. T' = Branch inp binp \<and> (inp i = Some T \<or> binp j = Some T)} \<Longrightarrow> \<forall>X A. (?T = qSkel X \<longrightarrow> phi X) \<and> (?T = qSkelAbs A \<longrightarrow> phiAbs A)
goal (1 subgoal):
1. T' = qSkel X \<Longrightarrow> phi X
[PROOF STEP]
by (cases X) (auto simp add: lift_def, metis option.simps(5))
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>X A. T' = qSkelAbs A \<Longrightarrow> phiAbs A
[PROOF STEP]
subgoal for _ A
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. T' = qSkelAbs A \<Longrightarrow> phiAbs A
[PROOF STEP]
apply (cases A)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>x1 x2 x3. \<lbrakk>T' = qSkelAbs A; A = qAbs x1 x2 x3\<rbrakk> \<Longrightarrow> phiAbs A
[PROOF STEP]
using assms 1
[PROOF STATE]
proof (prove)
using this:
(?X, ?Y) \<in> rel \<Longrightarrow> qSkel ?Y = qSkel ?X
phi (qVar ?xs ?x)
\<lbrakk>liftAll phi ?inp; liftAll phiAbs ?binp\<rbrakk> \<Longrightarrow> phi (qOp ?delta ?inp ?binp)
(\<And>Y. (?X, Y) \<in> rel \<Longrightarrow> phi Y) \<Longrightarrow> phiAbs (qAbs ?xs ?x ?X)
(?T, T') \<in> treeLess \<Longrightarrow> \<forall>X A. (?T = qSkel X \<longrightarrow> phi X) \<and> (?T = qSkelAbs A \<longrightarrow> phiAbs A)
goal (1 subgoal):
1. \<And>x1 x2 x3. \<lbrakk>T' = qSkelAbs A; A = qAbs x1 x2 x3\<rbrakk> \<Longrightarrow> phiAbs A
[PROOF STEP]
unfolding treeLess_def
[PROOF STATE]
proof (prove)
using this:
(?X, ?Y) \<in> rel \<Longrightarrow> qSkel ?Y = qSkel ?X
phi (qVar ?xs ?x)
\<lbrakk>liftAll phi ?inp; liftAll phiAbs ?binp\<rbrakk> \<Longrightarrow> phi (qOp ?delta ?inp ?binp)
(\<And>Y. (?X, Y) \<in> rel \<Longrightarrow> phi Y) \<Longrightarrow> phiAbs (qAbs ?xs ?x ?X)
(?T, T') \<in> {(T, T'). \<exists>inp binp i j. T' = Branch inp binp \<and> (inp i = Some T \<or> binp j = Some T)} \<Longrightarrow> \<forall>X A. (?T = qSkel X \<longrightarrow> phi X) \<and> (?T = qSkelAbs A \<longrightarrow> phiAbs A)
goal (1 subgoal):
1. \<And>x1 x2 x3. \<lbrakk>T' = qSkelAbs A; A = qAbs x1 x2 x3\<rbrakk> \<Longrightarrow> phiAbs A
[PROOF STEP]
by simp
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
.
[PROOF STATE]
proof (state)
this:
\<forall>X A. (T' = qSkel X \<longrightarrow> phi X) \<and> (T' = qSkelAbs A \<longrightarrow> phiAbs A)
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<forall>X A. (T = qSkel X \<longrightarrow> phi X) \<and> (T = qSkelAbs A \<longrightarrow> phiAbs A)
goal (1 subgoal):
1. phi X \<and> phiAbs A
[PROOF STEP]
}
[PROOF STATE]
proof (state)
this:
\<forall>X A. (?T2 = qSkel X \<longrightarrow> phi X) \<and> (?T2 = qSkelAbs A \<longrightarrow> phiAbs A)
goal (1 subgoal):
1. phi X \<and> phiAbs A
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
\<forall>X A. (?T2 = qSkel X \<longrightarrow> phi X) \<and> (?T2 = qSkelAbs A \<longrightarrow> phiAbs A)
goal (1 subgoal):
1. phi X \<and> phiAbs A
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
phi X \<and> phiAbs A
goal:
No subgoals!
[PROOF STEP]
qed |
As a business owner, what do you see your role in your business? Servicing your customers or spending time ensuring you meet your business obligations for the government? The reality is you need to do both, which can impede on your work/life balance.
Hi, my name is Lance Rebetzke and I own and operate FAB Bookkeeping Arana Hills. My role is to relieve you of the time and stress and keeping your financial records current and relevant to understand your business. This will assist you with finding additional time to service your clients as you would like and to have more time to enjoy your precious family time.
FAB Bookkeeping Arana Hills services Arana Hills, Ferny Hills, Everton Park, Stafford Heights, Keperra Mitchelton, Kedron, Everton Hills, Gaythorne and Brookside Centre.
As a fully compliant Authorized Representative specialising in Business Protection, I can provide plans ensuring that your business would survive financially should you suffer major illness, injury or death. |
import for_mathlib.derived.Ext_lemmas
import for_mathlib.Cech.homotopy
import for_mathlib.acyclic
import for_mathlib.exact_seq4
import for_mathlib.cech
import for_mathlib.chain_complex_exact
import for_mathlib.abelian_sheaves.exact
import for_mathlib.Cech.homotopy
import for_mathlib.wide_pullback_iso
import for_mathlib.equivalence_additive
import condensed.adjunctions2
import condensed.projective_resolution
import condensed.extr.equivalence
.
noncomputable theory
universes u
open category_theory category_theory.limits homotopy_category opposite
open function (surjective)
namespace condensed
set_option pp.universes true
-- ANNOYING!
instance presheaf_abelian : abelian (Profinite.{u}ᵒᵖ ⥤ Ab.{u+1}) :=
category_theory.functor_category_is_abelian.{(u+2) u (u+1)}
-- ANNOYING!
instance ExtrDisc_presheaf_abelian : abelian (ExtrDisc.{u}ᵒᵖ ⥤ Ab.{u+1}) :=
category_theory.functor_category_is_abelian.{(u+2) u (u+1)}
instance ExtrSheaf_abelian' : abelian (Sheaf ExtrDisc.proetale_topology.{u} Ab.{u+1}) :=
category_theory.Sheaf.abelian.{(u+2) u (u+1)}
instance ExtrSheaf_abelian : abelian (ExtrSheaf.{u} Ab.{u+1}) :=
category_theory.Sheaf.abelian.{(u+2) u (u+1)}
def Profinite_to_presheaf_Ab : Profinite.{u} ⥤ Profinite.{u}ᵒᵖ ⥤ Ab.{u+1} :=
yoneda ⋙ (whiskering_right _ _ _).obj (ulift_functor.{u+1} ⋙ AddCommGroup.free)
def Profinite_to_ExtrDisc_presheaf : Profinite.{u} ⥤ ExtrDisc.{u}ᵒᵖ ⥤ Type (u+1) :=
yoneda ⋙ (whiskering_left _ _ _).obj ExtrDisc_to_Profinite.op ⋙
(whiskering_right _ _ _).obj ulift_functor.{u+1}
def Profinite_to_ExtrDisc_presheaf_Ab : Profinite.{u} ⥤ ExtrDisc.{u}ᵒᵖ ⥤ Ab.{u+1} :=
yoneda ⋙ (whiskering_left _ _ _).obj ExtrDisc_to_Profinite.op ⋙
(whiskering_right _ _ _).obj (ulift_functor.{u+1} ⋙ AddCommGroup.free)
def unsheafified_free_Cech' (F : arrow Profinite.{u}) :
chain_complex (Profinite.{u}ᵒᵖ ⥤ Ab.{u+1}) ℕ :=
simplicial_object.augmented.to_complex $
(((simplicial_object.augmented.whiskering _ _).obj Profinite_to_presheaf_Ab).obj
F.augmented_cech_nerve)
def unsheafified_free_ExtrDiscr_Cech (F : arrow Profinite.{u}) :
chain_complex (ExtrDisc.{u}ᵒᵖ ⥤ Ab.{u+1}) ℕ :=
simplicial_object.augmented.to_complex $
(((simplicial_object.augmented.whiskering _ _).obj Profinite_to_ExtrDisc_presheaf_Ab).obj
F.augmented_cech_nerve)
def free_Cech' (F : arrow Profinite.{u}) :
chain_complex (Condensed.{u} Ab.{u+1}) ℕ :=
(((simplicial_object.augmented.whiskering _ _).obj
(Profinite_to_Condensed ⋙ CondensedSet_to_Condensed_Ab)).obj
F.augmented_cech_nerve).to_complex
def free_ExtrDisc_Cech' (F : arrow Profinite.{u}) :
chain_complex (ExtrSheaf.{u} Ab.{u+1}) ℕ :=
(((simplicial_object.augmented.whiskering _ _).obj
(Profinite_to_ExtrDisc_presheaf_Ab ⋙ presheaf_to_Sheaf _ _)).obj
F.augmented_cech_nerve).to_complex
def free_Cech (F : arrow Profinite.{u}) :
chain_complex (Condensed.{u} Ab.{u+1}) ℤ :=
(homological_complex.embed $ complex_shape.embedding.nat_down_int_down).obj (free_Cech' F)
instance Condensed_ExtrSheaf_equiv_additive :
functor.additive (Condensed_ExtrSheaf_equiv Ab.{u+1}).inverse :=
by constructor
def whiskering_Cech_comp_iso
{C : Type*} [category C] {𝓐 : Type*} [category 𝓐] [abelian 𝓐] {𝓑 : Type*} [category 𝓑] [abelian 𝓑]
(f : arrow C)
[∀ (n : ℕ), has_wide_pullback f.right (λ (i : fin (n + 1)), f.left) (λ (i : fin (n + 1)), f.hom)]
(F : C ⥤ 𝓐) (G : 𝓐 ⥤ 𝓑) (H : C ⥤ 𝓑) (E : F ⋙ G ≅ H) [G.additive] :
(G.map_homological_complex _).obj ((((simplicial_object.augmented.whiskering _ _).obj F).obj
f.augmented_cech_nerve).to_complex) ≅
(((simplicial_object.augmented.whiskering _ _).obj H).obj f.augmented_cech_nerve).to_complex :=
homological_complex.hom.iso_of_components
(λ i,
match i with
| 0 := E.app _
| i+1 := E.app _
end)
begin
rintros i j (rfl : j + 1 = i),
dsimp only [functor.map_homological_complex_obj_d,
unsheafified_free_ExtrDiscr_Cech, free_ExtrDisc_Cech',
simplicial_object.augmented.to_complex],
rw [chain_complex.of_d, chain_complex.of_d],
cases j,
{ dsimp only [whiskering_Cech_comp_iso._match_1],
dsimp only [simplicial_object.augmented.to_complex_d,
simplicial_object.augmented.whiskering_obj_2,
simplicial_object.augmented.whiskering_obj,
nat_trans.comp_app, whisker_right_app, functor.const_comp_hom_app],
rw [category.comp_id, category.comp_id, nat_iso.app_hom, ← E.hom.naturality],
refl },
{
dsimp only [whiskering_Cech_comp_iso._match_1],
dsimp only [simplicial_object.augmented.to_complex_d,
simplicial_object.augmented.drop_obj,
simplicial_object.augmented.whiskering_obj_2,
simplicial_object.augmented.whiskering_obj,
simplicial_object.whiskering_obj_obj_map,
simplicial_object.boundary,
nat_iso.app_hom],
simp only [functor.map_sum, functor.map_zsmul, preadditive.comp_sum,
preadditive.comp_zsmul, preadditive.sum_comp, preadditive.zsmul_comp],
apply finset.sum_congr rfl, intros _ _,
erw ← E.hom.naturality,
refl, },
end
def free_Cech'_iso_ExtrDisc (F : arrow Profinite.{u}) :
((Condensed_ExtrSheaf_equiv _).inverse.map_homological_complex _).obj (free_Cech' F) ≅
free_ExtrDisc_Cech' F :=
let e := ExtrDisc_sheafification_iso in
whiskering_Cech_comp_iso F
(Profinite_to_Condensed.{u} ⋙ CondensedSet_to_Condensed_Ab.{u})
((Condensed_ExtrSheaf_equiv.{u u+2} Ab.{u+1}).inverse)
(Profinite_to_ExtrDisc_presheaf_Ab.{u} ⋙ presheaf_to_Sheaf.{u+2 u u+1} ExtrDisc.proetale_topology.{u} Ab.{u+1}) $
nat_iso.of_components
(λ S, e.symm.app _)
begin
intros S T f,
dsimp only [nat_iso.app_hom],
erw e.symm.hom.naturality,
refl,
end
instance presheaf_to_Sheaf_additive :
(presheaf_to_Sheaf.{u+2 u u+1} ExtrDisc.proetale_topology.{u} Ab.{u+1}).additive :=
category_theory.Sheaf.presheaf_to_Sheaf_additive.{u+2 u u+1}
def acyclic_of_exact.induction_step_ex₂_aux
{C : Type*} [category C] {𝓐 : Type*} [category 𝓐] [abelian 𝓐] {𝓑 : Type*} [category 𝓑] [abelian 𝓑]
(f : arrow C)
[∀ (n : ℕ), has_wide_pullback f.right (λ (i : fin (n + 1)), f.left) (λ (i : fin (n + 1)), f.hom)]
(F : C ⥤ 𝓐) (G : 𝓐ᵒᵖ ⥤ 𝓑) [G.additive] :
(G.map_homological_complex _).obj ((((simplicial_object.augmented.whiskering _ _).obj F).obj
f.augmented_cech_nerve).to_complex).op ≅
(((cosimplicial_object.augmented.whiskering _ _).obj (F.op ⋙ G)).obj
f.augmented_cech_nerve.right_op).to_cocomplex :=
homological_complex.hom.iso_of_components
(λ i,
match i with
| 0 := iso.refl _
| i+1 := iso.refl _
end)
begin
rintros i j (rfl : i + 1 = j),
dsimp only [functor.map_homological_complex_obj_d,
unsheafified_free_ExtrDiscr_Cech, free_ExtrDisc_Cech',
cosimplicial_object.augmented.to_cocomplex,
simplicial_object.augmented.to_complex, homological_complex.op_d],
rw [cochain_complex.of_d, chain_complex.of_d],
cases i,
{ refine (category.id_comp _).trans ((category.comp_id _).trans _).symm,
dsimp only [simplicial_object.augmented.to_complex_d,
cosimplicial_object.augmented.to_cocomplex_d,
simplicial_object.augmented.whiskering_obj_2,
simplicial_object.augmented.whiskering_obj,
cosimplicial_object.augmented.whiskering_obj_2,
cosimplicial_object.augmented.whiskering_obj,
nat_trans.comp_app, whisker_right_app,
functor.const_comp_hom_app, functor.const_comp_inv_app],
rw [category.comp_id, category.id_comp],
refl, },
{ refine (category.id_comp _).trans ((category.comp_id _).trans _).symm,
dsimp only [simplicial_object.augmented.to_complex_d,
simplicial_object.augmented.drop_obj,
simplicial_object.augmented.whiskering_obj_2,
simplicial_object.augmented.whiskering_obj,
simplicial_object.whiskering_obj_obj_map,
simplicial_object.boundary,
cosimplicial_object.augmented.to_cocomplex_d,
cosimplicial_object.augmented.drop_obj,
cosimplicial_object.augmented.whiskering_obj_2,
cosimplicial_object.augmented.whiskering_obj,
cosimplicial_object.whiskering_obj_obj_map,
cosimplicial_object.coboundary],
simp only [G.map_sum, G.map_zsmul, op_sum, op_zsmul],
refl, },
end
def free_ExtrDisc_Cech'_iso (F : arrow Profinite.{u}) :
free_ExtrDisc_Cech' F ≅
((presheaf_to_Sheaf _ _).map_homological_complex _).obj (unsheafified_free_ExtrDiscr_Cech F) :=
(whiskering_Cech_comp_iso F _ _ _ $ iso.refl _).symm
/-
homological_complex.hom.iso_of_components
(λ i,
match i with
| 0 := iso.refl _
| i+1 := iso.refl _
end)
begin
rintros i j (rfl : j + 1 = i),
dsimp only [functor.map_homological_complex_obj_d,
unsheafified_free_ExtrDiscr_Cech, free_ExtrDisc_Cech',
simplicial_object.augmented.to_complex],
rw [chain_complex.of_d, chain_complex.of_d],
cases j,
{ refine (category.id_comp _).trans ((category.comp_id _).trans _).symm,
dsimp only [simplicial_object.augmented.to_complex_d,
simplicial_object.augmented.whiskering_obj_2,
simplicial_object.augmented.whiskering_obj,
nat_trans.comp_app, whisker_right_app, functor.const_comp_hom_app],
rw [category.comp_id, category.comp_id],
refl, },
{ refine (category.id_comp _).trans ((category.comp_id _).trans _).symm,
dsimp only [simplicial_object.augmented.to_complex_d,
simplicial_object.augmented.drop_obj,
simplicial_object.augmented.whiskering_obj_2,
simplicial_object.augmented.whiskering_obj,
simplicial_object.whiskering_obj_obj_map,
simplicial_object.boundary],
simp only [functor.map_sum, functor.map_zsmul],
refl, },
end
-/
/-
def free_Cech_iso (F : arrow Profinite.{u}) :
free_Cech F ≅ (homological_complex.embed $ complex_shape.embedding.nat_down_int_down).obj
((presheaf_to_Condensed_Ab.map_homological_complex _).obj
(unsheafified_free_Cech' F)) :=
homological_complex.hom.iso_of_components
(λ i,
match i with
| int.of_nat 0 := iso.refl _
| int.of_nat (n+1) := iso.refl _
| -[1+i] := iso.refl _
end)
(by admit)
-/
-- SO ANNOYING
instance evaluation_additive (X : ExtrDisc.{u}) :
functor.additive ((evaluation ExtrDisc.{u}ᵒᵖ Ab.{u+1}).obj (op X)) :=
category_theory.evaluation_additive.{(u+2) u (u+1)} _
def evaluated_free_ExtrDisc_Cech (F : arrow Profinite.{u}) (X : ExtrDisc.{u}) :
chain_complex Ab.{u+1} ℕ :=
(((simplicial_object.augmented.whiskering _ _).obj
AddCommGroup.free).obj $
((Profinite_to_ExtrDisc_presheaf.flip.obj (op X)).map_arrow.obj F).augmented_cech_nerve).to_complex
.
def yet_another_iso (F : arrow Profinite.{u}) (X : ExtrDisc.{u}) :
(((evaluation.{u u+1 u+1 u+2} ExtrDisc.{u}ᵒᵖ Ab.{u+1}).obj
(op X)).map_homological_complex
(complex_shape.down.{0} ℕ)).obj
(unsheafified_free_ExtrDiscr_Cech.{u} F) ≅
evaluated_free_ExtrDisc_Cech F X :=
homological_complex.hom.iso_of_components
(λ i,
match i with
| 0 := iso.refl _
| i+1 := begin apply AddCommGroup.free.map_iso, apply ulift_wide_pullback_iso, end
end)
begin
rintros (_|i) (_|j) ⟨rfl⟩,
{ dsimp [yet_another_iso._match_1, iso.refl_hom], rw category.comp_id,
dsimp [evaluated_free_ExtrDisc_Cech, unsheafified_free_ExtrDiscr_Cech],
rw if_pos (rfl : (1 : ℕ) = 0 + 1), erw category.id_comp,
rw if_pos (rfl : (1 : ℕ) = 0 + 1), erw category.id_comp,
apply free_abelian_group.lift.ext,
rintro ⟨t⟩,
dsimp [AddCommGroup.free, simplicial_object.augmented.to_complex_d],
simp only [category.comp_id, comp_apply, free_abelian_group.map_of_apply],
dsimp at t,
dsimp [ulift_wide_pullback_iso, ulift_wide_pullback_iso_hom_aux,
Profinite_to_ExtrDisc_presheaf_Ab], congr' 1,
have := types_comp_apply
(wide_pullback.lift (ulift_functor.{u+1 u}.map ((yoneda.{u u+1}.map
(wide_pullback.base (λ (_x : fin (0 + 0 + 1)), F.hom))).app
(op.{u+2} X.val))) (λ (q : fin (0 + 0 + 1)), ulift_functor.{u+1 u}.map
((yoneda.{u u+1}.map (wide_pullback.π (λ (_x : fin (0 + 0 + 1)),
F.hom) q)).app (op.{u+2} X.val))) _)
(wide_pullback.base (λ (i : fin (0 + 0 + 1)),
(Profinite_to_ExtrDisc_presheaf.{u}.map F.hom).app (op.{u+2} X)))
(ulift.up t),
rw ← this, clear this, rw wide_pullback.lift_base, refl },
{ dsimp [yet_another_iso._match_1,
evaluated_free_ExtrDisc_Cech,
unsheafified_free_ExtrDiscr_Cech],
rw [if_pos, if_pos], swap, refl, swap, refl, rw [category.id_comp, category.id_comp],
dsimp [simplicial_object.augmented.to_complex_d, simplicial_object.boundary],
simp only [preadditive.sum_comp, preadditive.comp_sum, preadditive.zsmul_comp,
preadditive.comp_zsmul, category_theory.nat_trans.app_sum,
category_theory.nat_trans.app_zsmul],
apply finset.sum_congr rfl, rintros i -, congr' 1,
dsimp [simplicial_object.δ],
apply free_abelian_group.lift.ext,
rintro ⟨t⟩,
simp only [comp_apply],
dsimp [AddCommGroup.free, Profinite_to_ExtrDisc_presheaf_Ab], congr' 1,
dsimp [ulift_wide_pullback_iso, ulift_wide_pullback_iso_hom_aux],
let f1 := wide_pullback.lift (wide_pullback.base
(λ (i : fin (j + 1 + 1)), (Profinite_to_ExtrDisc_presheaf.{u}.map F.hom).app (op.{u+2} X)))
(λ (k : fin (j + 1)), wide_pullback.π
(λ (i : fin (j + 1 + 1)), (Profinite_to_ExtrDisc_presheaf.{u}.map F.hom).app (op.{u+2} X))
((simplex_category.hom.to_order_hom (simplex_category.δ i)) k)) _,
let f2 := wide_pullback.lift (ulift_functor.{u+1 u}.map ((yoneda.{u u+1}.map
(wide_pullback.base (λ (_x : fin (j.succ + 0 + 1)), F.hom))).app (op.{u+2} X.val)))
(λ (q : fin (j.succ + 0 + 1)), ulift_functor.{u+1 u}.map
((yoneda.{u u+1}.map (wide_pullback.π
(λ (_x : fin (j.succ + 0 + 1)), F.hom) q)).app (op.{u+2} X.val))) _,
let f3 := wide_pullback.lift (ulift_functor.{u+1 u}.map ((yoneda.{u u+1}.map
(wide_pullback.base (λ (_x : fin (j + 0 + 1)), F.hom))).app (op.{u+2} X.val)))
(λ (q : fin (j + 0 + 1)), ulift_functor.{u+1 u}.map
((yoneda.{u u+1}.map (wide_pullback.π
(λ (_x : fin (j + 0 + 1)), F.hom) q)).app (op.{u+2} X.val))) _,
change (f2 ≫ f1) _ = f3 _,
let f4 := wide_pullback.lift (wide_pullback.base (λ (i : fin (j + 1 + 1)), F.hom))
(λ (k : fin (j + 1)), wide_pullback.π
(λ (i : fin (j + 1 + 1)), F.hom) ((simplex_category.hom.to_order_hom
(simplex_category.δ i)) k)) _,
suffices : f2 ≫ f1 = ((yoneda'.map f4).app (op X.val) ≫ f3),
{ rw this, refl },
apply wide_pullback.hom_ext,
{ intros k,
dsimp [f4,f3,f2,f1],
simp only [category.assoc, wide_pullback.lift_π, wide_pullback.lift_π_assoc],
erw [wide_pullback.lift_π],
erw [← functor.map_comp, ← nat_trans.comp_app, ← functor.map_comp, wide_pullback.lift_π] },
{ dsimp [f4,f3,f2,f1],
simp only [category.assoc, wide_pullback.lift_base, wide_pullback.lift_base_assoc],
erw wide_pullback.lift_base,
erw [← functor.map_comp, ← nat_trans.comp_app, ← functor.map_comp,
wide_pullback.lift_base] } }
end
lemma free_Cech_exact (F : arrow Profinite.{u}) (hF : function.surjective F.hom) : ∀ (n : ℤ),
is_zero $ (free_Cech F).homology n :=
begin
dsimp only [free_Cech],
rw chain_complex.homology_zero_iff_homology_zero,
rw chain_complex.homology_zero_iff_map_homology_zero _
(Condensed_ExtrSheaf_equiv Ab.{u+1}).symm,
intros i,
dsimp only [equivalence.symm_functor],
let E := (_root_.homology_functor _ _ i).map_iso (free_Cech'_iso_ExtrDisc F),
apply is_zero.of_iso _ E, clear E,
let E := (_root_.homology_functor _ _ i).map_iso (free_ExtrDisc_Cech'_iso F),
apply is_zero.of_iso _ E, clear E,
dsimp only [_root_.homology_functor],
revert i,
apply category_theory.Sheaf.map_presheaf_to_Sheaf_homology_zero_of_homology_zero.{(u+2) u (u+1)},
apply category_theory.homology_zero_of_eval.{(u+2) u (u+1)},
any_goals { apply_instance },
intros X, tactic.op_induction',
intros i,
let E := (_root_.homology_functor _ _ i).map_iso (yet_another_iso F X),
apply is_zero.of_iso _ E,
-- Now we can use the splitting similarly to arrow.conerve_to_cocomplex_homology_is_zero
-- but we need a dual variant.
let G := ((Profinite_to_ExtrDisc_presheaf.flip.obj (op X)).map_arrow.obj F),
haveI : G.split,
{ suffices : function.surjective G.hom,
{ refine ⟨λ i, (this i).some, _⟩,
ext1 i, exact (this i).some_spec },
dsimp [G, functor.map_arrow, Profinite_to_ExtrDisc_presheaf, ulift_functor, yoneda],
rintros ⟨e⟩,
use ExtrDisc.lift _ hF e,
ext1,
dsimp,
rw ExtrDisc.lift_lifts },
apply arrow.nerve_to_complex_homology_is_zero AddCommGroup.free G,
recover,
end
lemma free_Cech_kernel_SES (F : arrow Profinite.{u}) (hF : function.surjective F.hom) : ∀ n,
short_exact (kernel.ι $ (free_Cech F).d (n+1+1) (n+1)) (delta_to_kernel _ (n+1+1) (n+1) n) :=
begin
erw ← is_acyclic_iff_short_exact_to_cycles' (free_Cech F), exact free_Cech_exact F hF
end
variable (M : Condensed.{u} Ab.{u+1})
abbreviation HH (i : ℤ) (S : Profinite.{u}) (M : Condensed.{u} Ab.{u+1}) :=
((Ext' i).obj (op $ (CondensedSet_to_Condensed_Ab).obj $ Profinite.to_Condensed S)).obj M
def acyclic_of_exact.IH (n : ℤ) : Prop := ∀ S, ∀ i > 0, i ≤ n → is_zero (HH i S M)
/-- Consider the following commutative diagram
```
O₀
↓
A₁ → B₁ → C₁ → O₁
↘ ↓
B₂
↓ ↘
O₃ → B₃ → C₃
```
where `O₀`, `O₁`, and `O₃` are zero objects, and all sequence are exact.
Then `C₁` is also a zero object.
-/
lemma acyclic_of_exact.induction_step_aux {𝓐 : Type*} [category 𝓐] [abelian 𝓐]
{O₀ O₁ O₃ A₁ B₁ C₁ B₂ B₃ C₃ : 𝓐}
{α₁ : A₁ ⟶ B₁} {β₁ : B₁ ⟶ C₁} {γ₁ : C₁ ⟶ O₁} (ex₁ : exact_seq 𝓐 [α₁, β₁, γ₁])
{d₁ : A₁ ⟶ B₂} {d₂ : B₂ ⟶ C₃} (exd : exact d₁ d₂)
{b₀ : O₀ ⟶ B₁} {b₁ : B₁ ⟶ B₂} {b₂ : B₂ ⟶ B₃} (exb : exact_seq 𝓐 [b₀, b₁, b₂])
{α₃ : O₃ ⟶ B₃} {β₃ : B₃ ⟶ C₃} (ex₃ : exact α₃ β₃)
(hO₀ : is_zero O₀) (hO₁ : is_zero O₁) (hO₃ : is_zero O₃)
(tr₁ : α₁ ≫ b₁ = d₁) (tr₂ : b₂ ≫ β₃ = d₂) :
is_zero C₁ :=
begin
refine (ex₁.drop 1).pair.is_zero_of_eq_zero_eq_zero
(ex₁.pair.eq_zero_of_epi _) (hO₁.eq_of_tgt _ _),
haveI : mono b₁ := exb.pair.mono_of_eq_zero (hO₀.eq_of_src _ _),
haveI : mono β₃ := ex₃.mono_of_eq_zero (hO₃.eq_of_src _ _),
let l' := abelian.is_limit_of_exact_of_mono _ _ (exb.drop 1).pair,
let l := is_kernel_comp_mono l' β₃ tr₂.symm,
obtain rfl :
α₁ = kernel.lift _ _ exd.w ≫ (is_limit.cone_point_unique_up_to_iso (limit.is_limit _) l).hom,
{ erw [← cancel_mono b₁, category.assoc,
is_limit.cone_point_unique_up_to_iso_hom_comp _ _ walking_parallel_pair.zero, is_limit.fac,
fork.of_ι_π_app, tr₁] },
apply epi_comp
end
lemma acyclic_of_exact.induction_step_ex₁
(F : arrow Profinite.{u})
(h : ∀ i, is_zero (((((cosimplicial_object.augmented.whiskering _ _).obj M.val).obj
F.augmented_cech_nerve.right_op).to_cocomplex).homology i)) :
let C := (((cosimplicial_object.augmented.whiskering Profiniteᵒᵖ Ab).obj
((Profinite_to_Condensed ⋙ CondensedSet_to_Condensed_Ab).op ⋙ preadditive_yoneda.obj M)).obj
F.augmented_cech_nerve.right_op).to_cocomplex
in ∀ i, is_zero (C.homology i) :=
begin
intros C i,
apply is_zero.of_iso (h i),
refine (_root_.homology_functor _ _ i).map_iso _,
refine cosimplicial_object.augmented.cocomplex.map_iso _,
refine iso.app (functor.map_iso _ (condensed.profinite_free_adj _)) _,
end
lemma acyclic_of_exact.induction_step_ex₂
(F : arrow Profinite.{u})
(h : let C := (((cosimplicial_object.augmented.whiskering Profiniteᵒᵖ Ab).obj
((Profinite_to_Condensed ⋙ CondensedSet_to_Condensed_Ab).op ⋙ preadditive_yoneda.obj M)).obj
F.augmented_cech_nerve.right_op).to_cocomplex
in ∀ i, is_zero (C.homology i)) :
∀ i, is_zero ((((preadditive_yoneda.obj M).map_homological_complex _).obj (free_Cech' F).op).homology i) :=
begin
intro i, apply (h i).of_iso,
refine (_root_.homology_functor _ _ _).map_iso _,
apply acyclic_of_exact.induction_step_ex₂_aux,
end
lemma int.of_nat_add_one (i : ℕ) : int.of_nat i + 1 = int.of_nat (i+1) := rfl
lemma complex_shape.embedding.nat_down_int_down.r_int_of_nat (i : ℕ) :
complex_shape.embedding.nat_down_int_down.r (int.of_nat i) = option.some i := rfl
-- move me
lemma cochain_complex.mono_of_is_zero_homology_0
{𝓐 : Type*} [category 𝓐] [abelian 𝓐]
(C : cochain_complex 𝓐 ℕ) (h : is_zero $ C.homology 0) :
mono (C.d 0 1) :=
begin
replace h := exact_of_homology_is_zero h,
rw [C.d_from_eq (show (complex_shape.up ℕ).rel 0 1, by simp), exact_comp_iso] at h,
refine mono_of_exact_of_eq_zero _ _ _ _ _ h _,
rw homological_complex.d_to_eq_zero,
simp only [cochain_complex.prev_nat_zero, complex_shape.up_rel,
nat.one_ne_zero, not_false_iff],
end
lemma acyclic_of_exact.induction_step_ex₃
(F : arrow Profinite.{u}) (i : ℤ)
(h : ∀ i, is_zero ((((preadditive_yoneda.obj M).map_homological_complex _).obj (free_Cech' F).op).homology i)) :
exact ((preadditive_yoneda.obj M).map $ ((free_Cech F).d (i+1) i).op)
((preadditive_yoneda.obj M).map $ ((free_Cech F).d (i+1+1) (i+1)).op) :=
begin
rcases i with (i|i),
{ delta free_Cech,
dsimp only [homological_complex.embed, homological_complex.embed.obj],
rw [int.of_nat_add_one, int.of_nat_add_one],
erw [complex_shape.embedding.nat_down_int_down.r_int_of_nat],
erw [complex_shape.embedding.nat_down_int_down.r_int_of_nat],
erw [complex_shape.embedding.nat_down_int_down.r_int_of_nat],
dsimp only [homological_complex.embed.d],
refine exact_of_homology_is_zero ((h (i+1)).of_iso $ _),
{ rw [← functor.map_comp, ← op_comp, homological_complex.d_comp_d, op_zero, functor.map_zero] },
clear h,
refine _ ≪≫ (homology_iso _ i (i+1) (i+1+1) _ _).symm,
swap, { dsimp, refl }, swap, { dsimp, refl },
refl, },
{ have aux : (preadditive_yoneda.obj M).map ((free_Cech F).d (-[1+ i] + 1) -[1+ i]).op = 0,
{ cases i; erw [op_zero, functor.map_zero], },
rw [aux], clear aux, apply_with exact_zero_left_of_mono {instances:=ff}, { apply_instance },
cases i,
{ exact cochain_complex.mono_of_is_zero_homology_0 _ (h 0), },
{ apply mono_of_is_zero_object,
rw [is_zero_iff_id_eq_zero, ← category_theory.functor.map_id,
is_zero_iff_id_eq_zero.mp, functor.map_zero],
refine (is_zero_zero _).op, } },
end
lemma acyclic_of_exact.induction_step_ex₄
(F : arrow Profinite.{u}) (i : ℤ)
(h : exact ((preadditive_yoneda.obj M).map $ ((free_Cech F).d (i+1) i).op)
((preadditive_yoneda.obj M).map $ ((free_Cech F).d (i+1+1) (i+1)).op)) :
exact (((Ext' 0).flip.obj M).map $ ((free_Cech F).d (i+1) i).op)
(((Ext' 0).flip.obj M).map $ ((free_Cech F).d (i+1+1) (i+1)).op) :=
begin
let e := (bounded_derived_category.Ext'_zero_flip_iso _ M).symm,
apply preadditive.exact_of_iso_of_exact' _ _ _ _ (e.app _) (e.app _) (e.app _) _ _ h,
{ simp only [nat_iso.app_hom, nat_trans.naturality], },
{ simp only [nat_iso.app_hom, nat_trans.naturality], }
end
lemma acyclic_of_exact.induction_step_ex
(F : arrow Profinite.{u}) (surj : function.surjective F.hom)
(h : ∀ i, is_zero (((((cosimplicial_object.augmented.whiskering _ _).obj M.val).obj
F.augmented_cech_nerve.right_op).to_cocomplex).homology i))
(i : ℤ) :
exact (((Ext' 0).flip.obj M).map $ ((free_Cech F).d (i+1) i).op)
(((Ext' 0).flip.obj M).map $ ((free_Cech F).d (i+1+1) (i+1)).op) :=
begin
apply acyclic_of_exact.induction_step_ex₄,
apply acyclic_of_exact.induction_step_ex₃,
apply acyclic_of_exact.induction_step_ex₂,
apply acyclic_of_exact.induction_step_ex₁ _ F h,
end
lemma acyclic_of_exact.induction_step
(h : ∀ (F : arrow Profinite.{u}) (surj : function.surjective F.hom),
∀ i, is_zero (((((cosimplicial_object.augmented.whiskering _ _).obj M.val).obj
F.augmented_cech_nerve.right_op).to_cocomplex).homology i))
(n : ℤ) (ih : acyclic_of_exact.IH M n) :
acyclic_of_exact.IH M (n+1) :=
begin
intros S i h1 h2,
rw [le_iff_eq_or_lt, or_comm, int.lt_add_one_iff] at h2,
cases h2 with h2 h2, { exact ih S i h1 h2 },
subst i,
let F := arrow.mk S.projective_presentation.f,
have hF : function.surjective F.hom,
{ rw ← Profinite.epi_iff_surjective, apply projective_presentation.epi },
let E := λ i, (Ext' i).flip.obj M,
have ih' : ∀ (i j : ℤ) (h0i : 0 < i) (hin : i ≤ n),
is_zero ((E i).obj (op ((free_Cech F).X j))),
{ intros i j h0i hin,
cases j with j j,
{ cases j; exact ih _ _ h0i hin, },
{ apply bounded_derived_category.Ext'_zero_left_is_zero,
exact (is_zero_zero _).op, } },
let K := λ i, kernel ((free_Cech F).d (i + 1) i),
have LES := λ i j, (free_Cech_kernel_SES F hF i).Ext'_five_term_exact_seq M j,
have H1 : ∀ i > 0, is_zero ((E i).obj (op ((free_Cech F).X 1))),
{ intros i hi,
apply bounded_derived_category.Ext'_is_zero_of_projective _ _ _ _ hi,
apply_with Condensed_Ab.free.category_theory.projective {instances:=ff},
rw [simplicial_object.augmented.drop_obj, arrow.augmented_cech_nerve_left],
apply projective.of_iso (arrow.cech_nerve_obj_0 F).symm,
apply projective_presentation.projective, },
have aux0 : ∀ (i : ℤ) (h0i : 0 < i+1) (H : is_zero ((E i).obj (op $ K 0))),
is_zero ((E (i+1)).obj (op $ K (-1))),
{ intros i h0i H,
refine is_zero_of_exact_is_zero_is_zero _ _ ((LES (-1) i).drop 2).pair H (H1 _ h0i), },
have aux : ∀ (i j : ℤ) (h0i : 0 < i+1) (hi : i+1 ≤ n) (H : is_zero ((E i).obj (op $ K (j+1)))),
is_zero ((E (i+1)).obj (op $ K j)),
{ intros i j h0i hi H,
refine is_zero_of_exact_is_zero_is_zero _ _ ((LES j i).drop 2).pair H _,
refine ih' _ _ h0i hi },
suffices : ∀ i j, 0 < i → -1 ≤ j → i + j = n → is_zero ((E i).obj (op $ K j)),
{ refine is_zero_of_exact_is_zero_is_zero _ _ (LES (-2) (n+1)).pair _ _; clear LES,
{ apply bounded_derived_category.Ext'_zero_left_is_zero,
refine (is_zero_of_mono (kernel.ι _) _).op, refine is_zero_zero _, },
{ refine this (n+1) (-1) h1 le_rfl _, rw [← sub_eq_add_neg, add_sub_cancel] } },
obtain ⟨n, rfl⟩ : ∃ k, k+1 = n := ⟨n-1, sub_add_cancel _ _⟩,
suffices : is_zero ((E 1).obj (op $ K n)),
{ intro i,
apply int.induction_on' i 1; clear i,
{ intros j h0i hj hijn, rw [add_comm (1:ℤ), add_left_inj] at hijn, subst j, exact this },
{ intros i hi IH j hi' hj hijn,
rw le_iff_eq_or_lt at hj, cases hj with hj hj,
{ subst j, apply aux0 _ hi', apply IH; linarith only [hi, hijn] },
{ apply aux _ _ hi' _ (IH _ _ _ _); linarith only [hi, hijn, hj], } },
{ intros i hi IH j hi', exfalso, linarith only [hi, hi'] } },
clear aux0 aux,
have aux := λ i, ((LES i (-1)).drop 2).pair.cons (LES i 0),
have exd := acyclic_of_exact.induction_step_ex M F hF (h F hF) (n+1+1),
apply acyclic_of_exact.induction_step_aux
((LES n 0).drop 1) exd ((aux (n+1)).extract 0 3) (aux (n+1+1)).pair; clear LES aux exd,
{ apply Ext'_is_zero_of_neg, dec_trivial },
{ obtain (rfl|hn) : n = -1 ∨ 1 ≤ n + 1,
{ rw [or_iff_not_imp_right], intro h2, linarith only [h1, h2] },
{ exact H1 _ zero_lt_one },
{ exact ih' _ _ zero_lt_one hn } },
{ apply Ext'_is_zero_of_neg, dec_trivial },
{ conv_rhs { rw [← delta_to_kernel_ι _ _ _ (n+1), op_comp, functor.map_comp] }, refl },
{ conv_rhs { rw [← delta_to_kernel_ι _ _ _ (n+1+1), op_comp, functor.map_comp] }, refl },
end
lemma acyclic_of_exact
(h : ∀ (F : arrow Profinite.{u}) (surj : function.surjective F.hom),
∀ i, is_zero
(((((cosimplicial_object.augmented.whiskering _ _).obj M.val).obj
F.augmented_cech_nerve.right_op).to_cocomplex).homology i))
(S : Profinite.{u}) :
∀ i > 0, is_zero (HH i S M) :=
begin
intros i hi,
suffices : acyclic_of_exact.IH M i,
{ apply this S i hi le_rfl, },
apply int.induction_on' i 0; clear hi i S,
{ intros S i h1 h2, exfalso, exact h2.not_lt h1 },
{ intros k hk, apply acyclic_of_exact.induction_step M h, },
{ rintros k hk aux S i h1 h2, exfalso, linarith only [hk, h1, h2] }
end
end condensed
|
function setup_WSDDN()
%SETUP_WSDDN Sets up WSDDN, by adding its folders to the Matlab path
root = fileparts(mfilename('fullpath')) ;
addpath(root, [root '/matlab'], [root '/pascal'], [root '/core']) ;
addpath([vl_rootnn '/examples/']) ;
addpath([vl_rootnn '/examples/imagenet/']) ;
|
[STATEMENT]
lemma lspasl_magicr:
"(\<exists>h1 h0. Gamma \<and> (h1,h2\<triangleright>h0) \<and> (A h1) \<and> ((not B) h0)) \<longrightarrow> Delta \<Longrightarrow>
Gamma \<longrightarrow> ((A \<longrightarrow>* B) h2) \<or> Delta"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<exists>h1 h0. Gamma \<and> (h1,h2\<triangleright>h0) \<and> A h1 \<and> \<not> B h0) \<longrightarrow> Delta \<Longrightarrow> Gamma \<longrightarrow> (A \<longrightarrow>* B) h2 \<or> Delta
[PROOF STEP]
using local.sep_add_commute local.sep_disj_commute local.sep_impl_def tern_rel_def
[PROOF STATE]
proof (prove)
using this:
?x ## ?y \<Longrightarrow> ?x + ?y = ?y + ?x
?x ## ?y = ?y ## ?x
?P \<longrightarrow>* ?Q \<equiv> \<lambda>h. \<forall>h'. h ## h' \<and> ?P h' \<longrightarrow> ?Q (h + h')
?a,?b\<triangleright>?c \<equiv> ?a ## ?b \<and> ?a + ?b = ?c
goal (1 subgoal):
1. (\<exists>h1 h0. Gamma \<and> (h1,h2\<triangleright>h0) \<and> A h1 \<and> \<not> B h0) \<longrightarrow> Delta \<Longrightarrow> Gamma \<longrightarrow> (A \<longrightarrow>* B) h2 \<or> Delta
[PROOF STEP]
by auto |
# Details of defining a model
$$
\def\n{\mathbf{n}}
\def\x{\mathbf{x}}
\def\N{\mathbb{\mathbb{N}}}
\def\X{\mathbb{X}}
\def\NX{\mathbb{\N_0^\X}}
\def\C{\mathcal{C}}
\def\Jc{\mathcal{J}_c}
\def\DM{\Delta M_{c,j}}
\newcommand\diff{\mathop{}\!\mathrm{d}}
\def\Xc{\mathbf{X}_c}
\def\Yc{\mathbf{Y}_c}
\newcommand{\muset}[1]{\dot{\{}#1\dot{\}}}
$$
This notebook provides a more detailed view of how `TransitionClass`es of a population model are defined.
It describes the objects hidden behind syntactic sugar when writing something like
`TransitionClass([x] + [y] -to> [x+y], 'k_F')`
This will hopefully help deciphering error messages when making mistakes in the "short-hand" notation.
```python
# initialize sympy printing (for latex output)
from sympy import init_printing
init_printing()
# import functions and classes for compartment models
from compartor import *
```
## Basics
The left-hand-side and right-hand-site of transitions are expressions involving zero or more `Compartments`.
To define a compartment $[\x]$, first create a content variable $\x \in \N_0^D$, then define a compartment $[\x]$ with content $\x$.
```python
x = Content('x')
Compartment(x)
```
Content variables are $D$-dimensional. In equations, `x[d]` can be used to denote the copy number of chemical species `d`.
Next, we can build a stoichiometric equation using the `Transition` class, which takes two parameter: the reactants expression and the products expression. For empty reactants or products, use `EmptySet`.
The following defines the "Exit" transition from the nested birth-death process example.
```python
transition_E = Transition(Compartment(x), EmptySet, name='E')
display(transition_E)
```
`name="E"` is an optional parameter, defining the subscript used for the transition class. (It is only used for displaying equations, e.g., the $h_E$ over the arrow in the above example.)
To define a propensity for the transition class, we have to define a content-independent rate constant $k_c$ and a reactant tuning function $g_c$.
```python
k_E = Constant('k_E')
g_E = 1
```
To specify the transition class with its propensity, use the constructor `TransitionClass(transition_c, k_c, g_c)`.
```python
Exit = TransitionClass(transition_E, k_E, g_E)
display(Exit)
```
The optional 4th argument of `TransitionClass` specifies the outcome distribution $\pi_c$.
This must be defined, if content variables occur in products that do not occur in reactants.
The type of $\pi_c$ is `OutcomeDistribution`, which is a class comprising
* an expression or symbol to use for displaying $\pi_c$ in compound expressions
* a function `conditional_expectation` that takes an expression over reactants $\Xc$, and returns it's expectation over all product compartment variables.
There are generators for several predefined outcome distributions. If nothing is specified, as in the above "Exit" transition example, `OutcomeDistribution.Identity()` is used. This has symbol $1$ and `conditional_expectation` returns the expression over reactants $\Xc$ as is. This is appropriate when $\Yc = \emptyset$ or, more precisely, if all content variables occurring in products already occur in reactants.
Other generators include
* `Poisson()` which specifies a poisson distribution over a scalar, and
* `Uniform()` which specifies a uniform distribution over a scalar.
For example, `Poisson()` can be used to define an "Intake" transition class as follows:
```python
from sympy import Symbol
y = Content('y')
transition_I = Transition(EmptySet, Compartment(y), name='I')
k_I = Constant('k_I')
g_I = 1
pi_I = OutcomeDistribution.Poisson(
Symbol("\pi_{Poiss}(y; \lambda)"),
y[0],
Symbol("\lambda", positive=True))
Intake = TransitionClass(transition_I, k_I, g_I, pi_I)
display(Intake)
```
When displaying a `TransitionClass`, the assembled propensity function is shown, where $w(\n;\Xc)$ is derived from the reactants in the stoichiometric equation.
The function `display_propensity_details()` displays the constituent expressions $k_c$, $g_c$, and $\pi_c$.
```python
display_propensity_details(Exit)
```
To specify a reaction network, collect the transition classes in a list.
The function `display_transition_classes()` displays the equations and propensities of the network.
```python
transitions = [Exit, Intake]
display_transition_classes(transitions)
```
$\displaystyle \begin{align} \left[x\right]&\overset{h_{E}}{\longrightarrow}\emptyset && h_{E} = k_{E} n{\left(x \right)}\\\emptyset&\overset{h_{I}}{\longrightarrow}\left[y\right] && h_{I} = \pi_{Poiss}(y; \lambda) k_{I} \end{align}$
## Chemical Events
To specify chemical reactions, we need the `ContentChange()` class. It is constructed with $D$ (number of species) integer arguments, specifying the change (to a compartment variable) in each species.
For example, the "birth" transition from the nested birth-death process example can be defined as
```python
x = Content('x')
Transition(Compartment(x), Compartment(x + ContentChange(1)), name='b')
```
Note, that `Compartment(...)` in the product encloses `x + ContentChange(1)`, so the `+` acts on the compartment content, rather than specifying a set of compartments.
Besides addition, also multiplication can be used inside compartment content equations, e.g.
```python
Transition(Compartment(x), Compartment(2*x + ContentChange(1)))
```
## Compartment Events
To specify compartment events, simply construct (multi-)sets of compartments using `+`.
For example, a "Coagulation" transition can be specified as
```python
x = Content('x')
y = Content('y')
Transition(Compartment(x) + Compartment(y), Compartment(x + y), name='C')
```
In principle, also multiplication can be used, e.g., `2*Compartment(x)` means "two compartments of content 'x'".
But the moment derivation mechanics is not ready for that yet...
## Example: nested birth-death process
Finally, as a complete example, here is the definition of nested birth-death process.
```python
y = Content('y')
x = Content('x')
# Intake
transition_I = Transition(EmptySet, Compartment(y), name='I')
k_I = Constant('k_I')
g_I = 1
pi_I = OutcomeDistribution.Poisson(Symbol("\pi_{Poiss}(y; \lambda)"), y[0], Symbol("\lambda"))
Intake = TransitionClass(transition_I, k_I, g_I, pi_I)
# Exit
transition_E = Transition(Compartment(x), EmptySet, name='E')
k_E = Constant('k_E')
g_E = 1
Exit = TransitionClass(transition_E, k_E, g_E)
# birth
transition_b = Transition(Compartment(x), Compartment(x + ContentChange(1)), name='b')
k_b = Constant('k_b')
g_b = 1
Birth = TransitionClass(transition_b, k_b, g_b)
# death
transition_d = Transition(Compartment(x), Compartment(x + ContentChange(-1)), name='d')
k_d = Constant('k_d')
g_d = x[0] # TODO x should be enough here, in case D=1.
Death = TransitionClass(transition_d, k_d, g_d)
transitions = [Intake, Exit, Birth, Death]
display_transition_classes(transitions)
```
$\displaystyle \begin{align} \emptyset&\overset{h_{I}}{\longrightarrow}\left[y\right] && h_{I} = \pi_{Poiss}(y; \lambda) k_{I}\\\left[x\right]&\overset{h_{E}}{\longrightarrow}\emptyset && h_{E} = k_{E} n{\left(x \right)}\\\left[x\right]&\overset{h_{b}}{\longrightarrow}\left[\left( 1\right) + x\right] && h_{b} = k_{b} n{\left(x \right)}\\\left[x\right]&\overset{h_{d}}{\longrightarrow}\left[\left( -1\right) + x\right] && h_{d} = k_{d} n{\left(x \right)} {x}_{0} \end{align}$
The short-hand definition of the same model is given below. The two are 100% equivalent, they generate the same objects in the `transitions` list.
```python
x = Content('x')
y = Content('y')
pi_I = OutcomeDistribution.Poisson(Symbol("\pi_{Poiss}(y; \lambda)"), y[0], Symbol("\lambda"))
Intake = TransitionClass( {} -to> [y], 'k_I', pi=pi_I, name='I')
Exit = TransitionClass( [x] -to> {}, 'k_E', name='E')
Birth = TransitionClass( [x] -to> [x+1], 'k_b', name='b')
Death = TransitionClass( [x] -to> [x-1], 'k_d', x[0], name='d')
transitions = [Intake, Exit, Birth, Death]
display_transition_classes(transitions)
```
$\displaystyle \begin{align} \emptyset&\overset{h_{I}}{\longrightarrow}\left[y\right] && h_{I} = \pi_{Poiss}(y; \lambda) k_{I}\\\left[x\right]&\overset{h_{E}}{\longrightarrow}\emptyset && h_{E} = k_{E} n{\left(x \right)}\\\left[x\right]&\overset{h_{b}}{\longrightarrow}\left[\left( 1\right) + x\right] && h_{b} = k_{b} n{\left(x \right)}\\\left[x\right]&\overset{h_{d}}{\longrightarrow}\left[\left( -1\right) + x\right] && h_{d} = k_{d} n{\left(x \right)} {x}_{0} \end{align}$
|
[STATEMENT]
lemma not_UINF: "(\<not> (\<Sqinter> i\<in>A\<bullet> P(i))) = (\<Squnion> i\<in>A\<bullet> \<not> P(i))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<not> (\<Sqinter> i \<in> A \<bullet> P i)) = (\<Squnion> i \<in> A \<bullet> \<not> P i)
[PROOF STEP]
by (pred_auto) |
[GOAL]
α : Type u_1
inst✝¹ : PartialOrder α
inst✝ : NoMaxOrder α
a : α
⊢ NoMaxOrder ↑(Ici a)
[PROOFSTEP]
infer_instance
[GOAL]
α : Type u_1
inst✝ : ConditionallyCompleteLinearOrder α
a : α
h : sSup ∅ ≤ a
src✝¹ : OrderBot { x // a ≤ x } := orderBot
src✝ : ConditionallyCompleteLinearOrder { x // a ≤ x } := Nonneg.conditionallyCompleteLinearOrder
⊢ ↑(if ht : sSup (Subtype.val '' ∅) ∈ Ici a then { val := sSup (Subtype.val '' ∅), property := ht } else default) = ↑⊥
[PROOFSTEP]
rw [bot_eq]
[GOAL]
α : Type u_1
inst✝ : ConditionallyCompleteLinearOrder α
a : α
h : sSup ∅ ≤ a
src✝¹ : OrderBot { x // a ≤ x } := orderBot
src✝ : ConditionallyCompleteLinearOrder { x // a ≤ x } := Nonneg.conditionallyCompleteLinearOrder
⊢ ↑(if ht : sSup (Subtype.val '' ∅) ∈ Ici a then { val := sSup (Subtype.val '' ∅), property := ht } else default) =
↑{ val := a, property := (_ : a ≤ a) }
[PROOFSTEP]
cases' h.lt_or_eq with h2 h2
[GOAL]
case inl
α : Type u_1
inst✝ : ConditionallyCompleteLinearOrder α
a : α
h : sSup ∅ ≤ a
src✝¹ : OrderBot { x // a ≤ x } := orderBot
src✝ : ConditionallyCompleteLinearOrder { x // a ≤ x } := Nonneg.conditionallyCompleteLinearOrder
h2 : sSup ∅ < a
⊢ ↑(if ht : sSup (Subtype.val '' ∅) ∈ Ici a then { val := sSup (Subtype.val '' ∅), property := ht } else default) =
↑{ val := a, property := (_ : a ≤ a) }
[PROOFSTEP]
simp [h2.not_le]
[GOAL]
case inr
α : Type u_1
inst✝ : ConditionallyCompleteLinearOrder α
a : α
h : sSup ∅ ≤ a
src✝¹ : OrderBot { x // a ≤ x } := orderBot
src✝ : ConditionallyCompleteLinearOrder { x // a ≤ x } := Nonneg.conditionallyCompleteLinearOrder
h2 : sSup ∅ = a
⊢ ↑(if ht : sSup (Subtype.val '' ∅) ∈ Ici a then { val := sSup (Subtype.val '' ∅), property := ht } else default) =
↑{ val := a, property := (_ : a ≤ a) }
[PROOFSTEP]
simp [h2]
[GOAL]
α : Type u_1
inst✝ : OrderedSemiring α
src✝¹ : One { x // 0 ≤ x } := one
src✝ : OrderedAddCommMonoid { x // 0 ≤ x } := orderedAddCommMonoid
⊢ NatCast.natCast 0 = 0
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝ : OrderedSemiring α
src✝¹ : One { x // 0 ≤ x } := one
src✝ : OrderedAddCommMonoid { x // 0 ≤ x } := orderedAddCommMonoid
x✝ : ℕ
⊢ NatCast.natCast (x✝ + 1) = NatCast.natCast x✝ + 1
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝ : OrderedSemiring α
src✝¹ : One { x // 0 ≤ x } := one
src✝ : OrderedAddCommMonoid { x // 0 ≤ x } := orderedAddCommMonoid
x✝ : ℕ
⊢ { val := ↑x✝ + 1, property := (_ : (fun x => 0 ≤ x) (↑x✝ + 1)) } = { val := ↑x✝, property := (_ : 0 ≤ ↑x✝) } + 1
[PROOFSTEP]
rfl
[GOAL]
α : Type u_1
inst✝ : OrderedSemiring α
⊢ MonoidWithZero { x // 0 ≤ x }
[PROOFSTEP]
infer_instance
[GOAL]
α : Type u_1
inst✝ : OrderedCommSemiring α
⊢ CommMonoidWithZero { x // 0 ≤ x }
[PROOFSTEP]
infer_instance
[GOAL]
α : Type u_1
inst✝¹ : OrderedCommRing α
inst✝ : NoZeroDivisors α
src✝¹ : CanonicallyOrderedAddMonoid { x // 0 ≤ x } := canonicallyOrderedAddMonoid
src✝ : OrderedCommSemiring { x // 0 ≤ x } := orderedCommSemiring
⊢ ∀ {a b : { x // 0 ≤ x }}, a * b = 0 → a = 0 ∨ b = 0
[PROOFSTEP]
rintro ⟨a, ha⟩ ⟨b, hb⟩
[GOAL]
case mk.mk
α : Type u_1
inst✝¹ : OrderedCommRing α
inst✝ : NoZeroDivisors α
src✝¹ : CanonicallyOrderedAddMonoid { x // 0 ≤ x } := canonicallyOrderedAddMonoid
src✝ : OrderedCommSemiring { x // 0 ≤ x } := orderedCommSemiring
a : α
ha : 0 ≤ a
b : α
hb : 0 ≤ b
⊢ { val := a, property := ha } * { val := b, property := hb } = 0 →
{ val := a, property := ha } = 0 ∨ { val := b, property := hb } = 0
[PROOFSTEP]
simp only [mk_mul_mk, mk_eq_zero, mul_eq_zero, imp_self]
[GOAL]
α : Type u_1
inst✝¹ : Zero α
inst✝ : LinearOrder α
a : α
h : 0 ≤ a
⊢ toNonneg a = { val := a, property := h }
[PROOFSTEP]
simp [toNonneg, h]
[GOAL]
α : Type u_1
inst✝¹ : Zero α
inst✝ : LinearOrder α
a : α
b : { x // 0 ≤ x }
⊢ toNonneg a ≤ b ↔ a ≤ ↑b
[PROOFSTEP]
cases' b with b hb
[GOAL]
case mk
α : Type u_1
inst✝¹ : Zero α
inst✝ : LinearOrder α
a b : α
hb : 0 ≤ b
⊢ toNonneg a ≤ { val := b, property := hb } ↔ a ≤ ↑{ val := b, property := hb }
[PROOFSTEP]
simp [toNonneg, hb]
[GOAL]
α : Type u_1
inst✝¹ : Zero α
inst✝ : LinearOrder α
a : { x // 0 ≤ x }
b : α
⊢ a < toNonneg b ↔ ↑a < b
[PROOFSTEP]
cases' a with a ha
[GOAL]
case mk
α : Type u_1
inst✝¹ : Zero α
inst✝ : LinearOrder α
b a : α
ha : 0 ≤ a
⊢ { val := a, property := ha } < toNonneg b ↔ ↑{ val := a, property := ha } < b
[PROOFSTEP]
simp [toNonneg, ha.not_lt]
[GOAL]
α : Type u_1
inst✝ : LinearOrderedRing α
⊢ ∀ (a b c : { x // 0 ≤ x }), a - b ≤ c ↔ a ≤ c + b
[PROOFSTEP]
rintro ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩
[GOAL]
case mk.mk.mk
α : Type u_1
inst✝ : LinearOrderedRing α
a : α
ha : 0 ≤ a
b : α
hb : 0 ≤ b
c : α
hc : 0 ≤ c
⊢ { val := a, property := ha } - { val := b, property := hb } ≤ { val := c, property := hc } ↔
{ val := a, property := ha } ≤ { val := c, property := hc } + { val := b, property := hb }
[PROOFSTEP]
simp only [sub_le_iff_le_add, Subtype.mk_le_mk, mk_sub_mk, mk_add_mk, toNonneg_le, Subtype.coe_mk]
|
(* Title: A formalisation of the Cocke-Younger-Kasami algorithm
Author: Maksym Bortin <[email protected]>
*)
theory CYK
imports Main
begin
text \<open>The theory is structured as follows. First section deals with modelling
of grammars, derivations, and the language semantics. Then the basic
properties are proved. Further, CYK is abstractly specified and its
underlying recursive relationship proved. The final section contains a
prototypical implementation accompanied by a proof of its correctness.\<close>
section "Basic modelling"
subsection "Grammars in Chomsky normal form"
text "A grammar in Chomsky normal form is here simply modelled
by a list of production rules (the type CNG below), each having a non-terminal
symbol on the lhs and either two non-terminals or one terminal
symbol on the rhs."
datatype ('n, 't) RHS = Branch 'n 'n
| Leaf 't
type_synonym ('n, 't) CNG = "('n \<times> ('n, 't) RHS) list"
text "Abbreviating the list append symbol for better readability"
abbreviation list_append :: "'a list \<Rightarrow> 'a list \<Rightarrow> 'a list" (infixr "\<cdot>" 65)
where "xs \<cdot> ys \<equiv> xs @ ys"
subsection "Derivation by grammars"
text\<open>A \emph{word form} (or sentential form) may be built of both non-terminal and terminal
symbols, as opposed to a \emph{word} that contains only terminals. By the usage of disjoint
union, non-terminals are injected into a word form by @{term "Inl"} whereas terminals --
by @{term "Inr"}.\<close>
type_synonym ('n, 't) word_form = "('n + 't) list"
type_synonym 't word = "'t list"
text "A single step derivation relation on word forms is induced by a grammar in the standard way,
replacing a non-terminal within a word form in accordance to the production rules."
definition DSTEP :: "('n, 't) CNG \<Rightarrow> (('n, 't) word_form \<times> ('n, 't) word_form) set"
where "DSTEP G = {(l \<cdot> [Inl N] \<cdot> r, x) | l N r rhs x. (N, rhs) \<in> set G \<and>
(case rhs of
Branch A B \<Rightarrow> x = l \<cdot> [Inl A, Inl B] \<cdot> r
| Leaf t \<Rightarrow> x = l \<cdot> [Inr t] \<cdot> r)}"
abbreviation DSTEP' :: "('n, 't) word_form \<Rightarrow> ('n, 't) CNG \<Rightarrow> ('n, 't) word_form \<Rightarrow> bool" ("_ -_\<rightarrow> _" [60, 61, 60] 61)
where "w -G\<rightarrow> w' \<equiv> (w, w') \<in> DSTEP G"
abbreviation DSTEP_reflc :: "('n, 't) word_form \<Rightarrow> ('n, 't) CNG \<Rightarrow> ('n, 't) word_form \<Rightarrow> bool" ("_ -_\<rightarrow>\<^sup>= _" [60, 61, 60] 61)
where "w -G\<rightarrow>\<^sup>= w' \<equiv> (w, w') \<in> (DSTEP G)\<^sup>="
abbreviation DSTEP_transc :: "('n, 't) word_form \<Rightarrow> ('n, 't) CNG \<Rightarrow> ('n, 't) word_form \<Rightarrow> bool" ("_ -_\<rightarrow>\<^sup>+ _" [60, 61, 60] 61)
where "w -G\<rightarrow>\<^sup>+ w' \<equiv> (w, w') \<in> (DSTEP G)\<^sup>+"
abbreviation DSTEP_rtransc :: "('n, 't) word_form \<Rightarrow> ('n, 't) CNG \<Rightarrow> ('n, 't) word_form \<Rightarrow> bool" ("_ -_\<rightarrow>\<^sup>* _" [60, 61, 60] 61)
where "w -G\<rightarrow>\<^sup>* w' \<equiv> (w, w') \<in> (DSTEP G)\<^sup>*"
subsection "The generated language semantics"
text "The language generated by a grammar from a non-terminal symbol
comprises all words that can be derived from the non-terminal
in one or more steps.
Notice that by the presented grammar modelling, languages containing
the empty word cannot be generated. Hence in rare situations when such
languages are required, the empty word case should be treated separately."
definition Lang :: "('n, 't) CNG \<Rightarrow> 'n \<Rightarrow> 't word set"
where "Lang G S = {w. [Inl S] -G\<rightarrow>\<^sup>+ map Inr w }"
text\<open>So, for instance, a grammar generating the language $a^nb^n$
from the non-terminal @{term "''S''"} might look as follows.\<close>
definition "G_anbn =
[(''S'', Branch ''A'' ''T''),
(''S'', Branch ''A'' ''B''),
(''T'', Branch ''S'' ''B''),
(''A'', Leaf ''a''),
(''B'', Leaf ''b'')]"
text\<open>Now the term @{term "Lang G_anbn ''S''"} denotes the set of words of
the form $a^nb^n$ with $n > 0$. This is intuitively clear, but not
straight forward to show, and a lengthy proof for that is out of scope.\<close>
section "Basic properties"
lemma prod_into_DSTEP1 :
"(S, Branch A B) \<in> set G \<Longrightarrow>
L \<cdot> [Inl S] \<cdot> R -G\<rightarrow> L \<cdot> [Inl A, Inl B] \<cdot> R"
by(simp add: DSTEP_def, rule_tac x="L" in exI, force)
lemma prod_into_DSTEP2 :
"(S, Leaf a) \<in> set G \<Longrightarrow>
L \<cdot> [Inl S] \<cdot> R -G\<rightarrow> L \<cdot> [Inr a] \<cdot> R"
by(simp add: DSTEP_def, rule_tac x="L" in exI, force)
lemma DSTEP_D :
"s -G\<rightarrow> t \<Longrightarrow>
\<exists>L N R rhs. s = L \<cdot> [Inl N] \<cdot> R \<and> (N, rhs) \<in> set G \<and>
(\<forall>A B. rhs = Branch A B \<longrightarrow> t = L \<cdot> [Inl A, Inl B] \<cdot> R) \<and>
(\<forall>x. rhs = Leaf x \<longrightarrow> t = L \<cdot> [Inr x] \<cdot> R)"
by(unfold DSTEP_def, clarsimp, simp split: RHS.split_asm, blast+)
lemma DSTEP_append :
assumes a: "s -G\<rightarrow> t"
shows "L \<cdot> s \<cdot> R -G\<rightarrow> L \<cdot> t \<cdot> R"
proof -
from a have "\<exists>l N r rhs. s = l \<cdot> [Inl N] \<cdot> r \<and> (N, rhs) \<in> set G \<and>
(\<forall>A B. rhs = Branch A B \<longrightarrow> t = l \<cdot> [Inl A, Inl B] \<cdot> r) \<and>
(\<forall>x. rhs = Leaf x \<longrightarrow> t = l \<cdot> [Inr x] \<cdot> r)" (is "\<exists>l N r rhs. ?P l N r rhs")
by(rule DSTEP_D)
then obtain l N r rhs where "?P l N r rhs" by blast
thus ?thesis
by(simp add: DSTEP_def, rule_tac x="L \<cdot> l" in exI,
rule_tac x=N in exI, rule_tac x="r \<cdot> R" in exI,
simp, rule_tac x=rhs in exI, simp split: RHS.split)
qed
lemma DSTEP_star_mono :
"s -G\<rightarrow>\<^sup>* t \<Longrightarrow> length s \<le> length t"
proof(erule rtrancl_induct, simp)
fix t u
assume "s -G\<rightarrow>\<^sup>* t"
assume a: "t -G\<rightarrow> u"
assume b: "length s \<le> length t"
show "length s \<le> length u"
proof -
from a have "\<exists>L N R rhs. t = L \<cdot> [Inl N] \<cdot> R \<and> (N, rhs) \<in> set G \<and>
(\<forall>A B. rhs = Branch A B \<longrightarrow> u = L \<cdot> [Inl A, Inl B] \<cdot> R) \<and>
(\<forall>x. rhs = Leaf x \<longrightarrow> u = L \<cdot> [Inr x] \<cdot> R)" (is "\<exists>L N R rhs. ?P L N R rhs")
by(rule DSTEP_D)
then obtain L N R rhs where "?P L N R rhs" by blast
with b show ?thesis
by(case_tac rhs, clarsimp+)
qed
qed
lemma DSTEP_comp :
assumes a: "l \<cdot> r -G\<rightarrow> t"
shows "\<exists>l' r'. l -G\<rightarrow>\<^sup>= l' \<and> r -G\<rightarrow>\<^sup>= r' \<and> t = l' \<cdot> r'"
proof -
from a have "\<exists>L N R rhs. l \<cdot> r = L \<cdot> [Inl N] \<cdot> R \<and> (N, rhs) \<in> set G \<and>
(\<forall>A B. rhs = Branch A B \<longrightarrow> t = L \<cdot> [Inl A, Inl B] \<cdot> R) \<and>
(\<forall>x. rhs = Leaf x \<longrightarrow> t = L \<cdot> [Inr x] \<cdot> R)" (is "\<exists>L N R rhs. ?T L N R rhs")
by(rule DSTEP_D)
then obtain L N R rhs where b: "?T L N R rhs" by blast
hence "l \<cdot> r = L \<cdot> Inl N # R" by simp
hence "\<exists>u. (l = L \<cdot> u \<and> u \<cdot> r = Inl N # R) \<or> (l \<cdot> u = L \<and> r = u \<cdot> Inl N # R)" by(rule append_eq_append_conv2[THEN iffD1])
then obtain xs where c: "l = L \<cdot> xs \<and> xs \<cdot> r = Inl N # R \<or> l \<cdot> xs = L \<and> r = xs \<cdot> Inl N # R" (is "?C1 \<or> ?C2") by blast
show ?thesis
proof(cases rhs)
case (Leaf x)
with b have d: "t = L \<cdot> [Inr x] \<cdot> R \<and> (N, Leaf x) \<in> set G" by simp
from c show ?thesis
proof
assume e: "?C1"
show ?thesis
proof(cases xs)
case Nil with d and e show ?thesis
by(clarsimp, rule_tac x=L in exI, simp add: DSTEP_def, simp split: RHS.split, blast)
next
case (Cons z zs) with d and e show ?thesis
by(rule_tac x="L \<cdot> Inr x # zs" in exI, clarsimp, simp add: DSTEP_def, simp split: RHS.split, blast)
qed
next
assume e: "?C2"
show ?thesis
proof(cases xs)
case Nil with d and e show ?thesis
by(rule_tac x=L in exI, clarsimp, simp add: DSTEP_def, simp split: RHS.split, blast)
next
case (Cons z zs) with d and e show ?thesis
by(rule_tac x="l" in exI, clarsimp, simp add: DSTEP_def, simp split: RHS.split,
rule_tac x="z#zs" in exI, rule_tac x=N in exI, rule_tac x=R in exI, simp, rule_tac x="Leaf x" in exI, simp)
qed
qed
next
case (Branch A B)
with b have d: "t = L \<cdot> [Inl A, Inl B] \<cdot> R \<and> (N, Branch A B) \<in> set G" by simp
from c show ?thesis
proof
assume e: "?C1"
show ?thesis
proof(cases xs)
case Nil with d and e show ?thesis
by(clarsimp, rule_tac x=L in exI, simp add: DSTEP_def, simp split: RHS.split, blast)
next
case (Cons z zs) with d and e show ?thesis
by(rule_tac x="L \<cdot> [Inl A, Inl B] \<cdot> zs" in exI, clarsimp, simp add: DSTEP_def, simp split: RHS.split, blast)
qed
next
assume e: "?C2"
show ?thesis
proof(cases xs)
case Nil with d and e show ?thesis
by(rule_tac x=L in exI, clarsimp, simp add: DSTEP_def, simp split: RHS.split, blast)
next
case (Cons z zs) with d and e show ?thesis
by(rule_tac x="l" in exI, clarsimp, simp add: DSTEP_def, simp split: RHS.split,
rule_tac x="z#zs" in exI, rule_tac x=N in exI, rule_tac x=R in exI, simp, rule_tac x="Branch A B" in exI, simp)
qed
qed
qed
qed
theorem DSTEP_star_comp1 :
assumes A: "l \<cdot> r -G\<rightarrow>\<^sup>* t"
shows "\<exists>l' r'. l -G\<rightarrow>\<^sup>* l' \<and> r -G\<rightarrow>\<^sup>* r' \<and> t = l' \<cdot> r'"
proof -
have "\<And>s. s -G\<rightarrow>\<^sup>* t \<Longrightarrow>
\<forall>l r. s = l \<cdot> r \<longrightarrow> (\<exists>l' r'. l -G\<rightarrow>\<^sup>* l' \<and> r -G\<rightarrow>\<^sup>* r' \<and> t = l' \<cdot> r')" (is "\<And>s. ?P s t \<Longrightarrow> ?Q s t")
proof(erule rtrancl_induct, force)
fix s t u
assume "?P s t"
assume a: "t -G\<rightarrow> u"
assume b: "?Q s t"
show "?Q s u"
proof(clarify)
fix l r
assume "s = l \<cdot> r"
with b have "\<exists>l' r'. l -G\<rightarrow>\<^sup>* l' \<and> r -G\<rightarrow>\<^sup>* r' \<and> t = l' \<cdot> r'" by simp
then obtain l' r' where c: "l -G\<rightarrow>\<^sup>* l' \<and> r -G\<rightarrow>\<^sup>* r' \<and> t = l' \<cdot> r'" by blast
with a have "l' \<cdot> r' -G\<rightarrow> u" by simp
hence "\<exists>l'' r''. l' -G\<rightarrow>\<^sup>= l'' \<and> r' -G\<rightarrow>\<^sup>= r'' \<and> u = l'' \<cdot> r''" by(rule DSTEP_comp)
then obtain l'' r'' where "l' -G\<rightarrow>\<^sup>= l'' \<and> r' -G\<rightarrow>\<^sup>= r'' \<and> u = l'' \<cdot> r''" by blast
hence "l' -G\<rightarrow>\<^sup>* l'' \<and> r' -G\<rightarrow>\<^sup>* r'' \<and> u = l'' \<cdot> r''" by blast
with c show "\<exists>l' r'. l -G\<rightarrow>\<^sup>* l' \<and> r -G\<rightarrow>\<^sup>* r' \<and> u = l' \<cdot> r'"
by(rule_tac x=l'' in exI, rule_tac x=r'' in exI, force)
qed
qed
with A show ?thesis by force
qed
theorem DSTEP_star_comp2 :
assumes A: "l -G\<rightarrow>\<^sup>* l'"
and B: "r -G\<rightarrow>\<^sup>* r'"
shows "l \<cdot> r -G\<rightarrow>\<^sup>* l' \<cdot> r'"
proof -
have "l -G\<rightarrow>\<^sup>* l' \<Longrightarrow>
\<forall>r r'. r -G\<rightarrow>\<^sup>* r' \<longrightarrow> l \<cdot> r -G\<rightarrow>\<^sup>* l' \<cdot> r'" (is "?P l l' \<Longrightarrow> ?Q l l'")
proof(erule rtrancl_induct)
show "?Q l l"
proof(clarify, erule rtrancl_induct, simp)
fix r s t
assume a: "s -G\<rightarrow> t"
assume b: "l \<cdot> r -G\<rightarrow>\<^sup>* l \<cdot> s"
show "l \<cdot> r -G\<rightarrow>\<^sup>* l \<cdot> t"
proof -
from a have "l \<cdot> s -G\<rightarrow> l \<cdot> t" by(drule_tac L=l and R="[]" in DSTEP_append, simp)
with b show ?thesis by simp
qed
qed
next
fix s t
assume a: "s -G\<rightarrow> t"
assume b: "?Q l s"
show "?Q l t"
proof(clarsimp)
fix r r'
assume "r -G\<rightarrow>\<^sup>* r'"
with b have c: "l \<cdot> r -G\<rightarrow>\<^sup>* s \<cdot> r'" by simp
from a have "s \<cdot> r' -G\<rightarrow> t \<cdot> r'" by(drule_tac L="[]" and R=r' in DSTEP_append, simp)
with c show "l \<cdot> r -G\<rightarrow>\<^sup>* t \<cdot> r'" by simp
qed
qed
with A and B show ?thesis by simp
qed
lemma DSTEP_trancl_term :
assumes A: "[Inl S] -G\<rightarrow>\<^sup>+ t"
and B: "Inr x \<in> set t"
shows "\<exists>N. (N, Leaf x) \<in> set G"
proof -
have "[Inl S] -G\<rightarrow>\<^sup>+ t \<Longrightarrow>
\<forall>x. Inr x \<in> set t \<longrightarrow> (\<exists>N. (N, Leaf x) \<in> set G)" (is "?P t \<Longrightarrow> ?Q t")
proof(erule trancl_induct)
fix t
assume a: "[Inl S] -G\<rightarrow> t"
show "?Q t"
proof -
from a have "\<exists>rhs. (S, rhs) \<in> set G \<and>
(\<forall>A B. rhs = Branch A B \<longrightarrow> t = [Inl A, Inl B]) \<and>
(\<forall>x. rhs = Leaf x \<longrightarrow> t = [Inr x])" (is "\<exists>rhs. ?P rhs")
by(simp add: DSTEP_def, clarsimp, simp split: RHS.split_asm, case_tac l, force, simp,
clarsimp, simp split: RHS.split_asm, case_tac l, force, simp)
then obtain rhs where "?P rhs" by blast
thus ?thesis
by(case_tac rhs, clarsimp, force)
qed
next
fix s t
assume a: "s -G\<rightarrow> t"
assume b: "?Q s"
show "?Q t"
proof -
from a have "\<exists>L N R rhs. s = L \<cdot> [Inl N] \<cdot> R \<and> (N, rhs) \<in> set G \<and>
(\<forall>A B. rhs = Branch A B \<longrightarrow> t = L \<cdot> [Inl A, Inl B] \<cdot> R) \<and>
(\<forall>x. rhs = Leaf x \<longrightarrow> t = L \<cdot> [Inr x] \<cdot> R)" (is "\<exists>L N R rhs. ?P L N R rhs")
by(rule DSTEP_D)
then obtain L N R rhs where "?P L N R rhs" by blast
with b show ?thesis
by(case_tac rhs, clarsimp, force)
qed
qed
with A and B show ?thesis by simp
qed
subsection "Properties of generated languages"
lemma Lang_no_Nil :
"w \<in> Lang G S \<Longrightarrow> w \<noteq> []"
by(simp add: Lang_def, drule trancl_into_rtrancl, drule DSTEP_star_mono, force)
lemma Lang_rtrancl_eq :
"(w \<in> Lang G S) = [Inl S] -G\<rightarrow>\<^sup>* map Inr w" (is "?L = (?p \<in> ?R\<^sup>*)")
proof(simp add: Lang_def, rule iffI, erule trancl_into_rtrancl)
assume "?p \<in> ?R\<^sup>*"
hence "?p \<in> (?R\<^sup>+)\<^sup>=" by(subst rtrancl_trancl_reflcl[THEN sym], assumption)
hence "[Inl S] = map Inr w \<or> ?p \<in> ?R\<^sup>+" by force
thus "?p \<in> ?R\<^sup>+" by(case_tac w, simp_all)
qed
lemma Lang_term :
"w \<in> Lang G S \<Longrightarrow>
\<forall>x \<in> set w. \<exists>N. (N, Leaf x) \<in> set G"
by(clarsimp simp add: Lang_def, drule DSTEP_trancl_term,
simp, erule imageI, assumption)
lemma Lang_eq1 :
"([x] \<in> Lang G S) = ((S, Leaf x) \<in> set G)"
proof(simp add: Lang_def, rule iffI, subst (asm) trancl_unfold_left, clarsimp)
fix t
assume a: "[Inl S] -G\<rightarrow> t"
assume b: "t -G\<rightarrow>\<^sup>* [Inr x]"
note DSTEP_star_mono[OF b, simplified]
hence c: "length t \<le> 1" by simp
have "\<exists>z. t = [z]"
proof(cases t)
assume "t = []"
with b have d: "[] -G\<rightarrow>\<^sup>* [Inr x]" by simp
have "\<And>s. ([], s) \<in> (DSTEP G)\<^sup>* \<Longrightarrow> s = []"
by(erule rtrancl_induct, simp_all, drule DSTEP_D, clarsimp)
note this[OF d]
thus ?thesis by simp
next
fix z zs
assume "t = z#zs"
with c show ?thesis by force
qed
with a have "\<exists>z. (S, Leaf z) \<in> set G \<and> t = [Inr z]"
by(clarsimp simp add: DSTEP_def, simp split: RHS.split_asm, case_tac l, simp_all)
with b show "(S, Leaf x) \<in> set G"
proof(clarsimp)
fix z
assume c: "(S, Leaf z) \<in> set G"
assume "[Inr z] -G\<rightarrow>\<^sup>* [Inr x]"
hence "([Inr z], [Inr x]) \<in> ((DSTEP G)\<^sup>+)\<^sup>=" by simp
hence "[Inr z] = [Inr x] \<or> [Inr z] -G\<rightarrow>\<^sup>+ [Inr x]" by force
hence "x = z"
proof
assume "[Inr z] = [Inr x]" thus ?thesis by simp
next
assume "[Inr z] -G\<rightarrow>\<^sup>+ [Inr x]"
hence "\<exists>u. [Inr z] -G\<rightarrow> u \<and> u -G\<rightarrow>\<^sup>* [Inr x]" by(subst (asm) trancl_unfold_left, force)
then obtain u where "[Inr z] -G\<rightarrow> u" by blast
thus ?thesis by(clarsimp simp add: DSTEP_def, case_tac l, simp_all)
qed
with c show ?thesis by simp
qed
next
assume a: "(S, Leaf x) \<in> set G"
show "[Inl S] -G\<rightarrow>\<^sup>+ [Inr x]"
by(rule r_into_trancl, simp add: DSTEP_def, rule_tac x="[]" in exI,
rule_tac x="S" in exI, rule_tac x="[]" in exI, simp, rule_tac x="Leaf x" in exI,
simp add: a)
qed
theorem Lang_eq2 :
"(w \<in> Lang G S \<and> 1 < length w) =
(\<exists>A B. (S, Branch A B) \<in> set G \<and> (\<exists>l r. w = l \<cdot> r \<and> l \<in> Lang G A \<and> r \<in> Lang G B))"
(is "?L = ?R")
proof(rule iffI, clarify, subst (asm) Lang_def, simp, subst (asm) trancl_unfold_left, clarsimp)
have map_Inr_split : "\<And>xs. \<forall>zs w. map Inr w = xs \<cdot> zs \<longrightarrow>
(\<exists>u v. w = u \<cdot> v \<and> xs = map Inr u \<and> zs = map Inr v)"
by(induct_tac xs, simp, force)
fix t
assume a: "Suc 0 < length w"
assume b: "[Inl S] -G\<rightarrow> t"
assume c: "t -G\<rightarrow>\<^sup>* map Inr w"
from b have "\<exists>A B. (S, Branch A B) \<in> set G \<and> t = [Inl A, Inl B]"
proof(simp add: DSTEP_def, clarify, case_tac l, simp_all, simp split: RHS.split_asm, clarify)
fix x
assume "t = [Inr x]"
with c have d: "[Inr x] -G\<rightarrow>\<^sup>* map Inr w"by simp
have "\<And>x s. [Inr x] -G\<rightarrow>\<^sup>* s \<Longrightarrow> s = [Inr x]"
by(erule rtrancl_induct, simp_all, drule DSTEP_D, clarsimp, case_tac L, simp_all)
note this[OF d]
hence "w = [x]" by(case_tac w, simp_all)
with a show "False" by simp
qed
then obtain A B where d: "(S, Branch A B) \<in> set G \<and> t = [Inl A, Inl B]" by blast
with c have e: "[Inl A] \<cdot> [Inl B] -G\<rightarrow>\<^sup>* map Inr w" by simp
note DSTEP_star_comp1[OF e]
then obtain l' r' where e: "[Inl A] -G\<rightarrow>\<^sup>* l' \<and> [Inl B] -G\<rightarrow>\<^sup>* r' \<and>
map Inr w = l' \<cdot> r'" by blast
note map_Inr_split[rule_format, OF e[THEN conjunct2, THEN conjunct2]]
then obtain u v where f: "w = u \<cdot> v \<and> l' = map Inr u \<and> r' = map Inr v" by blast
with e have g: "[Inl A] -G\<rightarrow>\<^sup>* map Inr u \<and> [Inl B] -G\<rightarrow>\<^sup>* map Inr v" by simp
show "?R"
by(rule_tac x=A in exI, rule_tac x=B in exI, simp add: d,
rule_tac x=u in exI, rule_tac x=v in exI, simp add: f,
(subst Lang_rtrancl_eq)+, rule g)
next
assume "?R"
then obtain A B l r where a: "(S, Branch A B) \<in> set G \<and> w = l \<cdot> r \<and> l \<in> Lang G A \<and> r \<in> Lang G B" by blast
have "[Inl A] \<cdot> [Inl B] -G\<rightarrow>\<^sup>* map Inr l \<cdot> map Inr r"
by(rule DSTEP_star_comp2, subst Lang_rtrancl_eq[THEN sym], simp add: a,
subst Lang_rtrancl_eq[THEN sym], simp add: a)
hence b: "[Inl A] \<cdot> [Inl B] -G\<rightarrow>\<^sup>* map Inr w" by(simp add: a)
have c: "w \<in> Lang G S"
by(simp add: Lang_def, subst trancl_unfold_left, rule_tac b="[Inl A] \<cdot> [Inl B]" in relcompI,
simp add: DSTEP_def, rule_tac x="[]" in exI, rule_tac x="S" in exI, rule_tac x="[]" in exI,
simp, rule_tac x="Branch A B" in exI, simp add: a[THEN conjunct1], rule b)
thus "?L"
proof
show "1 < length w"
proof(simp add: a, rule ccontr, drule leI)
assume "length l + length r \<le> Suc 0"
hence "l = [] \<or> r = []" by(case_tac l, simp_all)
thus "False"
proof
assume "l = []"
with a have "[] \<in> Lang G A" by simp
note Lang_no_Nil[OF this]
thus ?thesis by simp
next
assume "r = []"
with a have "[] \<in> Lang G B" by simp
note Lang_no_Nil[OF this]
thus ?thesis by simp
qed
qed
qed
qed
section "Abstract specification of CYK"
text "A subword of a word $w$, starting at the position $i$
(first element is at the position $0$) and having the length $j$, is defined as follows."
definition "subword w i j = take j (drop i w)"
text "Thus, to any subword of the given word $w$ CYK assigns all non-terminals
from which this subword is derivable by the grammar $G$."
definition "CYK G w i j = {S. subword w i j \<in> Lang G S}"
subsection \<open>Properties of @{term "subword"}\<close>
lemma subword_length :
"i + j \<le> length w \<Longrightarrow> length(subword w i j) = j"
by(simp add: subword_def)
lemma subword_nth1 :
"i + j \<le> length w \<Longrightarrow> k < j \<Longrightarrow>
(subword w i j)!k = w!(i + k)"
by(simp add: subword_def)
lemma subword_nth2 :
assumes A: "i + 1 \<le> length w"
shows "subword w i 1 = [w!i]"
proof -
note subword_length[OF A]
hence "\<exists>x. subword w i 1 = [x]" by(case_tac "subword w i 1", simp_all)
then obtain x where a:"subword w i 1 = [x]" by blast
note subword_nth1[OF A, where k="(0 :: nat)", simplified]
with a have "x = w!i" by simp
with a show ?thesis by simp
qed
lemma subword_self :
"subword w 0 (length w) = w"
by(simp add: subword_def)
lemma take_split[rule_format] :
"\<forall>n m. n \<le> length xs \<longrightarrow> n \<le> m \<longrightarrow>
take n xs \<cdot> take (m - n) (drop n xs) = take m xs"
by(induct_tac xs, clarsimp+, case_tac n, simp_all, case_tac m, simp_all)
lemma subword_split :
"i + j \<le> length w \<Longrightarrow> 0 < k \<Longrightarrow> k < j \<Longrightarrow>
subword w i j = subword w i k \<cdot> subword w (i + k) (j - k)"
by(simp add: subword_def, subst take_split[where n=k, THEN sym], simp_all,
rule_tac f="\<lambda>x. take (j - k) (drop x w)" in arg_cong, simp)
lemma subword_split2 :
assumes A: "subword w i j = l \<cdot> r"
and B: "i + j \<le> length w"
and C: "0 < length l"
and D: "0 < length r"
shows "l = subword w i (length l) \<and> r = subword w (i + length l) (j - length l)"
proof -
have a: "length(subword w i j) = j" by(rule subword_length, rule B)
note arg_cong[where f=length, OF A]
with a and D have b: "length l < j" by force
with B have c: "i + length l \<le> length w" by force
have "subword w i j = subword w i (length l) \<cdot> subword w (i + length l) (j - length l)"
by(rule subword_split, rule B, rule C, rule b)
with A have d: "l \<cdot> r = subword w i (length l) \<cdot> subword w (i + length l) (j - length l)" by simp
show ?thesis
by(rule append_eq_append_conv[THEN iffD1], subst subword_length, rule c, simp, rule d)
qed
subsection \<open>Properties of @{term "CYK"}\<close>
lemma CYK_Lang :
"(S \<in> CYK G w 0 (length w)) = (w \<in> Lang G S)"
by(simp add: CYK_def subword_self)
lemma CYK_eq1 :
"i + 1 \<le> length w \<Longrightarrow>
CYK G w i 1 = {S. (S, Leaf (w!i)) \<in> set G}"
by(simp add: CYK_def, subst subword_nth2[simplified], assumption,
subst Lang_eq1, rule refl)
theorem CYK_eq2 :
assumes A: "i + j \<le> length w"
and B: "1 < j"
shows "CYK G w i j = {X | X A B k. (X, Branch A B) \<in> set G \<and> A \<in> CYK G w i k \<and> B \<in> CYK G w (i + k) (j - k) \<and> 1 \<le> k \<and> k < j}"
proof(rule set_eqI, rule iffI, simp_all add: CYK_def)
fix X
assume a: "subword w i j \<in> Lang G X"
show "\<exists>A B. (X, Branch A B) \<in> set G \<and> (\<exists>k. subword w i k \<in> Lang G A \<and> subword w (i + k) (j - k) \<in> Lang G B \<and> Suc 0 \<le> k \<and> k < j)"
proof -
have b: "1 < length(subword w i j)" by(subst subword_length, rule A, rule B)
note Lang_eq2[THEN iffD1, OF conjI, OF a b]
then obtain A B l r where c: "(X, Branch A B) \<in> set G \<and> subword w i j = l \<cdot> r \<and> l \<in> Lang G A \<and> r \<in> Lang G B" by blast
note Lang_no_Nil[OF c[THEN conjunct2, THEN conjunct2, THEN conjunct1]]
hence d: "0 < length l" by(case_tac l, simp_all)
note Lang_no_Nil[OF c[THEN conjunct2, THEN conjunct2, THEN conjunct2]]
hence e: "0 < length r" by(case_tac r, simp_all)
note subword_split2[OF c[THEN conjunct2, THEN conjunct1], OF A, OF d, OF e]
with c show ?thesis
proof(rule_tac x=A in exI, rule_tac x=B in exI, simp,
rule_tac x="length l" in exI, simp)
show "Suc 0 \<le> length l \<and> length l < j" (is "?A \<and> ?B")
proof
from d show "?A" by(case_tac l, simp_all)
next
note arg_cong[where f=length, OF c[THEN conjunct2, THEN conjunct1], THEN sym]
also have "length(subword w i j) = j" by(rule subword_length, rule A)
finally have "length l + length r = j" by simp
with e show ?B by force
qed
qed
qed
next
fix X
assume "\<exists>A B. (X, Branch A B) \<in> set G \<and> (\<exists>k. subword w i k \<in> Lang G A \<and> subword w (i + k) (j - k) \<in> Lang G B \<and> Suc 0 \<le> k \<and> k < j)"
then obtain A B k where a: "(X, Branch A B) \<in> set G \<and> subword w i k \<in> Lang G A \<and> subword w (i + k) (j - k) \<in> Lang G B \<and> Suc 0 \<le> k \<and> k < j" by blast
show "subword w i j \<in> Lang G X"
proof(rule Lang_eq2[THEN iffD2, THEN conjunct1], rule_tac x=A in exI, rule_tac x=B in exI, simp add: a,
rule_tac x="subword w i k" in exI, rule_tac x="subword w (i + k) (j - k)" in exI, simp add: a,
rule subword_split, rule A)
from a show "0 < k" by force
next
from a show "k < j" by simp
qed
qed
section "Implementation"
text "One of the particularly interesting features of CYK implementation
is that it follows the principles of dynamic programming, constructing a
table of solutions for sub-problems in the bottom-up style reusing already
stored results."
subsection "Main cycle"
text "This is an auxiliary implementation of the membership test on lists."
fun mem :: "'a \<Rightarrow> 'a list \<Rightarrow> bool"
where
"mem a [] = False" |
"mem a (x#xs) = (x = a \<or> mem a xs)"
lemma mem[simp] :
"mem x xs = (x \<in> set xs)"
by(induct_tac xs, simp, force)
text "The purpose of the following is to collect non-terminals that appear on the lhs of a production
such that the first non-terminal on its rhs appears in the first of two given lists and the second
non-terminal -- in the second list."
fun match_prods :: "('n, 't) CNG \<Rightarrow> 'n list \<Rightarrow> 'n list \<Rightarrow> 'n list"
where "match_prods [] ls rs = []" |
"match_prods ((X, Branch A B)#ps) ls rs =
(if mem A ls \<and> mem B rs then X # match_prods ps ls rs
else match_prods ps ls rs)" |
"match_prods ((X, Leaf a)#ps) ls rs = match_prods ps ls rs"
lemma match_prods :
"(X \<in> set(match_prods G ls rs)) =
(\<exists>A \<in> set ls. \<exists>B \<in> set rs. (X, Branch A B) \<in> set G)"
by(induct_tac G, clarsimp+, rename_tac l r ps, case_tac r, force+)
text "The following function is the inner cycle of the algorithm. The parameters $i$ and $j$
identify a subword starting at $i$ with the length $j$, whereas $k$ is used to iterate through
its splits (which are of course subwords as well) all having the length greater $0$ but less than $j$.
The parameter $T$ represents a table containing CYK solutions for those splits."
function inner :: "('n, 't) CNG \<Rightarrow> (nat \<times> nat \<Rightarrow> 'n list) \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> 'n list"
where "inner G T i k j =
(if k < j then match_prods G (T(i, k)) (T(i + k, j - k)) @ inner G T i (k + 1) j
else [])"
by pat_completeness auto
termination
by(relation "measure(\<lambda>(a, b, c, d, e). e - d)", rule wf_measure, simp)
declare inner.simps[simp del]
lemma inner :
"(X \<in> set(inner G T i k j)) =
(\<exists>l. k \<le> l \<and> l < j \<and> X \<in> set(match_prods G (T(i, l)) (T(i + l, j - l))))"
(is "?L G T i k j = ?R G T i k j")
proof(induct_tac G T i k j rule: inner.induct)
fix G T i k j
assume a: "k < j \<Longrightarrow> ?L G T i (k + 1) j = ?R G T i (k + 1) j"
show "?L G T i k j = ?R G T i k j"
proof(case_tac "k < j")
assume b: "k < j"
with a have c: "?L G T i (k + 1) j = ?R G T i (k + 1) j" by simp
show ?thesis
proof(subst inner.simps, simp add: b, rule iffI, erule disjE, rule_tac x=k in exI, simp add: b)
assume "X \<in> set(inner G T i (Suc k) j)"
with c have "?R G T i (k + 1) j" by simp
thus "?R G T i k j" by(clarsimp, rule_tac x=l in exI, simp)
next
assume "?R G T i k j"
then obtain l where d: "k \<le> l \<and> l < j \<and> X \<in> set(match_prods G (T(i, l)) (T(i + l, j - l)))" by blast
show "X \<in> set(match_prods G (T(i, k)) (T(i + k, j - k))) \<or> ?L G T i (Suc k) j"
proof(case_tac "Suc k \<le> l", rule disjI2, subst c[simplified], rule_tac x=l in exI, simp add: d,
rule disjI1)
assume "\<not> Suc k \<le> l"
with d have "l = k" by force
with d show "X \<in> set(match_prods G (T(i, k)) (T(i + k, j - k)))" by simp
qed
qed
next
assume "\<not> k < j"
thus ?thesis by(subst inner.simps, simp)
qed
qed
text\<open>Now the main part of the algorithm just iterates through all subwords up to the given length $len$,
calls @{term "inner"} on these, and stores the results in the table $T$. The length $j$ is supposed to
be greater than $1$ -- the subwords of length $1$ will be handled in the initialisation phase below.\<close>
function main :: "('n, 't) CNG \<Rightarrow> (nat \<times> nat \<Rightarrow> 'n list) \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> (nat \<times> nat \<Rightarrow> 'n list)"
where "main G T len i j = (let T' = T((i, j) := inner G T i 1 j) in
if i + j < len then main G T' len (i + 1) j
else if j < len then main G T' len 0 (j + 1)
else T')"
by pat_completeness auto
termination
by(relation "inv_image (less_than <*lex*> less_than) (\<lambda>(a, b, c, d, e). (c - e, c - (d + e)))", rule wf_inv_image, rule wf_lex_prod, (rule wf_less_than)+, simp_all)
declare main.simps[simp del]
lemma main :
assumes "1 < j"
and "i + j \<le> length w"
and "\<And>i' j'. j' < j \<Longrightarrow> 1 \<le> j' \<Longrightarrow> i' + j' \<le> length w \<Longrightarrow> set(T(i', j')) = CYK G w i' j'"
and "\<And>i'. i' < i \<Longrightarrow> i' + j \<le> length w \<Longrightarrow> set(T(i', j)) = CYK G w i' j"
and "1 \<le> j'"
and "i' + j' \<le> length w"
shows "set((main G T (length w) i j)(i', j')) = CYK G w i' j'"
proof -
have "\<forall>len T' w. main G T len i j = T' \<longrightarrow> length w = len \<longrightarrow> 1 < j \<longrightarrow> i + j \<le> len \<longrightarrow>
(\<forall>j' < j. \<forall>i'. 1 \<le> j' \<longrightarrow> i' + j' \<le> len \<longrightarrow> set(T(i', j')) = CYK G w i' j') \<longrightarrow>
(\<forall>i' < i. i' + j \<le> len \<longrightarrow> set(T(i', j)) = CYK G w i' j) \<longrightarrow>
(\<forall>j' \<ge> 1. \<forall>i'. i' + j' \<le> len \<longrightarrow> set(T'(i', j')) = CYK G w i' j')" (is "\<forall>len. ?P G T len i j")
proof(rule allI, induct_tac G T len i j rule: main.induct, (drule meta_spec, drule meta_mp, rule refl)+, clarify)
fix G T i j i' j'
fix w :: "'a list"
assume a: "i + j < length w \<Longrightarrow> ?P G (T((i, j) := inner G T i 1 j)) (length w) (i + 1) j"
assume b: "\<not> i + j < length w \<Longrightarrow> j < length w \<Longrightarrow> ?P G (T((i, j) := inner G T i 1 j)) (length w) 0 (j + 1)"
assume c: "1 < j"
assume d: "i + j \<le> length w"
assume e: "(1::nat) \<le> j'"
assume f: "i' + j' \<le> length w"
assume g: "\<forall>j' < j. \<forall>i'. 1 \<le> j' \<longrightarrow> i' + j' \<le> length w \<longrightarrow> set(T(i', j')) = CYK G w i' j'"
assume h: "\<forall>i' < i. i' + j \<le> length w \<longrightarrow> set(T(i', j)) = CYK G w i' j"
have inner: "set (inner G T i (Suc 0) j) = CYK G w i j"
proof(rule set_eqI, subst inner, subst match_prods, subst CYK_eq2, rule d, rule c, simp)
fix X
show "(\<exists>l\<ge>Suc 0. l < j \<and> (\<exists>A \<in> set(T(i, l)). \<exists>B \<in> set(T(i + l, j - l)). (X, Branch A B) \<in> set G)) =
(\<exists>A B. (X, Branch A B) \<in> set G \<and> (\<exists>k. A \<in> CYK G w i k \<and> B \<in> CYK G w (i + k) (j - k) \<and> Suc 0 \<le> k \<and> k < j))" (is "?L = ?R")
proof
assume "?L"
thus "?R"
proof(clarsimp, rule_tac x=A in exI, rule_tac x=B in exI, simp, rule_tac x=l in exI, simp)
fix l A B
assume i: "Suc 0 \<le> l"
assume j: "l < j"
assume k: "A \<in> set(T(i, l))"
assume l: "B \<in> set(T(i + l, j - l))"
note g[rule_format, where i'=i and j'=l]
with d i j have A: "set(T(i, l)) = CYK G w i l" by force
note g[rule_format, where i'="i + l" and j'="j - l"]
with d i j have "set(T(i + l, j - l)) = CYK G w (i + l) (j - l)" by force
with k l A show "A \<in> CYK G w i l \<and> B \<in> CYK G w (i + l) (j - l)" by simp
qed
next
assume "?R"
thus "?L"
proof(clarsimp, rule_tac x=k in exI, simp)
fix A B k
assume i: "Suc 0 \<le> k"
assume j: "k < j"
assume k: "A \<in> CYK G w i k"
assume l: "B \<in> CYK G w (i + k) (j - k)"
assume m: "(X, Branch A B) \<in> set G"
note g[rule_format, where i'=i and j'=k]
with d i j have A: "CYK G w i k = set(T(i, k))" by force
note g[rule_format, where i'="i + k" and j'="j - k"]
with d i j have "CYK G w (i + k) (j - k) = set(T(i + k, j - k))" by force
with k l A have "A \<in> set(T(i, k)) \<and> B \<in> set(T(i + k, j - k))" by simp
with m show "\<exists>A \<in> set(T(i, k)). \<exists>B \<in> set(T(i + k, j - k)). (X, Branch A B) \<in> set G" by force
qed
qed
qed (* inner *)
show "set((main G T (length w) i j)(i', j')) = CYK G w i' j'"
proof(case_tac "i + j = length w")
assume i: "i + j = length w"
show ?thesis
proof(case_tac "j < length w")
assume j: "j < length w"
show ?thesis
proof(subst main.simps, simp add: Let_def i j,
rule b[rule_format, where w=w and i'=i' and j'=j', OF _ _ refl, simplified],
simp_all add: inner)
from i show "\<not> i + j < length w" by simp
next
from c show "0 < j" by simp
next
from j show "Suc j \<le> length w" by simp
next
from e show "Suc 0 \<le> j'" by simp
next
from f show "i' + j' \<le> length w" by assumption
next
fix i'' j''
assume k: "j'' < Suc j"
assume l: "Suc 0 \<le> j''"
assume m: "i'' + j'' \<le> length w"
show "(i'' = i \<longrightarrow> j'' \<noteq> j) \<longrightarrow> set(T(i'',j'')) = CYK G w i'' j''"
proof(case_tac "j'' = j", simp_all, clarify)
assume n: "j'' = j"
assume "i'' \<noteq> i"
with i m n have "i'' < i" by simp
with n m h show "set(T(i'', j)) = CYK G w i'' j" by simp
next
assume "j'' \<noteq> j"
with k have "j'' < j" by simp
with l m g show "set(T(i'', j'')) = CYK G w i'' j''" by simp
qed
qed
next
assume "\<not> j < length w"
with i have j: "i = 0 \<and> j = length w" by simp
show ?thesis
proof(subst main.simps, simp add: Let_def j, intro conjI, clarify)
from j and inner show "set (inner G T 0 (Suc 0) (length w)) = CYK G w 0 (length w)" by simp
next
show "0 < i' \<longrightarrow> set(T(i', j')) = CYK G w i' j'"
proof
assume "0 < i'"
with j and f have "j' < j" by simp
with e g f show "set(T(i', j')) = CYK G w i' j'" by simp
qed
next
show "j' \<noteq> length w \<longrightarrow> set(T(i', j')) = CYK G w i' j'"
proof
assume "j' \<noteq> length w "
with j and f have "j' < j" by simp
with e g f show "set(T(i', j')) = CYK G w i' j'" by simp
qed
qed
qed
next
assume "i + j \<noteq> length w"
with d have i: "i + j < length w" by simp
show ?thesis
proof(subst main.simps, simp add: Let_def i,
rule a[rule_format, where w=w and i'=i' and j'=j', OF i, OF refl, simplified])
from c show "Suc 0 < j" by simp
next
from i show "Suc(i + j) \<le> length w" by simp
next
from e show "Suc 0 \<le> j'" by simp
next
from f show "i' + j' \<le> length w" by assumption
next
fix i'' j''
assume "j'' < j"
and "Suc 0 \<le> j''"
and "i'' + j'' \<le> length w"
with g show "set(T(i'', j'')) = CYK G w i'' j''" by simp
next
fix i'' assume j: "i'' < Suc i"
show "set(if i'' = i then inner G T i (Suc 0) j else T(i'', j)) = CYK G w i'' j"
proof(simp split: if_split, rule conjI, clarify, rule inner, clarify)
assume "i'' \<noteq> i"
with j have "i'' < i" by simp
with d h show "set(T(i'', j)) = CYK G w i'' j" by simp
qed
qed
qed
qed
with assms show ?thesis by force
qed
subsection "Initialisation phase"
text\<open>Similarly to @{term "match_prods"} above, here we collect non-terminals from which
the given terminal symbol can be derived.\<close>
fun init_match :: "('n, 't) CNG \<Rightarrow> 't \<Rightarrow> 'n list"
where "init_match [] t = []" |
"init_match ((X, Branch A B)#ps) t = init_match ps t" |
"init_match ((X, Leaf a)#ps) t = (if a = t then X # init_match ps t
else init_match ps t)"
lemma init_match :
"(X \<in> set(init_match G a)) =
((X, Leaf a) \<in> set G)"
by(induct_tac G a rule: init_match.induct, simp_all)
text "Representing the empty table."
definition "emptyT = (\<lambda>(i, j). [])"
text "The following function initialises the empty table for subwords of
length $1$, i.e. each symbol occurring in the given word."
fun init' :: "('n, 't) CNG \<Rightarrow> 't list \<Rightarrow> nat \<Rightarrow> nat \<times> nat \<Rightarrow> 'n list"
where "init' G [] k = emptyT" |
"init' G (t#ts) k = (init' G ts (k + 1))((k, 1) := init_match G t)"
text\<open>The next version of initialization refines @{term "init'"} in that
it takes additional account of the cases when the given word is
empty or contains a terminal symbol that does not have any matching
production (that is, @{term "init_match"} is an empty list). No initial
table is then needed as such words can immediately be rejected.\<close>
fun init :: "('n, 't) CNG \<Rightarrow> 't list \<Rightarrow> nat \<Rightarrow> (nat \<times> nat \<Rightarrow> 'n list) option"
where "init G [] k = None" |
"init G [t] k = (case (init_match G t) of
[] \<Rightarrow> None
| xs \<Rightarrow> Some(emptyT((k, 1) := xs)))" |
"init G (t#ts) k = (case (init_match G t) of
[] \<Rightarrow> None
| xs \<Rightarrow> (case (init G ts (k + 1)) of
None \<Rightarrow> None
| Some T \<Rightarrow> Some(T((k, 1) := xs))))"
lemma init1[rule_format] :
"\<forall>T. init G w k = Some T \<longrightarrow>
init' G w k = T"
by(induct_tac G w k rule: init.induct, clarsimp+, simp split: list.split_asm, rule ext, clarsimp+,
simp split: list.split_asm option.split_asm, rule ext, clarsimp, force)
lemma init2 :
"(init G w k = None) =
(w = [] \<or> (\<exists>a \<in> set w. init_match G a = []))"
by(induct_tac G w k rule: init.induct, simp, simp split: list.split,
simp split: list.split option.split, force)
subsection \<open>The overall procedure\<close>
definition "cyk G S w = (case init G w 0 of
None \<Rightarrow> False
| Some T \<Rightarrow> let len = length w in
if len = 1 then mem S (T(0, 1))
else let T' = main G T len 0 2 in
mem S (T'(0, len)))"
theorem cyk :
"cyk G S w = (w \<in> Lang G S)"
proof(simp add: cyk_def split: option.split, simp_all add: Let_def,
rule conjI, subst init2, simp, rule conjI)
show "w = [] \<longrightarrow> [] \<notin> Lang G S" by(clarify, drule Lang_no_Nil, clarify)
next
show "(\<exists>x\<in>set w. init_match G x = []) \<longrightarrow> w \<notin> Lang G S" by(clarify, drule Lang_term, subst (asm) init_match[THEN sym], force)
next
show "\<forall>T. init G w 0 = Some T \<longrightarrow>
((length w = Suc 0 \<longrightarrow> S \<in> set(T(0, Suc 0))) \<and>
(length w \<noteq> Suc 0 \<longrightarrow> S \<in> set(main G T (length w) 0 2 (0, length w)))) =
(w \<in> Lang G S)" (is "\<forall>T. ?P T \<longrightarrow> ?L T = ?R")
proof clarify
fix T
assume a: "?P T"
hence b: "init' G w 0 = T" by(rule init1)
note init2[THEN iffD2, OF disjI1]
have c: "w \<noteq> []" by(clarify, drule init2[where G=G and k=0, THEN iffD2, OF disjI1], simp add: a)
have "?L (init' G w 0) = ?R"
proof(case_tac "length w = 1", simp_all)
assume d: "length w = Suc 0"
show "S \<in> set(init' G w 0 (0, Suc 0)) = ?R"
by(subst init'[simplified], simp add: d, subst CYK_Lang[THEN sym], simp add: d)
next
assume "length w \<noteq> Suc 0"
with c have "1 < length w" by(case_tac w, simp_all)
hence d: "Suc(Suc 0) \<le> length w" by simp
show "(S \<in> set(main G (init' G w 0) (length w) 0 2 (0, length w))) = (w \<in> Lang G S)"
proof(subst main, simp_all, rule d)
fix i' j'
assume "j' < 2" and "Suc 0 \<le> j'"
hence e: "j' = 1" by simp
assume "i' + j' \<le> length w"
with e have f: "i' + 1 \<le> length w" by simp
have "set(init' G w 0 (i', 1)) = CYK G w i' 1" by(rule init', rule f)
with e show "set(init' G w 0 (i', j')) = CYK G w i' j'" by simp
next
from d show "Suc 0 \<le> length w" by simp
next
show "(S \<in> CYK G w 0 (length w)) = (w \<in> Lang G S)" by(rule CYK_Lang)
qed
qed
with b show "?L T = ?R" by simp
qed
qed
value [code]
"let G = [(0::int, Branch 1 2), (0, Branch 2 3),
(1, Branch 2 1), (1, Leaf ''a''),
(2, Branch 3 3), (2, Leaf ''b''),
(3, Branch 1 2), (3, Leaf ''a'')]
in map (cyk G 0)
[[''b'',''a'',''a'',''b'',''a''],
[''b'',''a'',''b'',''a'']]"
end
|
State Before: ι : Type u_2
α : ι → Type u_1
f f₁ f₂ : (i : ι) → Filter (α i)
s : (i : ι) → Set (α i)
inst✝ : ∀ (i : ι), NeBot (f i)
I : Set ι
⊢ NeBot (pi f ⊓ 𝓟 (Set.pi I s)) ↔ ∀ (i : ι), i ∈ I → NeBot (f i ⊓ 𝓟 (s i)) State After: no goals Tactic: simp [neBot_iff] |
[GOAL]
C : Type u₁
inst✝² : Category.{v₁, u₁} C
D : Type u₂
inst✝¹ : Category.{v₂, u₂} D
E : Type u₃
inst✝ : Category.{v₃, u₃} E
X : (C × D) × E
⊢ (𝟭 ((C × D) × E)).obj X = (associator C D E ⋙ inverseAssociator C D E).obj X
[PROOFSTEP]
simp
[GOAL]
C : Type u₁
inst✝² : Category.{v₁, u₁} C
D : Type u₂
inst✝¹ : Category.{v₂, u₂} D
E : Type u₃
inst✝ : Category.{v₃, u₃} E
X : C × D × E
⊢ (inverseAssociator C D E ⋙ associator C D E).obj X = (𝟭 (C × D × E)).obj X
[PROOFSTEP]
simp
[GOAL]
C : Type u₁
inst✝² : Category.{v₁, u₁} C
D : Type u₂
inst✝¹ : Category.{v₂, u₂} D
E : Type u₃
inst✝ : Category.{v₃, u₃} E
⊢ IsEquivalence (associativity C D E).functor
[PROOFSTEP]
infer_instance
[GOAL]
C : Type u₁
inst✝² : Category.{v₁, u₁} C
D : Type u₂
inst✝¹ : Category.{v₂, u₂} D
E : Type u₃
inst✝ : Category.{v₃, u₃} E
⊢ IsEquivalence (associativity C D E).inverse
[PROOFSTEP]
infer_instance
|
[STATEMENT]
lemma tj_stack_pop_set:
"tj_stack_pop tjs u \<le> SPEC (\<lambda>(tjs',scc). u \<in> set tjs \<longrightarrow> set tjs = set tjs' \<union> scc \<and> u \<in> scc)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. tj_stack_pop tjs u \<le> SPEC (\<lambda>(tjs', scc). u \<in> set tjs \<longrightarrow> set tjs = set tjs' \<union> scc \<and> u \<in> scc)
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. tj_stack_pop tjs u \<le> SPEC (\<lambda>(tjs', scc). u \<in> set tjs \<longrightarrow> set tjs = set tjs' \<union> scc \<and> u \<in> scc)
[PROOF STEP]
from tjs_union[of u tjs]
[PROOF STATE]
proof (chain)
picking this:
u \<in> set tjs \<Longrightarrow> set tjs = set (tl (dropWhile ((\<noteq>) u) tjs)) \<union> insert u (set (takeWhile ((\<noteq>) u) tjs))
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
u \<in> set tjs \<Longrightarrow> set tjs = set (tl (dropWhile ((\<noteq>) u) tjs)) \<union> insert u (set (takeWhile ((\<noteq>) u) tjs))
goal (1 subgoal):
1. tj_stack_pop tjs u \<le> SPEC (\<lambda>(tjs', scc). u \<in> set tjs \<longrightarrow> set tjs = set tjs' \<union> scc \<and> u \<in> scc)
[PROOF STEP]
unfolding tj_stack_pop_def
[PROOF STATE]
proof (prove)
using this:
u \<in> set tjs \<Longrightarrow> set tjs = set (tl (dropWhile ((\<noteq>) u) tjs)) \<union> insert u (set (takeWhile ((\<noteq>) u) tjs))
goal (1 subgoal):
1. RETURN (tl (dropWhile ((\<noteq>) u) tjs), insert u (set (takeWhile ((\<noteq>) u) tjs))) \<le> SPEC (\<lambda>(tjs', scc). u \<in> set tjs \<longrightarrow> set tjs = set tjs' \<union> scc \<and> u \<in> scc)
[PROOF STEP]
by (refine_vcg) auto
[PROOF STATE]
proof (state)
this:
tj_stack_pop tjs u \<le> SPEC (\<lambda>(tjs', scc). u \<in> set tjs \<longrightarrow> set tjs = set tjs' \<union> scc \<and> u \<in> scc)
goal:
No subgoals!
[PROOF STEP]
qed |
module FourierPinwheel.Hypergeo1F1 where
import Data.Complex
import Data.List as L
import Math.Sequence.Converge
{-# INLINE hypergeom #-}
hypergeom ::
(Eq a, RealFloat a, Enum a)
=> Complex a
-> Complex a
-> Complex a
-> Complex a
hypergeom a b z =
converge .
scanl (+) 0 .
scanl (*) 1 .
L.map (\i -> (a + ((i - 1) :+ 0)) / (b + ((i - 1) :+ 0)) * z / (i :+ 0)) $
[1 ..]
|
/**
*
* @file qwrapper_zlacpy.c
*
* PLASMA core_blas quark wrapper
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Julien Langou
* @author Henricus Bouwmeester
* @author Mathieu Faverge
* @date 2010-11-15
* @precisions normal z -> c d s
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
**/
void QUARK_CORE_zlacpy(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum uplo, int m, int n, int nb,
const PLASMA_Complex64_t *A, int lda,
PLASMA_Complex64_t *B, int ldb)
{
DAG_CORE_LACPY;
QUARK_Insert_Task(quark, CORE_zlacpy_quark, task_flags,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(PLASMA_Complex64_t)*nb*nb, A, INPUT,
sizeof(int), &lda, VALUE,
sizeof(PLASMA_Complex64_t)*nb*nb, B, OUTPUT,
sizeof(int), &ldb, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zlacpy_quark = PCORE_zlacpy_quark
#define CORE_zlacpy_quark PCORE_zlacpy_quark
#endif
void CORE_zlacpy_quark(Quark *quark)
{
PLASMA_enum uplo;
int M;
int N;
const PLASMA_Complex64_t *A;
int LDA;
PLASMA_Complex64_t *B;
int LDB;
quark_unpack_args_7(quark, uplo, M, N, A, LDA, B, LDB);
LAPACKE_zlacpy_work(
LAPACK_COL_MAJOR,
lapack_const(uplo),
M, N, A, LDA, B, LDB);
}
/***************************************************************************//**
*
**/
void QUARK_CORE_zlacpy_f1(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum uplo, int m, int n, int nb,
const PLASMA_Complex64_t *A, int lda,
PLASMA_Complex64_t *B, int ldb,
PLASMA_Complex64_t *fake1, int szefake1, int flag1)
{
DAG_CORE_LACPY;
if ( fake1 == B ) {
QUARK_Insert_Task(quark, CORE_zlacpy_quark, task_flags,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(PLASMA_Complex64_t)*nb*nb, A, INPUT,
sizeof(int), &lda, VALUE,
sizeof(PLASMA_Complex64_t)*nb*nb, B, OUTPUT | flag1,
sizeof(int), &ldb, VALUE,
0);
}
else {
QUARK_Insert_Task(quark, CORE_zlacpy_f1_quark, task_flags,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(PLASMA_Complex64_t)*nb*nb, A, INPUT,
sizeof(int), &lda, VALUE,
sizeof(PLASMA_Complex64_t)*nb*nb, B, OUTPUT,
sizeof(int), &ldb, VALUE,
sizeof(PLASMA_Complex64_t)*szefake1, fake1, flag1,
0);
}
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zlacpy_f1_quark = PCORE_zlacpy_f1_quark
#define CORE_zlacpy_f1_quark PCORE_zlacpy_f1_quark
#endif
void CORE_zlacpy_f1_quark(Quark *quark)
{
PLASMA_enum uplo;
int M;
int N;
const PLASMA_Complex64_t *A;
int LDA;
PLASMA_Complex64_t *B;
int LDB;
void *fake1;
quark_unpack_args_8(quark, uplo, M, N, A, LDA, B, LDB, fake1);
LAPACKE_zlacpy_work(
LAPACK_COL_MAJOR,
lapack_const(uplo),
M, N, A, LDA, B, LDB);
}
|
State Before: α : Type u
β : Type v
γ : Type w
ι : Type x
inst✝¹ : UniformSpace β
F : ι → α → β
f : α → β
s s' : Set α
x : α
p : Filter ι
p' : Filter α
g : ι → α
inst✝ : TopologicalSpace α
⊢ TendstoLocallyUniformly F f p ↔ ∀ (x : α), TendstoUniformlyOnFilter F f p (𝓝 x) State After: no goals Tactic: simpa [← tendstoLocallyUniformlyOn_univ, ← nhdsWithin_univ] using
@tendstoLocallyUniformlyOn_iff_filter _ _ _ _ F f univ p _ |
If $S$ is a discrete set, then $S$ is closed. |
SUBROUTINE DGET38( RMAX, LMAX, NINFO, KNT, NIN )
*
* -- LAPACK test routine (version 3.1) --
* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd..
* November 2006
*
* .. Scalar Arguments ..
INTEGER KNT, NIN
* ..
* .. Array Arguments ..
INTEGER LMAX( 3 ), NINFO( 3 )
DOUBLE PRECISION RMAX( 3 )
* ..
*
* Purpose
* =======
*
* DGET38 tests DTRSEN, a routine for estimating condition numbers of a
* cluster of eigenvalues and/or its associated right invariant subspace
*
* The test matrices are read from a file with logical unit number NIN.
*
* Arguments
* ==========
*
* RMAX (output) DOUBLE PRECISION array, dimension (3)
* Values of the largest test ratios.
* RMAX(1) = largest residuals from DHST01 or comparing
* different calls to DTRSEN
* RMAX(2) = largest error in reciprocal condition
* numbers taking their conditioning into account
* RMAX(3) = largest error in reciprocal condition
* numbers not taking their conditioning into
* account (may be larger than RMAX(2))
*
* LMAX (output) INTEGER array, dimension (3)
* LMAX(i) is example number where largest test ratio
* RMAX(i) is achieved. Also:
* If DGEHRD returns INFO nonzero on example i, LMAX(1)=i
* If DHSEQR returns INFO nonzero on example i, LMAX(2)=i
* If DTRSEN returns INFO nonzero on example i, LMAX(3)=i
*
* NINFO (output) INTEGER array, dimension (3)
* NINFO(1) = No. of times DGEHRD returned INFO nonzero
* NINFO(2) = No. of times DHSEQR returned INFO nonzero
* NINFO(3) = No. of times DTRSEN returned INFO nonzero
*
* KNT (output) INTEGER
* Total number of examples tested.
*
* NIN (input) INTEGER
* Input logical unit number.
*
* =====================================================================
*
* .. Parameters ..
DOUBLE PRECISION ZERO, ONE, TWO
PARAMETER ( ZERO = 0.0D0, ONE = 1.0D0, TWO = 2.0D0 )
DOUBLE PRECISION EPSIN
PARAMETER ( EPSIN = 5.9605D-8 )
INTEGER LDT, LWORK
PARAMETER ( LDT = 20, LWORK = 2*LDT*( 10+LDT ) )
INTEGER LIWORK
PARAMETER ( LIWORK = LDT*LDT )
* ..
* .. Local Scalars ..
INTEGER I, INFO, ISCL, ITMP, J, KMIN, M, N, NDIM
DOUBLE PRECISION BIGNUM, EPS, S, SEP, SEPIN, SEPTMP, SIN,
$ SMLNUM, STMP, TNRM, TOL, TOLIN, V, VIMIN, VMAX,
$ VMUL, VRMIN
* ..
* .. Local Arrays ..
LOGICAL SELECT( LDT )
INTEGER IPNT( LDT ), ISELEC( LDT ), IWORK( LIWORK )
DOUBLE PRECISION Q( LDT, LDT ), QSAV( LDT, LDT ),
$ QTMP( LDT, LDT ), RESULT( 2 ), T( LDT, LDT ),
$ TMP( LDT, LDT ), TSAV( LDT, LDT ),
$ TSAV1( LDT, LDT ), TTMP( LDT, LDT ), VAL( 3 ),
$ WI( LDT ), WITMP( LDT ), WORK( LWORK ),
$ WR( LDT ), WRTMP( LDT )
* ..
* .. External Functions ..
DOUBLE PRECISION DLAMCH, DLANGE
EXTERNAL DLAMCH, DLANGE
* ..
* .. External Subroutines ..
EXTERNAL DCOPY, DGEHRD, DHSEQR, DHST01, DLABAD, DLACPY,
$ DORGHR, DSCAL, DTRSEN
* ..
* .. Intrinsic Functions ..
INTRINSIC DBLE, MAX, SQRT
* ..
* .. Executable Statements ..
*
EPS = DLAMCH( 'P' )
SMLNUM = DLAMCH( 'S' ) / EPS
BIGNUM = ONE / SMLNUM
CALL DLABAD( SMLNUM, BIGNUM )
*
* EPSIN = 2**(-24) = precision to which input data computed
*
EPS = MAX( EPS, EPSIN )
RMAX( 1 ) = ZERO
RMAX( 2 ) = ZERO
RMAX( 3 ) = ZERO
LMAX( 1 ) = 0
LMAX( 2 ) = 0
LMAX( 3 ) = 0
KNT = 0
NINFO( 1 ) = 0
NINFO( 2 ) = 0
NINFO( 3 ) = 0
*
VAL( 1 ) = SQRT( SMLNUM )
VAL( 2 ) = ONE
VAL( 3 ) = SQRT( SQRT( BIGNUM ) )
*
* Read input data until N=0. Assume input eigenvalues are sorted
* lexicographically (increasing by real part, then decreasing by
* imaginary part)
*
10 CONTINUE
READ( NIN, FMT = * )N, NDIM
IF( N.EQ.0 )
$ RETURN
READ( NIN, FMT = * )( ISELEC( I ), I = 1, NDIM )
DO 20 I = 1, N
READ( NIN, FMT = * )( TMP( I, J ), J = 1, N )
20 CONTINUE
READ( NIN, FMT = * )SIN, SEPIN
*
TNRM = DLANGE( 'M', N, N, TMP, LDT, WORK )
DO 160 ISCL = 1, 3
*
* Scale input matrix
*
KNT = KNT + 1
CALL DLACPY( 'F', N, N, TMP, LDT, T, LDT )
VMUL = VAL( ISCL )
DO 30 I = 1, N
CALL DSCAL( N, VMUL, T( 1, I ), 1 )
30 CONTINUE
IF( TNRM.EQ.ZERO )
$ VMUL = ONE
CALL DLACPY( 'F', N, N, T, LDT, TSAV, LDT )
*
* Compute Schur form
*
CALL DGEHRD( N, 1, N, T, LDT, WORK( 1 ), WORK( N+1 ), LWORK-N,
$ INFO )
IF( INFO.NE.0 ) THEN
LMAX( 1 ) = KNT
NINFO( 1 ) = NINFO( 1 ) + 1
GO TO 160
END IF
*
* Generate orthogonal matrix
*
CALL DLACPY( 'L', N, N, T, LDT, Q, LDT )
CALL DORGHR( N, 1, N, Q, LDT, WORK( 1 ), WORK( N+1 ), LWORK-N,
$ INFO )
*
* Compute Schur form
*
CALL DHSEQR( 'S', 'V', N, 1, N, T, LDT, WR, WI, Q, LDT, WORK,
$ LWORK, INFO )
IF( INFO.NE.0 ) THEN
LMAX( 2 ) = KNT
NINFO( 2 ) = NINFO( 2 ) + 1
GO TO 160
END IF
*
* Sort, select eigenvalues
*
DO 40 I = 1, N
IPNT( I ) = I
SELECT( I ) = .FALSE.
40 CONTINUE
CALL DCOPY( N, WR, 1, WRTMP, 1 )
CALL DCOPY( N, WI, 1, WITMP, 1 )
DO 60 I = 1, N - 1
KMIN = I
VRMIN = WRTMP( I )
VIMIN = WITMP( I )
DO 50 J = I + 1, N
IF( WRTMP( J ).LT.VRMIN ) THEN
KMIN = J
VRMIN = WRTMP( J )
VIMIN = WITMP( J )
END IF
50 CONTINUE
WRTMP( KMIN ) = WRTMP( I )
WITMP( KMIN ) = WITMP( I )
WRTMP( I ) = VRMIN
WITMP( I ) = VIMIN
ITMP = IPNT( I )
IPNT( I ) = IPNT( KMIN )
IPNT( KMIN ) = ITMP
60 CONTINUE
DO 70 I = 1, NDIM
SELECT( IPNT( ISELEC( I ) ) ) = .TRUE.
70 CONTINUE
*
* Compute condition numbers
*
CALL DLACPY( 'F', N, N, Q, LDT, QSAV, LDT )
CALL DLACPY( 'F', N, N, T, LDT, TSAV1, LDT )
CALL DTRSEN( 'B', 'V', SELECT, N, T, LDT, Q, LDT, WRTMP, WITMP,
$ M, S, SEP, WORK, LWORK, IWORK, LIWORK, INFO )
IF( INFO.NE.0 ) THEN
LMAX( 3 ) = KNT
NINFO( 3 ) = NINFO( 3 ) + 1
GO TO 160
END IF
SEPTMP = SEP / VMUL
STMP = S
*
* Compute residuals
*
CALL DHST01( N, 1, N, TSAV, LDT, T, LDT, Q, LDT, WORK, LWORK,
$ RESULT )
VMAX = MAX( RESULT( 1 ), RESULT( 2 ) )
IF( VMAX.GT.RMAX( 1 ) ) THEN
RMAX( 1 ) = VMAX
IF( NINFO( 1 ).EQ.0 )
$ LMAX( 1 ) = KNT
END IF
*
* Compare condition number for eigenvalue cluster
* taking its condition number into account
*
V = MAX( TWO*DBLE( N )*EPS*TNRM, SMLNUM )
IF( TNRM.EQ.ZERO )
$ V = ONE
IF( V.GT.SEPTMP ) THEN
TOL = ONE
ELSE
TOL = V / SEPTMP
END IF
IF( V.GT.SEPIN ) THEN
TOLIN = ONE
ELSE
TOLIN = V / SEPIN
END IF
TOL = MAX( TOL, SMLNUM / EPS )
TOLIN = MAX( TOLIN, SMLNUM / EPS )
IF( EPS*( SIN-TOLIN ).GT.STMP+TOL ) THEN
VMAX = ONE / EPS
ELSE IF( SIN-TOLIN.GT.STMP+TOL ) THEN
VMAX = ( SIN-TOLIN ) / ( STMP+TOL )
ELSE IF( SIN+TOLIN.LT.EPS*( STMP-TOL ) ) THEN
VMAX = ONE / EPS
ELSE IF( SIN+TOLIN.LT.STMP-TOL ) THEN
VMAX = ( STMP-TOL ) / ( SIN+TOLIN )
ELSE
VMAX = ONE
END IF
IF( VMAX.GT.RMAX( 2 ) ) THEN
RMAX( 2 ) = VMAX
IF( NINFO( 2 ).EQ.0 )
$ LMAX( 2 ) = KNT
END IF
*
* Compare condition numbers for invariant subspace
* taking its condition number into account
*
IF( V.GT.SEPTMP*STMP ) THEN
TOL = SEPTMP
ELSE
TOL = V / STMP
END IF
IF( V.GT.SEPIN*SIN ) THEN
TOLIN = SEPIN
ELSE
TOLIN = V / SIN
END IF
TOL = MAX( TOL, SMLNUM / EPS )
TOLIN = MAX( TOLIN, SMLNUM / EPS )
IF( EPS*( SEPIN-TOLIN ).GT.SEPTMP+TOL ) THEN
VMAX = ONE / EPS
ELSE IF( SEPIN-TOLIN.GT.SEPTMP+TOL ) THEN
VMAX = ( SEPIN-TOLIN ) / ( SEPTMP+TOL )
ELSE IF( SEPIN+TOLIN.LT.EPS*( SEPTMP-TOL ) ) THEN
VMAX = ONE / EPS
ELSE IF( SEPIN+TOLIN.LT.SEPTMP-TOL ) THEN
VMAX = ( SEPTMP-TOL ) / ( SEPIN+TOLIN )
ELSE
VMAX = ONE
END IF
IF( VMAX.GT.RMAX( 2 ) ) THEN
RMAX( 2 ) = VMAX
IF( NINFO( 2 ).EQ.0 )
$ LMAX( 2 ) = KNT
END IF
*
* Compare condition number for eigenvalue cluster
* without taking its condition number into account
*
IF( SIN.LE.DBLE( 2*N )*EPS .AND. STMP.LE.DBLE( 2*N )*EPS ) THEN
VMAX = ONE
ELSE IF( EPS*SIN.GT.STMP ) THEN
VMAX = ONE / EPS
ELSE IF( SIN.GT.STMP ) THEN
VMAX = SIN / STMP
ELSE IF( SIN.LT.EPS*STMP ) THEN
VMAX = ONE / EPS
ELSE IF( SIN.LT.STMP ) THEN
VMAX = STMP / SIN
ELSE
VMAX = ONE
END IF
IF( VMAX.GT.RMAX( 3 ) ) THEN
RMAX( 3 ) = VMAX
IF( NINFO( 3 ).EQ.0 )
$ LMAX( 3 ) = KNT
END IF
*
* Compare condition numbers for invariant subspace
* without taking its condition number into account
*
IF( SEPIN.LE.V .AND. SEPTMP.LE.V ) THEN
VMAX = ONE
ELSE IF( EPS*SEPIN.GT.SEPTMP ) THEN
VMAX = ONE / EPS
ELSE IF( SEPIN.GT.SEPTMP ) THEN
VMAX = SEPIN / SEPTMP
ELSE IF( SEPIN.LT.EPS*SEPTMP ) THEN
VMAX = ONE / EPS
ELSE IF( SEPIN.LT.SEPTMP ) THEN
VMAX = SEPTMP / SEPIN
ELSE
VMAX = ONE
END IF
IF( VMAX.GT.RMAX( 3 ) ) THEN
RMAX( 3 ) = VMAX
IF( NINFO( 3 ).EQ.0 )
$ LMAX( 3 ) = KNT
END IF
*
* Compute eigenvalue condition number only and compare
* Update Q
*
VMAX = ZERO
CALL DLACPY( 'F', N, N, TSAV1, LDT, TTMP, LDT )
CALL DLACPY( 'F', N, N, QSAV, LDT, QTMP, LDT )
SEPTMP = -ONE
STMP = -ONE
CALL DTRSEN( 'E', 'V', SELECT, N, TTMP, LDT, QTMP, LDT, WRTMP,
$ WITMP, M, STMP, SEPTMP, WORK, LWORK, IWORK,
$ LIWORK, INFO )
IF( INFO.NE.0 ) THEN
LMAX( 3 ) = KNT
NINFO( 3 ) = NINFO( 3 ) + 1
GO TO 160
END IF
IF( S.NE.STMP )
$ VMAX = ONE / EPS
IF( -ONE.NE.SEPTMP )
$ VMAX = ONE / EPS
DO 90 I = 1, N
DO 80 J = 1, N
IF( TTMP( I, J ).NE.T( I, J ) )
$ VMAX = ONE / EPS
IF( QTMP( I, J ).NE.Q( I, J ) )
$ VMAX = ONE / EPS
80 CONTINUE
90 CONTINUE
*
* Compute invariant subspace condition number only and compare
* Update Q
*
CALL DLACPY( 'F', N, N, TSAV1, LDT, TTMP, LDT )
CALL DLACPY( 'F', N, N, QSAV, LDT, QTMP, LDT )
SEPTMP = -ONE
STMP = -ONE
CALL DTRSEN( 'V', 'V', SELECT, N, TTMP, LDT, QTMP, LDT, WRTMP,
$ WITMP, M, STMP, SEPTMP, WORK, LWORK, IWORK,
$ LIWORK, INFO )
IF( INFO.NE.0 ) THEN
LMAX( 3 ) = KNT
NINFO( 3 ) = NINFO( 3 ) + 1
GO TO 160
END IF
IF( -ONE.NE.STMP )
$ VMAX = ONE / EPS
IF( SEP.NE.SEPTMP )
$ VMAX = ONE / EPS
DO 110 I = 1, N
DO 100 J = 1, N
IF( TTMP( I, J ).NE.T( I, J ) )
$ VMAX = ONE / EPS
IF( QTMP( I, J ).NE.Q( I, J ) )
$ VMAX = ONE / EPS
100 CONTINUE
110 CONTINUE
*
* Compute eigenvalue condition number only and compare
* Do not update Q
*
CALL DLACPY( 'F', N, N, TSAV1, LDT, TTMP, LDT )
CALL DLACPY( 'F', N, N, QSAV, LDT, QTMP, LDT )
SEPTMP = -ONE
STMP = -ONE
CALL DTRSEN( 'E', 'N', SELECT, N, TTMP, LDT, QTMP, LDT, WRTMP,
$ WITMP, M, STMP, SEPTMP, WORK, LWORK, IWORK,
$ LIWORK, INFO )
IF( INFO.NE.0 ) THEN
LMAX( 3 ) = KNT
NINFO( 3 ) = NINFO( 3 ) + 1
GO TO 160
END IF
IF( S.NE.STMP )
$ VMAX = ONE / EPS
IF( -ONE.NE.SEPTMP )
$ VMAX = ONE / EPS
DO 130 I = 1, N
DO 120 J = 1, N
IF( TTMP( I, J ).NE.T( I, J ) )
$ VMAX = ONE / EPS
IF( QTMP( I, J ).NE.QSAV( I, J ) )
$ VMAX = ONE / EPS
120 CONTINUE
130 CONTINUE
*
* Compute invariant subspace condition number only and compare
* Do not update Q
*
CALL DLACPY( 'F', N, N, TSAV1, LDT, TTMP, LDT )
CALL DLACPY( 'F', N, N, QSAV, LDT, QTMP, LDT )
SEPTMP = -ONE
STMP = -ONE
CALL DTRSEN( 'V', 'N', SELECT, N, TTMP, LDT, QTMP, LDT, WRTMP,
$ WITMP, M, STMP, SEPTMP, WORK, LWORK, IWORK,
$ LIWORK, INFO )
IF( INFO.NE.0 ) THEN
LMAX( 3 ) = KNT
NINFO( 3 ) = NINFO( 3 ) + 1
GO TO 160
END IF
IF( -ONE.NE.STMP )
$ VMAX = ONE / EPS
IF( SEP.NE.SEPTMP )
$ VMAX = ONE / EPS
DO 150 I = 1, N
DO 140 J = 1, N
IF( TTMP( I, J ).NE.T( I, J ) )
$ VMAX = ONE / EPS
IF( QTMP( I, J ).NE.QSAV( I, J ) )
$ VMAX = ONE / EPS
140 CONTINUE
150 CONTINUE
IF( VMAX.GT.RMAX( 1 ) ) THEN
RMAX( 1 ) = VMAX
IF( NINFO( 1 ).EQ.0 )
$ LMAX( 1 ) = KNT
END IF
160 CONTINUE
GO TO 10
*
* End of DGET38
*
END
|
from behave import *
from hamcrest import assert_that, equal_to
import base
from parse_type import TypeBuilder
import numpy as np
from step_helper import *
valid_test_matrices = ["m"]
parse_test_matrix = TypeBuilder.make_choice(valid_test_matrices)
register_type(TestMatrix=parse_test_matrix)
valid_vec4_extensions = ["x", "y", "z", "w"]
parse_vec4_extension = TypeBuilder.make_choice(valid_vec4_extensions)
register_type(Vec4Ext=parse_vec4_extension)
valid_test_variables = ["origin", "direction", "m"]
parse_test_variable = TypeBuilder.make_choice(valid_test_variables)
register_type(TestVariable=parse_test_variable)
valid_test_rays = ["r", "r2"]
parse_test_ray = TypeBuilder.make_choice(valid_test_rays)
register_type(TestRay=parse_test_ray)
valid_ray_elements = ["origin", "direction"]
parse_ray_element = TypeBuilder.make_choice(valid_ray_elements)
register_type(RayElement=parse_ray_element)
@given(u'{item:TestVariable} ← point({x:g}, {y:g}, {z:g})')
def step_impl_generic_point(context, item, x, y, z):
ensure_context_has_tuple(context)
context.tuple[item] = base.point(float(x), float(y), float(z))
@given(u'{item:TestVariable} ← vector({x:g}, {y:g}, {z:g})')
def step_impl_generic_vector(context, item, x, y, z):
ensure_context_has_tuple(context)
context.tuple[item] = base.vector(float(x), float(y), float(z))
@given("{item:TestMatrix} ← translation({x:g}, {y:g}, {z:g})")
def step_impl_generic_translation_matrix(context, item, x, y, z):
ensure_context_has_dict(context)
context.dict[item] = base.translation(float(x), float(y), float(z))
@given("{item:TestMatrix} ← scaling({x:g}, {y:g}, {z:g})")
def step_impl_generic_scaling_matrix(context, item, x, y, z):
ensure_context_has_dict(context)
context.dict[item] = base.scaling(float(x), float(y), float(z))
@given("{item:TestRay} ← ray(point({px}, {py}, {pz}), vector({vx}, -√{vynum:g}/{vydenom:g}, √{vznum:g}/{vzdenom:g}))")
def step_impl_generic_ray_full_with_sqrt(context, item, px, py, pz, vx, vynum, vydenom, vznum, vzdenom):
pt = base.point(float(px), float(py), float(pz))
vc = base.vector(float(vx), -math.sqrt(float(vynum))/float(vydenom), math.sqrt(float(vznum))/float(vzdenom))
ensure_context_has_dict(context)
context.dict[item] = base.ray(pt, vc)
@given("{item:TestRay} ← ray(point(0, 0, √{pznum:g}/{pzdenom:g}), vector({vx}, {vy:g}, {vz:g}))")
def step_impl_generic_ray_full_with_sqrt2(context, item, pznum, pzdenom, vx, vy, vz):
pt = base.point(np.float32(0), np.float32(0), np.float32(math.sqrt(float(pznum))/float(pzdenom)))
vc = base.vector(np.float32(vx), np.float32(vy), np.float32(vz))
ensure_context_has_dict(context)
context.dict[item] = base.ray(pt, vc)
@given("{item:TestRay} ← ray(point({px}, {py}, {pz}), vector({vx}, {vy}, {vz}))")
def step_impl_generic_ray_full(context, item, px, py, pz, vx, vy, vz):
pt = base.point(float(px), float(py), float(pz))
vc = base.vector(float(vx), float(vy), float(vz))
ensure_context_has_dict(context)
context.dict[item] = base.ray(pt, vc)
@when("{item:TestRay} ← ray(point({px}, {py}, {pz}), vector({vx}, {vy}, {vz}))")
def step_impl_generic_when_ray_full(context, item, px, py, pz, vx, vy, vz):
pt = base.point(float(px), float(py), float(pz))
vc = base.vector(float(vx), float(vy), float(vz))
ensure_context_has_dict(context)
context.dict[item] = base.ray(pt, vc)
@when("{item:TestRay} ← ray({origin}, {direction})")
def step_impl_generic_ray_implied(context, item, origin, direction):
ensure_context_has_tuple(context)
assert(origin in context.tuple.keys())
assert(direction in context.tuple.keys())
origin_pt = context.tuple[str(origin)]
dir_vector = context.tuple[str(direction)]
ensure_context_has_dict(context)
context.dict[item] = base.ray(origin_pt, dir_vector)
@when("{ray2:TestRay} ← transform({ray1:TestRay}, {m:TestMatrix})")
def step_impl_generic_ray_implied(context, ray2, ray1, m):
assert(m in context.dict.keys())
assert(ray1 in context.dict.keys())
original_ray = context.dict[str(ray1)]
transform_matrix = context.dict[str(m)]
context.dict[str(ray2)] = base.transform(original_ray, transform_matrix)
@then("{item:TestRay}.{element:RayElement} = point({x:g}, {y:g}, {z:g})")
def step_impl_ray_element_point(context, item, element, x, y, z):
assert(item in context.dict.keys())
assert(element in valid_ray_elements)
thing = context.dict[str(item)].__dict__[str(element)]
vec4_value = base.point(float(x), float(y), float(z))
assert(base.equal(thing, vec4_value))
@then("{item:TestRay}.{element:RayElement} = vector(√{xnum}/{xdenom:g}, 0, -√{znum}/{zdenom:g})")
def step_impl_ray_element_vector(context, item, element, xnum, xdenom, znum, zdenom):
assert(item in context.dict.keys())
assert(element in valid_ray_elements)
ray = context.dict[str(item)]
thing = eval("ray."+str(element))
vec4_value = base.vector(np.sqrt(float(xnum))/float(xdenom), 0, -np.sqrt(float(znum))/float(zdenom))
assert(base.equal(thing, vec4_value))
@then("{item:TestRay}.{element:RayElement} = vector({x}, {y}, {z})")
def step_impl_ray_element_vector(context, item, element, x, y, z):
assert(item in context.dict.keys())
assert(element in valid_ray_elements)
ray = context.dict[str(item)]
thing = eval("ray."+str(element))
vec4_value = base.vector(float(x), float(y), float(z))
assert(base.equal(thing, vec4_value))
@then("{item:TestRay}.{element:RayElement} = {value:RayElement}")
def step_impl_ray_element(context, item, element, value):
assert(item in context.dict.keys())
assert(element in valid_ray_elements)
ray = context.dict[str(item)]
thing = eval("ray."+str(element))
vec4_value = context.tuple[str(value)]
assert(base.equal(thing, vec4_value))
@then("position({item:TestRay}, {t}) = point({x}, {y}, {z})")
def step_impl_eval_ray_position(context, item, t, x, y, z):
assert (item in context.dict.keys())
ray = context.dict[str(item)]
ray_position = ray.position(float(eval(t)))
test_point = base.point(float(x), float(y), float(z))
assert (base.equal(ray_position, test_point))
|
import Lib.Meta
import Lib.Tactic
namespace Lean.Elab.Tactic
open Lean.Elab.Tactic
open Lean Lean.Meta
open Lean.Elab
open Lean.Elab.Term
open Lean.PrettyPrinter.Delaborator.TopDownAnalyze
open Lean.Elab.Tactic
declare_syntax_cat move_intro_pat
declare_syntax_cat move_revert_pat
syntax tactic colGt " => " (colGt move_intro_pat)+ : tactic
-- #exit
syntax (name := skip) "_" : move_intro_pat
syntax (name := auto) "//" : move_intro_pat
syntax (name := simp) "/=" : move_intro_pat
syntax (name := autoSimp) "//=" : move_intro_pat
syntax (name := introIdent) ident : move_intro_pat
syntax (name := apply) "/" group(ident <|> ("(" term ")")) : move_intro_pat
-- syntax (name := applyTerm) "/" "(" term ")" : move_intro_pat
syntax (name := casePat) "[" sepBy(move_intro_pat*, "|", " | ") "]" : move_intro_pat
syntax (name := revertIdent) ident : move_revert_pat
syntax (name := revertGen) (group(("!")? "(" term ")") <|> group("!" ident)) : move_revert_pat
-- TODO: clear pattern, `_`, `?` patterns
-- TODO: using intro patterns with `have`
-- #exit
-- syntax "move" : tactic
-- syntax withPosition("move" ":" (colGt move_revert_pat)+) : tactic
-- #exit
inductive MoveIntroPat where
-- | auto (ref : Syntax)
-- | simp (ref : Syntax)
| autoSimp (ref : Syntax) (simp auto : Bool := true)
| intro (ref : Syntax) (n : Name)
| apply (e : Syntax)
| case (opS clS : Syntax) (brs : Array (Array MoveIntroPat))
deriving Repr, Inhabited, BEq -- , DecidableEq
def MoveIntroPat.auto (ref : Syntax) : MoveIntroPat :=
.autoSimp ref false true
def MoveIntroPat.simp (ref : Syntax) : MoveIntroPat :=
.autoSimp ref true false
mutual
partial def parseMoveIntroPat (pat : Syntax) : TacticM MoveIntroPat := do
if pat.getKind == ``skip then
return .intro pat `_
else if pat.getKind == ``introIdent then
return .intro pat pat[0].getId
else if pat.getKind == ``auto then
return .auto pat
else if pat.getKind == ``simp then
return .simp pat
else if pat.getKind == ``autoSimp then
return .autoSimp pat
else if pat.getKind == ``apply then
let fn := pat[1]
if pat[1].getNumArgs == 1 then
return .apply pat[1][0]
if pat[1].getNumArgs == 3 then
return .apply pat[1][1]
else if pat.getKind == ``casePat then
return .case pat[0] pat[2] (← pat[1].getArgs.getSepElems.mapM parseMoveIntroPatArray)
throwIllFormedSyntax
partial def parseMoveIntroPatArray (pat : Syntax) :
TacticM (Array MoveIntroPat) := do
pat.getArgs.mapM parseMoveIntroPat
end
/-
6 2 1 0 0 0 1 0 0 0
0 1 2 3 4 5 6 7 8 9
-/
-- #exit
def runintro (ref : Syntax) (n : Name) : TacticM Unit :=
withTacticInfoContext ref <|
discard <| liftMetaTactic1' (intro . n)
-- #fullname auto
-- #check Lean.Elab.Tactic.auto
-- #check autoTac
partial def runMoveIntroPat : MoveIntroPat → TacticM Unit
| .intro ref n =>
-- runintro ref n
withTacticInfoContext ref <|
discard <| liftMetaTactic1' (intro . n)
| .case opBrack clBrack pats => do
withTacticInfoContext opBrack (pure ())
liftMetaTactic λ g => do
let (v, g) ← intro1 g
let gs ← cases g v
-- let mut gs' := #[]
unless pats.size == gs.size ||
(pats == #[#[]]) do
throwError "mismatched numbers of branches and patterns"
gs.toList.mapM λ ⟨g, p⟩ => do
let vs := g.fields.map (·.fvarId!)
let g := g.mvarId
(·.2) <$> revert g vs
let gs ← getGoals
let gs' ← gs.zip pats.toList |>.mapM λ ⟨g,ps⟩ => do
setGoals [g]
for p in ps do
allGoals <| runMoveIntroPat p
getGoals
setGoals gs'.join
withTacticInfoContext clBrack (pure ())
| .apply rule =>
withTacticInfoContext rule <|
liftMetaTactic1' λ g => do
let (v, g) ← intro1 g
let rule ← Term.elabTerm rule none |>.run'
withMVarContext g do
let pr ← mkAppM' rule #[mkFVar v]
let typ ← inferType pr
let g ← assert g `h typ pr
let g ← clear g v
return ((), g)
-- | .auto ref =>
| .autoSimp ref callSimp callAuto => do
-- let stx ← `(tactic| simp)
if callSimp then
withTacticInfoContext ref <|
liftMetaTactic1 (simpTarget . {})
if callAuto then
withTacticInfoContext ref autoTac
-- evalTactic (← `(tactic| try auto))
-- | _ => throwError "foo"
-- #check Lean.Elab.Tactic.simp
-- #check Lean.Meta.Simp.simp
-- partial def runMoveIntroPat : MoveIntroPat → TacticM Unit
-- | .intro ref n => runintro ref n
-- -- withTacticInfoContext ref <|
-- -- discard <| liftMetaTactic1' (intro . n)
-- | .case opBrack clBrack pats => do
-- withTacticInfoContext opBrack (pure ())
-- liftMetaTactic λ g => do
-- let (v, g) ← intro1 g
-- let gs ← cases g v
-- -- let mut gs' := #[]
-- unless pats.size == gs.size ||
-- (pats == #[#[]]) do
-- throwError "mismatched numbers of branches and patterns"
-- gs.toList.mapM λ g => do
-- let vs := g.fields.map (·.fvarId!)
-- let g := g.mvarId
-- (·.2) <$> revert g vs
-- withTacticInfoContext clBrack (pure ())
-- -- sorry
-- -- | .apply rule =>
-- -- withTacticInfoContext rule <|
-- -- liftMetaTactic1' λ g => do
-- -- let (v, g) ← intro1 g
-- -- let rule ← Term.elabTerm rule none |>.run'
-- -- withMVarContext g do
-- -- let pr ← mkAppM' rule #[mkFVar v]
-- -- let typ ← inferType pr
-- -- let g ← assert g `h typ pr
-- -- let g ← clear g v
-- -- return ((), g)
-- -- | .simp ref => do
-- -- -- let stx ← `(tactic| simp)
-- -- withTacticInfoContext ref do
-- -- Elab.Tactic.simp
-- -- | .auto ref =>
-- -- withTacticInfoContext ref do
-- -- evalTactic (← `(tactic| try auto))
-- -- | .autoSimp ref => sorry
-- -- -- withTacticInfoContext ref do
-- -- -- evalTactic (← `(tactic| simp; try auto))
-- | _ => throwError "foo"
-- #synth BEq Syntax
-- #print Syntax.instBEqSyntax
inductive MoveRevertPat where
| revert (ref : Syntax) (n : Name)
| generalize (ref : Syntax) (n : Bool) (t : Syntax)
deriving Repr, BEq
-- #check BEq
-- #exit
-- #check SepArray.getSepElems
def parseMoveRevertPat (s : Syntax) : TacticM MoveRevertPat := do
if s.getKind == ``revertIdent then
return .revert s s[0].getId
else if s.getKind == ``revertGen then
-- let tag :=
-- if
-- then none
-- else some s[0][0].getId
let term :=
if s[0].getKind == groupKind
then s[0][2]
else s[0]
return .generalize s (s[0].getNumArgs != 0) term
throwError "invalid revert pattern {s} ({s.getKind}, {s.getArgs})"
def MoveRevertPat.toRef : MoveRevertPat → Syntax
| .revert ref n => ref
| .generalize ref _ _ => ref
def runMoveRevertPat : MoveRevertPat → TacticM Unit
| .revert ref n =>
withMainContext do
-- withTacticInfoContext ref <| do
let v ← getLocalDeclFromUserName n
discard <| liftMetaTactic1' (revert . #[v.fvarId])
| .generalize ref h e =>
withMainContext do
-- withTacticInfoContext ref <| do
-- print_vars![mainGoal, e]
let e ← elabTerm e none
let h := if h then some `h else none
print_vars![mainGoal, e]
let vs ← liftMetaTactic1' (generalize .
#[ { expr := e, hName? := h, xName? := some `x }])
withMainContext do
discard <| liftMetaTactic1' (revert . vs.reverse)
-- #eval "A"
-- #exit
-- macro_rules
-- | `(tactic| move ) => `(tactic| skip)
-- #eval "A"
declare_syntax_cat revert_pats
-- #eval "A"
syntax ":" (colGt move_revert_pat)+ : revert_pats
-- #eval "A"
syntax "move" (colGt revert_pats)? : tactic
elab_rules : tactic
| `(tactic| move%$token $[$xs:revert_pats]? ) => do
match xs with
| some xs =>
let colon := xs[0]
let xs := xs[1].getArgs
withTacticInfoContext (mkNullNode #[token, colon]) (pure ())
for x in xs.reverse do
let x' ← parseMoveRevertPat x
runMoveRevertPat x'
| none => return ()
-- println!"{}"
-- xs.reverse.forM runMoveRevertPat
-- #eval "B"
-- #exit
elab_rules : tactic
| `(tactic| $tac => $pats*) => do
-- let pats' ← pats.mapM parseMoveIntroPat
evalTactic tac
let arrow := (← getRef)[1]
withTacticInfoContext arrow (pure ())
for pat in pats do
let pat' ← parseMoveIntroPat pat
-- let next := pats.getD (i+1) Syntax.missing
allGoals <| runMoveIntroPat pat'
-- println!"repr: {repr xs}"
-- #check [1:3]
-- #check Std.Range
-- move => a b c
-- ^
-- -- ⊢ T → V → U → True
-- move => a b c
-- ^
-- ⊢ T → V → U → True
-- u : T
-- ⊢ V → U → True
-- example : True := by
-- let T := True
-- let U := True
-- let V := True
-- -- have h₀ : T ↔ U := sorry
-- -- have h₁ : U ↔ V := sorry
-- have t : T := True.intro
-- have v : V := True.intro
-- have u : U := True.intro
-- have x : Nat × Nat := sorry
-- have y : List Nat ⊕ List Nat := sorry
-- -- revert e
-- -- rewrite [h₀, h₁]
-- have f : T → U := id
-- -- move: t u v => /f u v t
-- -- have' h : T ⊕' U := sorry
-- -- move: !(T ⊕' U) h
-- move: t u v y x
-- move => v u t
-- move => [ |] ys [ x y ] ;
-- -- move => [ x y ]
-- -- move => [ xs |]
-- skip
-- -- move: f h:(f) => y x
-- -- move => /f d // ;
end Lean.Elab.Tactic
-- Local Variables:
-- lean4-test-file: "/Users/simon/google stuff/lean/sat/concrete-semantics/ConcreteSemantics/ch7.lean"
-- End:
|
import group_theory.order_of_element
-- Order of a Subgroup
theorem t071 {α : Type*} [group α] [fintype α] [decidable_eq α] (s : set α) [is_subgroup s] [fintype s] :
fintype.card s ∣ fintype.card α
:= card_subgroup_dvd_card s
|
#-------------------------------------------------------------------
#* EMSO Model Library (EML) Copyright (C) 2004 - 2007 ALSOC.
#*
#* This LIBRARY is free software; you can distribute it and/or modify
#* it under the therms of the ALSOC FREE LICENSE as available at
#* http://www.enq.ufrgs.br/alsoc.
#*
#* EMSO Copyright (C) 2004 - 2007 ALSOC, original code
#* from http://www.rps.eng.br Copyright (C) 2002-2004.
#* All rights reserved.
#*
#* EMSO is distributed under the therms of the ALSOC LICENSE as
#* available at http://www.enq.ufrgs.br/alsoc.
#*
#*---------------------------------------------------------------------
#* Author: Gerson B. Bicca
#*$Id:$
#*-------------------------------------------------------------------
type heat_flow
heat_flow()=begin
new(
power(Dict{Symbol,Any}(
:Brief=>"Minimum of Heat Flow",
:Default=>-1000
)),
power(Dict{Symbol,Any}(
:Brief=>"Maximum of Heat Flow",
:Default=>1000
)),
power(Dict{Symbol,Any}(
:Brief=>"Heat Flow",
:PosX=>0,
:PosY=>0.60,
:Protected=>true
)),
fraction(Dict{Symbol,Any}(
:Brief=>"Flow Signal",
:PosX=>0.50,
:PosY=>0,
:Protected=>true
)),
[
:(HeatFlow = MinHeatFlow + HeatFlowFraction*(MaxHeatFlow-MinHeatFlow)),
],
[
"Heat Flow",
],
[:MinHeatFlow,:MaxHeatFlow,],
[:HeatFlow,:HeatFlowFraction,]
)
end
MinHeatFlow::power
MaxHeatFlow::power
HeatFlow::power
HeatFlowFraction::fraction
equations::Array{Expr,1}
equationNames::Array{String,1}
parameters::Array{Symbol,1}
variables::Array{Symbol,1}
attributes::Dict{Symbol,Any}
end
export heat_flow
function setEquationFlow(in::heat_flow)
addEquation(1)
end
function atributes(in::heat_flow,_::Dict{Symbol,Any})
fields::Dict{Symbol,Any}=Dict{Symbol,Any}()
fields[:Pallete]=true
fields[:Icon]="icon/heat_flow"
fields[:Brief]="Model of a very simple valve for setting the energy flow with a controller."
fields[:Info]="== ASSUMPTIONS ==
* nothing happens in this valve
== SET ==
* MinHeatFlow: the Minimum Heat Flow Allowable in the valve;
* MaxHeatFlow: the Maximum Heat Flow Allowable in the valve;
== SPECIFY ==
* the HeatFlowFraction (the model requires an inlet signal, also you can use a controller for setting the HeatFlowFraction)
"
drive!(fields,_)
return fields
end
heat_flow(_::Dict{Symbol,Any})=begin
newModel=heat_flow()
newModel.attributes=atributes(newModel,_)
newModel
end
|
hello world
line 1
hello world!
line 2
line 3
line 4
line5
hello world!!
|
[GOAL]
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
h : IsUnit (↑(germ X.presheaf x) f)
⊢ ∃ V i x, IsUnit (↑(X.presheaf.map i.op) f)
[PROOFSTEP]
obtain ⟨g', heq⟩ := h.exists_right_inv
[GOAL]
case intro
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
h : IsUnit (↑(germ X.presheaf x) f)
g' : (CategoryTheory.forget CommRingCat).obj (stalk X.presheaf ↑x)
heq : ↑(germ X.presheaf x) f * g' = 1
⊢ ∃ V i x, IsUnit (↑(X.presheaf.map i.op) f)
[PROOFSTEP]
obtain ⟨V, hxV, g, rfl⟩ := X.presheaf.germ_exist x.1 g'
[GOAL]
case intro.intro.intro.intro
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
h : IsUnit (↑(germ X.presheaf x) f)
V : Opens ↑↑X.toPresheafedSpace
hxV : ↑x ∈ V
g : (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op V))
heq : ↑(germ X.presheaf x) f * ↑(germ X.presheaf { val := ↑x, property := hxV }) g = 1
⊢ ∃ V i x, IsUnit (↑(X.presheaf.map i.op) f)
[PROOFSTEP]
let W := U ⊓ V
[GOAL]
case intro.intro.intro.intro
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
h : IsUnit (↑(germ X.presheaf x) f)
V : Opens ↑↑X.toPresheafedSpace
hxV : ↑x ∈ V
g : (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op V))
heq : ↑(germ X.presheaf x) f * ↑(germ X.presheaf { val := ↑x, property := hxV }) g = 1
W : Opens ↑↑X.toPresheafedSpace := U ⊓ V
⊢ ∃ V i x, IsUnit (↑(X.presheaf.map i.op) f)
[PROOFSTEP]
have hxW : x.1 ∈ W :=
⟨x.2, hxV⟩
-- Porting note : `erw` can't write into `HEq`, so this is replaced with another `HEq` in the
-- desired form
[GOAL]
case intro.intro.intro.intro
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
h : IsUnit (↑(germ X.presheaf x) f)
V : Opens ↑↑X.toPresheafedSpace
hxV : ↑x ∈ V
g : (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op V))
heq : ↑(germ X.presheaf x) f * ↑(germ X.presheaf { val := ↑x, property := hxV }) g = 1
W : Opens ↑↑X.toPresheafedSpace := U ⊓ V
hxW : ↑x ∈ W
⊢ ∃ V i x, IsUnit (↑(X.presheaf.map i.op) f)
[PROOFSTEP]
replace heq :
(X.presheaf.germ ⟨x.val, hxW⟩) ((X.presheaf.map (U.infLELeft V).op) f * (X.presheaf.map (U.infLERight V).op) g) =
(X.presheaf.germ ⟨x.val, hxW⟩) 1
[GOAL]
case heq
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
h : IsUnit (↑(germ X.presheaf x) f)
V : Opens ↑↑X.toPresheafedSpace
hxV : ↑x ∈ V
g : (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op V))
heq : ↑(germ X.presheaf x) f * ↑(germ X.presheaf { val := ↑x, property := hxV }) g = 1
W : Opens ↑↑X.toPresheafedSpace := U ⊓ V
hxW : ↑x ∈ W
⊢ ↑(germ X.presheaf { val := ↑x, property := hxW })
(↑(X.presheaf.map (Opens.infLELeft U V).op) f * ↑(X.presheaf.map (Opens.infLERight U V).op) g) =
↑(germ X.presheaf { val := ↑x, property := hxW }) 1
[PROOFSTEP]
dsimp [germ]
[GOAL]
case heq
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
h : IsUnit (↑(germ X.presheaf x) f)
V : Opens ↑↑X.toPresheafedSpace
hxV : ↑x ∈ V
g : (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op V))
heq : ↑(germ X.presheaf x) f * ↑(germ X.presheaf { val := ↑x, property := hxV }) g = 1
W : Opens ↑↑X.toPresheafedSpace := U ⊓ V
hxW : ↑x ∈ W
⊢ ↑(Limits.colimit.ι ((OpenNhds.inclusion ↑x).op ⋙ X.presheaf)
(op { obj := U ⊓ V, property := (_ : ↑{ val := ↑x, property := hxW } ∈ U ⊓ V) }))
(↑(X.presheaf.map (Opens.infLELeft U V).op) f * ↑(X.presheaf.map (Opens.infLERight U V).op) g) =
↑(Limits.colimit.ι ((OpenNhds.inclusion ↑x).op ⋙ X.presheaf)
(op { obj := U ⊓ V, property := (_ : ↑{ val := ↑x, property := hxW } ∈ U ⊓ V) }))
1
[PROOFSTEP]
erw [map_mul, map_one,
show X.presheaf.germ ⟨x, hxW⟩ ((X.presheaf.map (U.infLELeft V).op) f) = X.presheaf.germ x f from
X.presheaf.germ_res_apply (Opens.infLELeft U V) ⟨x.1, hxW⟩ f,
show X.presheaf.germ ⟨x, hxW⟩ (X.presheaf.map (U.infLERight V).op g) = X.presheaf.germ ⟨x, hxV⟩ g from
X.presheaf.germ_res_apply (Opens.infLERight U V) ⟨x.1, hxW⟩ g]
[GOAL]
case heq
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
h : IsUnit (↑(germ X.presheaf x) f)
V : Opens ↑↑X.toPresheafedSpace
hxV : ↑x ∈ V
g : (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op V))
heq : ↑(germ X.presheaf x) f * ↑(germ X.presheaf { val := ↑x, property := hxV }) g = 1
W : Opens ↑↑X.toPresheafedSpace := U ⊓ V
hxW : ↑x ∈ W
⊢ ↑(germ X.presheaf x) f * ↑(germ X.presheaf { val := ↑x, property := hxV }) g = 1
[PROOFSTEP]
exact heq
[GOAL]
case intro.intro.intro.intro
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
h : IsUnit (↑(germ X.presheaf x) f)
V : Opens ↑↑X.toPresheafedSpace
hxV : ↑x ∈ V
g : (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op V))
W : Opens ↑↑X.toPresheafedSpace := U ⊓ V
hxW : ↑x ∈ W
heq :
↑(germ X.presheaf { val := ↑x, property := hxW })
(↑(X.presheaf.map (Opens.infLELeft U V).op) f * ↑(X.presheaf.map (Opens.infLERight U V).op) g) =
↑(germ X.presheaf { val := ↑x, property := hxW }) 1
⊢ ∃ V i x, IsUnit (↑(X.presheaf.map i.op) f)
[PROOFSTEP]
obtain ⟨W', hxW', i₁, i₂, heq'⟩ := X.presheaf.germ_eq x.1 hxW hxW _ _ heq
[GOAL]
case intro.intro.intro.intro.intro.intro.intro.intro
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
h : IsUnit (↑(germ X.presheaf x) f)
V : Opens ↑↑X.toPresheafedSpace
hxV : ↑x ∈ V
g : (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op V))
W : Opens ↑↑X.toPresheafedSpace := U ⊓ V
hxW : ↑x ∈ W
heq :
↑(germ X.presheaf { val := ↑x, property := hxW })
(↑(X.presheaf.map (Opens.infLELeft U V).op) f * ↑(X.presheaf.map (Opens.infLERight U V).op) g) =
↑(germ X.presheaf { val := ↑x, property := hxW }) 1
W' : Opens ↑↑X.toPresheafedSpace
hxW' : ↑x ∈ W'
i₁ i₂ : W' ⟶ W
heq' :
↑(X.presheaf.map i₁.op)
(↑(X.presheaf.map (Opens.infLELeft U V).op) f * ↑(X.presheaf.map (Opens.infLERight U V).op) g) =
↑(X.presheaf.map i₂.op) 1
⊢ ∃ V i x, IsUnit (↑(X.presheaf.map i.op) f)
[PROOFSTEP]
use W', i₁ ≫ Opens.infLELeft U V, hxW'
[GOAL]
case h
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
h : IsUnit (↑(germ X.presheaf x) f)
V : Opens ↑↑X.toPresheafedSpace
hxV : ↑x ∈ V
g : (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op V))
W : Opens ↑↑X.toPresheafedSpace := U ⊓ V
hxW : ↑x ∈ W
heq :
↑(germ X.presheaf { val := ↑x, property := hxW })
(↑(X.presheaf.map (Opens.infLELeft U V).op) f * ↑(X.presheaf.map (Opens.infLERight U V).op) g) =
↑(germ X.presheaf { val := ↑x, property := hxW }) 1
W' : Opens ↑↑X.toPresheafedSpace
hxW' : ↑x ∈ W'
i₁ i₂ : W' ⟶ W
heq' :
↑(X.presheaf.map i₁.op)
(↑(X.presheaf.map (Opens.infLELeft U V).op) f * ↑(X.presheaf.map (Opens.infLERight U V).op) g) =
↑(X.presheaf.map i₂.op) 1
⊢ IsUnit (↑(X.presheaf.map (i₁ ≫ Opens.infLELeft U V).op) f)
[PROOFSTEP]
rw [(X.presheaf.map i₂.op).map_one, (X.presheaf.map i₁.op).map_mul] at heq'
[GOAL]
case h
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
h : IsUnit (↑(germ X.presheaf x) f)
V : Opens ↑↑X.toPresheafedSpace
hxV : ↑x ∈ V
g : (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op V))
W : Opens ↑↑X.toPresheafedSpace := U ⊓ V
hxW : ↑x ∈ W
heq :
↑(germ X.presheaf { val := ↑x, property := hxW })
(↑(X.presheaf.map (Opens.infLELeft U V).op) f * ↑(X.presheaf.map (Opens.infLERight U V).op) g) =
↑(germ X.presheaf { val := ↑x, property := hxW }) 1
W' : Opens ↑↑X.toPresheafedSpace
hxW' : ↑x ∈ W'
i₁ i₂ : W' ⟶ W
heq' :
↑(X.presheaf.map i₁.op) (↑(X.presheaf.map (Opens.infLELeft U V).op) f) *
↑(X.presheaf.map i₁.op) (↑(X.presheaf.map (Opens.infLERight U V).op) g) =
1
⊢ IsUnit (↑(X.presheaf.map (i₁ ≫ Opens.infLELeft U V).op) f)
[PROOFSTEP]
rw [← comp_apply, ← X.presheaf.map_comp, ← comp_apply, ← X.presheaf.map_comp, ← op_comp] at heq'
[GOAL]
case h
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
h : IsUnit (↑(germ X.presheaf x) f)
V : Opens ↑↑X.toPresheafedSpace
hxV : ↑x ∈ V
g : (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op V))
W : Opens ↑↑X.toPresheafedSpace := U ⊓ V
hxW : ↑x ∈ W
heq :
↑(germ X.presheaf { val := ↑x, property := hxW })
(↑(X.presheaf.map (Opens.infLELeft U V).op) f * ↑(X.presheaf.map (Opens.infLERight U V).op) g) =
↑(germ X.presheaf { val := ↑x, property := hxW }) 1
W' : Opens ↑↑X.toPresheafedSpace
hxW' : ↑x ∈ W'
i₁ i₂ : W' ⟶ W
heq' : ↑(X.presheaf.map (i₁ ≫ Opens.infLELeft U V).op) f * ↑(X.presheaf.map ((Opens.infLERight U V).op ≫ i₁.op)) g = 1
⊢ IsUnit (↑(X.presheaf.map (i₁ ≫ Opens.infLELeft U V).op) f)
[PROOFSTEP]
exact isUnit_of_mul_eq_one _ _ heq'
[GOAL]
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
h : ∀ (x : { x // x ∈ U }), IsUnit (↑(germ X.presheaf x) f)
⊢ IsUnit f
[PROOFSTEP]
choose V iVU m h_unit using fun x : U => X.isUnit_res_of_isUnit_germ U f x (h x)
[GOAL]
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
h : ∀ (x : { x // x ∈ U }), IsUnit (↑(germ X.presheaf x) f)
V : { x // x ∈ U } → Opens ↑↑X.toPresheafedSpace
iVU : (x : { x // x ∈ U }) → V x ⟶ U
m : ∀ (x : { x // x ∈ U }), ↑x ∈ V x
h_unit : ∀ (x : { x // x ∈ U }), IsUnit (↑(X.presheaf.map (iVU x).op) f)
⊢ IsUnit f
[PROOFSTEP]
have hcover : U ≤ iSup V
[GOAL]
case hcover
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
h : ∀ (x : { x // x ∈ U }), IsUnit (↑(germ X.presheaf x) f)
V : { x // x ∈ U } → Opens ↑↑X.toPresheafedSpace
iVU : (x : { x // x ∈ U }) → V x ⟶ U
m : ∀ (x : { x // x ∈ U }), ↑x ∈ V x
h_unit : ∀ (x : { x // x ∈ U }), IsUnit (↑(X.presheaf.map (iVU x).op) f)
⊢ U ≤ iSup V
[PROOFSTEP]
intro x hxU
[GOAL]
case hcover
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
h : ∀ (x : { x // x ∈ U }), IsUnit (↑(germ X.presheaf x) f)
V : { x // x ∈ U } → Opens ↑↑X.toPresheafedSpace
iVU : (x : { x // x ∈ U }) → V x ⟶ U
m : ∀ (x : { x // x ∈ U }), ↑x ∈ V x
h_unit : ∀ (x : { x // x ∈ U }), IsUnit (↑(X.presheaf.map (iVU x).op) f)
x : ↑↑X.toPresheafedSpace
hxU : x ∈ ↑U
⊢ x ∈ ↑(iSup V)
[PROOFSTEP]
erw [Opens.mem_iSup]
[GOAL]
case hcover
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
h : ∀ (x : { x // x ∈ U }), IsUnit (↑(germ X.presheaf x) f)
V : { x // x ∈ U } → Opens ↑↑X.toPresheafedSpace
iVU : (x : { x // x ∈ U }) → V x ⟶ U
m : ∀ (x : { x // x ∈ U }), ↑x ∈ V x
h_unit : ∀ (x : { x // x ∈ U }), IsUnit (↑(X.presheaf.map (iVU x).op) f)
x : ↑↑X.toPresheafedSpace
hxU : x ∈ ↑U
⊢ ∃ i, x ∈ V i
[PROOFSTEP]
exact
⟨⟨x, hxU⟩, m ⟨x, hxU⟩⟩
-- Let `g x` denote the inverse of `f` in `U x`.
[GOAL]
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
h : ∀ (x : { x // x ∈ U }), IsUnit (↑(germ X.presheaf x) f)
V : { x // x ∈ U } → Opens ↑↑X.toPresheafedSpace
iVU : (x : { x // x ∈ U }) → V x ⟶ U
m : ∀ (x : { x // x ∈ U }), ↑x ∈ V x
h_unit : ∀ (x : { x // x ∈ U }), IsUnit (↑(X.presheaf.map (iVU x).op) f)
hcover : U ≤ iSup V
⊢ IsUnit f
[PROOFSTEP]
choose g hg using fun x : U => IsUnit.exists_right_inv (h_unit x)
[GOAL]
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
h : ∀ (x : { x // x ∈ U }), IsUnit (↑(germ X.presheaf x) f)
V : { x // x ∈ U } → Opens ↑↑X.toPresheafedSpace
iVU : (x : { x // x ∈ U }) → V x ⟶ U
m : ∀ (x : { x // x ∈ U }), ↑x ∈ V x
h_unit : ∀ (x : { x // x ∈ U }), IsUnit (↑(X.presheaf.map (iVU x).op) f)
hcover : U ≤ iSup V
g : (x : { x // x ∈ U }) → (fun x_1 => (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op (V x)))) f
hg : ∀ (x : { x // x ∈ U }), ↑(X.presheaf.map (iVU x).op) f * g x = 1
⊢ IsUnit f
[PROOFSTEP]
have ic : IsCompatible (sheaf X).val V g
[GOAL]
case ic
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
h : ∀ (x : { x // x ∈ U }), IsUnit (↑(germ X.presheaf x) f)
V : { x // x ∈ U } → Opens ↑↑X.toPresheafedSpace
iVU : (x : { x // x ∈ U }) → V x ⟶ U
m : ∀ (x : { x // x ∈ U }), ↑x ∈ V x
h_unit : ∀ (x : { x // x ∈ U }), IsUnit (↑(X.presheaf.map (iVU x).op) f)
hcover : U ≤ iSup V
g : (x : { x // x ∈ U }) → (fun x_1 => (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op (V x)))) f
hg : ∀ (x : { x // x ∈ U }), ↑(X.presheaf.map (iVU x).op) f * g x = 1
⊢ IsCompatible (sheaf X).val V g
[PROOFSTEP]
intro x y
[GOAL]
case ic
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
h : ∀ (x : { x // x ∈ U }), IsUnit (↑(germ X.presheaf x) f)
V : { x // x ∈ U } → Opens ↑↑X.toPresheafedSpace
iVU : (x : { x // x ∈ U }) → V x ⟶ U
m : ∀ (x : { x // x ∈ U }), ↑x ∈ V x
h_unit : ∀ (x : { x // x ∈ U }), IsUnit (↑(X.presheaf.map (iVU x).op) f)
hcover : U ≤ iSup V
g : (x : { x // x ∈ U }) → (fun x_1 => (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op (V x)))) f
hg : ∀ (x : { x // x ∈ U }), ↑(X.presheaf.map (iVU x).op) f * g x = 1
x y : { x // x ∈ U }
⊢ ↑((sheaf X).val.map (Opens.infLELeft (V x) (V y)).op) (g x) =
↑((sheaf X).val.map (Opens.infLERight (V x) (V y)).op) (g y)
[PROOFSTEP]
apply section_ext X.sheaf (V x ⊓ V y)
[GOAL]
case ic.h
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
h : ∀ (x : { x // x ∈ U }), IsUnit (↑(germ X.presheaf x) f)
V : { x // x ∈ U } → Opens ↑↑X.toPresheafedSpace
iVU : (x : { x // x ∈ U }) → V x ⟶ U
m : ∀ (x : { x // x ∈ U }), ↑x ∈ V x
h_unit : ∀ (x : { x // x ∈ U }), IsUnit (↑(X.presheaf.map (iVU x).op) f)
hcover : U ≤ iSup V
g : (x : { x // x ∈ U }) → (fun x_1 => (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op (V x)))) f
hg : ∀ (x : { x // x ∈ U }), ↑(X.presheaf.map (iVU x).op) f * g x = 1
x y : { x // x ∈ U }
⊢ ∀ (x_1 : { x_1 // x_1 ∈ V x ⊓ V y }),
↑(germ (Sheaf.presheaf (sheaf X)) x_1) (↑((sheaf X).val.map (Opens.infLELeft (V x) (V y)).op) (g x)) =
↑(germ (Sheaf.presheaf (sheaf X)) x_1) (↑((sheaf X).val.map (Opens.infLERight (V x) (V y)).op) (g y))
[PROOFSTEP]
rintro ⟨z, hzVx, hzVy⟩
[GOAL]
case ic.h.mk.intro
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
h : ∀ (x : { x // x ∈ U }), IsUnit (↑(germ X.presheaf x) f)
V : { x // x ∈ U } → Opens ↑↑X.toPresheafedSpace
iVU : (x : { x // x ∈ U }) → V x ⟶ U
m : ∀ (x : { x // x ∈ U }), ↑x ∈ V x
h_unit : ∀ (x : { x // x ∈ U }), IsUnit (↑(X.presheaf.map (iVU x).op) f)
hcover : U ≤ iSup V
g : (x : { x // x ∈ U }) → (fun x_1 => (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op (V x)))) f
hg : ∀ (x : { x // x ∈ U }), ↑(X.presheaf.map (iVU x).op) f * g x = 1
x y : { x // x ∈ U }
z : ↑↑X.toPresheafedSpace
hzVx : z ∈ ↑(V x)
hzVy : z ∈ ↑(V y)
⊢ ↑(germ (Sheaf.presheaf (sheaf X)) { val := z, property := (_ : z ∈ ↑(V x) ∧ z ∈ ↑(V y)) })
(↑((sheaf X).val.map (Opens.infLELeft (V x) (V y)).op) (g x)) =
↑(germ (Sheaf.presheaf (sheaf X)) { val := z, property := (_ : z ∈ ↑(V x) ∧ z ∈ ↑(V y)) })
(↑((sheaf X).val.map (Opens.infLERight (V x) (V y)).op) (g y))
[PROOFSTEP]
erw [germ_res_apply, germ_res_apply]
[GOAL]
case ic.h.mk.intro
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
h : ∀ (x : { x // x ∈ U }), IsUnit (↑(germ X.presheaf x) f)
V : { x // x ∈ U } → Opens ↑↑X.toPresheafedSpace
iVU : (x : { x // x ∈ U }) → V x ⟶ U
m : ∀ (x : { x // x ∈ U }), ↑x ∈ V x
h_unit : ∀ (x : { x // x ∈ U }), IsUnit (↑(X.presheaf.map (iVU x).op) f)
hcover : U ≤ iSup V
g : (x : { x // x ∈ U }) → (fun x_1 => (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op (V x)))) f
hg : ∀ (x : { x // x ∈ U }), ↑(X.presheaf.map (iVU x).op) f * g x = 1
x y : { x // x ∈ U }
z : ↑↑X.toPresheafedSpace
hzVx : z ∈ ↑(V x)
hzVy : z ∈ ↑(V y)
⊢ ↑(germ (Sheaf.presheaf (sheaf X))
((fun x_1 => { val := ↑x_1, property := (_ : ↑x_1 ∈ ↑(V x)) })
{ val := z, property := (_ : z ∈ ↑(V x) ∧ z ∈ ↑(V y)) }))
(g x) =
↑(germ (Sheaf.presheaf (sheaf X))
((fun x_1 => { val := ↑x_1, property := (_ : ↑x_1 ∈ ↑(V y)) })
{ val := z, property := (_ : z ∈ ↑(V x) ∧ z ∈ ↑(V y)) }))
(g y)
[PROOFSTEP]
apply (IsUnit.mul_right_inj (h ⟨z, (iVU x).le hzVx⟩)).mp
[GOAL]
case ic.h.mk.intro
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
h : ∀ (x : { x // x ∈ U }), IsUnit (↑(germ X.presheaf x) f)
V : { x // x ∈ U } → Opens ↑↑X.toPresheafedSpace
iVU : (x : { x // x ∈ U }) → V x ⟶ U
m : ∀ (x : { x // x ∈ U }), ↑x ∈ V x
h_unit : ∀ (x : { x // x ∈ U }), IsUnit (↑(X.presheaf.map (iVU x).op) f)
hcover : U ≤ iSup V
g : (x : { x // x ∈ U }) → (fun x_1 => (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op (V x)))) f
hg : ∀ (x : { x // x ∈ U }), ↑(X.presheaf.map (iVU x).op) f * g x = 1
x y : { x // x ∈ U }
z : ↑↑X.toPresheafedSpace
hzVx : z ∈ ↑(V x)
hzVy : z ∈ ↑(V y)
⊢ ↑(germ X.presheaf { val := z, property := (_ : z ∈ ↑U) }) f *
↑(germ (Sheaf.presheaf (sheaf X))
((fun x_1 => { val := ↑x_1, property := (_ : ↑x_1 ∈ ↑(V x)) })
{ val := z, property := (_ : z ∈ ↑(V x) ∧ z ∈ ↑(V y)) }))
(g x) =
↑(germ X.presheaf { val := z, property := (_ : z ∈ ↑U) }) f *
↑(germ (Sheaf.presheaf (sheaf X))
((fun x_1 => { val := ↑x_1, property := (_ : ↑x_1 ∈ ↑(V y)) })
{ val := z, property := (_ : z ∈ ↑(V x) ∧ z ∈ ↑(V y)) }))
(g y)
[PROOFSTEP]
rw [←
show X.presheaf.germ ⟨z, hzVx⟩ (X.presheaf.map (iVU x).op f) = X.presheaf.germ ⟨z, ((iVU x) ⟨z, hzVx⟩).2⟩ f from
X.presheaf.germ_res_apply (iVU x) ⟨z, hzVx⟩ f]
-- Porting note : change was not necessary in Lean3
[GOAL]
case ic.h.mk.intro
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
h : ∀ (x : { x // x ∈ U }), IsUnit (↑(germ X.presheaf x) f)
V : { x // x ∈ U } → Opens ↑↑X.toPresheafedSpace
iVU : (x : { x // x ∈ U }) → V x ⟶ U
m : ∀ (x : { x // x ∈ U }), ↑x ∈ V x
h_unit : ∀ (x : { x // x ∈ U }), IsUnit (↑(X.presheaf.map (iVU x).op) f)
hcover : U ≤ iSup V
g : (x : { x // x ∈ U }) → (fun x_1 => (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op (V x)))) f
hg : ∀ (x : { x // x ∈ U }), ↑(X.presheaf.map (iVU x).op) f * g x = 1
x y : { x // x ∈ U }
z : ↑↑X.toPresheafedSpace
hzVx : z ∈ ↑(V x)
hzVy : z ∈ ↑(V y)
⊢ ↑(germ X.presheaf { val := z, property := hzVx }) (↑(X.presheaf.map (iVU x).op) f) *
↑(germ (Sheaf.presheaf (sheaf X))
((fun x_1 => { val := ↑x_1, property := (_ : ↑x_1 ∈ ↑(V x)) })
{ val := z, property := (_ : z ∈ ↑(V x) ∧ z ∈ ↑(V y)) }))
(g x) =
↑(germ X.presheaf { val := z, property := hzVx }) (↑(X.presheaf.map (iVU x).op) f) *
↑(germ (Sheaf.presheaf (sheaf X))
((fun x_1 => { val := ↑x_1, property := (_ : ↑x_1 ∈ ↑(V y)) })
{ val := z, property := (_ : z ∈ ↑(V x) ∧ z ∈ ↑(V y)) }))
(g y)
[PROOFSTEP]
change
X.presheaf.germ ⟨z, hzVx⟩ _ * (X.presheaf.germ ⟨z, hzVx⟩ _) =
X.presheaf.germ ⟨z, hzVx⟩ _ * X.presheaf.germ ⟨z, hzVy⟩ (g y)
[GOAL]
case ic.h.mk.intro
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
h : ∀ (x : { x // x ∈ U }), IsUnit (↑(germ X.presheaf x) f)
V : { x // x ∈ U } → Opens ↑↑X.toPresheafedSpace
iVU : (x : { x // x ∈ U }) → V x ⟶ U
m : ∀ (x : { x // x ∈ U }), ↑x ∈ V x
h_unit : ∀ (x : { x // x ∈ U }), IsUnit (↑(X.presheaf.map (iVU x).op) f)
hcover : U ≤ iSup V
g : (x : { x // x ∈ U }) → (fun x_1 => (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op (V x)))) f
hg : ∀ (x : { x // x ∈ U }), ↑(X.presheaf.map (iVU x).op) f * g x = 1
x y : { x // x ∈ U }
z : ↑↑X.toPresheafedSpace
hzVx : z ∈ ↑(V x)
hzVy : z ∈ ↑(V y)
⊢ ↑(germ X.presheaf { val := z, property := hzVx }) (↑(X.presheaf.map (iVU x).op) f) *
↑(germ X.presheaf { val := z, property := hzVx }) (g x) =
↑(germ X.presheaf { val := z, property := hzVx }) (↑(X.presheaf.map (iVU x).op) f) *
↑(germ X.presheaf { val := z, property := hzVy }) (g y)
[PROOFSTEP]
rw [← RingHom.map_mul, congr_arg (X.presheaf.germ (⟨z, hzVx⟩ : V x)) (hg x),
-- Porting note : now need explicitly typing the rewritesshow
X.presheaf.germ ⟨z, hzVx⟩ (X.presheaf.map (iVU x).op f) = X.presheaf.germ ⟨z, ((iVU x) ⟨z, hzVx⟩).2⟩ f from
X.presheaf.germ_res_apply _ _ f,
-- Porting note : now need explicitly typing the rewrites←
show X.presheaf.germ ⟨z, hzVy⟩ (X.presheaf.map (iVU y).op f) = X.presheaf.germ ⟨z, ((iVU x) ⟨z, hzVx⟩).2⟩ f from
X.presheaf.germ_res_apply (iVU y) ⟨z, hzVy⟩ f,
← RingHom.map_mul, congr_arg (X.presheaf.germ (⟨z, hzVy⟩ : V y)) (hg y), RingHom.map_one, RingHom.map_one]
-- We claim that these local inverses glue together to a global inverse of `f`.
[GOAL]
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
h : ∀ (x : { x // x ∈ U }), IsUnit (↑(germ X.presheaf x) f)
V : { x // x ∈ U } → Opens ↑↑X.toPresheafedSpace
iVU : (x : { x // x ∈ U }) → V x ⟶ U
m : ∀ (x : { x // x ∈ U }), ↑x ∈ V x
h_unit : ∀ (x : { x // x ∈ U }), IsUnit (↑(X.presheaf.map (iVU x).op) f)
hcover : U ≤ iSup V
g : (x : { x // x ∈ U }) → (fun x_1 => (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op (V x)))) f
hg : ∀ (x : { x // x ∈ U }), ↑(X.presheaf.map (iVU x).op) f * g x = 1
ic : IsCompatible (sheaf X).val V g
⊢ IsUnit f
[PROOFSTEP]
obtain ⟨gl, gl_spec, -⟩ := X.sheaf.existsUnique_gluing' V U iVU hcover g ic
[GOAL]
case intro.intro
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
h : ∀ (x : { x // x ∈ U }), IsUnit (↑(germ X.presheaf x) f)
V : { x // x ∈ U } → Opens ↑↑X.toPresheafedSpace
iVU : (x : { x // x ∈ U }) → V x ⟶ U
m : ∀ (x : { x // x ∈ U }), ↑x ∈ V x
h_unit : ∀ (x : { x // x ∈ U }), IsUnit (↑(X.presheaf.map (iVU x).op) f)
hcover : U ≤ iSup V
g : (x : { x // x ∈ U }) → (fun x_1 => (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op (V x)))) f
hg : ∀ (x : { x // x ∈ U }), ↑(X.presheaf.map (iVU x).op) f * g x = 1
ic : IsCompatible (sheaf X).val V g
gl : (CategoryTheory.forget CommRingCat).obj ((sheaf X).val.obj (op U))
gl_spec : ∀ (i : { x // x ∈ U }), ↑((sheaf X).val.map (iVU i).op) gl = g i
⊢ IsUnit f
[PROOFSTEP]
apply isUnit_of_mul_eq_one f gl
[GOAL]
case intro.intro
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
h : ∀ (x : { x // x ∈ U }), IsUnit (↑(germ X.presheaf x) f)
V : { x // x ∈ U } → Opens ↑↑X.toPresheafedSpace
iVU : (x : { x // x ∈ U }) → V x ⟶ U
m : ∀ (x : { x // x ∈ U }), ↑x ∈ V x
h_unit : ∀ (x : { x // x ∈ U }), IsUnit (↑(X.presheaf.map (iVU x).op) f)
hcover : U ≤ iSup V
g : (x : { x // x ∈ U }) → (fun x_1 => (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op (V x)))) f
hg : ∀ (x : { x // x ∈ U }), ↑(X.presheaf.map (iVU x).op) f * g x = 1
ic : IsCompatible (sheaf X).val V g
gl : (CategoryTheory.forget CommRingCat).obj ((sheaf X).val.obj (op U))
gl_spec : ∀ (i : { x // x ∈ U }), ↑((sheaf X).val.map (iVU i).op) gl = g i
⊢ f * gl = 1
[PROOFSTEP]
apply X.sheaf.eq_of_locally_eq' V U iVU hcover
[GOAL]
case intro.intro.h
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
h : ∀ (x : { x // x ∈ U }), IsUnit (↑(germ X.presheaf x) f)
V : { x // x ∈ U } → Opens ↑↑X.toPresheafedSpace
iVU : (x : { x // x ∈ U }) → V x ⟶ U
m : ∀ (x : { x // x ∈ U }), ↑x ∈ V x
h_unit : ∀ (x : { x // x ∈ U }), IsUnit (↑(X.presheaf.map (iVU x).op) f)
hcover : U ≤ iSup V
g : (x : { x // x ∈ U }) → (fun x_1 => (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op (V x)))) f
hg : ∀ (x : { x // x ∈ U }), ↑(X.presheaf.map (iVU x).op) f * g x = 1
ic : IsCompatible (sheaf X).val V g
gl : (CategoryTheory.forget CommRingCat).obj ((sheaf X).val.obj (op U))
gl_spec : ∀ (i : { x // x ∈ U }), ↑((sheaf X).val.map (iVU i).op) gl = g i
⊢ ∀ (i : { x // x ∈ U }), ↑((sheaf X).val.map (iVU i).op) (f * gl) = ↑((sheaf X).val.map (iVU i).op) 1
[PROOFSTEP]
intro i
[GOAL]
case intro.intro.h
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
h : ∀ (x : { x // x ∈ U }), IsUnit (↑(germ X.presheaf x) f)
V : { x // x ∈ U } → Opens ↑↑X.toPresheafedSpace
iVU : (x : { x // x ∈ U }) → V x ⟶ U
m : ∀ (x : { x // x ∈ U }), ↑x ∈ V x
h_unit : ∀ (x : { x // x ∈ U }), IsUnit (↑(X.presheaf.map (iVU x).op) f)
hcover : U ≤ iSup V
g : (x : { x // x ∈ U }) → (fun x_1 => (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op (V x)))) f
hg : ∀ (x : { x // x ∈ U }), ↑(X.presheaf.map (iVU x).op) f * g x = 1
ic : IsCompatible (sheaf X).val V g
gl : (CategoryTheory.forget CommRingCat).obj ((sheaf X).val.obj (op U))
gl_spec : ∀ (i : { x // x ∈ U }), ↑((sheaf X).val.map (iVU i).op) gl = g i
i : { x // x ∈ U }
⊢ ↑((sheaf X).val.map (iVU i).op) (f * gl) = ↑((sheaf X).val.map (iVU i).op) 1
[PROOFSTEP]
rw [RingHom.map_one, RingHom.map_mul, gl_spec]
[GOAL]
case intro.intro.h
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
h : ∀ (x : { x // x ∈ U }), IsUnit (↑(germ X.presheaf x) f)
V : { x // x ∈ U } → Opens ↑↑X.toPresheafedSpace
iVU : (x : { x // x ∈ U }) → V x ⟶ U
m : ∀ (x : { x // x ∈ U }), ↑x ∈ V x
h_unit : ∀ (x : { x // x ∈ U }), IsUnit (↑(X.presheaf.map (iVU x).op) f)
hcover : U ≤ iSup V
g : (x : { x // x ∈ U }) → (fun x_1 => (CategoryTheory.forget CommRingCat).obj (X.presheaf.obj (op (V x)))) f
hg : ∀ (x : { x // x ∈ U }), ↑(X.presheaf.map (iVU x).op) f * g x = 1
ic : IsCompatible (sheaf X).val V g
gl : (CategoryTheory.forget CommRingCat).obj ((sheaf X).val.obj (op U))
gl_spec : ∀ (i : { x // x ∈ U }), ↑((sheaf X).val.map (iVU i).op) gl = g i
i : { x // x ∈ U }
⊢ ↑((sheaf X).val.map (iVU i).op) f * g i = 1
[PROOFSTEP]
exact hg i
[GOAL]
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
⊢ IsOpen (Subtype.val '' {x | IsUnit (↑(germ X.presheaf x) f)})
[PROOFSTEP]
rw [isOpen_iff_forall_mem_open]
[GOAL]
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
⊢ ∀ (x : ↑↑X.toPresheafedSpace),
x ∈ Subtype.val '' {x | IsUnit (↑(germ X.presheaf x) f)} →
∃ t, t ⊆ Subtype.val '' {x | IsUnit (↑(germ X.presheaf x) f)} ∧ IsOpen t ∧ x ∈ t
[PROOFSTEP]
rintro _ ⟨x, hx, rfl⟩
[GOAL]
case intro.intro
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
hx : x ∈ {x | IsUnit (↑(germ X.presheaf x) f)}
⊢ ∃ t, t ⊆ Subtype.val '' {x | IsUnit (↑(germ X.presheaf x) f)} ∧ IsOpen t ∧ ↑x ∈ t
[PROOFSTEP]
obtain ⟨V, i, hxV, hf⟩ := X.isUnit_res_of_isUnit_germ U f x hx
[GOAL]
case intro.intro.intro.intro.intro
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
hx : x ∈ {x | IsUnit (↑(germ X.presheaf x) f)}
V : Opens ↑↑X.toPresheafedSpace
i : V ⟶ U
hxV : ↑x ∈ V
hf : IsUnit (↑(X.presheaf.map i.op) f)
⊢ ∃ t, t ⊆ Subtype.val '' {x | IsUnit (↑(germ X.presheaf x) f)} ∧ IsOpen t ∧ ↑x ∈ t
[PROOFSTEP]
use V.1
[GOAL]
case h
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
hx : x ∈ {x | IsUnit (↑(germ X.presheaf x) f)}
V : Opens ↑↑X.toPresheafedSpace
i : V ⟶ U
hxV : ↑x ∈ V
hf : IsUnit (↑(X.presheaf.map i.op) f)
⊢ V.carrier ⊆ Subtype.val '' {x | IsUnit (↑(germ X.presheaf x) f)} ∧ IsOpen V.carrier ∧ ↑x ∈ V.carrier
[PROOFSTEP]
refine' ⟨_, V.2, hxV⟩
[GOAL]
case h
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
hx : x ∈ {x | IsUnit (↑(germ X.presheaf x) f)}
V : Opens ↑↑X.toPresheafedSpace
i : V ⟶ U
hxV : ↑x ∈ V
hf : IsUnit (↑(X.presheaf.map i.op) f)
⊢ V.carrier ⊆ Subtype.val '' {x | IsUnit (↑(germ X.presheaf x) f)}
[PROOFSTEP]
intro y hy
[GOAL]
case h
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
hx : x ∈ {x | IsUnit (↑(germ X.presheaf x) f)}
V : Opens ↑↑X.toPresheafedSpace
i : V ⟶ U
hxV : ↑x ∈ V
hf : IsUnit (↑(X.presheaf.map i.op) f)
y : ↑↑X.toPresheafedSpace
hy : y ∈ V.carrier
⊢ y ∈ Subtype.val '' {x | IsUnit (↑(germ X.presheaf x) f)}
[PROOFSTEP]
use(⟨y, i.le hy⟩ : U)
[GOAL]
case h
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
hx : x ∈ {x | IsUnit (↑(germ X.presheaf x) f)}
V : Opens ↑↑X.toPresheafedSpace
i : V ⟶ U
hxV : ↑x ∈ V
hf : IsUnit (↑(X.presheaf.map i.op) f)
y : ↑↑X.toPresheafedSpace
hy : y ∈ V.carrier
⊢ { val := y, property := (_ : y ∈ ↑U) } ∈ {x | IsUnit (↑(germ X.presheaf x) f)} ∧
↑{ val := y, property := (_ : y ∈ ↑U) } = y
[PROOFSTEP]
rw [Set.mem_setOf_eq]
[GOAL]
case h
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
hx : x ∈ {x | IsUnit (↑(germ X.presheaf x) f)}
V : Opens ↑↑X.toPresheafedSpace
i : V ⟶ U
hxV : ↑x ∈ V
hf : IsUnit (↑(X.presheaf.map i.op) f)
y : ↑↑X.toPresheafedSpace
hy : y ∈ V.carrier
⊢ IsUnit (↑(germ X.presheaf { val := y, property := (_ : y ∈ ↑U) }) f) ∧ ↑{ val := y, property := (_ : y ∈ ↑U) } = y
[PROOFSTEP]
constructor
[GOAL]
case h.left
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
hx : x ∈ {x | IsUnit (↑(germ X.presheaf x) f)}
V : Opens ↑↑X.toPresheafedSpace
i : V ⟶ U
hxV : ↑x ∈ V
hf : IsUnit (↑(X.presheaf.map i.op) f)
y : ↑↑X.toPresheafedSpace
hy : y ∈ V.carrier
⊢ IsUnit (↑(germ X.presheaf { val := y, property := (_ : y ∈ ↑U) }) f)
[PROOFSTEP]
convert RingHom.isUnit_map (X.presheaf.germ ⟨y, hy⟩) hf
[GOAL]
case h.e'_3
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
hx : x ∈ {x | IsUnit (↑(germ X.presheaf x) f)}
V : Opens ↑↑X.toPresheafedSpace
i : V ⟶ U
hxV : ↑x ∈ V
hf : IsUnit (↑(X.presheaf.map i.op) f)
y : ↑↑X.toPresheafedSpace
hy : y ∈ V.carrier
⊢ ↑(germ X.presheaf { val := y, property := (_ : y ∈ ↑U) }) f =
↑(germ X.presheaf { val := y, property := hy }) (↑(X.presheaf.map i.op) f)
[PROOFSTEP]
exact (X.presheaf.germ_res_apply i ⟨y, hy⟩ f).symm
[GOAL]
case h.right
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
hx : x ∈ {x | IsUnit (↑(germ X.presheaf x) f)}
V : Opens ↑↑X.toPresheafedSpace
i : V ⟶ U
hxV : ↑x ∈ V
hf : IsUnit (↑(X.presheaf.map i.op) f)
y : ↑↑X.toPresheafedSpace
hy : y ∈ V.carrier
⊢ ↑{ val := y, property := (_ : y ∈ ↑U) } = y
[PROOFSTEP]
rfl
[GOAL]
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
⊢ ↑x ∈ basicOpen X f ↔ IsUnit (↑(germ X.presheaf x) f)
[PROOFSTEP]
constructor
[GOAL]
case mp
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
⊢ ↑x ∈ basicOpen X f → IsUnit (↑(germ X.presheaf x) f)
[PROOFSTEP]
rintro ⟨x, hx, a⟩
[GOAL]
case mp.intro.intro
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x✝ x : { x // x ∈ U }
hx : x ∈ {x | IsUnit (↑(germ X.presheaf x) f)}
a : ↑x = ↑x✝
⊢ IsUnit (↑(germ X.presheaf x✝) f)
[PROOFSTEP]
cases Subtype.eq a
[GOAL]
case mp.intro.intro.refl
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
hx : x ∈ {x | IsUnit (↑(germ X.presheaf x) f)}
a : ↑x = ↑x
⊢ IsUnit (↑(germ X.presheaf x) f)
[PROOFSTEP]
exact hx
[GOAL]
case mpr
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
⊢ IsUnit (↑(germ X.presheaf x) f) → ↑x ∈ basicOpen X f
[PROOFSTEP]
intro h
[GOAL]
case mpr
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
h : IsUnit (↑(germ X.presheaf x) f)
⊢ ↑x ∈ basicOpen X f
[PROOFSTEP]
exact ⟨x, h, rfl⟩
[GOAL]
X : RingedSpace
f : ↑(X.presheaf.obj (op ⊤))
x : ↑↑X.toPresheafedSpace
⊢ x ∈ ⊤
[PROOFSTEP]
trivial
[GOAL]
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
⊢ basicOpen X f ≤ U
[PROOFSTEP]
rintro _ ⟨x, _, rfl⟩
[GOAL]
case intro.intro
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
left✝ : x ∈ {x | IsUnit (↑(germ X.presheaf x) f)}
⊢ ↑x ∈ ↑U
[PROOFSTEP]
exact x.2
[GOAL]
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
⊢ IsUnit (↑(X.presheaf.map (homOfLE (_ : basicOpen X f ≤ U)).op) f)
[PROOFSTEP]
apply isUnit_of_isUnit_germ
[GOAL]
case h
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
⊢ ∀ (x : { x // x ∈ basicOpen X f }),
IsUnit (↑(germ X.presheaf x) (↑(X.presheaf.map (homOfLE (_ : basicOpen X f ≤ U)).op) f))
[PROOFSTEP]
rintro ⟨_, ⟨x, (hx : IsUnit _), rfl⟩⟩
[GOAL]
case h.mk.intro.intro
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
hx : IsUnit (↑(germ X.presheaf x) f)
⊢ IsUnit
(↑(germ X.presheaf { val := ↑x, property := (_ : ∃ a, a ∈ {x | IsUnit (↑(germ X.presheaf x) f)} ∧ ↑a = ↑x) })
(↑(X.presheaf.map (homOfLE (_ : basicOpen X f ≤ U)).op) f))
[PROOFSTEP]
convert hx
[GOAL]
case h.e'_3
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
x : { x // x ∈ U }
hx : IsUnit (↑(germ X.presheaf x) f)
⊢ ↑(germ X.presheaf { val := ↑x, property := (_ : ∃ a, a ∈ {x | IsUnit (↑(germ X.presheaf x) f)} ∧ ↑a = ↑x) })
(↑(X.presheaf.map (homOfLE (_ : basicOpen X f ≤ U)).op) f) =
↑(germ X.presheaf x) f
[PROOFSTEP]
convert X.presheaf.germ_res_apply _ _ _
[GOAL]
X : RingedSpace
U V : (Opens ↑↑X.toPresheafedSpace)ᵒᵖ
i : U ⟶ V
f : ↑(X.presheaf.obj U)
⊢ basicOpen X (↑(X.presheaf.map i) f) = V.unop ⊓ basicOpen X f
[PROOFSTEP]
induction U using Opposite.rec'
[GOAL]
case h
X : RingedSpace
V : (Opens ↑↑X.toPresheafedSpace)ᵒᵖ
X✝ : Opens ↑↑X.toPresheafedSpace
i : op X✝ ⟶ V
f : ↑(X.presheaf.obj (op X✝))
⊢ basicOpen X (↑(X.presheaf.map i) f) = V.unop ⊓ basicOpen X f
[PROOFSTEP]
induction V using Opposite.rec'
[GOAL]
case h.h
X : RingedSpace
X✝¹ : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op X✝¹))
X✝ : Opens ↑↑X.toPresheafedSpace
i : op X✝¹ ⟶ op X✝
⊢ basicOpen X (↑(X.presheaf.map i) f) = (op X✝).unop ⊓ basicOpen X f
[PROOFSTEP]
let g := i.unop
[GOAL]
case h.h
X : RingedSpace
X✝¹ : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op X✝¹))
X✝ : Opens ↑↑X.toPresheafedSpace
i : op X✝¹ ⟶ op X✝
g : (op X✝).unop ⟶ (op X✝¹).unop := i.unop
⊢ basicOpen X (↑(X.presheaf.map i) f) = (op X✝).unop ⊓ basicOpen X f
[PROOFSTEP]
have : i = g.op := rfl
[GOAL]
case h.h
X : RingedSpace
X✝¹ : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op X✝¹))
X✝ : Opens ↑↑X.toPresheafedSpace
i : op X✝¹ ⟶ op X✝
g : (op X✝).unop ⟶ (op X✝¹).unop := i.unop
this : i = g.op
⊢ basicOpen X (↑(X.presheaf.map i) f) = (op X✝).unop ⊓ basicOpen X f
[PROOFSTEP]
clear_value g
[GOAL]
case h.h
X : RingedSpace
X✝¹ : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op X✝¹))
X✝ : Opens ↑↑X.toPresheafedSpace
i : op X✝¹ ⟶ op X✝
g : (op X✝).unop ⟶ (op X✝¹).unop
this : i = g.op
⊢ basicOpen X (↑(X.presheaf.map i) f) = (op X✝).unop ⊓ basicOpen X f
[PROOFSTEP]
subst this
[GOAL]
case h.h
X : RingedSpace
X✝¹ : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op X✝¹))
X✝ : Opens ↑↑X.toPresheafedSpace
g : (op X✝).unop ⟶ (op X✝¹).unop
⊢ basicOpen X (↑(X.presheaf.map g.op) f) = (op X✝).unop ⊓ basicOpen X f
[PROOFSTEP]
ext
[GOAL]
case h.h.h.h
X : RingedSpace
X✝¹ : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op X✝¹))
X✝ : Opens ↑↑X.toPresheafedSpace
g : (op X✝).unop ⟶ (op X✝¹).unop
x✝ : ↑↑X.toPresheafedSpace
⊢ x✝ ∈ ↑(basicOpen X (↑(X.presheaf.map g.op) f)) ↔ x✝ ∈ ↑((op X✝).unop ⊓ basicOpen X f)
[PROOFSTEP]
constructor
[GOAL]
case h.h.h.h.mp
X : RingedSpace
X✝¹ : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op X✝¹))
X✝ : Opens ↑↑X.toPresheafedSpace
g : (op X✝).unop ⟶ (op X✝¹).unop
x✝ : ↑↑X.toPresheafedSpace
⊢ x✝ ∈ ↑(basicOpen X (↑(X.presheaf.map g.op) f)) → x✝ ∈ ↑((op X✝).unop ⊓ basicOpen X f)
[PROOFSTEP]
rintro ⟨x, hx : IsUnit _, rfl⟩
[GOAL]
case h.h.h.h.mp.intro.intro
X : RingedSpace
X✝¹ : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op X✝¹))
X✝ : Opens ↑↑X.toPresheafedSpace
g : (op X✝).unop ⟶ (op X✝¹).unop
x : { x // x ∈ (op X✝).unop }
hx : IsUnit (↑(germ X.presheaf x) (↑(X.presheaf.map g.op) f))
⊢ ↑x ∈ ↑((op X✝).unop ⊓ basicOpen X f)
[PROOFSTEP]
erw [X.presheaf.germ_res_apply _ _ _] at hx
[GOAL]
case h.h.h.h.mp.intro.intro
X : RingedSpace
X✝¹ : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op X✝¹))
X✝ : Opens ↑↑X.toPresheafedSpace
g : (op X✝).unop ⟶ (op X✝¹).unop
x : { x // x ∈ (op X✝).unop }
hx : IsUnit (↑(germ X.presheaf ((fun x => { val := ↑x, property := (_ : ↑x ∈ ↑(op X✝¹).unop) }) x)) f)
⊢ ↑x ∈ ↑((op X✝).unop ⊓ basicOpen X f)
[PROOFSTEP]
exact ⟨x.2, g x, hx, rfl⟩
[GOAL]
case h.h.h.h.mpr
X : RingedSpace
X✝¹ : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op X✝¹))
X✝ : Opens ↑↑X.toPresheafedSpace
g : (op X✝).unop ⟶ (op X✝¹).unop
x✝ : ↑↑X.toPresheafedSpace
⊢ x✝ ∈ ↑((op X✝).unop ⊓ basicOpen X f) → x✝ ∈ ↑(basicOpen X (↑(X.presheaf.map g.op) f))
[PROOFSTEP]
rintro ⟨hxV, x, hx, rfl⟩
[GOAL]
case h.h.h.h.mpr.intro.intro.intro
X : RingedSpace
X✝¹ : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op X✝¹))
X✝ : Opens ↑↑X.toPresheafedSpace
g : (op X✝).unop ⟶ (op X✝¹).unop
x : { x // x ∈ (op X✝¹).unop }
hx : x ∈ {x | IsUnit (↑(germ X.presheaf x) f)}
hxV : ↑x ∈ ↑(op X✝).unop
⊢ ↑x ∈ ↑(basicOpen X (↑(X.presheaf.map g.op) f))
[PROOFSTEP]
refine' ⟨⟨x, hxV⟩, (_ : IsUnit _), rfl⟩
[GOAL]
case h.h.h.h.mpr.intro.intro.intro
X : RingedSpace
X✝¹ : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op X✝¹))
X✝ : Opens ↑↑X.toPresheafedSpace
g : (op X✝).unop ⟶ (op X✝¹).unop
x : { x // x ∈ (op X✝¹).unop }
hx : x ∈ {x | IsUnit (↑(germ X.presheaf x) f)}
hxV : ↑x ∈ ↑(op X✝).unop
⊢ IsUnit (↑(germ X.presheaf { val := ↑x, property := hxV }) (↑(X.presheaf.map g.op) f))
[PROOFSTEP]
erw [X.presheaf.germ_res_apply _ _ _]
[GOAL]
case h.h.h.h.mpr.intro.intro.intro
X : RingedSpace
X✝¹ : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op X✝¹))
X✝ : Opens ↑↑X.toPresheafedSpace
g : (op X✝).unop ⟶ (op X✝¹).unop
x : { x // x ∈ (op X✝¹).unop }
hx : x ∈ {x | IsUnit (↑(germ X.presheaf x) f)}
hxV : ↑x ∈ ↑(op X✝).unop
⊢ IsUnit
(↑(germ X.presheaf ((fun x => { val := ↑x, property := (_ : ↑x ∈ ↑(op X✝¹).unop) }) { val := ↑x, property := hxV }))
f)
[PROOFSTEP]
exact hx
[GOAL]
X : RingedSpace
U V : (Opens ↑↑X.toPresheafedSpace)ᵒᵖ
i : U ⟶ V
inst✝ : IsIso i
f : ↑(X.presheaf.obj U)
⊢ basicOpen X (↑(X.presheaf.map i) f) = basicOpen X f
[PROOFSTEP]
apply le_antisymm
[GOAL]
case a
X : RingedSpace
U V : (Opens ↑↑X.toPresheafedSpace)ᵒᵖ
i : U ⟶ V
inst✝ : IsIso i
f : ↑(X.presheaf.obj U)
⊢ basicOpen X (↑(X.presheaf.map i) f) ≤ basicOpen X f
[PROOFSTEP]
rw [X.basicOpen_res i f]
[GOAL]
case a
X : RingedSpace
U V : (Opens ↑↑X.toPresheafedSpace)ᵒᵖ
i : U ⟶ V
inst✝ : IsIso i
f : ↑(X.presheaf.obj U)
⊢ V.unop ⊓ basicOpen X f ≤ basicOpen X f
[PROOFSTEP]
exact inf_le_right
[GOAL]
case a
X : RingedSpace
U V : (Opens ↑↑X.toPresheafedSpace)ᵒᵖ
i : U ⟶ V
inst✝ : IsIso i
f : ↑(X.presheaf.obj U)
⊢ basicOpen X f ≤ basicOpen X (↑(X.presheaf.map i) f)
[PROOFSTEP]
have := X.basicOpen_res (inv i) (X.presheaf.map i f)
[GOAL]
case a
X : RingedSpace
U V : (Opens ↑↑X.toPresheafedSpace)ᵒᵖ
i : U ⟶ V
inst✝ : IsIso i
f : ↑(X.presheaf.obj U)
this : basicOpen X (↑(X.presheaf.map (inv i)) (↑(X.presheaf.map i) f)) = U.unop ⊓ basicOpen X (↑(X.presheaf.map i) f)
⊢ basicOpen X f ≤ basicOpen X (↑(X.presheaf.map i) f)
[PROOFSTEP]
rw [← comp_apply, ← X.presheaf.map_comp, IsIso.hom_inv_id, X.presheaf.map_id, id_apply] at this
[GOAL]
case a
X : RingedSpace
U V : (Opens ↑↑X.toPresheafedSpace)ᵒᵖ
i : U ⟶ V
inst✝ : IsIso i
f : ↑(X.presheaf.obj U)
this : basicOpen X f = U.unop ⊓ basicOpen X (↑(X.presheaf.map i) f)
⊢ basicOpen X f ≤ basicOpen X (↑(X.presheaf.map i) f)
[PROOFSTEP]
rw [this]
[GOAL]
case a
X : RingedSpace
U V : (Opens ↑↑X.toPresheafedSpace)ᵒᵖ
i : U ⟶ V
inst✝ : IsIso i
f : ↑(X.presheaf.obj U)
this : basicOpen X f = U.unop ⊓ basicOpen X (↑(X.presheaf.map i) f)
⊢ U.unop ⊓ basicOpen X (↑(X.presheaf.map i) f) ≤ basicOpen X (↑(X.presheaf.map i) f)
[PROOFSTEP]
exact inf_le_right
[GOAL]
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f g : ↑(X.presheaf.obj (op U))
⊢ basicOpen X (f * g) = basicOpen X f ⊓ basicOpen X g
[PROOFSTEP]
ext1
[GOAL]
case h
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f g : ↑(X.presheaf.obj (op U))
⊢ ↑(basicOpen X (f * g)) = ↑(basicOpen X f ⊓ basicOpen X g)
[PROOFSTEP]
dsimp [RingedSpace.basicOpen]
[GOAL]
case h
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f g : ↑(X.presheaf.obj (op U))
⊢ Subtype.val '' {x | IsUnit (↑(germ X.presheaf x) (f * g))} =
Subtype.val '' {x | IsUnit (↑(germ X.presheaf x) f)} ∩ Subtype.val '' {x | IsUnit (↑(germ X.presheaf x) g)}
[PROOFSTEP]
rw [← Set.image_inter Subtype.coe_injective]
[GOAL]
case h
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f g : ↑(X.presheaf.obj (op U))
⊢ Subtype.val '' {x | IsUnit (↑(germ X.presheaf x) (f * g))} =
(fun a => ↑a) '' ({x | IsUnit (↑(germ X.presheaf x) f)} ∩ {x | IsUnit (↑(germ X.presheaf x) g)})
[PROOFSTEP]
congr
[GOAL]
case h
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f g : ↑(X.presheaf.obj (op U))
⊢ Subtype.val '' {x | IsUnit (↑(germ X.presheaf x) (f * g))} =
(fun a => ↑a) '' ({x | IsUnit (↑(germ X.presheaf x) f)} ∩ {x | IsUnit (↑(germ X.presheaf x) g)})
[PROOFSTEP]
ext x
[GOAL]
case h.h
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f g : ↑(X.presheaf.obj (op U))
x : ↑↑X.toPresheafedSpace
⊢ x ∈ Subtype.val '' {x | IsUnit (↑(germ X.presheaf x) (f * g))} ↔
x ∈ (fun a => ↑a) '' ({x | IsUnit (↑(germ X.presheaf x) f)} ∩ {x | IsUnit (↑(germ X.presheaf x) g)})
[PROOFSTEP]
simp [map_mul, Set.mem_image]
[GOAL]
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
hf : IsUnit f
⊢ basicOpen X f = U
[PROOFSTEP]
apply le_antisymm
[GOAL]
case a
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
hf : IsUnit f
⊢ basicOpen X f ≤ U
[PROOFSTEP]
exact X.basicOpen_le f
[GOAL]
case a
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
hf : IsUnit f
⊢ U ≤ basicOpen X f
[PROOFSTEP]
intro x hx
[GOAL]
case a
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
hf : IsUnit f
x : ↑↑X.toPresheafedSpace
hx : x ∈ ↑U
⊢ x ∈ ↑(basicOpen X f)
[PROOFSTEP]
erw [X.mem_basicOpen f (⟨x, hx⟩ : U)]
[GOAL]
case a
X : RingedSpace
U : Opens ↑↑X.toPresheafedSpace
f : ↑(X.presheaf.obj (op U))
hf : IsUnit f
x : ↑↑X.toPresheafedSpace
hx : x ∈ ↑U
⊢ IsUnit (↑(germ X.presheaf { val := x, property := hx }) f)
[PROOFSTEP]
exact RingHom.isUnit_map _ hf
|
// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE
#include "purchase_ticket_command.h"
#ifdef WIN32
#include <regex>
#else
#include <boost/regex.hpp>
#endif
#include <swganh/app/swganh_kernel.h>
#include <swganh/service/service_manager.h>
#include <swganh_core/travel/travel_service.h>
using swganh::app::SwganhKernel;
using swganh::travel::PurchaseTicketCommand;
using swganh::command::CommandProperties;
using namespace swganh::service;
using namespace swganh::app;
#ifdef WIN32
using std::wregex;
using std::wsmatch;
using std::regex_match;
#else
using boost::wregex;
using boost::wsmatch;
using boost::regex_match;
#endif
void PurchaseTicketCommand::Run()
{
travel_ = GetKernel()->GetServiceManager()->GetService<TravelService>("TravelService");
const wregex p(L"(.*) (.*) (.*) (.*) (\\d+)");
wsmatch m;
if(regex_match(GetCommandString(), m, p)) {
auto source_scene = m[1].str();
auto source_location = m[2].str();
auto target_scene = m[3].str();
auto target_location = m[4].str();
travel_->PurchaseTicket(GetActor(),
std::string(source_scene.begin(), source_scene.end()),
std::string(source_location.begin(), source_location.end()),
std::string(target_scene.begin(), target_scene.end()),
std::string(target_location.begin(), target_location.end()),
0,
0,
std::stoi(m[5].str()) ? true : false);
}
}
|
Formal statement is: lemma emeasure_empty[simp, intro]: "emeasure M {} = 0" Informal statement is: The measure of the empty set is zero. |
Require Import VST.veric.compcert_rmaps.
Require Export VST.msl.ghost.
Require Import VST.msl.sepalg.
Require Import VST.msl.sepalg_generators.
Require Import VST.veric.SeparationLogic.
Require Import VST.progs.conclib.
Import List.
(* Lemmas about ghost state and common instances *)
(* Where should this sit? *)
Hint Resolve Share.nontrivial : core.
Definition gname := own.gname.
Instance Inhabitant_preds : Inhabitant preds := NoneP.
Section ghost.
Context {RA: Ghost}.
Lemma own_op' : forall g a1 a2 pp,
own g a1 pp * own g a2 pp = EX a3 : _, !!(join a1 a2 a3 /\ valid a3) && own g a3 pp.
Proof.
intros.
apply pred_ext.
- assert_PROP (valid_2 a1 a2) as Hjoin by (apply own_valid_2).
destruct Hjoin as (a3 & ? & ?); Exists a3; entailer!.
erewrite <- own_op by eauto. apply derives_refl.
- Intros a3.
erewrite own_op by eauto. apply derives_refl.
Qed.
Lemma own_op_gen : forall g a1 a2 a3 pp, (valid_2 a1 a2 -> join a1 a2 a3) ->
own g a1 pp * own g a2 pp = !!(valid_2 a1 a2) && own g a3 pp.
Proof.
intros; apply pred_ext.
- assert_PROP (valid_2 a1 a2) as Hv by apply own_valid_2.
erewrite <- own_op by eauto; entailer!.
- Intros.
erewrite own_op by eauto; entailer!.
Qed.
(* own isn't precise unless the ghost is a Disj_alg. Is this a problem? *)
Lemma own_list_alloc : forall la lp, Forall valid la -> length lp = length la ->
emp |-- |==> (EX lg : _, !!(Zlength lg = Zlength la) &&
iter_sepcon (fun '(g, a, p) => own g a p) (combine (combine lg la) lp)).
Proof.
intros until 1; revert lp; induction H; intros.
- eapply derives_trans, bupd_intro.
Exists (@nil own.gname). simpl. entailer!.
- destruct lp; inv H1.
rewrite <- emp_sepcon at 1.
eapply derives_trans; [apply sepcon_derives; [apply IHForall; eauto | apply own_alloc; eauto]|].
eapply derives_trans; [apply bupd_sepcon|].
apply bupd_mono.
Intros lg g.
Exists (g :: lg); rewrite !Zlength_cons; simpl.
rewrite sepcon_comm; entailer!.
apply derives_refl.
Qed.
Corollary own_list_alloc' : forall a pp i, 0 <= i -> valid a ->
emp |-- |==> (EX lg : _, !!(Zlength lg = i) && iter_sepcon (fun g => own g a pp) lg).
Proof.
intros.
eapply derives_trans;
[apply own_list_alloc with (la := repeat a (Z.to_nat i))(lp := repeat pp (Z.to_nat i))|].
{ apply Forall_repeat; auto. }
{ rewrite !repeat_length; auto. }
apply bupd_mono; Intros lg; Exists lg.
rewrite Zlength_repeat, Z2Nat.id in H1 by lia.
rewrite !combine_const1 by (rewrite ?Zlength_combine, ?Zlength_repeat, ?Z2Nat.id, ?Z.min_r; lia).
entailer!.
clear H; induction lg; simpl; entailer!.
Qed.
Lemma own_list_dealloc : forall {A} f (l : list A),
(forall b, exists g a pp, f b |-- own g a pp) ->
iter_sepcon f l |-- |==> emp.
Proof.
intros; induction l; simpl.
- apply bupd_intro.
- eapply derives_trans; [apply sepcon_derives, IHl|].
+ destruct (H a) as (? & ? & ? & Hf).
eapply derives_trans; [apply Hf | apply own_dealloc].
+ eapply derives_trans, bupd_mono; [apply bupd_sepcon | cancel].
Qed.
Lemma own_list_dealloc' : forall {A} g a p (l : list A),
iter_sepcon (fun x => own (g x) (a x) (p x)) l |-- |==> emp.
Proof.
intros; apply own_list_dealloc.
repeat eexists; apply derives_refl.
Qed.
End ghost.
Program Instance exclusive_PCM A : Ghost := { valid a := True;
Join_G := Join_lower (Join_discrete A) }.
Definition excl {A} g a := own(RA := exclusive_PCM A) g (Some a) NoneP.
Lemma exclusive_update : forall {A} (v v' : A) p, excl p v |-- |==> excl p v'.
Proof.
intros; apply own_update.
intros ? (? & ? & _).
exists (Some v'); split; simpl; auto; inv H; constructor.
inv H1.
Qed.
Local Obligation Tactic := idtac.
Program Instance prod_PCM (GA GB: Ghost): Ghost := { G := @G GA * @G GB;
valid a := valid (fst a) /\ valid (snd a); Join_G := Join_prod _ _ _ _ }.
Next Obligation.
intros GA GB ??? [] []; split; eapply join_valid; eauto.
Defined.
(* Can we use Santiago and Qinxiang's paper to simplify this? *)
Class PCM_order `{P : Ghost} (ord : G -> G -> Prop) := { ord_refl :> RelationClasses.Reflexive ord;
ord_trans :> RelationClasses.Transitive ord;
ord_lub : forall a b c, ord a c -> ord b c -> {c' | join a b c' /\ ord c' c};
join_ord : forall a b c, join a b c -> ord a c /\ ord b c; ord_join : forall a b, ord b a -> join a b a }.
(*Class lub_ord {A} (ord : A -> A -> Prop) := { lub_ord_refl :> RelationClasses.Reflexive ord;
lub_ord_trans :> RelationClasses.Transitive ord;
has_lub : forall a b c, ord a c -> ord b c -> exists c', ord a c' /\ ord b c' /\
forall d, ord a d -> ord b d -> ord c' d }.
Global Instance ord_PCM `{lub_ord} : Ghost := { Join_G a b c := ord a c /\ ord b c /\
forall c', ord a c' -> ord b c' -> ord c c' }.
Proof.
-
- intros ??? (? & ? & ?); eauto.
- intros ????? (? & ? & Hc) (? & ? & He).
destruct (has_lub b d e) as (c' & ? & ? & Hlub); try solve [etransitivity; eauto].
exists c'; repeat split; auto.
+ etransitivity; eauto.
+ apply Hlub; auto; transitivity c; auto.
+ intros.
apply He.
* apply Hc; auto; etransitivity; eauto.
* etransitivity; eauto.
Defined.
Global Instance ord_PCM_ord `{lub_ord} : PCM_order ord.
Proof.
constructor.
- apply lub_ord_refl.
- apply lub_ord_trans.
- intros ??? Ha Hb.
destruct (has_lub _ _ _ Ha Hb) as (c' & ? & ? & ?).
exists c'; simpl; eauto.
- simpl; intros; tauto.
- intros; simpl.
repeat split; auto.
reflexivity.
Defined.*)
(* Instances of ghost state *)
Section Snapshot.
(* One common kind of PCM is one in which a central authority has a reference copy, and clients pass around
partial knowledge. *)
Context `{ORD : PCM_order}.
Lemma join_refl : forall (v : G), join v v v.
Proof.
intros. apply ord_join; reflexivity.
Qed.
Lemma join_compat : forall v1 v2 v' v'', join v2 v' v'' -> ord v1 v2 -> exists v0, join v1 v' v0 /\ ord v0 v''.
Proof.
intros.
destruct (join_ord _ _ _ H).
destruct (ord_lub v1 v' v'') as (? & ? & ?); eauto.
etransitivity; eauto.
Qed.
Lemma join_ord_eq : forall a b, ord a b <-> exists c, join a c b.
Proof.
split.
- intros; exists b.
apply ord_join in H.
apply join_comm; auto.
- intros (? & H); apply join_ord in H; tauto.
Qed.
(* The master-snapshot PCM in the RCU paper divides the master into shares, which is useful for having both
an authoritative writer and an up-to-date invariant. *)
Global Program Instance snap_PCM : Ghost :=
{ valid _ := True; Join_G a b c := sepalg.join (fst a) (fst b) (fst c) /\
if eq_dec (fst a) Share.bot then if eq_dec (fst b) Share.bot then join (snd a) (snd b) (snd c)
else ord (snd a) (snd b) /\ snd c = snd b else snd c = snd a /\
if eq_dec (fst b) Share.bot then ord (snd b) (snd a) else snd c = snd b }.
Next Obligation.
exists (fun '(sh, a) => (Share.bot, core a)); repeat intro.
+ destruct t; constructor; auto; simpl.
rewrite eq_dec_refl.
if_tac; [apply core_unit | split; auto].
rewrite join_ord_eq; eexists; apply core_unit.
+ destruct a, b, c; f_equal.
inv H; simpl in *.
destruct (eq_dec t Share.bot); [|destruct H1; subst; auto].
subst; apply bot_identity in H0; subst.
destruct (eq_dec t1 Share.bot); [|destruct H1; subst; auto].
* eapply join_core; eauto.
* rewrite join_ord_eq in H; destruct H.
eapply join_core; eauto.
Defined.
Next Obligation.
constructor.
- intros ???? [? Hjoin1] [? Hjoin2].
assert (fst z = fst z') by (eapply join_eq; eauto).
destruct z, z'; simpl in *; subst; f_equal.
destruct (eq_dec (fst x) Share.bot); [|destruct Hjoin1, Hjoin2; subst; auto].
destruct (eq_dec (fst y) Share.bot); [|destruct Hjoin1, Hjoin2; subst; auto].
eapply join_eq; eauto.
- intros ????? [Hsh1 Hjoin1] [Hsh2 Hjoin2].
destruct (sepalg.join_assoc Hsh1 Hsh2) as [sh' []].
destruct (eq_dec (fst b) Share.bot) eqn: Hb.
+ assert (fst d = fst a) as Hd.
{ eapply sepalg.join_eq; eauto.
rewrite e0; apply join_bot_eq. }
rewrite Hd in *.
assert (sh' = fst c) as Hc.
{ eapply sepalg.join_eq; eauto.
rewrite e0; apply bot_join_eq. }
rewrite Hc in *.
destruct (eq_dec (fst c) Share.bot) eqn: Hc1.
* destruct (eq_dec (fst a) Share.bot) eqn: Ha.
-- destruct (join_assoc Hjoin1 Hjoin2) as [c' []].
exists (Share.bot, c'); split; split; rewrite ?e2, ?e0, ?e1, ?eq_dec_refl in *; auto.
-- destruct Hjoin1 as [Hc' ?]; rewrite Hc' in *.
destruct Hjoin2, (ord_lub (snd b) (snd c) (snd a)) as [c' []]; eauto.
exists (Share.bot, c'); split; split; rewrite ?e0, ?e1, ?eq_dec_refl, ?Ha in *; auto.
* exists c.
destruct (eq_dec (fst a) Share.bot) eqn: Ha; try solve [split; split; auto].
-- destruct Hjoin2.
apply join_ord in Hjoin1; destruct Hjoin1.
split; split; rewrite ?e0, ?Ha, ?Hc1, ?eq_dec_refl; auto; split; auto; etransitivity; eauto.
-- destruct Hjoin2 as [He1 He2]; rewrite He1, He2 in *.
destruct Hjoin1 as [Hd' ?]; rewrite Hd' in *; split; split; rewrite ?e0, ?Ha, ?Hc1, ?eq_dec_refl, ?Hd'; auto.
+ exists (sh', snd b); simpl.
destruct (eq_dec (fst d) Share.bot).
{ rewrite e0 in Hsh1; apply join_Bot in Hsh1; destruct Hsh1; contradiction. }
destruct (eq_dec sh' Share.bot) eqn: Hn'.
{ subst; apply join_Bot in H; destruct H; contradiction. }
assert (snd d = snd b) as Hd by (destruct (eq_dec (fst a) Share.bot); tauto).
destruct Hjoin2 as [He ?]; rewrite He in *; split; split; simpl; rewrite ?Hb, ?Hn', ?Hd, ?He in *; auto.
- intros ??? []; split; [apply join_comm; auto|].
if_tac; if_tac; auto; tauto.
- intros ???? [? Hjoin1] [? Hjoin2].
assert (fst a = fst b) by (eapply join_positivity; eauto).
destruct (eq_dec (fst a) Share.bot), a, a', b, b'; simpl in *; subst; f_equal.
+ apply join_Bot in H0 as []; subst.
apply join_Bot in H as []; subst.
rewrite eq_dec_refl in Hjoin1, Hjoin2, Hjoin2.
eapply join_positivity; eauto.
+ destruct Hjoin1; auto.
Defined.
Next Obligation.
auto.
Defined.
Definition ghost_snap (a : @G P) p := own p (Share.bot, a) NoneP.
Lemma ghost_snap_join : forall v1 v2 p v, join v1 v2 v ->
ghost_snap v1 p * ghost_snap v2 p = ghost_snap v p.
Proof.
intros; symmetry; apply own_op.
split; simpl; rewrite ?eq_dec_refl; auto.
Qed.
Lemma ghost_snap_conflict : forall v1 v2 p, ghost_snap v1 p * ghost_snap v2 p |-- !!(joins v1 v2).
Proof.
intros; eapply derives_trans; [apply own_valid_2|].
apply prop_left; intros ((?, a) & (? & Hj) & _); simpl in Hj.
rewrite !eq_dec_refl in Hj.
apply prop_right; exists a; auto.
Qed.
Lemma ghost_snap_join' : forall v1 v2 p,
ghost_snap v1 p * ghost_snap v2 p = EX v : _, !!(join v1 v2 v) && ghost_snap v p.
Proof.
intros; apply pred_ext.
- assert_PROP (joins v1 v2) as H by apply ghost_snap_conflict.
destruct H as [v]; Exists v; entailer!.
erewrite ghost_snap_join; eauto. apply derives_refl.
- Intros v; erewrite ghost_snap_join; eauto. apply derives_refl.
Qed.
Definition ghost_master sh (a : @G P) p := own p (sh, a) NoneP.
Lemma snap_master_join : forall v1 sh v2 p, sh <> Share.bot ->
ghost_snap v1 p * ghost_master sh v2 p = !!(ord v1 v2) && ghost_master sh v2 p.
Proof.
intros; setoid_rewrite own_op'.
apply pred_ext.
- Intros a3.
destruct a3 as (sh', ?), H0 as [Hsh Hj]; simpl in *.
apply bot_identity in Hsh; subst sh'.
rewrite eq_dec_refl in Hj.
destruct (eq_dec sh Share.bot); [contradiction|].
destruct Hj; subst; entailer!.
- Intros; Exists (sh, v2); entailer!.
split; simpl; rewrite ?eq_dec_refl.
+ apply bot_join_eq.
+ if_tac; auto; contradiction.
+ apply derives_refl.
Qed.
Corollary snaps_master_join : forall lv sh v2 p, sh <> Share.bot ->
fold_right sepcon emp (map (fun v => ghost_snap v p) lv) * ghost_master sh v2 p =
!!(Forall (fun v1 => ord v1 v2) lv) && ghost_master sh v2 p.
Proof.
induction lv; simpl; intros.
- rewrite emp_sepcon, prop_true_andp; auto.
- rewrite sepcon_comm, <- sepcon_assoc, (sepcon_comm (ghost_master _ _ _)), snap_master_join by auto.
apply pred_ext.
+ Intros; rewrite sepcon_comm, IHlv by auto; entailer!.
+ Intros.
match goal with H : Forall _ _ |- _ => inv H end.
rewrite prop_true_andp, sepcon_comm, IHlv by auto; entailer!.
Qed.
Lemma master_update : forall v v' p, ord v v' -> ghost_master Tsh v p |-- |==> ghost_master Tsh v' p.
Proof.
intros; apply own_update.
intros ? (x & Hj & _); simpl in Hj.
exists (Tsh, v'); simpl; split; auto.
destruct Hj as [Hsh Hj]; simpl in *.
apply join_Tsh in Hsh as []; destruct c, x; simpl in *; subst.
split; auto; simpl.
fold share in *; destruct (eq_dec Tsh Share.bot); [contradiction Share.nontrivial|].
destruct Hj as [? Hc']; subst.
rewrite eq_dec_refl in Hc' |- *; split; auto.
etransitivity; eauto.
Qed.
Lemma master_init : forall (a : @G P), exists g', joins (Tsh, a) g'.
Proof.
intros; exists (Share.bot, a), (Tsh, a); simpl.
split; auto; simpl.
apply join_refl.
Qed.
Lemma make_snap : forall (sh : share) v p, ghost_master sh v p |-- |==> ghost_snap v p * ghost_master sh v p.
Proof.
intros; destruct (eq_dec sh Share.bot).
- subst; setoid_rewrite ghost_snap_join; [apply bupd_intro | apply join_refl].
- rewrite snap_master_join by auto.
eapply derives_trans, bupd_intro; entailer!.
Qed.
Lemma ghost_snap_forget : forall v1 v2 p, ord v1 v2 -> ghost_snap v2 p |-- |==> ghost_snap v1 p.
Proof.
intros; apply own_update.
intros (shc, c) [(shx, x) [[? Hj] _]]; simpl in *.
rewrite eq_dec_refl in Hj.
assert (shx = shc) by (eapply sepalg.join_eq; eauto); subst.
unfold share in Hj; destruct (eq_dec shc Share.bot); subst.
- destruct (join_compat _ _ _ _ Hj H) as [x' []].
exists (Share.bot, x'); simpl; split; auto; split; auto; simpl.
rewrite !eq_dec_refl; auto.
- destruct Hj; subst.
exists (shc, c); simpl; split; auto; split; auto; simpl.
rewrite eq_dec_refl; if_tac; [contradiction|].
split; auto.
etransitivity; eauto.
Qed.
Lemma ghost_snap_choose : forall v1 v2 p, ghost_snap v1 p * ghost_snap v2 p |-- |==> ghost_snap v1 p.
Proof.
intros.
setoid_rewrite own_op'.
Intros v'.
destruct v', H as [Hsh Hj]; apply bot_identity in Hsh; simpl in *; subst.
rewrite !eq_dec_refl in Hj.
apply ghost_snap_forget.
rewrite join_ord_eq; eauto.
Qed.
Lemma master_share_join : forall sh1 sh2 sh v p, sepalg.join sh1 sh2 sh ->
ghost_master sh1 v p * ghost_master sh2 v p = ghost_master sh v p.
Proof.
intros; symmetry; apply own_op; split; auto; simpl.
if_tac; if_tac; try split; auto; try apply ord_refl; apply join_refl.
Qed.
Lemma master_inj : forall sh1 sh2 v1 v2 p, readable_share sh1 -> readable_share sh2 ->
ghost_master sh1 v1 p * ghost_master sh2 v2 p |-- !!(v1 = v2).
Proof.
intros.
eapply derives_trans; [apply own_valid_2|].
apply prop_left; intros ((?, ?) & [[? Hj] _]); simpl in Hj.
fold share in *.
destruct (eq_dec sh1 Share.bot); [subst; contradiction unreadable_bot|].
destruct (eq_dec sh2 Share.bot); [subst; contradiction unreadable_bot|].
destruct Hj; subst; apply prop_right; auto.
Qed.
Lemma master_share_join' : forall sh1 sh2 sh v1 v2 p, readable_share sh1 -> readable_share sh2 ->
sepalg.join sh1 sh2 sh ->
ghost_master sh1 v1 p * ghost_master sh2 v2 p = !!(v1 = v2) && ghost_master sh v2 p.
Proof.
intros; apply pred_ext.
- assert_PROP (v1 = v2) by (apply master_inj; auto).
subst; erewrite master_share_join; eauto; entailer!.
- Intros; subst.
erewrite master_share_join; eauto. apply derives_refl.
Qed.
(* useful when we only want to deal with full masters *)
Definition ghost_master1 a p := ghost_master Tsh a p.
Lemma snap_master_join1 : forall v1 v2 p,
ghost_snap v1 p * ghost_master1 v2 p = !!(ord v1 v2) && ghost_master1 v2 p.
Proof.
intros; apply snap_master_join, Share.nontrivial.
Qed.
Lemma snap_master_update1 : forall v1 v2 p v', ord v2 v' ->
ghost_snap v1 p * ghost_master1 v2 p |-- |==> ghost_snap v' p * ghost_master1 v' p.
Proof.
intros; rewrite !snap_master_join1.
Intros.
eapply derives_trans; [apply master_update; eauto|].
apply bupd_mono; entailer!.
apply derives_refl.
Qed.
End Snapshot.
Definition pos_PCM := ghost_PCM.pos_PCM.
Definition ref_PCM := ghost_PCM.ref_PCM.
Notation completable := ghost_PCM.completable.
Section Reference.
Context {P : Ghost}.
Definition ghost_reference g a := own(RA := ref_PCM P) g (None, Some a) NoneP.
Definition ghost_part g sh a := own(RA := ref_PCM P) g (Some (sh, a), None) NoneP.
Definition ghost_part_ref g sh a r :=
own(RA := ref_PCM P) g (Some (sh, a), Some r) NoneP.
Lemma ghost_part_ref_join : forall g (sh : share) a b,
ghost_part g sh a * ghost_reference g b = ghost_part_ref g sh a b.
Proof.
intros.
symmetry; apply own_op.
hnf; simpl.
split; auto; constructor.
Qed.
Lemma ref_sub : forall g sh a b pp,
own(RA := ref_PCM P) g (Some (sh, a), None) pp * own(RA := ref_PCM P) g (None, Some b) pp |--
!!(if eq_dec sh Tsh then a = b else exists x, join a x b).
Proof.
intros.
eapply derives_trans; [apply own_valid_2|].
apply prop_left; intros (c & [Hsh Hj] & ?); simpl in *.
apply prop_right.
destruct (fst c); [subst | contradiction].
inv Hj.
rewrite <- H0 in H.
destruct H as (? & c' & Hsub).
destruct c' as [(?, ?)|].
- destruct Hsub as (? & ? & Hsh & ?).
if_tac; eauto; subst.
apply join_Tsh in Hsh; tauto.
- inv Hsub.
rewrite eq_dec_refl; auto.
Qed.
Lemma ref_add : forall g sh a r b a' r' pp
(Ha : join a b a') (Hr : join r b r') (Hb : forall c, join_sub a c -> join_sub c r -> joins c b),
own(RA := ref_PCM P) g (Some (sh, a), Some r) pp |-- |==>
own(RA := ref_PCM P) g (Some (sh, a'), Some r') pp.
Proof.
intros; apply own_update.
intros (c, ?) ((x, ?) & [J1 J2] & [? Hvalid]); simpl in *.
inv J2; [|contradiction].
destruct c as [(?, c)|], x as [(shx, x)|]; try contradiction.
- destruct J1 as (? & ? & ? & Hx).
destruct (Hb x) as [x' Hx'].
{ eexists; eauto. }
{ destruct Hvalid as [[(?, ?)|] Hvalid]; hnf in Hvalid.
+ destruct Hvalid as (? & ? & ? & ?); eexists; eauto.
+ inv Hvalid; apply join_sub_refl. }
exists (Some (shx, x'), Some r'); repeat (split; auto); try constructor; simpl.
+ destruct (join_assoc (join_comm Hx) Hx') as (? & ? & ?).
eapply join_eq in Ha; eauto; subst; auto.
+ destruct Hvalid as (d & Hvalid); hnf in Hvalid.
exists d; destruct d as [(shd, d)|]; hnf.
* destruct Hvalid as (? & ? & ? & Hd); repeat (split; auto).
destruct (join_assoc (join_comm Hd) Hr) as (? & ? & ?).
eapply join_eq in Hx'; eauto; subst; auto.
* inv Hvalid; f_equal.
eapply join_eq; eauto.
- inv J1.
exists (Some (sh, a'), Some r'); repeat split; simpl; auto; try constructor.
destruct Hvalid as (d & Hvalid); hnf in Hvalid.
exists d; destruct d as [(shd, d)|]; hnf.
+ destruct Hvalid as (? & ? & ? & Hd); repeat (split; auto).
destruct (join_assoc (join_comm Hd) Hr) as (? & ? & ?).
eapply join_eq in Ha; eauto; subst; auto.
+ inv Hvalid; f_equal.
eapply join_eq; eauto.
Qed.
Lemma self_completable : forall a, completable (Some (Tsh, a)) a.
Proof.
intros; unfold completable.
exists None; constructor.
Qed.
End Reference.
Hint Resolve self_completable : init.
Section Discrete.
Program Instance discrete_PCM (A : Type) : Ghost := { valid a := True;
Join_G := Join_equiv A }.
Next Obligation.
auto.
Defined.
End Discrete.
Section GVar.
Context {A : Type}.
Definition ghost_var (sh : share) (v : A) g :=
own(RA := @pos_PCM (discrete_PCM A)) g (Some (sh, v)) NoneP.
Lemma ghost_var_share_join : forall sh1 sh2 sh v p, sepalg.join sh1 sh2 sh ->
sh1 <> Share.bot -> sh2 <> Share.bot ->
ghost_var sh1 v p * ghost_var sh2 v p = ghost_var sh v p.
Proof.
intros; symmetry; apply own_op.
repeat (split; auto).
Qed.
Lemma ghost_var_share_join_gen : forall sh1 sh2 v1 v2 p,
ghost_var sh1 v1 p * ghost_var sh2 v2 p = EX sh : _,
!!(v1 = v2 /\ sh1 <> Share.bot /\ sh2 <> Share.bot /\ sepalg.join sh1 sh2 sh) && ghost_var sh v1 p.
Proof.
intros; setoid_rewrite own_op'.
apply pred_ext.
- Intros a.
destruct a as [(sh, v')|]; inv H.
destruct H2 as (? & ? & Hv); inv Hv.
Exists sh; entailer!.
- Intros sh; subst.
Exists (Some (sh, v2)); apply andp_right, derives_refl.
apply prop_right; repeat (split; auto); simpl.
intro; subst; apply join_Bot in H2 as []; contradiction.
Qed.
Lemma ghost_var_inj : forall sh1 sh2 v1 v2 p, sh1 <> Share.bot -> sh2 <> Share.bot ->
ghost_var sh1 v1 p * ghost_var sh2 v2 p |-- !!(v1 = v2).
Proof.
intros; rewrite ghost_var_share_join_gen; Intros sh; entailer!.
Qed.
Lemma ghost_var_share_join' : forall sh1 sh2 sh v1 v2 p, sh1 <> Share.bot -> sh2 <> Share.bot ->
sepalg.join sh1 sh2 sh ->
ghost_var sh1 v1 p * ghost_var sh2 v2 p = !!(v1 = v2) && ghost_var sh v2 p.
Proof.
intros; rewrite ghost_var_share_join_gen.
apply pred_ext.
- Intros sh'; entailer!.
eapply join_eq in H1; eauto; subst; auto.
- Intros; Exists sh; entailer!.
Qed.
Lemma ghost_var_update : forall v p v', ghost_var Tsh v p |-- |==> ghost_var Tsh v' p.
Proof.
intros; apply own_update.
intros [[]|] ([[]|] & J & ?); inv J.
- destruct H1 as (? & ?%join_Tsh & ?); tauto.
- exists (Some (Tsh, v')); split; [constructor | auto].
Qed.
(*Lemma ghost_var_precise : forall sh p, precise (EX v : A, ghost_var sh v p).
Proof.
intros; apply derives_precise' with (EX g : share * A, ghost g p), ex_ghost_precise.
Intro v; Exists (sh, v); auto. apply derives_refl.
Qed.
Lemma ghost_var_precise' : forall sh v p, precise (ghost_var sh v p).
Proof.
intros; apply derives_precise with (Q := EX v : A, ghost_var sh v p);
[exists v; auto | apply ghost_var_precise].
Qed.*)
End GVar.
Section PVar.
(* Like ghost variables, but the partial values may be out of date. *)
Global Program Instance nat_PCM: Ghost := { valid a := True; Join_G a b c := c = Nat.max a b }.
Next Obligation.
exists (fun _ => O); auto; intros.
apply Nat.max_0_l.
Defined.
Next Obligation.
constructor.
- unfold join; congruence.
- unfold join; eexists; split; eauto.
rewrite Nat.max_assoc; subst; auto.
- unfold join; intros.
rewrite Nat.max_comm; auto.
- unfold join; intros.
apply Nat.le_antisymm; [subst b | subst a]; apply Nat.le_max_l.
Defined.
Next Obligation.
auto.
Defined.
Global Instance max_order : PCM_order Peano.le.
Proof.
constructor; auto; intros.
- intros ???; lia.
- eexists; unfold join; simpl; split; eauto.
apply Nat.max_lub; auto.
- hnf in H; subst.
split; [apply Nat.le_max_l | apply Nat.le_max_r].
- hnf.
rewrite Nat.max_l; auto.
Defined.
Lemma ghost_snap_join_N : forall v1 v2 p, ghost_snap v1 p * ghost_snap v2 p = ghost_snap (Nat.max v1 v2) p.
Proof.
intros; apply ghost_snap_join; hnf; auto.
Qed.
Lemma snap_master_join' : forall v1 v2 p,
ghost_snap v1 p * ghost_master1 v2 p = !!(v1 <= v2)%nat && ghost_master1 v2 p.
Proof.
intros; apply snap_master_join1.
Qed.
Lemma snap_master_update' : forall (v1 v2 : nat) p v', (v2 <= v')%nat ->
ghost_snap v1 p * ghost_master1 v2 p |-- |==> ghost_snap v' p * ghost_master1 v' p.
Proof.
intros; apply snap_master_update1; auto.
Qed.
End PVar.
Section Maps.
Context {A B : Type} {A_eq : EqDec A}.
Implicit Types (k : A) (v : B) (m : A -> option B).
Definition map_upd m k v k' := if eq_dec k' k then Some v else m k'.
Lemma map_upd_triv : forall m k v, m k = Some v -> map_upd m k v = m.
Proof.
intros; extensionality; unfold map_upd.
if_tac; subst; auto.
Qed.
Fixpoint map_upd_list m l :=
match l with
| [] => m
| (k, v) :: rest => map_upd_list (map_upd m k v) rest
end.
Definition map_add m1 m2 k := match m1 k with Some v' => Some v' | None => m2 k end.
Definition empty_map k : option B := None.
Global Instance Inhabitant_map : Inhabitant (A -> option B) := empty_map.
Definition singleton k v k1 := if eq_dec k1 k then Some v else None.
Definition map_incl m1 m2 := forall k v, m1 k = Some v -> m2 k = Some v.
Global Instance map_incl_refl : Reflexive map_incl.
Proof.
repeat intro; auto.
Qed.
Global Instance map_incl_antisym : Antisymmetric _ _ map_incl.
Proof.
intros x y Hx Hy a.
specialize (Hx a); specialize (Hy a).
destruct (x a); [erewrite Hx; eauto|].
destruct (y a); auto.
Qed.
Global Instance map_incl_trans : Transitive map_incl.
Proof.
repeat intro; auto.
Qed.
Lemma map_add_incl_compat : forall m1 m2 m3, map_incl m1 m2 -> map_incl (map_add m3 m1) (map_add m3 m2).
Proof.
unfold map_add; repeat intro.
destruct (m3 k); auto.
Qed.
Definition compatible m1 m2 := forall k v1 v2, m1 k = Some v1 -> m2 k = Some v2 -> v1 = v2.
Global Instance compatible_refl : Reflexive compatible.
Proof.
repeat intro.
congruence.
Qed.
Global Instance compatible_comm : Symmetric compatible.
Proof.
repeat intro.
symmetry; eauto.
Qed.
Lemma map_add_comm : forall m1 m2, compatible m1 m2 -> map_add m1 m2 = map_add m2 m1.
Proof.
intros; extensionality x; unfold map_add.
destruct (m1 x) eqn: Hm1, (m2 x) eqn: Hm2; eauto.
Qed.
Lemma map_add_assoc : forall m1 m2 m3, map_add (map_add m1 m2) m3 = map_add m1 (map_add m2 m3).
Proof.
intros; extensionality; unfold map_add.
destruct (m1 x); auto.
Qed.
Lemma compatible_add_assoc : forall m1 m2 m3, compatible m1 m2 ->
compatible (map_add m1 m2) m3 -> compatible m1 (map_add m2 m3).
Proof.
unfold compatible, map_add; intros.
repeat match goal with H : forall _, _ |- _ => specialize (H k) end.
replace (m1 k) with (Some v1) in *.
destruct (m2 k); auto.
Qed.
Lemma compatible_incl : forall m1 m2 m (Hcompat : compatible m2 m) (Hincl : map_incl m1 m2), compatible m1 m.
Proof.
repeat intro; eauto.
Qed.
Lemma map_incl_add : forall m1 m2, map_incl m1 (map_add m1 m2).
Proof.
repeat intro; unfold map_add.
rewrite H; auto.
Qed.
Lemma map_incl_compatible : forall m1 m2 m3 (Hincl1 : map_incl m1 m3) (Hincl2 : map_incl m2 m3),
compatible m1 m2.
Proof.
intros; intros ??? Hk1 Hk2.
apply Hincl1 in Hk1; apply Hincl2 in Hk2.
rewrite Hk1 in Hk2; inv Hk2; auto.
Qed.
Lemma map_add_incl : forall m1 m2 m3, map_incl m1 m3 -> map_incl m2 m3 -> map_incl (map_add m1 m2) m3.
Proof.
unfold map_add; intros.
intros ?? Hk.
destruct (m1 k) eqn: Hk1; auto.
inv Hk; auto.
Qed.
Global Instance map_join : Join (A -> option B) :=
fun a b c => forall k v, c k = Some v <-> a k = Some v \/ b k = Some v.
Lemma map_join_spec : forall m1 m2 m3, join m1 m2 m3 <-> compatible m1 m2 /\ m3 = map_add m1 m2.
Proof.
unfold join, map_join; simpl; split; intros.
- split.
+ repeat intro.
assert (m3 k = Some v1) as Hk by (rewrite H; auto).
replace (m3 k) with (Some v2) in Hk by (symmetry; rewrite H; auto).
inv Hk; auto.
+ extensionality x; unfold map_add.
destruct (m1 x) eqn: Hm1; [rewrite H; auto|].
destruct (m2 x) eqn: Hm2; [rewrite H; auto|].
destruct (m3 x) eqn: Hm3; auto.
rewrite H in Hm3; destruct Hm3 as [Hm3 | Hm3]; rewrite Hm3 in *; discriminate.
- destruct H as [Hcompat]; subst; unfold map_add.
destruct (m1 k) eqn: Hm1; split; auto; intros [?|?]; eauto; discriminate.
Qed.
Global Program Instance map_PCM : Ghost := { valid a := True; Join_G := map_join }.
Next Obligation.
exists (fun _ => empty_map); auto; repeat intro.
split; auto; intros [|]; auto; discriminate.
Defined.
Next Obligation.
constructor.
- intros.
extensionality k.
specialize (H k); specialize (H0 k).
destruct (z k).
+ destruct (H b) as [X _]; specialize (X eq_refl).
rewrite <- H0 in X; auto.
+ destruct (z' k); auto.
destruct (H0 b) as [X _]; specialize (X eq_refl).
rewrite <- H in X; auto.
- intros.
rewrite map_join_spec in *.
destruct H, H0; subst.
rewrite map_add_assoc.
eexists; rewrite !map_join_spec; repeat split.
+ eapply compatible_incl; eauto.
rewrite map_add_comm by auto; apply map_incl_add.
+ apply compatible_add_assoc; auto.
- intros ???; rewrite !map_join_spec; intros []; subst.
split; [symmetry | apply map_add_comm]; auto.
- intros.
extensionality k; specialize (H k); specialize (H0 k).
destruct (a k), (b k); auto.
+ apply H0; auto.
+ destruct (H b0) as [_ H']; lapply H'; auto.
+ destruct (H0 b0) as [_ H']; lapply H'; auto.
Defined.
Next Obligation.
auto.
Defined.
Instance fmap_order : PCM_order map_incl.
Proof.
constructor.
- apply map_incl_refl.
- apply map_incl_trans.
- intros ??? Ha Hb; exists (map_add a b); split; simpl.
+ rewrite map_join_spec; split; auto.
eapply map_incl_compatible; eauto.
+ apply map_add_incl; auto.
- split; repeat intro; specialize (H k v); rewrite H; auto.
- split; auto; intros [|]; auto.
Defined.
Lemma map_snap_join : forall m1 m2 p,
ghost_snap m1 p * ghost_snap m2 p = !!(compatible m1 m2) && ghost_snap (map_add m1 m2) p.
Proof.
intros; rewrite ghost_snap_join'.
apply pred_ext.
- Intros m.
rewrite map_join_spec in H; destruct H; subst; entailer!.
- Intros; Exists (map_add m1 m2).
rewrite map_join_spec; entailer!.
Qed.
Lemma map_upd_list_app : forall l1 l2 m, map_upd_list m (l1 ++ l2) = map_upd_list (map_upd_list m l1) l2.
Proof.
induction l1; auto; simpl; intros.
destruct a; auto.
Qed.
Lemma map_upd_list_out : forall l m k, m k = None -> ~In k (map fst l) -> map_upd_list m l k = None.
Proof.
induction l; auto; simpl; intros.
destruct a; apply IHl.
- unfold map_upd; if_tac; auto.
subst; simpl in *; tauto.
- tauto.
Qed.
Lemma compatible_k : forall m1 m2 (Hcompat : compatible m1 m2) k v, m2 k = Some v -> map_add m1 m2 k = Some v.
Proof.
unfold compatible; intros.
unfold map_add.
destruct (m1 k) eqn: Hk; eauto.
Qed.
Lemma map_join_incl_compat : forall m1 m2 m' m'' (Hincl : map_incl m1 m2) (Hjoin : join m2 m' m''),
exists m, join m1 m' m /\ map_incl m m''.
Proof.
intros; apply (@join_comm _ _ (@Perm_G map_PCM)) in Hjoin.
rewrite map_join_spec in Hjoin; destruct Hjoin as [Hjoin]; subst.
do 2 eexists; [|apply map_add_incl_compat; eauto].
symmetry in Hjoin; eapply compatible_incl in Hjoin; eauto.
rewrite map_join_spec; split; auto.
rewrite <- map_add_comm; auto.
Qed.
Lemma map_add_empty : forall m, map_add m empty_map = m.
Proof.
intros; extensionality; unfold map_add, empty_map.
destruct (m x); auto.
Qed.
Lemma map_upd_incl : forall m1 m2 k v, map_incl m1 m2 ->
m2 k = Some v -> map_incl (map_upd m1 k v) m2.
Proof.
unfold map_upd; repeat intro.
destruct (eq_dec k0 k); [congruence | auto].
Qed.
Lemma map_add_single : forall m k v, map_add (singleton k v) m = map_upd m k v.
Proof.
intros; extensionality; unfold map_add, singleton, map_upd; if_tac; auto.
Qed.
Lemma incl_compatible : forall m1 m2, map_incl m1 m2 -> compatible m1 m2.
Proof.
intros; intros ??? Hk1 Hk2.
specialize (H _ _ Hk1); rewrite H in Hk2; inv Hk2; auto.
Qed.
Lemma map_add_redundant : forall m1 m2, map_incl m1 m2 -> map_add m1 m2 = m2.
Proof.
intros; unfold map_add; extensionality k.
destruct (m1 k) eqn: Hk; auto; symmetry; auto.
Qed.
Lemma empty_map_incl : forall m, map_incl empty_map m.
Proof.
repeat intro; discriminate.
Qed.
Lemma map_upd2_incl : forall m1 m2 k v, map_incl m1 m2 -> map_incl (map_upd m1 k v) (map_upd m2 k v).
Proof.
unfold map_upd; repeat intro.
if_tac; auto.
Qed.
Lemma compatible_upd : forall m1 m2 k v, compatible m1 m2 -> m2 k = None ->
compatible (map_upd m1 k v) m2.
Proof.
unfold map_upd; repeat intro.
destruct (eq_dec k0 k); eauto; congruence.
Qed.
Lemma map_add_upd : forall m1 m2 k v, map_upd (map_add m1 m2) k v = map_add (map_upd m1 k v) m2.
Proof.
intros.
rewrite <- !map_add_single.
rewrite map_add_assoc; auto.
Qed.
Notation maps_add l := (fold_right map_add empty_map l).
Lemma in_maps_add : forall l (k : A) (v : B), maps_add l k = Some v -> exists m, In m l /\ m k = Some v.
Proof.
induction l; [discriminate | simpl; intros].
unfold map_add at 1 in H.
destruct (a k) eqn: Ha.
- inv H; eauto.
- destruct (IHl _ _ H) as (? & ? & ?); eauto.
Qed.
Definition all_compatible (l : list (A -> option B)) := forall m1 m2, In m1 l -> In m2 l -> compatible m1 m2.
Lemma all_compatible_cons : forall (m : A -> option B) l, all_compatible (m :: l) -> compatible m (maps_add l) /\ all_compatible l.
Proof.
split; repeat intro.
- eapply in_maps_add in H1 as (m2 & ? & ?).
eapply (H m m2); simpl; eauto.
- eapply (H m1 m2); simpl; eauto.
Qed.
Lemma maps_add_in : forall l m (k : A) (v : B) (Hcompat : all_compatible l),
In m l -> m k = Some v -> maps_add l k = Some v.
Proof.
induction l; [contradiction | simpl; intros].
destruct H.
- subst.
unfold map_add.
replace (m k) with (Some v); auto.
- apply all_compatible_cons in Hcompat as [].
rewrite map_add_comm by auto.
unfold map_add.
erewrite IHl; eauto.
Qed.
Lemma fold_right_maps_add : forall l (e : A -> option B), fold_right map_add e l = map_add (maps_add l) e.
Proof.
induction l; auto; simpl; intros.
rewrite map_add_assoc, IHl; auto.
Qed.
Section Maps_Disjoint.
(* This map instance requires that maps be disjoint, providing e.g. uniqueness of
timestamps for histories. *)
Definition disjoint m1 m2 := forall k v1, m1 k = Some v1 -> m2 k = None.
Global Instance disjoint_comm : Symmetric disjoint.
Proof.
repeat intro.
destruct (x k) eqn: Hx; auto.
specialize (H _ _ Hx); congruence.
Qed.
Lemma disjoint_compatible : forall m1 m2, disjoint m1 m2 -> compatible m1 m2.
Proof.
repeat intro.
specialize (H _ _ H0); congruence.
Qed.
Instance map_disj_join : Join (A -> option B) :=
fun a b c => forall k, match a k, b k with Some v, None | None, Some v => c k = Some v | None, None => c k = None | _, _ => False end.
Lemma map_disj_join_spec : forall m1 m2 m3, join m1 m2 m3 <-> disjoint m1 m2 /\ m3 = map_add m1 m2.
Proof.
unfold join, map_disj_join; simpl; split; intros.
- split.
+ repeat intro.
specialize (H k); rewrite H0 in H.
destruct (m2 k); auto; contradiction.
+ extensionality k; unfold map_add.
specialize (H k).
destruct (m1 k), (m2 k); auto; contradiction.
- destruct H as [Hdisj]; subst; unfold map_add.
specialize (Hdisj k).
destruct (m1 k); [specialize (Hdisj _ eq_refl) as ->; auto|].
destruct (m2 k); auto.
Qed.
Lemma disjoint_incl : forall m1 m2 m (Hcompat : disjoint m2 m) (Hincl : map_incl m1 m2), disjoint m1 m.
Proof.
repeat intro; eauto.
Qed.
Lemma disjoint_add : forall m1 m2 m3, disjoint m1 m2 -> disjoint m1 m3 -> disjoint m1 (map_add m2 m3).
Proof.
unfold disjoint; intros.
unfold map_add.
specialize (H _ _ H1); specialize (H0 _ _ H1).
rewrite H, H0; auto.
Qed.
Global Program Instance map_disj_PCM : Ghost := { valid a := True; Join_G := map_disj_join }.
Next Obligation.
exists (fun _ => empty_map); auto; repeat intro.
simpl.
destruct (t k); auto.
Defined.
Next Obligation.
constructor.
- intros.
extensionality k.
specialize (H k); specialize (H0 k).
destruct (x k), (y k); try congruence; contradiction.
- intros.
rewrite map_disj_join_spec in *.
destruct H, H0; subst.
rewrite map_add_assoc.
eexists; rewrite !map_disj_join_spec; repeat split.
+ eapply disjoint_incl; eauto.
rewrite map_add_comm by (apply disjoint_compatible; auto); apply map_incl_add.
+ apply disjoint_add; auto.
eapply disjoint_incl; eauto.
apply map_incl_add.
- intros ???; rewrite !map_disj_join_spec; intros []; subst.
split; [symmetry | apply map_add_comm, disjoint_compatible]; auto.
- intros.
extensionality k; specialize (H k); specialize (H0 k).
destruct (a k), (b k); auto.
+ destruct (a' k); [contradiction | auto].
+ destruct (a' k); [contradiction | auto].
+ destruct (b' k); [contradiction | auto].
Defined.
Next Obligation.
auto.
Defined.
Lemma disj_join_sub : forall m1 m2, map_incl m1 m2 -> exists m3, join m1 m3 m2.
Proof.
intros; exists (fun x => match m2 x, m1 x with Some v, None => Some v | _, _ => None end).
intro k; specialize (H k).
destruct (m1 k).
- erewrite H; eauto.
- destruct (m2 k); auto.
Qed.
Definition all_disjoint (l : list (A -> option B)) := forall i j, 0 <= i < Zlength l -> 0 <= j < Zlength l ->
i <> j -> disjoint (Znth i l) (Znth j l).
Lemma all_disjoint_compatible : forall l, all_disjoint l -> all_compatible l.
Proof.
unfold all_disjoint, all_compatible; intros.
apply In_Znth in H0 as (i & ? & ?); apply In_Znth in H1 as (j & ? & ?); subst.
destruct (eq_dec i j); [subst; reflexivity|].
apply disjoint_compatible; auto.
Qed.
Lemma all_disjoint_nil : all_disjoint [].
Proof.
repeat intro.
rewrite Zlength_nil in *; lia.
Qed.
Lemma all_disjoint_cons : forall (m : A -> option B) l, all_disjoint (m :: l) <-> disjoint m (maps_add l) /\ all_disjoint l.
Proof.
split.
- split; repeat intro.
+ destruct (maps_add l k) eqn: Hl; auto.
eapply in_maps_add in Hl as (m2 & ? & ?).
apply In_Znth in H1 as (j & ? & ?); subst.
specialize (H 0 (j + 1)).
rewrite Znth_0_cons, Znth_pos_cons, Z.add_simpl_r, Zlength_cons in H by lia.
erewrite H in H2; eauto; lia.
+ specialize (H (i + 1) (j + 1)).
rewrite !Znth_pos_cons, !Z.add_simpl_r, Zlength_cons in H by lia.
eapply H; eauto; lia.
- intros []; repeat intro.
rewrite Zlength_cons in *.
destruct (eq_dec i 0), (eq_dec j 0); subst; try contradiction.
+ rewrite Znth_0_cons in H4; rewrite Znth_pos_cons by lia.
specialize (H _ _ H4).
destruct (Znth _ _ _) eqn: Hj; auto.
apply maps_add_in with (l := l) in Hj; try congruence.
* apply all_disjoint_compatible; auto.
* apply Znth_In; lia.
+ rewrite Znth_0_cons; rewrite Znth_pos_cons in H4 by lia.
destruct (m k) eqn: Hm; auto.
specialize (H _ _ Hm).
apply maps_add_in with (l := l) in H4; try congruence.
* apply all_disjoint_compatible; auto.
* apply Znth_In; lia.
+ rewrite Znth_pos_cons in * by lia.
eapply (H0 (i - 1) (j - 1)); eauto; lia.
Qed.
Lemma all_disjoint_rev1 : forall l, all_disjoint l -> all_disjoint (rev l).
Proof.
unfold all_disjoint; intros.
rewrite Zlength_rev in *.
rewrite !Znth_rev by auto.
apply H; lia.
Qed.
Lemma all_disjoint_rev : forall l, all_disjoint l <-> all_disjoint (rev l).
Proof.
split; [apply all_disjoint_rev1|].
intros ?%all_disjoint_rev1.
rewrite rev_involutive in *; auto.
Qed.
Lemma maps_add_rev : forall l, all_compatible l -> maps_add (rev l) = maps_add l.
Proof.
induction l; auto; simpl; intros.
apply all_compatible_cons in H as [].
rewrite map_add_comm, fold_right_app by auto; simpl.
rewrite map_add_empty.
rewrite (fold_right_maps_add _ a).
rewrite <- IHl; auto.
Qed.
Lemma all_disjoint_snoc : forall m l, all_disjoint (l ++ [m]) <-> disjoint m (maps_add l) /\ all_disjoint l.
Proof.
intros.
replace (l ++ [m]) with (rev (m :: rev l)) by (simpl; rewrite rev_involutive; auto).
rewrite all_disjoint_rev, rev_involutive, all_disjoint_cons, <- all_disjoint_rev.
split; intros []; rewrite maps_add_rev in *; auto; apply all_disjoint_compatible; auto.
Qed.
Lemma empty_map_disjoint : forall m, disjoint empty_map m.
Proof.
repeat intro; discriminate.
Qed.
Definition map_sub (m : A -> option B) k := fun x => if eq_dec x k then None else m x.
Lemma map_upd_sub : forall m (k : A) (v : B), m k = Some v -> map_upd (map_sub m k) k v = m.
Proof.
intros; unfold map_upd, map_sub.
extensionality x.
if_tac; subst; auto.
Qed.
Lemma map_sub_upd : forall m (k : A) (v : B), m k = None -> map_sub (map_upd m k v) k = m.
Proof.
intros; unfold map_upd, map_sub.
extensionality x.
if_tac; subst; auto.
Qed.
Lemma disjoint_sub : forall (m1 m2 : A -> option B) k, disjoint m1 m2 ->
disjoint (map_sub m1 k) m2.
Proof.
unfold map_sub, disjoint; intros.
destruct (eq_dec _ _); [discriminate | eauto].
Qed.
End Maps_Disjoint.
End Maps.
Notation maps_add l := (fold_right map_add empty_map l).
Hint Resolve empty_map_incl empty_map_disjoint all_disjoint_nil : core.
Section GHist.
(* Ghost histories in the style of Nanevsky *)
Context {hist_el : Type}.
Notation hist_part := (nat -> option hist_el).
Definition hist_sub sh (h : hist_part) hr := sh <> Share.bot /\ if eq_dec sh Tsh then h = hr
else map_incl h hr.
Lemma completable_alt : forall sh h hr, @completable map_disj_PCM (Some (sh, h)) hr <-> hist_sub sh h hr.
Proof.
unfold completable, hist_sub; intros; simpl; split.
- intros ([(?, ?)|] & Hcase).
+ destruct Hcase as (? & ? & Hsh & Hj); split; auto.
if_tac.
* subst; apply join_Tsh in Hsh; tauto.
* rewrite map_disj_join_spec in Hj; destruct Hj; subst.
apply map_incl_add.
+ hnf in Hcase.
inv Hcase.
rewrite eq_dec_refl; auto.
- if_tac.
+ intros []; subst; exists None; split; auto.
+ intros [? Hincl].
apply disj_join_sub in Hincl as (h' & ?).
exists (Some (Share.comp sh, h')).
split; auto.
split.
{ intro Hbot; contradiction H.
rewrite <- Share.comp_inv at 1.
rewrite Hbot; apply comp_bot. }
split; [apply comp_join_top | auto].
Qed.
Lemma hist_sub_upd : forall sh h hr t' e (Hsub : hist_sub sh h hr),
hist_sub sh (map_upd h t' e) (map_upd hr t' e).
Proof.
unfold hist_sub; intros.
destruct Hsub; split; auto.
if_tac; subst; auto.
apply map_upd2_incl; auto.
Qed.
Definition ghost_hist (sh : share) (h : hist_part) g :=
own(RA := ref_PCM map_disj_PCM) g (Some (sh, h), None) NoneP.
Lemma ghost_hist_join : forall sh1 sh2 sh h1 h2 p (Hsh : sepalg.join sh1 sh2 sh)
(Hsh1 : sh1 <> Share.bot) (Hsh2 : sh2 <> Share.bot),
ghost_hist sh1 h1 p * ghost_hist sh2 h2 p = !!(disjoint h1 h2) && ghost_hist sh (map_add h1 h2) p.
Proof.
intros; unfold ghost_hist.
erewrite own_op_gen.
apply pred_ext; Intros; apply andp_right, derives_refl; apply prop_right.
- destruct H as (? & [] & ?); simpl in *.
destruct (fst x) as [[]|]; [|contradiction].
rewrite map_disj_join_spec in H; tauto.
- eexists (Some (sh, map_add h1 h2), None); split; [split|]; simpl.
+ rewrite map_disj_join_spec; auto.
+ constructor.
+ split; auto.
intro; subst.
apply join_Bot in Hsh as []; auto.
- intros (? & [] & ?); simpl in *.
destruct (fst x) as [[]|]; [|contradiction].
split; [simpl | constructor].
rewrite map_disj_join_spec in *; tauto.
Qed.
Definition hist_incl (h : hist_part) l := forall t e, h t = Some e -> nth_error l t = Some e.
Definition hist_list (h : hist_part) l := forall t e, h t = Some e <-> nth_error l t = Some e.
Lemma hist_list_inj : forall h l1 l2 (Hl1 : hist_list h l1) (Hl2 : hist_list h l2), l1 = l2.
Proof.
unfold hist_list; intros; apply list_nth_error_eq.
intro j; specialize (Hl1 j); specialize (Hl2 j).
destruct (nth_error l1 j).
- symmetry; rewrite <- Hl2, Hl1; auto.
- destruct (nth_error l2 j); auto.
specialize (Hl2 h0); rewrite Hl1 in Hl2; tauto.
Qed.
Lemma hist_list_nil_inv1 : forall l, hist_list empty_map l -> l = [].
Proof.
unfold hist_list; intros.
destruct l; auto.
specialize (H O h); destruct H as [_ H]; specialize (H eq_refl); discriminate.
Qed.
Lemma hist_list_nil_inv2 : forall h, hist_list h [] -> h = empty_map.
Proof.
unfold hist_list; intros.
extensionality t.
specialize (H t); destruct (h t); auto.
destruct (H h0) as [H' _].
specialize (H' eq_refl); rewrite nth_error_nil in H'; discriminate.
Qed.
Definition ghost_ref l g := EX hr : hist_part, !!(hist_list hr l) &&
own(RA := ref_PCM map_disj_PCM) g (None, Some hr) NoneP.
Lemma hist_next : forall h l (Hlist : hist_list h l), h (length l) = None.
Proof.
intros.
specialize (Hlist (length l)).
destruct (h (length l)); auto.
destruct (Hlist h0) as [H' _].
pose proof (nth_error_Some l (length l)) as (Hlt & _).
lapply Hlt; [lia|].
rewrite H' by auto; discriminate.
Qed.
Definition ghost_hist_ref sh (h r : hist_part) g :=
own(RA := ref_PCM map_disj_PCM) g (Some (sh, h), Some r) NoneP.
Lemma hist_add : forall (sh : share) (h h' : hist_part) e p t' (Hfresh : h' t' = None),
ghost_hist_ref sh h h' p |-- |==> ghost_hist_ref sh (map_upd h t' e) (map_upd h' t' e) p.
Proof.
intros.
erewrite (add_andp (ghost_hist_ref _ _ _ _)) by apply own_valid.
Intros.
destruct H as [? Hcomp]; simpl in *.
rewrite completable_alt in Hcomp; destruct Hcomp as [_ Hcomp].
apply (ref_add(P := map_disj_PCM)) with (b := fun k => if eq_dec k t' then Some e else None).
- repeat intro.
unfold map_upd.
if_tac; [|destruct (h k); auto].
subst; destruct (h t') eqn: Hh; auto.
if_tac in Hcomp; [congruence|].
apply Hcomp in Hh; congruence.
- repeat intro.
unfold map_upd.
if_tac; [|destruct (h' k); auto].
subst; rewrite Hfresh; auto.
- intros ?? Hsub.
exists (map_upd c t' e); repeat intro.
unfold map_upd.
if_tac; [|destruct (c k); auto].
subst; destruct (c t') eqn: Hc; auto.
destruct Hsub as [x Hsub]; hnf in Hsub.
specialize (Hsub t'); rewrite Hc in Hsub.
destruct (x t'); congruence.
Qed.
Lemma hist_incl_nil : forall h, hist_incl empty_map h.
Proof.
repeat intro; discriminate.
Qed.
Lemma hist_list_nil : hist_list empty_map [].
Proof.
split; [discriminate|].
rewrite nth_error_nil; discriminate.
Qed.
Lemma hist_list_snoc : forall h l e, hist_list h l ->
hist_list (map_upd h (length l) e) (l ++ [e]).
Proof.
unfold hist_list, map_upd; split.
- if_tac.
+ intro X; inv X.
rewrite nth_error_app2, minus_diag; auto.
+ rewrite H.
intro X; rewrite nth_error_app1; auto.
rewrite <- nth_error_Some, X; discriminate.
- if_tac.
+ subst; rewrite nth_error_app2, minus_diag; auto.
+ intro X; apply H; rewrite nth_error_app1 in X; auto.
assert (t < length (l ++ [e]))%nat; [|rewrite app_length in *; simpl in *; lia].
rewrite <- nth_error_Some, X; discriminate.
Qed.
Lemma hist_sub_list_incl : forall sh h h' l (Hsub : hist_sub sh h h') (Hlist : hist_list h' l),
hist_incl h l.
Proof.
unfold hist_list, hist_incl; intros.
apply Hlist.
destruct Hsub.
destruct (eq_dec sh Tsh); subst; auto.
Qed.
Lemma hist_sub_Tsh : forall h h', hist_sub Tsh h h' <-> (h = h').
Proof.
intros; unfold hist_sub; rewrite eq_dec_refl; repeat split; auto; tauto.
Qed.
Lemma hist_ref_join : forall sh h l p, sh <> Share.bot ->
ghost_hist sh h p * ghost_ref l p =
EX h' : hist_part, !!(hist_list h' l /\ hist_sub sh h h') && ghost_hist_ref sh h h' p.
Proof.
unfold ghost_hist, ghost_ref; intros; apply pred_ext.
- Intros hr; Exists hr.
erewrite own_op_gen.
+ Intros; apply andp_right, derives_refl; apply prop_right.
split; auto.
destruct H1 as ([g] & [H1 H2] & [? Hcompat]); simpl in *.
destruct g as [[]|]; [|contradiction].
inv H1; inv H2.
apply completable_alt; auto.
+ split; simpl; auto; constructor.
- Intros h'; Exists h'; entailer!.
erewrite <- own_op; [apply derives_refl|].
split; simpl; auto; constructor.
Qed.
Corollary hist_ref_join_nil : forall sh p, sh <> Share.bot ->
ghost_hist sh empty_map p * ghost_ref [] p = ghost_hist_ref sh empty_map empty_map p.
Proof.
intros; rewrite hist_ref_join by auto.
apply pred_ext; entailer!.
- apply hist_list_nil_inv2 in H0; subst; auto.
- Exists (fun _ : nat => @None hist_el); apply andp_right, derives_refl.
apply prop_right; split; [apply hist_list_nil|].
split; auto.
if_tac; auto.
Qed.
Lemma hist_ref_incl : forall sh h h' p, sh <> Share.bot ->
ghost_hist sh h p * ghost_ref h' p |-- !!hist_incl h h'.
Proof.
intros; rewrite hist_ref_join by auto.
Intros l; eapply prop_right, hist_sub_list_incl; eauto.
Qed.
Lemma hist_add' : forall sh h h' e p, sh <> Share.bot ->
ghost_hist sh h p * ghost_ref h' p |-- |==>
ghost_hist sh (map_upd h (length h') e) p * ghost_ref (h' ++ [e]) p.
Proof.
intros; rewrite !hist_ref_join by auto.
Intros hr.
eapply derives_trans; [apply hist_add|].
{ apply hist_next; eauto. }
apply bupd_mono.
Exists (map_upd hr (length h') e); apply andp_right, derives_refl.
apply prop_right; split; [apply hist_list_snoc | apply hist_sub_upd]; auto.
Qed.
Definition newer (l : hist_part) t := forall t', l t' <> None -> (t' < t)%nat.
Lemma newer_trans : forall l t1 t2, newer l t1 -> (t1 <= t2)%nat -> newer l t2.
Proof.
repeat intro.
specialize (H _ H1); lia.
Qed.
Corollary newer_upd : forall l t1 e t2, newer l t1 -> (t1 < t2)%nat ->
newer (map_upd l t1 e) t2.
Proof.
unfold newer, map_upd; intros.
destruct (eq_dec t' t1); [lia|].
eapply newer_trans; eauto; lia.
Qed.
Lemma newer_over : forall h t t', newer h t -> (t <= t')%nat -> h t' = None.
Proof.
intros.
specialize (H t').
destruct (h t'); auto.
lapply H; [lia | discriminate].
Qed.
Corollary newer_out : forall h t, newer h t -> h t = None.
Proof.
intros; eapply newer_over; eauto.
Qed.
Lemma add_new_inj : forall h h' t t' v v' (Ht : newer h t) (Ht' : newer h' t'),
map_upd h t v = map_upd h' t' v' -> h = h' /\ t = t' /\ v = v'.
Proof.
intros.
pose proof (equal_f H t) as Hh.
pose proof (equal_f H t') as Hh'.
pose proof (newer_out _ _ Ht) as Hout.
pose proof (newer_out _ _ Ht') as Hout'.
unfold map_upd in Hh, Hh'.
rewrite eq_dec_refl in Hh, Hh'.
if_tac in Hh.
- inv Hh; clear Hh'.
repeat split; auto.
erewrite <- (map_sub_upd h) by (eapply newer_out; eauto).
rewrite H, map_sub_upd; auto.
- rewrite if_false in Hh' by auto.
lapply (Ht t'); [|rewrite Hh'; discriminate].
lapply (Ht' t); [|rewrite <- Hh; discriminate].
lia.
Qed.
Lemma hist_incl_lt : forall h l, hist_incl h l -> newer h (length l).
Proof.
unfold hist_incl; repeat intro.
specialize (H t').
destruct (h t'); [|contradiction].
specialize (H _ eq_refl).
rewrite <- nth_error_Some, H; discriminate.
Qed.
Corollary hist_list_lt : forall h l, hist_list h l -> newer h (length l).
Proof.
intros; apply hist_incl_lt; repeat intro; apply H; auto.
Qed.
(* We want to be able to remove irrelevant operations from a history, leading to a slightly weaker
correspondence between history and list of operations. *)
Inductive hist_list' : hist_part -> list hist_el -> Prop :=
| hist_list'_nil : hist_list' empty_map []
| hist_list'_snoc : forall h l t e (Hlast : newer h t) (Hrest : hist_list' h l),
hist_list' (map_upd h t e) (l ++ [e]).
Hint Resolve hist_list'_nil : core.
Lemma hist_list'_in : forall h l (Hl : hist_list' h l) e, (exists t, h t = Some e) <-> In e l.
Proof.
induction 1.
- split; [intros (? & ?); discriminate | contradiction].
- intro; subst; split.
+ unfold map_upd; intros (? & Hin); rewrite in_app in *.
destruct (eq_dec x t); [inv Hin; simpl; auto|].
rewrite <- IHHl; eauto.
+ rewrite in_app; intros [Hin | [Heq | ?]]; [| inv Heq | contradiction].
* rewrite <- IHHl in Hin; destruct Hin as (? & ?).
apply newer_out in Hlast.
unfold map_upd; exists x; if_tac; auto; congruence.
* unfold map_upd; eexists; apply eq_dec_refl.
Qed.
Lemma hist_list_weak : forall l h (Hl : hist_list h l), hist_list' h l.
Proof.
induction l using rev_ind; intros.
- apply hist_list_nil_inv2 in Hl; subst; auto.
- destruct (Hl (length l) x) as (_ & H); exploit H.
{ rewrite nth_error_app2, minus_diag by lia; auto. }
intro Hx.
set (h0 := fun k => if eq_dec k (length l) then None else h k).
replace h with (map_upd h0 (length l) x).
constructor.
+ pose proof (hist_list_lt _ _ Hl) as Hn.
intro t; specialize (Hn t).
subst h0; simpl; if_tac; [contradiction|].
intro X; specialize (Hn X); rewrite app_length in Hn; simpl in Hn; lia.
+ apply IHl.
intros t e; specialize (Hl t e).
subst h0; simpl; if_tac.
* split; [discriminate|].
intro X; assert (t < length l)%nat by (rewrite <- nth_error_Some, X; discriminate); lia.
* rewrite Hl; destruct (lt_dec t (length l)).
{ rewrite nth_error_app1 by auto; reflexivity. }
split; intro X.
-- assert (t < length (l ++ [x]))%nat by (rewrite <- nth_error_Some, X; discriminate);
rewrite app_length in *; simpl in *; lia.
-- assert (t < length l)%nat by (rewrite <- nth_error_Some, X; discriminate); contradiction.
+ unfold map_upd; subst h0; simpl.
extensionality k'; if_tac; subst; auto.
Qed.
Lemma hist_list'_add : forall h1 h2 (l : list hist_el) (Hdisj : disjoint h1 h2), hist_list' (map_add h1 h2) l ->
exists l1 l2, Permutation l (l1 ++ l2) /\ hist_list' h1 l1 /\ hist_list' h2 l2.
Proof.
intros.
remember (map_add h1 h2) as h.
revert dependent h2; revert h1; induction H; intros.
- exists [], []; split; [reflexivity|].
assert (h1 = empty_map /\ h2 = empty_map) as [].
{ split; extensionality k; apply equal_f with (x := k) in Heqh; unfold map_add in Heqh;
destruct (h1 k); auto; discriminate. }
subst; split; constructor.
- pose proof (equal_f Heqh t) as Ht.
unfold map_upd, map_add in Ht.
rewrite eq_dec_refl in Ht by auto.
destruct (h1 t) eqn: Hh1.
+ inv Ht.
destruct (IHhist_list' (map_sub h1 t) h2) as (l1 & l2 & ? & ? & ?).
{ apply disjoint_sub; auto. }
{ extensionality k.
apply equal_f with (x := k) in Heqh.
unfold map_upd, map_sub, map_add in *.
if_tac; auto; subst.
apply newer_out in Hlast.
apply Hdisj in Hh1; congruence. }
exists (l1 ++ [h0]), l2; repeat split; auto.
* etransitivity; [|apply Permutation_app_comm].
rewrite app_assoc; apply Permutation_app_tail.
etransitivity; eauto.
apply Permutation_app_comm.
* erewrite <- (map_upd_sub h1 t) by eauto.
constructor; auto.
repeat intro.
unfold map_sub in *.
apply equal_f with (x := t') in Heqh.
unfold map_upd, map_add in Heqh.
apply Hlast.
destruct (eq_dec _ _); [contradiction|].
destruct (h1 t'); [congruence | contradiction].
+ destruct (IHhist_list' h1 (map_sub h2 t)) as (l1 & l2 & ? & ? & ?).
{ symmetry; apply disjoint_sub; symmetry; auto. }
{ extensionality k.
apply equal_f with (x := k) in Heqh.
unfold map_upd, map_sub, map_add in *.
if_tac; auto; subst.
apply newer_out in Hlast.
rewrite Hh1; auto. }
exists l1, (l2 ++ [e]); repeat split; auto.
* rewrite app_assoc; apply Permutation_app_tail; auto.
* erewrite <- (map_upd_sub h2 t) by eauto.
constructor; auto.
repeat intro.
unfold map_sub in *.
apply equal_f with (x := t') in Heqh.
unfold map_upd, map_add in Heqh.
apply Hlast.
destruct (eq_dec _ _); [contradiction|].
destruct (h1 t'); congruence.
Qed.
Lemma ghost_hist_init : @valid (ref_PCM (@map_disj_PCM nat hist_el)) (Some (Tsh, empty_map), Some empty_map).
Proof.
split; simpl; auto.
rewrite completable_alt; split; auto.
rewrite eq_dec_refl; auto.
Qed.
Inductive add_events h : list hist_el -> hist_part -> Prop :=
| add_events_nil : add_events h [] h
| add_events_snoc : forall le h' t e (Hh' : add_events h le h') (Ht : newer h' t),
add_events h (le ++ [e]) (map_upd h' t e).
Hint Resolve add_events_nil : core.
Lemma add_events_1 : forall h t e (Ht : newer h t), add_events h [e] (map_upd h t e).
Proof.
intros; apply (add_events_snoc _ []); auto.
Qed.
Lemma add_events_trans : forall h le h' le' h'' (H1 : add_events h le h') (H2 : add_events h' le' h''),
add_events h (le ++ le') h''.
Proof.
induction 2.
- rewrite app_nil_r; auto.
- rewrite app_assoc; constructor; auto.
Qed.
Lemma add_events_add : forall h le h', add_events h le h' ->
exists h2, h' = map_add h h2 /\ forall t e, h2 t = Some e -> newer h t /\ In e le.
Proof.
induction 1.
- eexists; rewrite map_add_empty; split; auto; discriminate.
- destruct IHadd_events as (h2 & ? & Hh2); subst.
assert (compatible h h2).
{ repeat intro.
destruct (Hh2 _ _ H1) as [Hk _].
specialize (Hk k); lapply Hk; [lia | congruence]. }
assert (newer h t).
{ repeat intro; apply Ht.
unfold map_add.
destruct (h t'); auto. }
rewrite map_add_comm, map_add_upd, map_add_comm; auto.
eexists; split; eauto; intros.
unfold map_upd in *.
rewrite in_app; simpl.
destruct (eq_dec t0 t); [inv H2; auto|].
destruct (Hh2 _ _ H2); auto.
{ apply compatible_upd; [symmetry; auto|].
specialize (H1 t).
destruct (h t); auto.
lapply H1; [lia | discriminate]. }
Qed.
Corollary add_events_dom : forall h le h' t e, add_events h le h' -> h' t = Some e ->
h t = Some e \/ In e le.
Proof.
intros; apply add_events_add in H as (? & ? & Hh2); subst.
unfold map_add in H0.
destruct (h t); [inv H0; auto|].
destruct (Hh2 _ _ H0); auto.
Qed.
Corollary add_events_incl : forall h le h', add_events h le h' -> map_incl h h'.
Proof.
intros; apply add_events_add in H as (? & ? & ?); subst.
apply map_incl_add.
Qed.
Corollary add_events_newer : forall h le h' t, add_events h le h' -> newer h' t -> newer h t.
Proof.
repeat intro.
apply H0.
destruct (h t') eqn: Ht'; [|contradiction].
eapply add_events_incl in Ht' as ->; eauto.
Qed.
Lemma add_events_in : forall h le h' e, add_events h le h' -> In e le ->
exists t, newer h t /\ h' t = Some e.
Proof.
induction 1; [contradiction|].
rewrite in_app; intros [? | [? | ?]]; try contradiction.
- destruct IHadd_events as (? & ? & ?); auto.
do 2 eexists; eauto.
unfold map_upd; if_tac; auto; subst.
specialize (Ht t); rewrite H2 in Ht; lapply Ht; [lia | discriminate].
- subst; unfold map_upd; do 2 eexists; [|apply eq_dec_refl].
eapply add_events_newer; eauto.
Qed.
End GHist.
Hint Resolve hist_incl_nil hist_list_nil hist_list'_nil add_events_nil : core.
(*Hint Resolve ghost_var_precise ghost_var_precise'.*)
Hint Resolve (*ghost_var_init*) master_init (*ghost_map_init*) ghost_hist_init : init.
Ltac ghost_alloc G :=
match goal with |-semax _ (PROPx ?P (LOCALx ?Q (SEPx ?R))) _ _ =>
apply (semax_pre_bupd (PROPx P (LOCALx Q (SEPx ((EX g : _, G g) :: R)))));
[go_lower; rewrite !prop_true_andp by (repeat (split; auto));
rewrite <- emp_sepcon at 1; eapply derives_trans, bupd_frame_r;
apply sepcon_derives, derives_refl; apply own_alloc; auto; simpl; auto with init|] end.
Ltac ghosts_alloc G n :=
match goal with |-semax _ (PROPx ?P (LOCALx ?Q (SEPx ?R))) _ _ =>
apply (semax_pre_bupd (PROPx P (LOCALx Q (SEPx ((EX lg : _, !!(Zlength lg = n) && iter_sepcon G lg) :: R)))));
[go_lower; rewrite !prop_true_andp by (repeat (split; auto));
rewrite <- emp_sepcon at 1; eapply derives_trans, bupd_frame_r;
apply sepcon_derives, derives_refl; apply own_list_alloc'; auto; simpl; auto with init|] end.
Lemma wand_nonexpansive_l: forall P Q n,
approx n (P -* Q)%logic = approx n (approx n P -* Q)%logic.
Proof.
repeat intro.
apply (nonexpansive_super_non_expansive (fun P => predicates_sl.wand P Q)).
split; intros ?? Hshift ??????.
- eapply Hshift; eauto.
apply necR_level in H1; apply necR_level in H2.
apply join_level in H3 as [].
apply (H y0); auto; lia.
- eapply Hshift; eauto.
apply necR_level in H1; apply necR_level in H2.
apply join_level in H3 as [].
apply (H y0); auto; lia.
Qed.
Lemma wand_nonexpansive_r: forall P Q n,
approx n (P -* Q)%logic = approx n (P -* approx n Q)%logic.
Proof.
repeat intro.
apply (nonexpansive_super_non_expansive (fun Q => predicates_sl.wand P Q)).
split; intros ?? Hshift ??????.
- eapply Hshift in H4; eauto.
apply necR_level in H1; apply necR_level in H2.
apply join_level in H3 as [].
apply (H z); auto; lia.
- eapply Hshift in H4; eauto.
apply necR_level in H1; apply necR_level in H2.
apply join_level in H3 as [].
apply (H z); auto; lia.
Qed.
Lemma wand_nonexpansive: forall P Q n,
approx n (P -* Q)%logic = approx n (approx n P -* approx n Q)%logic.
Proof.
intros; rewrite wand_nonexpansive_l, wand_nonexpansive_r; reflexivity.
Qed.
Lemma approx_bupd: forall P n, approx n (|==> P) = (|==> approx n P).
Proof.
intros; apply predicates_hered.pred_ext.
- intros ? [? HP].
change ((own.bupd (approx n P)) a).
intros ? J.
destruct (HP _ J) as (? & ? & m' & ? & ? & ? & ?);
eexists; split; eauto; eexists; split; eauto; repeat split; auto; lia.
- intros ? HP.
destruct (HP nil) as (? & ? & m' & ? & ? & ? & []).
{ eexists; constructor. }
split; [lia|].
change ((own.bupd P) a).
intros ? J.
destruct (HP _ J) as (? & ? & m'' & ? & ? & ? & []);
eexists; split; eauto; eexists; split; eauto; repeat split; auto.
Qed.
Corollary view_shift_nonexpansive : forall P Q n,
approx n (P -* |==> Q)%logic = approx n (approx n P -* |==> approx n Q)%logic.
Proof.
intros.
rewrite wand_nonexpansive, approx_bupd; reflexivity.
Qed.
|
module vorticity_routines
use spherepack_precision, only: &
wp, & ! working precision
ip ! integer precision
use spherepack_interfaces, only: &
scalar_synthesis, &
vector_synthesis
use scalar_synthesis_routines, only: &
ScalarSynthesisUtility, &
shsec, shses, shsgc, shsgs
use vector_synthesis_routines, only: &
VectorSynthesisUtility, &
vhses, vhsec, vhsgc, vhsgs
use type_ScalarHarmonic, only: &
ScalarHarmonic
use type_VectorHarmonic, only: &
VectorHarmonic
! Explicit typing only
implicit none
! Everything is private unless stated otherwise
private
public :: vrtec, vrtes, vrtgc, vrtgs
public :: ivrtec, ivrtes, ivrtgc, ivrtgs
public :: vorticity_lower_utility_routine
public :: invert_vorticity_lower_utility_routine
! Parameters confined to the module
real(wp), parameter :: ZERO = 0.0_wp
real(wp), parameter :: ONE = 1.0_wp
real(wp), parameter :: TWO = 2.0_wp
real(wp), parameter :: SQRT_2 = sqrt(TWO)
! Declare interfaces for submodule implementation
interface
module subroutine vrtec(nlat, nlon, isym, nt, vort, ivrt, jvrt, cr, ci, mdc, ndc, &
wshsec, ierror)
! Dummy arguments
integer(ip), intent(in) :: nlat
integer(ip), intent(in) :: nlon
integer(ip), intent(in) :: isym
integer(ip), intent(in) :: nt
real(wp), intent(out) :: vort(ivrt, jvrt, nt)
integer(ip), intent(in) :: ivrt
integer(ip), intent(in) :: jvrt
real(wp), intent(in) :: cr(mdc, ndc, nt)
real(wp), intent(in) :: ci(mdc, ndc, nt)
integer(ip), intent(in) :: mdc
integer(ip), intent(in) :: ndc
real(wp), intent(in) :: wshsec(:)
integer(ip), intent(out) :: ierror
end subroutine vrtec
module subroutine vrtes(nlat, nlon, isym, nt, vort, ivrt, jvrt, cr, ci, mdc, ndc, &
wshses, ierror)
! Dummy arguments
integer(ip), intent(in) :: nlat
integer(ip), intent(in) :: nlon
integer(ip), intent(in) :: isym
integer(ip), intent(in) :: nt
real(wp), intent(out) :: vort(ivrt, jvrt, nt)
integer(ip), intent(in) :: ivrt
integer(ip), intent(in) :: jvrt
real(wp), intent(in) :: cr(mdc, ndc, nt)
real(wp), intent(in) :: ci(mdc, ndc, nt)
integer(ip), intent(in) :: mdc
integer(ip), intent(in) :: ndc
real(wp), intent(in) :: wshses(:)
integer(ip), intent(out) :: ierror
end subroutine vrtes
module subroutine vrtgc(nlat, nlon, isym, nt, vort, ivrt, jvrt, cr, ci, mdc, ndc, &
wshsgc, ierror)
! Dummy arguments
integer(ip), intent(in) :: nlat
integer(ip), intent(in) :: nlon
integer(ip), intent(in) :: isym
integer(ip), intent(in) :: nt
real(wp), intent(out) :: vort(ivrt, jvrt, nt)
integer(ip), intent(in) :: ivrt
integer(ip), intent(in) :: jvrt
real(wp), intent(in) :: cr(mdc, ndc, nt)
real(wp), intent(in) :: ci(mdc, ndc, nt)
integer(ip), intent(in) :: mdc
integer(ip), intent(in) :: ndc
real(wp), intent(in) :: wshsgc(:)
integer(ip), intent(out) :: ierror
end subroutine vrtgc
module subroutine vrtgs(nlat, nlon, isym, nt, vort, ivrt, jvrt, cr, ci, mdc, ndc, &
wshsgs, ierror)
! Dummy arguments
integer(ip), intent(in) :: nlat
integer(ip), intent(in) :: nlon
integer(ip), intent(in) :: isym
integer(ip), intent(in) :: nt
real(wp), intent(out) :: vort(ivrt, jvrt, nt)
integer(ip), intent(in) :: ivrt
integer(ip), intent(in) :: jvrt
real(wp), intent(in) :: cr(mdc, ndc, nt)
real(wp), intent(in) :: ci(mdc, ndc, nt)
integer(ip), intent(in) :: mdc
integer(ip), intent(in) :: ndc
real(wp), intent(in) :: wshsgs(:)
integer(ip), intent(out) :: ierror
end subroutine vrtgs
module subroutine ivrtec(nlat, nlon, isym, nt, v, w, idvw, jdvw, a, b, mdab, ndab, &
wvhsec, pertrb, ierror)
! Dummy arguments
integer(ip), intent(in) :: nlat
integer(ip), intent(in) :: nlon
integer(ip), intent(in) :: isym
integer(ip), intent(in) :: nt
real(wp), intent(out) :: v(idvw, jdvw, nt)
real(wp), intent(out) :: w(idvw, jdvw, nt)
integer(ip), intent(in) :: idvw
integer(ip), intent(in) :: jdvw
real(wp), intent(in) :: a(mdab, ndab, nt)
real(wp), intent(in) :: b(mdab, ndab, nt)
integer(ip), intent(in) :: mdab
integer(ip), intent(in) :: ndab
real(wp), intent(out) :: wvhsec(:)
real(wp), intent(out) :: pertrb(:)
integer(ip), intent(out) :: ierror
end subroutine ivrtec
module subroutine ivrtes(nlat, nlon, isym, nt, v, w, idvw, jdvw, a, b, mdab, ndab, &
wvhses, pertrb, ierror)
! Dummy arguments
integer(ip), intent(in) :: nlat
integer(ip), intent(in) :: nlon
integer(ip), intent(in) :: isym
integer(ip), intent(in) :: nt
real(wp), intent(out) :: v(idvw, jdvw, nt)
real(wp), intent(out) :: w(idvw, jdvw, nt)
integer(ip), intent(in) :: idvw
integer(ip), intent(in) :: jdvw
real(wp), intent(in) :: a(mdab, ndab, nt)
real(wp), intent(in) :: b(mdab, ndab, nt)
integer(ip), intent(in) :: mdab
integer(ip), intent(in) :: ndab
real(wp), intent(out) :: wvhses(:)
real(wp), intent(out) :: pertrb(:)
integer(ip), intent(out) :: ierror
end subroutine ivrtes
module subroutine ivrtgc(nlat, nlon, isym, nt, v, w, idvw, jdvw, a, b, mdab, ndab, &
wvhsgc, pertrb, ierror)
! Dummy arguments
integer(ip), intent(in) :: nlat
integer(ip), intent(in) :: nlon
integer(ip), intent(in) :: isym
integer(ip), intent(in) :: nt
real(wp), intent(out) :: v(idvw, jdvw, nt)
real(wp), intent(out) :: w(idvw, jdvw, nt)
integer(ip), intent(in) :: idvw
integer(ip), intent(in) :: jdvw
real(wp), intent(in) :: a(mdab, ndab, nt)
real(wp), intent(in) :: b(mdab, ndab, nt)
integer(ip), intent(in) :: mdab
integer(ip), intent(in) :: ndab
real(wp), intent(out) :: wvhsgc(:)
real(wp), intent(out) :: pertrb(:)
integer(ip), intent(out) :: ierror
end subroutine ivrtgc
module subroutine ivrtgs(nlat, nlon, isym, nt, v, w, idvw, jdvw, a, b, mdab, ndab, &
wvhsgs, pertrb, ierror)
! Dummy arguments
integer(ip), intent(in) :: nlat
integer(ip), intent(in) :: nlon
integer(ip), intent(in) :: isym
integer(ip), intent(in) :: nt
real(wp), intent(out) :: v(idvw, jdvw, nt)
real(wp), intent(out) :: w(idvw, jdvw, nt)
integer(ip), intent(in) :: idvw
integer(ip), intent(in) :: jdvw
real(wp), intent(in) :: a(mdab, ndab, nt)
real(wp), intent(in) :: b(mdab, ndab, nt)
integer(ip), intent(in) :: mdab
integer(ip), intent(in) :: ndab
real(wp), intent(out) :: wvhsgs(:)
real(wp), intent(out) :: pertrb(:)
integer(ip), intent(out) :: ierror
end subroutine ivrtgs
end interface
contains
pure subroutine compute_coefficient_multipliers(sqnn)
! Dummy arguments
real(wp), intent(out) :: sqnn(:)
! Local variables
integer(ip) :: n
sqnn = [(sqrt(real(n - 1, kind=wp) * (real(n - 1, kind=wp) + ONE)), n=1, size(sqnn))]
end subroutine compute_coefficient_multipliers
pure function get_perturbation(a, k) &
result(return_value)
! Dummy arguments
real(wp), intent(in) :: a(:, :, :)
integer(ip), intent(in) :: k
real(wp) :: return_value
return_value = a(1, 1, k)/(TWO * SQRT_2)
end function get_perturbation
pure subroutine perform_setup_for_vorticity(nlon, a, b, cr, ci, sqnn)
! Dummy arguments
integer(ip), intent(in) :: nlon
real(wp), intent(out) :: a(:, :, :)
real(wp), intent(out) :: b(:, :, :)
real(wp), intent(in) :: cr(:, :, :)
real(wp), intent(in) :: ci(:, :, :)
real(wp), intent(out) :: sqnn(:)
! Local variables
integer(ip) :: k, n, m
associate (&
order_m => size(a, dim=1), &
degree_n => size(a, dim=2), &
number_of_syntheses => size(a, dim=3) &
)
! Set coefficient multiplyers
call compute_coefficient_multipliers(sqnn)
! Preset coefficients to 0.0
a = ZERO
b = ZERO
! Compute vorticity scalar coefficients for each vector field
do k=1, number_of_syntheses
! Compute m=0 coefficients
do n=2, degree_n
a(1, n, k) = sqnn(n) * cr(1, n, k)
b(1, n, k) = sqnn(n) * ci(1, n, k)
end do
! Compute m > 0 coefficients
do m=2, order_m
do n=m, degree_n
a(m, n, k) = sqnn(n) * cr(m, n, k)
b(m, n, k) = sqnn(n) * ci(m, n, k)
end do
end do
end do
end associate
end subroutine perform_setup_for_vorticity
subroutine vorticity_lower_utility_routine(nlat, nlon, isym, nt, vort, &
cr, ci, wavetable, synth_routine, error_flag)
! Dummy arguments
integer(ip), intent(in) :: nlat
integer(ip), intent(in) :: nlon
integer(ip), intent(in) :: isym
integer(ip), intent(in) :: nt
real(wp), dimension(:,:,:), intent(out) :: vort
real(wp), dimension(:,:,:), intent(in) :: cr, ci
real(wp), intent(in) :: wavetable(:)
procedure(scalar_synthesis) :: synth_routine
integer(ip), intent(out) :: error_flag
block
real(wp) :: sqnn(nlat)
type(ScalarHarmonic) :: harmonic
! Allocate memory
harmonic = ScalarHarmonic(nlat, nlon, nt)
associate( &
ivrt => size(vort, dim=1), &
jvrt => size(vort, dim=2), &
a => harmonic%real_component, &
b => harmonic%imaginary_component, &
order_m => harmonic%ORDER_M, &
degree_n => harmonic%DEGREE_N &
)
call perform_setup_for_vorticity(nlon, a, b, cr, ci, sqnn)
! Synthesize a, b into vort
call synth_routine(nlat, nlon, isym, nt, vort, ivrt, jvrt, &
a, b, order_m, degree_n, wavetable, error_flag)
end associate
! Release memory
call harmonic%destroy()
end block
end subroutine vorticity_lower_utility_routine
pure subroutine perform_setup_for_inversion(isym, ityp, a, b, sqnn, pertrb, cr, ci)
! Dummy arguments
integer(ip), intent(in) :: isym
integer(ip), intent(out) :: ityp
real(wp), intent(in) :: a(:, :, :)
real(wp), intent(in) :: b(:, :, :)
real(wp), intent(out) :: sqnn(:)
real(wp), intent(out) :: pertrb(:)
real(wp), intent(out) :: cr(:, :, :)
real(wp), intent(out) :: ci(:, :, :)
! Local variables
integer(ip) :: k, n, m
associate (&
order_m => size(cr, dim=1), &
degree_n => size(cr, dim=2), &
number_of_syntheses => size(cr, dim=3) &
)
! Preset coefficient multiplyers in vector
call compute_coefficient_multipliers(sqnn)
! Preset cr, ci to 0.0
cr = ZERO
ci = ZERO
! Compute multiple vector fields coefficients
do k=1, number_of_syntheses
! Set vorticity field perturbation adjustment
pertrb(k) = get_perturbation(a, k)
! Compute m = 0 coefficients
do n=2, degree_n
cr(1, n, k) = a(1, n, k)/sqnn(n)
ci(1, n, k) = b(1, n, k)/sqnn(n)
end do
! Compute m > 0 coefficients
do m=2, order_m
do n=m, degree_n
cr(m, n, k) = a(m, n, k)/sqnn(n)
ci(m, n, k) = b(m, n, k)/sqnn(n)
end do
end do
end do
! Set ityp for vector synthesis with divergence=0
select case (isym)
case (0)
ityp = 2
case (1)
ityp = 5
case (2)
ityp = 8
end select
end associate
end subroutine perform_setup_for_inversion
subroutine invert_vorticity_lower_utility_routine(nlat, nlon, isym, nt, &
v, w, a, b, wavetable, perturbation, synth_routine, error_flag)
! Dummy arguments
integer(ip), intent(in) :: nlat
integer(ip), intent(in) :: nlon
integer(ip), intent(in) :: isym
integer(ip), intent(in) :: nt
real(wp), dimension(:,:,:), intent(out) :: v, w
real(wp), dimension(:,:,:), intent(in) :: a, b
real(wp), intent(in) :: wavetable(:)
real(wp), intent(out) :: perturbation(:)
procedure(vector_synthesis) :: synth_routine
integer(ip), intent(out) :: error_flag
block
integer(ip) :: ityp
real(wp) :: sqnn(nlat)
type(VectorHarmonic) :: harmonic
! Allocate memory
harmonic = VectorHarmonic(nlat, nlon, nt)
associate( &
idvw => size(v, dim=1), &
jdvw => size(w, dim=2), &
br => harmonic%polar%real_component, &
bi => harmonic%polar%imaginary_component, &
cr => harmonic%azimuthal%real_component, &
ci => harmonic%azimuthal%imaginary_component, &
order_m => harmonic%ORDER_M, &
degree_n => harmonic%DEGREE_N &
)
call perform_setup_for_inversion(isym, ityp, a, b, sqnn, perturbation, cr, ci)
! Vector synthesize cr, ci into divergence free vector field (v, w)
call synth_routine(nlat, nlon, ityp, nt, v, w, idvw, jdvw, &
br, bi, cr, ci, order_m, degree_n, wavetable, error_flag)
end associate
! Release memory
call harmonic%destroy()
end block
end subroutine invert_vorticity_lower_utility_routine
end module vorticity_routines
|
------------------------------------------------------------------------
-- The Agda standard library
--
-- Definition of and lemmas related to "true infinitely often"
------------------------------------------------------------------------
{-# OPTIONS --without-K --safe #-}
module Data.Nat.InfinitelyOften where
open import Category.Monad using (RawMonad)
open import Level using (0ℓ)
open import Data.Empty using (⊥-elim)
open import Data.Nat
open import Data.Nat.Properties
open import Data.Product as Prod hiding (map)
open import Data.Sum hiding (map)
open import Function
open import Relation.Binary.PropositionalEquality
open import Relation.Nullary using (¬_)
open import Relation.Nullary.Negation using (¬¬-Monad; call/cc)
open import Relation.Unary using (Pred; _∪_; _⊆_)
open RawMonad (¬¬-Monad {p = 0ℓ})
-- Only true finitely often.
Fin : ∀ {ℓ} → Pred ℕ ℓ → Set ℓ
Fin P = ∃ λ i → ∀ j → i ≤ j → ¬ P j
-- A non-constructive definition of "true infinitely often".
Inf : ∀ {ℓ} → Pred ℕ ℓ → Set ℓ
Inf P = ¬ Fin P
-- Fin is preserved by binary sums.
_∪-Fin_ : ∀ {ℓp ℓq P Q} → Fin {ℓp} P → Fin {ℓq} Q → Fin (P ∪ Q)
_∪-Fin_ {P = P} {Q} (i , ¬p) (j , ¬q) = (i ⊔ j , helper)
where
open ≤-Reasoning
helper : ∀ k → i ⊔ j ≤ k → ¬ (P ∪ Q) k
helper k i⊔j≤k (inj₁ p) = ¬p k (begin
i ≤⟨ m≤m⊔n i j ⟩
i ⊔ j ≤⟨ i⊔j≤k ⟩
k ∎) p
helper k i⊔j≤k (inj₂ q) = ¬q k (begin
j ≤⟨ m≤m⊔n j i ⟩
j ⊔ i ≡⟨ ⊔-comm j i ⟩
i ⊔ j ≤⟨ i⊔j≤k ⟩
k ∎) q
-- Inf commutes with binary sums (in the double-negation monad).
commutes-with-∪ : ∀ {P Q} → Inf (P ∪ Q) → ¬ ¬ (Inf P ⊎ Inf Q)
commutes-with-∪ p∪q =
call/cc λ ¬[p⊎q] →
(λ ¬p ¬q → ⊥-elim (p∪q (¬p ∪-Fin ¬q)))
<$> ¬[p⊎q] ∘ inj₁ ⊛ ¬[p⊎q] ∘ inj₂
-- Inf is functorial.
map : ∀ {ℓp ℓq P Q} → P ⊆ Q → Inf {ℓp} P → Inf {ℓq} Q
map P⊆Q ¬fin = ¬fin ∘ Prod.map id (λ fin j i≤j → fin j i≤j ∘ P⊆Q)
-- Inf is upwards closed.
up : ∀ {ℓ P} n → Inf {ℓ} P → Inf (P ∘ _+_ n)
up zero = id
up {P = P} (suc n) = up n ∘ up₁
where
up₁ : Inf P → Inf (P ∘ suc)
up₁ ¬fin (i , fin) = ¬fin (suc i , helper)
where
helper : ∀ j → 1 + i ≤ j → ¬ P j
helper ._ (s≤s i≤j) = fin _ i≤j
-- A witness.
witness : ∀ {ℓ P} → Inf {ℓ} P → ¬ ¬ ∃ P
witness ¬fin ¬p = ¬fin (0 , λ i _ Pi → ¬p (i , Pi))
-- Two different witnesses.
twoDifferentWitnesses
: ∀ {P} → Inf P → ¬ ¬ ∃₂ λ m n → m ≢ n × P m × P n
twoDifferentWitnesses inf =
witness inf >>= λ w₁ →
witness (up (1 + proj₁ w₁) inf) >>= λ w₂ →
return (_ , _ , m≢1+m+n (proj₁ w₁) , proj₂ w₁ , proj₂ w₂)
|
import Oscar.Class.Reflexivity.Function
import Oscar.Class.Transextensionality.Proposequality -- FIXME why not use the instance here?
open import Oscar.Class
open import Oscar.Class.Category
open import Oscar.Class.HasEquivalence
open import Oscar.Class.IsCategory
open import Oscar.Class.IsPrecategory
open import Oscar.Class.Precategory
open import Oscar.Class.Reflexivity
open import Oscar.Class.Transassociativity
open import Oscar.Class.Transextensionality
open import Oscar.Class.Transitivity
open import Oscar.Class.Transleftidentity
open import Oscar.Class.Transrightidentity
open import Oscar.Class.[IsExtensionB]
open import Oscar.Data.Proposequality
open import Oscar.Prelude
open import Oscar.Property.Category.Function
open import Oscar.Property.Setoid.Proposextensequality
open import Oscar.Property.Setoid.Proposequality
module Oscar.Property.Category.Proposequality where
module _
{a} {A : Ø a}
where
instance
𝓣ransassociativityProposequality : Transassociativity.class Proposequality⟦ A ⟧ Proposequality transitivity
𝓣ransassociativityProposequality .⋆ ∅ _ _ = !
{-
module _
{a} {A : Ø a}
where
instance
𝓣ransextensionalityProposequality : Transextensionality.class Proposequality⟦ A ⟧ Proposequality transitivity
𝓣ransextensionalityProposequality .⋆ ∅ ∅ = !
-}
module _
{a} {A : Ø a}
where
instance
𝓣ransleftidentityProposequality : Transleftidentity.class Proposequality⟦ A ⟧ Proposequality ε transitivity
𝓣ransleftidentityProposequality .⋆ {f = ∅} = ∅
module _
{a} {A : Ø a}
where
instance
𝓣ransrightidentityProposequality : Transrightidentity.class Proposequality⟦ A ⟧ Proposequality ε transitivity
𝓣ransrightidentityProposequality .⋆ = ∅
{-
module _
{a} (A : Ø a)
where
instance
HasEquivalenceExtension : ∀ {x y : A} ⦃ _ : [IsExtensionB] B ⦄ → HasEquivalence (Extension B x y) _
HasEquivalenceExtension = ∁ Proposextensequality
-}
module _
{a} {A : Ø a}
where
instance
IsPrecategoryProposequality : IsPrecategory Proposequality⟦ A ⟧ Proposequality transitivity
IsPrecategoryProposequality = ∁
IsCategoryProposequality : IsCategory Proposequality⟦ A ⟧ Proposequality ε transitivity
IsCategoryProposequality = ∁
module _
{a} (A : Ø a)
where
PrecategoryProposequality : Precategory _ _ _
PrecategoryProposequality = ∁ Proposequality⟦ A ⟧ Proposequality transitivity
CategoryProposequality : Category _ _ _
CategoryProposequality = ∁ Proposequality⟦ A ⟧ Proposequality ε transitivity
|
lemma to_fract_diff [simp]: "to_fract (x - y) = to_fract x - to_fract y" |
#include <boost/xpressive/xpressive.hpp>
#include <jsoncons/json.hpp>
#include "modules/songrequest/soundcloud_api.h"
#include "http_client.h"
#include "modules/songrequest/song.h"
#include "tokens.h"
namespace ashbot {
namespace modules {
namespace songrequest {
namespace bx = boost::xpressive;
namespace jc = jsoncons;
bool soundcloud::retrieve_song_data(song& songData)
{
static constexpr char Url[] = "https://api.soundcloud.com/resolve.json?url=%s&client_id=%s";
char actualUrl[512];
snprintf(actualUrl, 512, Url, songData.Link.c_str(), tokens::soundcloud());
http_client client;
client.add_header("Referer", "https://www.ashwini.tv");
http_response response = client.send_request(actualUrl, true, false);
if (response.has_error())
{
if (response.status_code() == 404) songData.Error = song::error::does_not_exist;
else songData.Error = song::error::host_error;
return false;
}
if (response.redirect_url().find("/tracks/") == std::string::npos)
{
songData.Error = song::error::not_a_track;
return false;
}
response = client.send_request(response.redirect_url().c_str(), true);
if (response.has_error())
{
songData.Error = song::error::host_error;
return false;
}
return parse_json(response.data(), songData);
}
std::string soundcloud::strip_soundcloud_link(const std::string& link)
{
static const bx::sregex rx = "http" >> -*bx::as_xpr('s') >> "://soundcloud.com/";
return regex_replace(link, rx, "");
}
bool soundcloud::parse_json(std::string& json, song& song)
{
jc::json jsonObject = jc::json::parse(json);
if (jsonObject["embeddable_by"].as_string() != "all")
{
song.Error = song::error::not_embeddable;
return false;
}
song.Name.assign(jsonObject["title"].as_string());
song.Link.assign(strip_soundcloud_link(jsonObject["permalink_url"].as_string()));
song.Length = std::chrono::seconds(jsonObject["duration"].as_integer());
song.Error = song::error::none;
return true;
}
}
}
}
|
subroutine n0
type mytype
integer i
real x
end type mytype
type (mytype) con
! Note that the typename is required in the syntax.
parameter (con = mytype(1,1.2))
! This can not be a normal function, from this we can conclude that the
! IR should not be building a function to represent the initializer.
! parameter (con = mytype(1,cos(1.2)))
end
|
function combo_test16 ( )
%*****************************************************************************80
%
%% COMBO_TEST16 tests MARRIAGE.
%
% Licensing:
%
% This code is distributed under the GNU LGPL license.
%
% Modified:
%
% 25 January 2011
%
% Author:
%
% John Burkardt
%
n = 5;
%
% PREFER(M,W) is the index of women W on man M's list.
%
prefer = [ ...
2, 1, 2, 1, 5; ...
5, 2, 3, 3, 3; ...
1, 3, 5, 2, 2; ...
3, 4, 4, 4, 1; ...
4, 5, 1, 5, 4 ]';
%
% RANK(W,M) is the index of man M on woman W's list.
%
rank = [ ...
2, 4, 1, 4, 5; ...
4, 3, 3, 2, 2; ...
5, 5, 4, 1, 3; ...
3, 1, 2, 3, 1; ...
1, 2, 5, 5, 4 ]';
fprintf ( 1, ' \n' );
fprintf ( 1, 'COMBO_TEST16\n' );
fprintf ( 1, ' MARRIAGE arranges a set of stable marriages\n' );
fprintf ( 1, ' given a set of preferences.\n' );
[ fiancee, next ] = marriage ( n, prefer, rank );
fprintf ( 1, ' \n' );
fprintf ( 1, ' Man, Wife''s rank, Wife\n' );
fprintf ( 1, ' \n' );
for i = 1 : n
fprintf ( 1, ' %6d %6d %6d\n', i, next(i), prefer(i,next(i)) );
end
fprintf ( 1, ' \n' );
fprintf ( 1, ' Woman, Husband''s rank, Husband\n' );
fprintf ( 1, ' \n' );
for i = 1 : n
fprintf ( 1, ' %6d %6d %6d\n', i, rank(i,fiancee(i)), fiancee(i) );
end
fprintf ( 1, ' \n' );
fprintf ( 1, ' Correct result:\n' );
fprintf ( 1, ' \n' );
fprintf ( 1, ' M:W 1 2 3 4 5\n' );
fprintf ( 1, ' 1 + . . . .\n' );
fprintf ( 1, ' 2 . . . + .\n' );
fprintf ( 1, ' 3 . . . . +\n' );
fprintf ( 1, ' 4 . . + . .\n' );
fprintf ( 1, ' 5 . + . . .\n' );
return
end
|
(* -------------------------------------------------------------------------- *
* Vellvm - the Verified LLVM project *
* *
* Copyright (c) 2017 Steve Zdancewic <[email protected]> *
* *
* This file is distributed under the terms of the GNU General Public *
* License as published by the Free Software Foundation, either version *
* 3 of the License, or (at your option) any later version. *
---------------------------------------------------------------------------- *)
From Coq Require Import
ZArith
List
String
Setoid
Morphisms
Omega
Classes.RelationClasses.
From ExtLib Require Import
Core.RelDec
Programming.Eqv
Programming.Show
Structures.Monads.
From ITree Require Import
ITree
Events.Exception.
From Vellvm Require Import
Util
LLVMAst
MemoryAddress
DynamicTypes
DynamicValues
Error.
(****************************** LLVM Events *******************************)
(**
Vellvm's semantics relies on _Interaction Trees_, a generic data-structure allowing to model
effectful computations.
This file defined the interface provided to the interaction trees, that is the set of
events that a LLVM program can trigger.
These events are then concretely interpreted as a succesion of handler, as defined in the
_Handlers_ folder.
The possible events are:
* Function calls [CallE]
* Calls to intrinsics whose implementation _do not_ depends on the memory [IntrinsicE]
* Interactions with the global environment [GlobalE]
* Interactions with the local environment [LocalE]
* Manipulation of the frame stack for local environments [StackE]
* Interactions with the memory [MemoryE]
* Concretization of a under-defined value [PickE]
* Undefined behaviour [UBE]
* Failure [FailureE]
* Debugging messages [DebugE]
*)
Set Implicit Arguments.
Set Contextual Implicit.
(* Interactions with global variables for the LLVM IR *)
(* YZ: Globals are read-only, except for the initialization. We may want to reflect this in the events. *)
Variant GlobalE (k v:Type) : Type -> Type :=
| GlobalWrite (id: k) (dv: v): GlobalE k v unit
| GlobalRead (id: k): GlobalE k v v.
(* Interactions with local variables for the LLVM IR *)
Variant LocalE (k v:Type) : Type -> Type :=
| LocalWrite (id: k) (dv: v): LocalE k v unit
| LocalRead (id: k): LocalE k v v.
Variant StackE (k v:Type) : Type -> Type :=
| StackPush (args: list (k * v)) : StackE k v unit (* Pushes a fresh environment during a call *)
| StackPop : StackE k v unit. (* Pops it back during a ret *)
(* Undefined behaviour carries a string. *)
Variant UBE : Type -> Type :=
| ThrowUB : string -> UBE void.
(** Since the output type of [ThrowUB] is [void], we can make it an action
with any return type. *)
Definition raiseUB {E : Type -> Type} `{UBE -< E} {X}
(e : string)
: itree E X
:= vis (ThrowUB e) (fun v : void => match v with end).
(* Debug is identical to the "Trace" effect from the itrees library,
but debug is probably a less confusing name for us. *)
Variant DebugE : Type -> Type :=
| Debug : string -> DebugE unit.
(* Utilities to conveniently trigger debug events *)
Definition debug {E} `{DebugE -< E} (msg : string) : itree E unit :=
trigger (Debug msg).
Definition FailureE := exceptE string.
Definition raise {E} {A} `{FailureE -< E} (msg : string) : itree E A :=
throw msg.
Definition lift_err {A B} {E} `{FailureE -< E} (f : A -> itree E B) (m:err A) : itree E B :=
match m with
| inl x => throw x
| inr x => f x
end.
(* YZ : to double check that I did not mixed up the error and the ub positions *)
Definition lift_undef_or_err {A B} {E} `{FailureE -< E} `{UBE -< E} (f : A -> itree E B) (m:undef_or_err A) : itree E B :=
match m with
| mkEitherT m =>
match m with
| inl x => throw x
| inr (inl x) => raiseUB x
| inr (inr x) => f x
end
end.
(* SAZ: TODO: decouple these definitions from the instance of DVALUE and DTYP by using polymorphism
not functors. *)
Module Type LLVM_INTERACTIONS (ADDR : MemoryAddress.ADDRESS).
Global Instance eq_dec_addr : RelDec (@eq ADDR.addr) := RelDec_from_dec _ ADDR.eq_dec.
Global Instance Eqv_addr : Eqv ADDR.addr := (@eq ADDR.addr).
(* The set of dynamic types manipulated by an LLVM program. Mostly
isomorphic to LLVMAst.typ but
- pointers have no further detail
- identified types are not allowed
Questions:
- What to do with Opaque?
*)
Module DV := DynamicValues.DVALUE(ADDR).
Export DV.
(* Generic calls, refined by [denote_mcfg] *)
Variant CallE : Type -> Type :=
| Call : forall (t:dtyp) (f:dvalue) (args:list dvalue), CallE uvalue.
(* Call to an intrinsic whose implementation do not rely on the implementation of the memory model *)
Variant IntrinsicE : Type -> Type :=
| Intrinsic : forall (t:dtyp) (f:string) (args:list dvalue), IntrinsicE dvalue.
(* Interactions with the memory for the LLVM IR *)
Variant MemoryE : Type -> Type :=
| MemPush : MemoryE unit
| MemPop : MemoryE unit
| Alloca : forall (t:dtyp), (MemoryE dvalue)
| Load : forall (t:dtyp) (a:dvalue), (MemoryE uvalue)
| Store : forall (a:dvalue) (v:dvalue), (MemoryE unit)
| GEP : forall (t:dtyp) (v:dvalue) (vs:list dvalue), (MemoryE dvalue)
| ItoP : forall (i:dvalue), (MemoryE dvalue)
| PtoI : forall (a:dvalue), (MemoryE dvalue)
(* | MemoryIntrinsic : forall (t:dtyp) (f:function_id) (args:list dvalue), MemoryE dvalue *)
.
(* An event resolving the non-determinism induced by undef.
The argument _P_ is intended to be a predicate over the set
of dvalues _u_ can take such that if it is not satisfied, the
only possible execution is to raise _UB_.
*)
Variant PickE : Type -> Type :=
| pick (u:uvalue) (P : Prop) : PickE dvalue.
(* The signatures for computations that we will use during the successive stages of the interpretation of LLVM programs *)
(* YZ TODO: The events and handlers are parameterized by the types of key and value.
It's weird for it to be the case if the events are concretely instantiated right here *)
Definition LLVMGEnvE := (GlobalE raw_id dvalue).
Definition LLVMEnvE := (LocalE raw_id uvalue).
Definition LLVMStackE := (StackE raw_id uvalue).
Definition conv_E := MemoryE +' PickE +' UBE +' DebugE +' FailureE.
Definition lookup_E := LLVMGEnvE +' LLVMEnvE.
Definition exp_E := LLVMGEnvE +' LLVMEnvE +' MemoryE +' PickE +' UBE +' DebugE +' FailureE.
Definition lookup_E_to_exp_E : lookup_E ~> exp_E :=
fun T e =>
match e with
| inl1 e => inl1 e
| inr1 e => inr1 (inl1 e)
end.
Definition conv_E_to_exp_E : conv_E ~> exp_E :=
fun T e => inr1 (inr1 e).
Definition instr_E := CallE +' IntrinsicE +' exp_E.
Definition exp_E_to_instr_E : exp_E ~> instr_E:=
fun T e => inr1 (inr1 e).
Definition fun_E := LLVMStackE +' CallE +' IntrinsicE +' exp_E.
Definition instr_E_to_fun_E : instr_E ~> fun_E :=
fun T e => inr1 e.
(* Core effects - no distinction between "internal" and "external" calls. *)
Definition L0 := CallE +' IntrinsicE +' LLVMGEnvE +' (LLVMEnvE +' LLVMStackE) +' MemoryE +' PickE +' UBE +' DebugE +' FailureE.
Definition _funE_to_L0 : fun_E ~> L0 :=
fun R e =>
match e with
| inl1 e' => (inr1 (inr1 (inr1 (inl1 (inr1 e')))))
| inr1 (inl1 e') => inl1 e'
| inr1 (inr1 (inl1 e')) => (inr1 (inl1 e'))
| inr1 (inr1 (inr1 (inl1 e'))) => (inr1 (inr1 (inl1 e')))
| inr1 (inr1 (inr1 (inr1 (inl1 e')))) => (inr1 (inr1 (inr1 (inl1 (inl1 e')))))
| inr1 (inr1 (inr1 (inr1 (inr1 e)))) => (inr1 (inr1 (inr1 (inr1 e))))
end.
(* Distinction made between internal and external calls -- intermediate step in denote_mcfg.
Note that [CallE] appears _twice_ in the [INTERNAL] type. The left one is
meant to be the "internal" call event and the right one is the "external" call event.
The [denote_mcfg] function, which uses [mrec] to tie the recursive knot distinguishes
the two. It re-triggers an unknown [Call] event as an [ExternalCall] (which is just
an injection into the right-hand side.
*)
Definition INTERNAL := CallE +' L0.
Definition ExternalCall t f args : INTERNAL uvalue := (inr1 (inl1 (Call t f args))).
(* This inclusion "assumes" that all call events are internal. The
dispatch in denote_mcfg then interprets some of the calls directly,
if their definitions are known, or it "externalizes" the calls
whose definitions are not known.
*)
Definition L0_to_INTERNAL : L0 ~> INTERNAL :=
fun R e =>
match e with
| inl1 e' => inl1 e'
| inr1 e' => inr1 (inr1 e')
end.
Definition _funE_to_INTERNAL (T:Type) e := @L0_to_INTERNAL T (_funE_to_L0 e).
Definition _exp_E_to_L0 : exp_E ~> L0 :=
fun T e => @_funE_to_L0 T (instr_E_to_fun_E (exp_E_to_instr_E e)).
Definition _failure_UB_to_ExpE : (FailureE +' UBE) ~> exp_E :=
fun T e =>
match e with
| inl1 x => inr1 (inr1 (inr1 (inr1 (inr1 (inr1 x)))))
| inr1 x => inr1 (inr1 (inr1 (inr1 (inl1 x))))
end.
(* For multiple CFG, after interpreting [GlobalE] *)
Definition L1 := CallE +' IntrinsicE +' (LLVMEnvE +' LLVMStackE) +' MemoryE +' PickE +' UBE +' DebugE +' FailureE.
(* For multiple CFG, after interpreting [LocalE] *)
Definition L2 := CallE +' IntrinsicE +' MemoryE +' PickE +' UBE +' DebugE +' FailureE.
(* For multiple CFG, after interpreting [LocalE] and [MemoryE] and [IntrinsicE] that are memory intrinsics *)
Definition L3 := CallE +' PickE +' UBE +' DebugE +' FailureE.
(* For multiple CFG, after interpreting [LocalE] and [MemoryE] and [IntrinsicE] that are memory intrinsics and [PickE]*)
Definition L4 := CallE +' UBE +' DebugE +' FailureE.
Definition L5 := CallE +' DebugE +' FailureE.
Hint Unfold L0 L1 L2 L3 L4 L5.
Definition _failure_UB_to_L4 : (FailureE +' UBE) ~> L4:=
fun T e =>
match e with
| inl1 x => inr1 (inr1 (inr1 x))
| inr1 x => inr1 (inl1 x)
end.
End LLVM_INTERACTIONS.
Module Make(ADDR : MemoryAddress.ADDRESS) <: LLVM_INTERACTIONS(ADDR).
Include LLVM_INTERACTIONS(ADDR).
End Make.
|
import isomorphism
variables (G : Type*) [group G] (𝕜 : Type*) [field 𝕜]
variables (V : Type*) [add_comm_group V] [has_scalar G V] [vector_space 𝕜 V]
variables (W : Type*) [add_comm_group W] [has_scalar G W] [vector_space 𝕜 W]
variables [rep G 𝕜 V] [rep G 𝕜 W]
theorem schur1 (irred_V : irreducible G 𝕜 V) (irred_W : irreducible G 𝕜 W) (φ : hom G 𝕜 V W) :
(φ = 0) ∨ (iso G 𝕜 V W φ) :=
begin
cases irred_V (ker G 𝕜 V W φ) with hV hV,
cases irred_W (im G 𝕜 V W φ) with hW hW,
left,
exact im_trivial_implies_zero G 𝕜 V W φ hW,
right,
exact ⟨ker_trivial_implies_mono G 𝕜 V W φ hV,im_all_implies_epi G 𝕜 V W φ hW⟩,
left,
exact ker_all_implies_zero G 𝕜 V W φ hV,
end
theorem schur2 (irred_V : irreducible G 𝕜 V) (φ : hom G 𝕜 V V) : ∃ k : 𝕜, φ = k • 1 :=
begin
have fact : ∃ k : 𝕜, ∃ v : V, v ≠ 0 ∧ φ v = k • v,sorry,
cases fact with k fact,
use k,
cases fact with v fact,
cases fact with hv hφ,
rw ←sub_eq_zero at hφ,
change (φ - k • 1) v = 0 at hφ,
cases schur1 G 𝕜 V V irred_V irred_V (φ - k • 1) with h h,
exact sub_eq_zero.1 h,
exfalso,
exact hv (h.1 v hφ),
end |
-- Andreas, 2017-01-19, issue #2416, probably regression
-- Give failed for constrained size
-- {-# OPTIONS -v interaction.give:40 #-}
-- {-# OPTIONS -v tc.conv:10 #-}
-- {-# OPTIONS -v tc.conv.coerce:70 #-}
-- {-# OPTIONS -v tc.size:40 #-}
-- {-# OPTIONS -v tc.check.internal:40 #-}
open import Common.Size
open import Common.Equality
data Nat i : Set where
zero : Nat i
suc : (j : Size< i) (n : Nat j) → Nat i
postulate
divideBySuc : Nat ∞ → ∀ k → Nat k → Nat k
div-self : ∀ l (n : Nat l) → divideBySuc n (↑ l) (suc {! l !} n) ≡ suc l zero
-- Cannot solve size constraints
-- [i, n] i ≤ _j_19 i n
-- [i, n] (↑ _j_19 i n) ≤ _i_18 i n
-- [i, n] (↑ _j_20 i n) ≤ _i_18 i n
-- Reason: inconsistent upper bound for 20
-- when checking that zero is a valid argument to a function of type
|
# This file was generated, do not modify it. # hide
@load DecisionTreeRegressor pkg=DecisionTree
boston = dataset("MASS", "Boston")
y, X = unpack(boston, ==(:MedV), col -> true)
train, test = partition(eachindex(y), 0.5, shuffle=true, rng=551);
scitype(X) |
\documentclass[aspectratio=1610,t]{beamer}
% Colors
\usepackage{color}
\definecolor{mainorange}{HTML}{EC811B}
\definecolor{lightgrey}{HTML}{888888}
% Syntax highlighting
\usepackage{minted}
\usepackage{alltt}
\newcommand\hi[1]{{\color{mainorange} \textbf{#1}}}
% Theme
\usetheme[%
subsectionpage=progressbar,
numbering=fraction,
progressbar=foot,
]{metropolis}
% Customization
\setbeamertemplate{section in toc}[sections numbered]
\setbeamerfont{title}{size=\fontsize{30}{30}}
\setbeamerfont{block title}{size=\large}
\newcommand\sep{\textcolor{lightgrey}{\rule{\linewidth}{0.05mm}}}
% Meta
\title{Rust<T>}
\date{5. 9. 2016}
\author{Stefan Schindler (@dns2utf8)}
\institute{Coredump Rapperswil @ Mozilla.ch Meetup}
% Backgrounds
\pgfdeclareimage[width=\paperwidth]{bglight}{background-light.pdf}
\pgfdeclareimage[width=\paperwidth]{bgdark}{background-dark.pdf}
\pgfdeclareimage[width=\paperwidth]{bginverted}{background-inverted.pdf}
\begin{document}
{
\usebackgroundtemplate{\pgfuseimage{bgdark}}
\maketitle
}
% ----------------------------------------------------------------- %
\usebackgroundtemplate{\pgfuseimage{bglight}}
\begin{frame}[noframenumbering]
\frametitle{Outline}
\tableofcontents
\end{frame}
% ----------------------------------------------------------------- %
\usebackgroundtemplate{\pgfuseimage{bglight}}
{
\usebackgroundtemplate{\pgfuseimage{bgdark}}
\section{Admin}
}
\begin{frame}[fragile]{Admin}
\begin{itemize}
\item Slides are online:
\url{https://github.com/coredump-ch/rust-t}
\\ Please report issues in the presentation
\item Examples are included in the \texttt{examples} directory.
\item Slides of Danilo \& Raphael:
\url{https://github.com/coredump-ch/intro-to-rust}
\end{itemize}
\end{frame}
{
\usebackgroundtemplate{\pgfuseimage{bgdark}}
\section{Recap from last time}
}
\begin{frame}[fragile]{Example 2: Generics}
\begin{minted}{rust}
fn min<T: Ord>(a: T, b: T) -> T {
if a <= b { a } else { b }
}
\end{minted}
\pause
\begin{minted}{rust}
...
min(10i8, 20) == 10; // T is i8
min(10, 20u32) == 10; // T is u32
min("abc", "xyz") == "abc"; // &str or Strings are Ord
min("abc".to_string(), "ABC".into()) == "ABC";
min(10i32, "xyz"); // error: mismatched types
\end{minted}
\end{frame}
{
\usebackgroundtemplate{\pgfuseimage{bgdark}}
\section{Simple Generics}
}
\begin{frame}[fragile]{Enum}
\begin{minted}{rust}
enum Colors {
Red,
Green,
Blue,
}
use Colors::*;
fn draw(color: Colors) {
match color {
...
}
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{Enum}
\begin{minted}{rust}
use Colors::*;
fn main() {
draw(Red);
draw(Blue);
}
fn draw(color: Colors) {
match color {
Red => 0xff0000,
Green => 0x00ff00,
Blue => 0x0000ff,
}; // no return
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{Enum: non-exhaustive patterns}
\begin{minted}{rust}
fn draw(color: Colors) {
match color {
Red => 0xff0000,
// Green => 0x00ff00,
Blue => 0x0000ff,
};
}
\end{minted}
\end{frame}
% \pause
% error: non-exhaustive patterns: `Green` not covered [E0004]
\begin{frame}[fragile]{Enum: non-exhaustive patterns}
\begin{minted}[breaklines=true]{sh}
$ cargo run
src/main.rs:15:3: 19:4 error: non-exhaustive patterns: `Green` not covered [E0004]
src/main.rs:15 match color {
src/main.rs:16 Red => 0xff0000,
src/main.rs:17 // Green => 0x00ff00,
src/main.rs:18 Blue => 0x0000ff,
src/main.rs:19 }; // no return
src/main.rs:15:3: 19:4 help: run `rustc --explain E0004` to see a detailed explanation
error: aborting due to previous error
error: Could not compile `enum`.
To learn more, run the command again with --verbose.
\end{minted}
\end{frame}
{
\usebackgroundtemplate{\pgfuseimage{bgdark}}
\section{Into() complex Type}
}
\begin{frame}[fragile]{Into() complex Type: Infrastructure}
\begin{minted}[breaklines=true]{rust}
#[derive(Debug, Clone)]
struct MyObject {
is : Option<isize>,
st : Option<String>,
}
impl Into<MyObject> for isize {
fn into(self) -> MyObject {
MyObject {
is : Some(self),
st : None,
}
}
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{Into() complex Type: Infrastructure}
and the implementation for \texttt{String}:
\begin{minted}[breaklines=true]{rust}
impl Into<MyObject> for String {
fn into(self) -> MyObject {
MyObject {
is : None,
st : Some(self),
}
}
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{Into\(\) complex Type: Usage}
\begin{minted}[breaklines=true]{rust}
let m0 = MyObject { is : Some(42), st : Some("Self Made".into()) };
\end{minted}
\pause
use with \texttt{isize}:
\begin{minted}[breaklines=true]{rust}
let m1 : MyObject = 23.into();
\end{minted}
\pause
with \texttt{to\_owned()} for \texttt{String}:
\begin{minted}[breaklines=true]{rust}
let m2 : MyObject = "Coredump.ch".to_owned().into();
\end{minted}
\end{frame}
{
\usebackgroundtemplate{\pgfuseimage{bgdark}}
\section{Enum impl}
}
\begin{frame}[fragile]{Enum impl: Infrastructure}
\begin{minted}[breaklines=true]{rust}
impl Person {
// A function which takes a `Person` enum as an argument
// and returns nothing.
fn inspect(self) {
// Usage of an `enum` must cover all cases (irrefutable)
// so a `match` is used to branch over it.
match self {
Person::Engineer => { ... },
...
}
}
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{Enum impl: Usage}
if we have an \texttt{Enum}:
\begin{minted}[breaklines=true]{rust}
let rohan = Person::Engineer;
\end{minted}
%\pause
we can then use the method on the instance:
\begin{minted}[breaklines=true]{rust}
rohan.inspect();
\end{minted}
\end{frame}
{
\usebackgroundtemplate{\pgfuseimage{bgdark}}
\section{Transport Data with Enums}
}
\begin{frame}[fragile]{Enum Transport: Infrastructure}
\begin{minted}[breaklines=true]{rust}
#[derive(Debug)]
enum CompoundIndex {
SearchIsize(isize),
SearchString(String),
}
use CompoundIndex::*;
\end{minted}
\end{frame}
\begin{frame}[fragile]{Enum Transport: Usage}
a number:
\begin{minted}[breaklines=true]{rust}
let number = SearchIsize(42);
\end{minted}
\pause
a \texttt{String}:
\begin{minted}[breaklines=true]{rust}
let string = SearchString("Coredump.ch".into());
\end{minted}
\pause
an empty \texttt{String}:
\begin{minted}[breaklines=true]{rust}
let string = SearchString("".into());
\end{minted}
\end{frame}
{
\usebackgroundtemplate{\pgfuseimage{bgdark}}
\section{Search a Vector<T>}
}
\begin{frame}[fragile]{Search a Vector<T>: Infrastructure}
\begin{minted}[breaklines=true]{rust}
fn find(haystack : &Vec<MyObject>, needle : &CompoundIndex) -> Option<MyObject> {
for ref hay in haystack {
match needle {
&SearchIsize(ref needle) => {
if let Some(ref is) = hay.is {
if is == needle {
return Some( (*hay).clone() );
}
}
},
...
} // end match
}
None
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{Search a Vector<T>: Infrastructure}
\begin{minted}[breaklines=true]{rust}
fn find(haystack : &Vec<MyObject>, needle : &CompoundIndex) -> Option<MyObject> {
for ref hay in haystack {
match needle {
...
&SearchString(ref needle) => {
if let Some(ref st) = hay.st {
if st == needle {
return Some( (*hay).clone() );
}
}
},
} // end match
}
None
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{Search a Vector<T>: Usage}
Prepare the \texttt{Vector<MyObject>}:
\begin{minted}[breaklines=true]{rust}
let m0 = MyObject { is : Some(42), st : Some("Self Made".into()) };
let m1 : MyObject = 23.into();
let m2 : MyObject = "Coredump.ch".to_owned().into();
let v = vec![m0, m1, m2];
\end{minted}
\end{frame}
\begin{frame}[fragile]{Search a Vector<T>: Usage}
and search it:
\begin{minted}[breaklines=true]{rust}
let number = SearchIsize(42);
println!("\n Find with number: {:?} => {:?}", number, find(&v, &number));
let string = SearchString("".into());
println!("\n Find with String: {:?} => {:?}", string, find(&v, &string));
let string = SearchString("Coredump.ch".into());
println!("\n Find with String: {:?} => {:?}", string, find(&v, &string));
\end{minted}
\end{frame}
\begin{frame}[fragile]{Search a Vector<T>: Output}
\begin{minted}[breaklines=true]{sh}
Find with number: SearchIsize(42) => Some(MyObject { is: Some(42), st: Some("Self Made") })
Find with String: SearchString("") => None
Find with String: SearchString("Coredump.ch") => Some(MyObject { is: None, st: Some("Coredump.ch") })
\end{minted}
\end{frame}
{
\usebackgroundtemplate{\pgfuseimage{bgdark}}
\section{Sending Commands over Channels}
}
\begin{frame}[fragile]{Sending Commands over Channels}
Infrastructure:
\begin{minted}[breaklines=true]{rust}
use std::sync::mpsc::channel;
let (tx, rx) = channel();
\end{minted}
\pause
Usage:
\begin{minted}[breaklines=true]{rust}
tx.send(42).unwrap();
assert_eq!(42, rx.recv().unwrap());
\end{minted}
\pause
Works with complex Types:
\begin{minted}[breaklines=true]{rust}
let (tx, rx) = channel::<MyCommands<u64>>();
\end{minted}
\end{frame}
\begin{frame}[fragile]{Massive errors}
Natural occurences:
\begin{minted}[breaklines=true]{rust}
let n = 10;
let y = (["a", "b"])[n]; // panics
my_io_function().unwrap() // maybe panics
\end{minted}
\pause
Synthesized:
\begin{minted}[breaklines=true]{rust}
panic!("with a message")
\end{minted}
\end{frame}
\begin{frame}[fragile]{Handling panic: 1/3}
\begin{minted}[breaklines=true]{rust}
let pool = ThreadPool::new(4);
let (tx, rx) = channel();
for i in 0..8 {
let tx = tx.clone();
pool.execute(move|| {
// -- panicking work here --
});
}
assert_eq!(24, rx.iter().take(8).fold(0, |a, b| a + b));
\end{minted}
\end{frame}
\begin{frame}[fragile]{Handling panic: 2/3}
\begin{minted}[breaklines=true]{rust}
let rx = {
let (tx, rx) = channel();
for i in 0..8 {
let tx = tx.clone();
pool.execute(move|| {
// -- panicking work here --
});
}
rx
};
assert_eq!(24, rx.iter().take(8).fold(0, |a, b| a + b));
\end{minted}
\end{frame}
\begin{frame}[fragile]{Handling panic: 3/3}
\begin{minted}[breaklines=true]{rust}
let rx = {
let (tx, rx) = channel();
for i in 0..8 { let tx = tx.clone();
pool.execute(move|| {
if i == 4 { // -- unexpected failure added here --
panic!("unexpected panic");
}
tx.send(i).unwrap();
});
}
rx
};
// And now this code waits for all the senders to be destructed or the first 8 values:
assert_eq!(24, rx.iter().take(8).fold(0, |a, b| a + b));
\end{minted}
\end{frame}
{
\usebackgroundtemplate{\pgfuseimage{bgdark}}
\section{Day-Time-Tools}
}
\begin{frame}[fragile]{Day-Time-Tools}
Ease your day
\begin{itemize}[<+- | alert@+>]
\item git
\item cargo \raisebox{-.25\height}{\includegraphics[height=0.5cm]{cargo.png}}
\item cargo outdated \\ \includegraphics[height=4cm]{cargo_outdated.png}
\end{itemize}
\end{frame}
{
\usebackgroundtemplate{\pgfuseimage{bgdark}}
\section{Demotime}
}
{
\usebackgroundtemplate{\pgfuseimage{bgdark}}
\section{Questions?}
}
% ----------------------------------------------------------------- %
{
\usebackgroundtemplate{\pgfuseimage{bginverted}}
\begin{frame}[standout]
\begin{centering}
{\Huge Thank you!}\\
{\normalsize www.coredump.ch}
\end{centering}
\end{frame}
}
\end{document}
|
JAKARTA ~ Indonesia and Pakistan have agreed to work together to stamp out radical Islam as part of efforts to stop future deadly militant attacks, state media said.
They have formed a joint working group amid concerns some Indonesians have attended Islamic schools in Pakistan and have later undergone training in extremist camps, said Indonesian senior anti-terror officer Ansyaad Mbai.
“We will work together in a joint working group to find, among others, a new method to eradicate radicalism in Islam that often becomes the root of terrorism,” Mbai was quoted as saying by the Antara news agency.
He did not say whether Pakistani officials had visited the Southeast Asian nation recently to formalize the agreement, nor who would make up the group.
Mbai said Indonesia had formed similar working groups with Saudi Arabia and Turkey. |
http://docs.idris-lang.org/en/latest/tutorial/miscellany.html
> module literate
This is a comment. The main program is below
> main : IO ()
> main = putStrLn "Hello literate world!\n"
|
# Built-in
L := List([1 .. 100], n -> Random(1, 10));
MaximumList(L);
# 10
|
#!/usr/bin/python3
from __future__ import print_function
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from autobahn.wamp.serializer import MsgPackSerializer
from autobahn.wamp.types import ComponentConfig
from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner
import argparse
import random
import math
import sys
import base64
import numpy as np
import helper
# reset_reason
NONE = 0
GAME_START = 1
SCORE_MYTEAM = 2
SCORE_OPPONENT = 3
GAME_END = 4
DEADLOCK = 5
GOALKICK = 6
CORNERKICK = 7
PENALTYKICK = 8
HALFTIME = 9
EPISODE_END = 10
# game_state
STATE_DEFAULT = 0
STATE_KICKOFF = 1
STATE_GOALKICK = 2
STATE_CORNERKICK = 3
STATE_PENALTYKICK = 4
# coordinates
MY_TEAM = 0
OP_TEAM = 1
BALL = 2
X = 0
Y = 1
TH = 2
ACTIVE = 3
TOUCH = 4
class Received_Image(object):
def __init__(self, resolution, colorChannels):
self.resolution = resolution
self.colorChannels = colorChannels
# need to initialize the matrix at timestep 0
self.ImageBuffer = np.zeros((resolution[1], resolution[0], colorChannels)) # rows, columns, colorchannels
def update_image(self, received_parts):
self.received_parts = received_parts
for i in range(0, len(received_parts)):
dec_msg = base64.b64decode(self.received_parts[i].b64, '-_') # decode the base64 message
np_msg = np.fromstring(dec_msg, dtype=np.uint8) # convert byte array to numpy array
reshaped_msg = np_msg.reshape((self.received_parts[i].height, self.received_parts[i].width, 3))
for j in range(0, self.received_parts[i].height): # y axis
for k in range(0, self.received_parts[i].width): # x axis
self.ImageBuffer[j + self.received_parts[i].y, k + self.received_parts[i].x, 0] = reshaped_msg[
j, k, 0] # blue channel
self.ImageBuffer[j + self.received_parts[i].y, k + self.received_parts[i].x, 1] = reshaped_msg[
j, k, 1] # green channel
self.ImageBuffer[j + self.received_parts[i].y, k + self.received_parts[i].x, 2] = reshaped_msg[
j, k, 2] # red channel
class SubImage(object):
def __init__(self, x, y, width, height, b64):
self.x = x
self.y = y
self.width = width
self.height = height
self.b64 = b64
class Frame(object):
def __init__(self):
self.time = None
self.score = None
self.reset_reason = None
self.game_state = None
self.subimages = None
self.coordinates = None
self.half_passed = None
class Component(ApplicationSession):
"""
AI Base + Rule Based Algorithm
"""
def __init__(self, config):
ApplicationSession.__init__(self, config)
def printConsole(self, message):
print(message)
sys.__stdout__.flush()
def onConnect(self):
self.join(self.config.realm)
@inlineCallbacks
def onJoin(self, details):
##############################################################################
def init_variables(self, info):
# Here you have the information of the game (virtual init() in random_walk.cpp)
# List: game_time, number_of_robots
# field, goal, penalty_area, goal_area, resolution Dimension: [x, y]
# ball_radius, ball_mass,
# robot_size, robot_height, axle_length, robot_body_mass, ID: [0, 1, 2, 3, 4]
# wheel_radius, wheel_mass, ID: [0, 1, 2, 3, 4]
# max_linear_velocity, max_torque, codewords, ID: [0, 1, 2, 3, 4]
self.game_time = info['game_time']
self.number_of_robots = info['number_of_robots']
self.field = info['field']
self.goal = info['goal']
self.penalty_area = info['penalty_area']
# self.goal_area = info['goal_area']
self.resolution = info['resolution']
self.ball_radius = info['ball_radius']
# self.ball_mass = info['ball_mass']
self.robot_size = info['robot_size']
# self.robot_height = info['robot_height']
# self.axle_length = info['axle_length']
# self.robot_body_mass = info['robot_body_mass']
# self.wheel_radius = info['wheel_radius']
# self.wheel_mass = info['wheel_mass']
self.max_linear_velocity = info['max_linear_velocity']
# self.max_torque = info['max_torque']
# self.codewords = info['codewords']
self.colorChannels = 3
self.end_of_frame = False
self.image = Received_Image(self.resolution, self.colorChannels)
self.cur_posture = []
self.cur_ball = []
self.prev_posture = []
self.prev_ball = []
self.previous_frame = Frame()
self.received_frame = Frame()
self.cur_count = 0
self.end_count = 0
self.prev_sender = None
self.sender = None
self.touch = [False,False,False,False,False]
self.prev_receiver = None
self.receiver = None
self.def_idx = 0
self.atk_idx = 0
self.closest_order = []
self.player_state = [None,None,None,None,None]
self.wheels = [0 for _ in range(10)]
return
##############################################################################
try:
info = yield self.call(u'aiwc.get_info', args.key)
except Exception as e:
self.printConsole("Error: {}".format(e))
else:
try:
self.sub = yield self.subscribe(self.on_event, args.key)
except Exception as e2:
self.printConsole("Error: {}".format(e2))
init_variables(self, info)
try:
yield self.call(u'aiwc.ready', args.key)
except Exception as e:
self.printConsole("Error: {}".format(e))
else:
self.printConsole("I am ready for the game!")
# set the left and right wheel velocities of robot with id 'id'
# 'max_velocity' scales the velocities up to the point where at least one of wheel is operating at max velocity
def set_wheel_velocity(self, id, left_wheel, right_wheel, max_velocity):
multiplier = 1
# wheel velocities need to be scaled so that none of wheels exceed the maximum velocity available
# otherwise, the velocity above the limit will be set to the max velocity by the simulation program
# if that happens, the velocity ratio between left and right wheels will be changed that the robot may not execute
# turning actions correctly.
if (abs(left_wheel) > self.max_linear_velocity[id] or abs(right_wheel) > self.max_linear_velocity[
id] or max_velocity):
if (abs(left_wheel) > abs(right_wheel)):
multiplier = self.max_linear_velocity[id] / abs(left_wheel)
else:
multiplier = self.max_linear_velocity[id] / abs(right_wheel)
self.wheels[2 * id] = left_wheel * multiplier
self.wheels[2 * id + 1] = right_wheel * multiplier
# let the robot with id 'id' move to a target position (x, y)
# the trajectory to reach the target position is determined by several different parameters
def set_target_position(self, id, x, y, scale, mult_lin, mult_ang, max_velocity):
damping = 0.35
ka = 0
sign = 1
# calculate how far the target position is from the robot
dx = x - self.cur_posture[id][X]
dy = y - self.cur_posture[id][Y]
d_e = math.sqrt(math.pow(dx, 2) + math.pow(dy, 2))
# calculate how much the direction is off
desired_th = (math.pi / 2) if (dx == 0 and dy == 0) else math.atan2(dy, dx)
d_th = desired_th - self.cur_posture[id][TH]
while (d_th > math.pi):
d_th -= 2 * math.pi
while (d_th < -math.pi):
d_th += 2 * math.pi
# based on how far the target position is, set a parameter that
# decides how much importance should be put into changing directions
# farther the target is, less need to change directions fastly
if (d_e > 1):
ka = 17 / 90
elif (d_e > 0.5):
ka = 19 / 90
elif (d_e > 0.3):
ka = 21 / 90
elif (d_e > 0.2):
ka = 23 / 90
else:
ka = 25 / 90
# if the target position is at rear of the robot, drive backward instead
if (d_th > helper.d2r(95)):
d_th -= math.pi
sign = -1
elif (d_th < helper.d2r(-95)):
d_th += math.pi
sign = -1
# if the direction is off by more than 85 degrees,
# make a turn first instead of start moving toward the target
if (abs(d_th) > helper.d2r(85)):
self.set_wheel_velocity(id, -mult_ang * d_th, mult_ang * d_th, False)
# otherwise
else:
# scale the angular velocity further down if the direction is off by less than 40 degrees
if (d_e < 5 and abs(d_th) < helper.d2r(40)):
ka = 0.1
ka *= 4
# set the wheel velocity
# 'sign' determines the direction [forward, backward]
# 'scale' scales the overall velocity at which the robot is driving
# 'mult_lin' scales the linear velocity at which the robot is driving
# larger distance 'd_e' scales the base linear velocity higher
# 'damping' slows the linear velocity down
# 'mult_ang' and 'ka' scales the angular velocity at which the robot is driving
# larger angular difference 'd_th' scales the base angular velocity higher
# if 'max_velocity' is true, the overall velocity is scaled to the point
# where at least one wheel is operating at maximum velocity
self.set_wheel_velocity(id,
sign * scale * (mult_lin * (
1 / (1 + math.exp(-3 * d_e)) - damping) - mult_ang * ka * d_th),
sign * scale * (mult_lin * (
1 / (1 + math.exp(-3 * d_e)) - damping) + mult_ang * ka * d_th),
max_velocity)
# copy coordinates from frames to different variables just for convenience
def get_coord(self):
self.cur_ball = self.received_frame.coordinates[BALL]
self.cur_posture = self.received_frame.coordinates[MY_TEAM]
self.cur_posture_op = self.received_frame.coordinates[OP_TEAM]
self.prev_ball = self.previous_frame.coordinates[BALL]
self.prev_posture = self.previous_frame.coordinates[MY_TEAM]
self.prev_posture_op = self.previous_frame.coordinates[OP_TEAM]
# find a defender and a forward closest to the ball
def find_closest_robot(self):
# find the closest defender
min_idx = 0
min_dist = 9999.99
def_dist = 9999.99
all_dist = []
for i in [1, 2]:
measured_dist = helper.dist(self.cur_ball[X], self.cur_posture[i][X], self.cur_ball[Y],
self.cur_posture[i][Y])
all_dist.append(measured_dist)
if (measured_dist < min_dist):
min_dist = measured_dist
def_dist = min_dist
min_idx = i
self.def_idx = min_idx
# find the closest forward
min_idx = 0
min_dist = 9999.99
atk_dist = 9999.99
for i in [3, 4]:
measured_dist = helper.dist(self.cur_ball[X], self.cur_posture[i][X], self.cur_ball[Y],
self.cur_posture[i][Y])
all_dist.append(measured_dist)
if (measured_dist < min_dist):
min_dist = measured_dist
atk_dist = min_dist
min_idx = i
self.atk_idx = min_idx
# record the robot closer to the ball between the two too
self.closest_order = np.argsort(all_dist) + 1
# predict where the ball will be located after 'steps' steps
def predict_ball_location(self, steps):
dx = self.cur_ball[X] - self.prev_ball[X]
dy = self.cur_ball[Y] - self.prev_ball[Y]
return [self.cur_ball[X] + steps * dx, self.cur_ball[Y] + steps * dy]
# let the robot face toward specific direction
def face_specific_position(self, id, x, y):
dx = x - self.cur_posture[id][X]
dy = y - self.cur_posture[id][Y]
desired_th = (math.pi / 2) if (dx == 0 and dy == 0) else math.atan2(dy, dx)
self.angle(id, desired_th)
# returns the angle toward a specific position from current robot posture
def direction_angle(self, id, x, y):
dx = x - self.cur_posture[id][X]
dy = y - self.cur_posture[id][Y]
return ((math.pi / 2) if (dx == 0 and dy == 0) else math.atan2(dy, dx))
# turn to face 'desired_th' direction
def angle(self, id, desired_th):
mult_ang = 0.4
d_th = desired_th - self.cur_posture[id][TH]
d_th = helper.trim_radian(d_th)
# the robot instead puts the direction rear if the angle difference is large
if (d_th > helper.d2r(95)):
d_th -= math.pi
sign = -1
elif (d_th < helper.d2r(-95)):
d_th += math.pi
sign = -1
self.set_wheel_velocity(id, -mult_ang * d_th, mult_ang * d_th, False)
# checks if a certain position is inside the penalty area of 'team'
def in_penalty_area(self, obj, team):
if (abs(obj[Y]) > self.penalty_area[Y] / 2):
return False
if (team == MY_TEAM):
return (obj[X] < -self.field[X] / 2 + self.penalty_area[X])
else:
return (obj[X] > self.field[X] / 2 - self.penalty_area[X])
# check if the ball is coming toward the robot
def ball_coming_toward_robot(self, id):
x_dir = abs(self.cur_posture[id][X] - self.prev_ball[X]) > abs(self.cur_posture[id][X] - self.cur_ball[X])
y_dir = abs(self.cur_posture[id][Y] - self.prev_ball[Y]) > abs(self.cur_posture[id][Y] - self.cur_ball[Y])
# ball is coming closer
if (x_dir and y_dir):
return True
else:
return False
# check if the robot with id 'id' has a chance to shoot
def shoot_chance(self, id):
dx = self.cur_ball[X] - self.cur_posture[id][X]
dy = self.cur_ball[Y] - self.cur_posture[id][Y]
# if the ball is located further on left than the robot, it will be hard to shoot
if (dx < 0):
return False
# if the robot->ball direction aligns with opponent's goal, the robot can shoot
y = (self.field[X] / 2 - self.cur_ball[X]) * dy / dx + self.cur_posture[id][Y]
if (abs(y) < self.goal[Y] / 2):
return True
else:
return False
# check if sender/receiver pair should be reset
def reset_condition(self) :
# if the time is over, setting is reset
if (self.end_count > 0 and self.end_count - self.cur_count < 0) :
return True
# if there is no sender and receiver is not in shoot chance, setting is cleared
if not self.sender is None :
if not self.shoot_chance(self.sender) :
return True
return False
# check if a sender can be selected
def set_sender_condition(self) :
for i in range(1,5) :
# if this robot is near the ball, it will be a sender candidate
dist = helper.dist(self.cur_posture[i][X], self.cur_ball[X], self.cur_posture[i][Y], self.cur_ball[Y])
if dist < 0.5 and self.cur_posture[i][ACTIVE]: return True
return False
# check if a receiver should be selected
def set_receiver_condition(self) :
# if a sender exists, any other robots can be receiver candidates
if self.sender != None and self.receiver == None: return True
return False
# select a sender
def set_sender(self, _player_list):
distance_list = []
for sender in _player_list :
predict_ball = self.predict_ball_location(3)
ball_distance = helper.dist(predict_ball[X], self.cur_posture[sender][X], predict_ball[Y], self.cur_posture[sender][Y])
distance_list.append(ball_distance)
# if the distance between ball and sender is less than 1, choose the closest robot as the sender
if min(distance_list) < 1.0 :
return distance_list.index(min(distance_list)) + 1
# otherwise, there is no sender
return None
# select a receiver
def set_receiver(self, _player_list):
receiver_op_dist_list = []
for receiver in _player_list :
temp_receiver_op_dist_list = []
# the sender is not a receiver candidate
if receiver == self.sender :
receiver_op_dist_list.append(999)
continue
# the distance between the robot and opponents
for op in range(1, 5) : #[1,2,3,4]
op_distance = helper.dist(self.cur_posture[receiver][X], self.cur_posture_op[op][X], self.cur_posture[receiver][Y], self.cur_posture_op[op][Y])
temp_receiver_op_dist_list.append(op_distance)
# save the shortest distance between this robot and one of opponents
receiver_op_dist_list.append(min(temp_receiver_op_dist_list))
receiver_ball_list = []
for r in receiver_op_dist_list :
# if the minimum distance between player and opponent's player is less than 0.5, this robot cannot be receiver
if r < 0.5 or r == 999:
receiver_ball_list.append(999)
continue
id = receiver_op_dist_list.index(r) + 1
receiver_ball_distance = helper.dist(self.cur_ball[X], self.cur_posture[id][X], self.cur_ball[Y], self.cur_posture[id][Y])
receiver_ball_list.append(receiver_ball_distance)
if min(receiver_ball_list) < 999 :
min_id = receiver_ball_list.index(min(receiver_ball_list)) + 1
return min_id
return None
def pass_ball(self):
if self.prev_sender == self.receiver or self.prev_receiver == self.sender :# and not None in [self.prev_sender, self.prev_receiver, self.sender, self.receiver] :
self.sender = self.prev_sender
self.receiver = self.prev_receiver
self.receive_ball()
self.send_ball()
self.prev_sender = self.sender
self.prev_receiver = self.receiver
def send_ball(self) :
if self.sender == None :
return
goal_dist = helper.dist(4.0, self.cur_posture[self.sender][X], 0, self.cur_posture[self.sender][Y])
# if the sender has a shoot chance, it tries to shoot
if self.shoot_chance(self.sender) :
if goal_dist > 0.3 * self.field[X] / 2:
self.actions(self.sender, 'dribble',refine=True)
return
else :
self.actions(self.sender, 'kick')
return
# if the receiver exists, get the distance between the sender and the receiver
sender_receiver_dist = None
if not self.receiver == None :
sender_receiver_dist = helper.dist(self.cur_posture[self.sender][X], self.cur_posture[self.receiver][X],self.cur_posture[self.sender][Y], self.cur_posture[self.receiver][Y])
# if the sender is close to the receiver, the sender kicks the ball
if not sender_receiver_dist == None :
if sender_receiver_dist < 0.3 and not self.cur_posture[self.receiver][TOUCH]:
self.actions(self.sender, 'kick')
return
ift, theta_diff = self.is_facing_target(self.sender, self.cur_ball[X], self.cur_ball[Y])
if not ift :
# after the sender kicks, it stops
if theta_diff > math.pi * 3/4 :
self.actions(self.sender, None)
return
else :
self.actions(self.sender, 'follow',refine=True)
return
# if the ball is in front of the sender and sender is moving backward
if self.cur_posture[self.sender][X] < - 0.8 * self.field[X] / 2 :
if self.cur_posture[self.sender][X] - self.prev_posture[self.sender][X] < 0 :
self.actions(self.sender, 'backward')
self.actions(self.sender, 'dribble',refine=True)
return
def receive_ball(self) :
# if receiver does not exist, do nothing
if self.receiver == None :
return
goal_dist = helper.dist(4.0, self.cur_posture[self.receiver][X], 0, self.cur_posture[self.receiver][Y])
# if sender is in shoot chance, receiver does nothing(reset)
if self.shoot_chance(self.sender) :
self.actions(self.receiver,None)
return
# if receiver is in shoot chance, receiver try to shoot
if self.shoot_chance(self.receiver) :
if goal_dist > 0.3 * self.field[X] / 2:
self.actions(self.receiver, 'dribble',refine=True)
return
else :
self.actions(self.receiver, 'kick')
return
# if sender exists
if not self.sender == None :
s2risFace, _ = self.is_facing_target(self.sender, self.cur_posture[self.receiver][X], self.cur_posture[self.receiver][Y],4)
r2sisFace, _ = self.is_facing_target(self.receiver, self.cur_posture[self.sender][X], self.cur_posture[self.sender][Y],4)
# if sender and receiver directs each other
if s2risFace and r2sisFace :
if self.cur_posture[self.receiver][TH] > 0 or self.cur_posture[self.receiver][TH] < -3 :
self.actions(self.receiver,'follow', [self.prev_posture[self.receiver][X], self.prev_posture[self.receiver][Y] - 0.5 * self.field[Y]])
return
self.actions(self.receiver, 'follow',[self.prev_posture[self.receiver][X], self.prev_posture[self.receiver][Y] + 0.5 * self.field[Y]])
return
r_point = self.cur_ball
# if sender exists
if not self.sender == None:
r_point = self.receive_position()
receiver_ball_dist = helper.dist(self.cur_ball[X], self.cur_posture[self.receiver][X], self.cur_ball[Y],self.cur_posture[self.receiver][Y])
# if ball is close to receiver
if receiver_ball_dist > 0.3 * self.field[X] / 2 :
self.actions(self.receiver, 'follow', [r_point[X], r_point[Y]],refine=True)
return
r2bisFace, _ = self.is_facing_target(self.receiver, self.cur_ball[X], self.cur_ball[Y], 4)
if not r2bisFace :
self.actions(self.receiver, 'follow',refine=True)
return
# if receiver is moving to our goal area
if self.cur_posture[self.receiver][X] < - 0.8 * self.field[X] / 2 :
if self.cur_posture[self.receiver][X] - self.prev_posture[self.receiver][X] < 0 :
self.actions(self.receiver, 'backward')
self.actions(self.receiver, 'dribble')
return
# let robot with id 'id' execute an action directed by 'mode'
def actions(self, id, mode = None, target_pts = None, params = None, refine = False) :
if id == None :
return
# if the player state is set to 'stop', force the mode to be 'stop'
if self.player_state[id] == 'stop' :
mode = 'stop'
if mode == None :
# reset all robot status
if self.sender == id :
self.sender = None
self.touch = [False, False, False, False, False]
if self.receiver == id :
self.receiver = None
self.player_state[id] = None
return
if mode == 'follow' :
# let the robot follow the ball
if target_pts == None :
target_pts = self.predict_ball_location(3)
if params == None :
params = [1.0, 3.0, 0.6, False]
if refine :
self.set_pos_parameters(id, target_pts, params)
self.set_target_position(id, target_pts[X], target_pts[Y], params[0], params[1], params[2], params[3])
self.player_state[id] = 'follow'
return
if mode == 'dribble' :
# let the robot follow the ball but at a faster speed
if target_pts == None :
target_pts = self.cur_ball
if params == None :
params = [1.4, 5.0, 0.8, False]
if refine :
self.set_pos_parameters(id, target_pts, params)
self.set_target_position(id, target_pts[X], target_pts[Y], params[0], params[1], params[2], params[3])
self.player_state[id] = 'dribble'
return
if mode == 'kick' :
# kick the ball
if target_pts == None :
target_pts = self.cur_ball
if params == None :
params = [1.4, 5.0, 0.8, True]
if self.end_count == 0 and not self.touch[id] :
self.end_count = self.cur_count + 10 # 0.05 * cnt seconds
self.player_state[id] = 'kick'
if self.touch[id] :
self.player_state[id] = 'stop'
if not self.touch[id] :
self.touch[id] = self.cur_posture[id][TOUCH]
if self.player_state[id] == 'stop' :
params = [0.0, 0.0, 0.0, False]
self.set_target_position(id, target_pts[X], target_pts[Y], params[0], params[1], params[2], params[3])
return
if mode == 'stop' :
# stop while counter is on
if params == None :
params = [0.0, 0.0, False]
self.set_wheel_velocity(id, params[0], params[1], params[2])
if self.end_count == 0 :
self.end_count = self.cur_count + 5 # 0.05 * cnt seconds
self.player_state[id] = 'stop'
if self.end_count - 1 == self.cur_count :
self.player_state[id] = None
return
if mode == 'backward' :
# retreat from the current position
if target_pts == None :
target_pts = [self.cur_posture[id][X] + 0.2, self.cur_posture[id][Y]]
if params == None :
params = [1.4, 5.0, 0.8, False]
if refine :
self.set_pos_parameters(id, target_pts, params)
self.set_target_position(id, target_pts[X], target_pts[Y], params[0], params[1], params[2], params[3])
self.player_state[id] = 'backward'
return
if mode == 'position' :
# go toward target position
self.set_target_position(id, target_pts[X], target_pts[Y], params[0], params[1], params[2], params[3])
return
def set_pos_parameters(self,id,target_pts,params,mult = 1.2):
prev_dist = helper.dist(self.prev_posture[id][X],target_pts[X],self.prev_posture[id][Y],target_pts[Y])
cur_dist = helper.dist(self.cur_posture[id][X],target_pts[X],self.cur_posture[id][Y],target_pts[Y])
if cur_dist > prev_dist - 0.02 :
params = [params[0] * mult, params[1] * mult, params[2] * mult, params[3]]
return params
def is_facing_target(self, id, x, y, div = 4):
dx = x - self.cur_posture[id][X]
dy = y - self.cur_posture[id][Y]
ds = math.sqrt(dx * dx + dy * dy)
desired_th = (self.cur_posture[id][TH] if (ds == 0) else math.acos(dx / ds))
theta = self.cur_posture[id][TH]
if desired_th < 0:
desired_th += math.pi * 2
if theta < 0:
theta += math.pi * 2
diff_theta = abs(desired_th - theta)
if diff_theta > math.pi:
diff_theta = min(diff_theta, math.pi * 2 - diff_theta)
if diff_theta < math.pi / div or diff_theta > math.pi * (1 - 1 / div):
return [True, diff_theta]
return [False, diff_theta]
def receive_position(self):
step = 5
ball_receiver_dist = helper.dist(self.cur_ball[X], self.cur_posture[self.receiver][X], self.cur_ball[Y],
self.cur_posture[self.receiver][Y])
prev_ball_receiver_dist = helper.dist(self.prev_ball[X], self.prev_posture[self.receiver][X],
self.prev_ball[Y], self.prev_posture[self.receiver][Y])
diff_dist = prev_ball_receiver_dist - ball_receiver_dist
if diff_dist > 0:
step = ball_receiver_dist # diff_dist
step = min(step, 15)
predict_pass_point = self.predict_ball_location(step)
ball_goal_dist = helper.dist(self.cur_ball[X], self.field[X] / 2, self.cur_ball[Y], 0)
prev_ball_goal_dist = helper.dist(self.prev_ball[X], self.field[X] / 2, self.prev_ball[Y], 0)
if ball_goal_dist > prev_ball_goal_dist:
predict_pass_point[X] = predict_pass_point[X] - 0.15
return predict_pass_point
@inlineCallbacks
def on_event(self, f):
@inlineCallbacks
def set_wheel(self, robot_wheels):
yield self.call(u'aiwc.set_speed', args.key, robot_wheels)
return
# a basic goalkeeper rulbased algorithm
def goalkeeper(self, id):
# default desired position
x = (-self.field[X] / 2) + (self.robot_size[id] / 2) + 0.05
y = max(min(self.cur_ball[Y], (self.goal[Y] / 2 - self.robot_size[id] / 2)),
-self.goal[Y] / 2 + self.robot_size[id] / 2)
# if the robot is inside the goal, try to get out
if (self.cur_posture[id][X] < -self.field[X] / 2):
if (self.cur_posture[id][Y] < 0):
self.set_target_position(id, x, self.cur_posture[id][Y] + 0.2, 1.4, 5.0, 0.4, False)
else:
self.set_target_position(id, x, self.cur_posture[id][Y] - 0.2, 1.4, 5.0, 0.4, False)
# if the goalkeeper is outside the penalty area
elif (not self.in_penalty_area(self.cur_posture[id], MY_TEAM)):
# return to the desired position
self.set_target_position(id, x, y, 1.4, 5.0, 0.4, True)
# if the goalkeeper is inside the penalty area
else:
# if the ball is inside the penalty area
if (self.in_penalty_area(self.cur_ball, MY_TEAM)):
# if the ball is behind the goalkeeper
if (self.cur_ball[X] < self.cur_posture[id][X]):
# if the ball is not blocking the goalkeeper's path
if (abs(self.cur_ball[Y] - self.cur_posture[id][Y]) > 2 * self.robot_size[id]):
# try to get ahead of the ball
self.set_target_position(id, self.cur_ball[X] - self.robot_size[id], self.cur_posture[id][Y], 1.4, 5.0,
0.4, False)
else:
# just give up and try not to make a suicidal goal
self.angle(id, math.pi / 2)
# if the ball is ahead of the goalkeeper
else:
desired_th = self.direction_angle(id, self.cur_ball[X], self.cur_ball[Y])
rad_diff = helper.trim_radian(desired_th - self.cur_posture[id][TH])
# if the robot direction is too away from the ball direction
if (rad_diff > math.pi / 3):
# give up kicking the ball and block the goalpost
self.set_target_position(id, x, y, 1.4, 5.0, 0.4, False)
else:
# try to kick the ball away from the goal
self.set_target_position(id, self.cur_ball[X], self.cur_ball[Y], 1.4, 3.0, 0.8, True)
# if the ball is not in the penalty area
else:
# if the ball is within alert range and y position is not too different
if (self.cur_ball[X] < -self.field[X] / 2 + 1.5 * self.penalty_area[X] and abs(
self.cur_ball[Y]) < 1.5 * self.penalty_area[Y] / 2 and abs(
self.cur_ball[Y] - self.cur_posture[id][Y]) < 0.2):
self.face_specific_position(id, self.cur_ball[X], self.cur_ball[Y])
# otherwise
else:
self.set_target_position(id, x, y, 1.4, 5.0, 0.4, True)
# a basic defender rulebased algorithm
def defender(self, id):
# if the robot is inside the goal, try to get out
if (self.cur_posture[id][X] < -self.field[X] / 2):
if (self.cur_posture[id][Y] < 0):
self.set_target_position(id, -0.7 * self.field[X] / 2, self.cur_posture[id][Y] + 0.2, 1.4, 3.5, 0.6, False)
else:
self.set_target_position(id, -0.7 * self.field[X] / 2, self.cur_posture[id][Y] - 0.2, 1.4, 3.5, 0.6, False)
return
# the defender may try to shoot if condition meets
if (id == self.def_idx and self.shoot_chance(id) and self.cur_ball[X] < 0.3 * self.field[X] / 2):
self.set_target_position(id, self.cur_ball[X], self.cur_ball[Y], 1.4, 5.0, 0.4, True)
return
# if this defender is closer to the ball than the other defender
if (id == self.def_idx):
# ball is on our side
if (self.cur_ball[X] < 0):
# if the robot can push the ball toward opponent's side, do it
if (self.cur_posture[id][X] < self.cur_ball[X] - self.ball_radius):
self.set_target_position(id, self.cur_ball[X], self.cur_ball[Y], 1.4, 5.0, 0.4, True)
else:
# otherwise go behind the ball
if (abs(self.cur_ball[Y] - self.cur_posture[id][Y]) > 0.3):
self.set_target_position(id, max(self.cur_ball[X] - 0.5, -self.field[X] / 2 + self.robot_size[id] / 2),
self.cur_ball[Y], 1.4, 3.5, 0.6, False)
else:
self.set_target_position(id, max(self.cur_ball[X] - 0.5, -self.field[X] / 2 + self.robot_size[id] / 2),
self.cur_posture[id][Y], 1.4, 3.5, 0.6, False)
else:
self.set_target_position(id, -0.7 * self.field[X] / 2, self.cur_ball[Y], 1.4, 3.5, 0.4, False)
# if this defender is not closer to the ball than the other defender
else:
# ball is on our side
if (self.cur_ball[X] < 0):
# ball is on our left
if (self.cur_ball[Y] > self.goal[Y] / 2 + 0.15):
self.set_target_position(id,
max(self.cur_ball[X] - 0.5, -self.field[X] / 2 + self.robot_size[id] / 2 + 0.1),
self.goal[Y] / 2 + 0.15, 1.4, 3.5, 0.4, False)
# ball is on our right
elif (self.cur_ball[Y] < -self.goal[Y] / 2 - 0.15):
self.set_target_position(id,
max(self.cur_ball[X] - 0.5, -self.field[X] / 2 + self.robot_size[id] / 2 + 0.1),
-self.goal[Y] / 2 - 0.15, 1.4, 3.5, 0.4, False)
# ball is in center
else:
self.set_target_position(id,
max(self.cur_ball[X] - 0.5, -self.field[X] / 2 + self.robot_size[id] / 2 + 0.1),
self.cur_ball[Y], 1.4, 3.5, 0.4, False)
else:
# ball is on right side
if (self.cur_ball[Y] < 0):
self.set_target_position(id, -0.7 * self.field[X] / 2,
min(self.cur_ball[Y] + 0.5, self.field[Y] / 2 - self.robot_size[id] / 2), 1.4,
3.5, 0.4, False)
# ball is on left side
else:
self.set_target_position(id, -0.7 * self.field[X] / 2,
max(self.cur_ball[Y] - 0.5, -self.field[Y] / 2 + self.robot_size[id] / 2), 1.4,
3.5, 0.4, False)
# a basic forward rulebased algorithm
def forward(self, id):
# if the robot is blocking the ball's path toward opponent side
if (self.cur_ball[X] > -0.3 * self.field[X] / 2 and self.cur_ball[X] < 0.3 * self.field[X] / 2 and
self.cur_posture[id][X] > self.cur_ball[X] + 0.1 and abs(
self.cur_posture[id][Y] - self.cur_ball[Y]) < 0.3):
if (self.cur_ball[Y] < 0):
self.set_target_position(id, self.cur_posture[id][X] - 0.25, self.cur_ball[Y] + 0.75, 1.4, 3.0, 0.8, False)
else:
self.set_target_position(id, self.cur_posture[id][X] - 0.25, self.cur_ball[Y] - 0.75, 1.4, 3.0, 0.8, False)
return
# if the robot can shoot from current position
if (id == self.atk_idx and self.shoot_chance(id)):
pred_ball = self.predict_ball_location(2)
self.set_target_position(id, pred_ball[X], pred_ball[Y], 1.4, 5.0, 0.4, True)
return
# if the ball is coming toward the robot, seek for shoot chance
if (id == self.atk_idx and self.ball_coming_toward_robot(id)):
dx = self.cur_ball[X] - self.prev_ball[X]
dy = self.cur_ball[Y] - self.prev_ball[Y]
pred_x = (self.cur_posture[id][Y] - self.cur_ball[Y]) * dx / dy + self.cur_ball[X]
steps = (self.cur_posture[id][Y] - self.cur_ball[Y]) / dy
# if the ball will be located in front of the robot
if (pred_x > self.cur_posture[id][X]):
pred_dist = pred_x - self.cur_posture[id][X]
# if the predicted ball location is close enough
if (pred_dist > 0.1 and pred_dist < 0.3 and steps < 10):
# find the direction towards the opponent goal and look toward it
goal_angle = self.direction_angle(id, self.field[X] / 2, 0)
self.angle(id, goal_angle)
return
# if this forward is closer to the ball than the other forward
if (id == self.atk_idx):
if (self.cur_ball[X] > -0.3 * self.field[X] / 2):
# if the robot can push the ball toward opponent's side, do it
if (self.cur_posture[id][X] < self.cur_ball[X] - self.ball_radius):
self.set_target_position(id, self.cur_ball[X], self.cur_ball[Y], 1.4, 5.0, 0.4, True)
else:
# otherwise go behind the ball
if (abs(self.cur_ball[Y] - self.cur_posture[id][Y]) > 0.3):
self.set_target_position(id, self.cur_ball[X] - 0.2, self.cur_ball[Y], 1.4, 3.5, 0.6, False)
else:
self.set_target_position(id, self.cur_ball[X] - 0.2, self.cur_posture[id][Y], 1.4, 3.5, 0.6, False)
else:
self.set_target_position(id, -0.1 * self.field[X] / 2, self.cur_ball[Y], 1.4, 3.5, 0.4, False)
# if this forward is not closer to the ball than the other forward
else:
if (self.cur_ball[X] > -0.3 * self.field[X] / 2):
# ball is on our right
if (self.cur_ball[Y] < 0):
self.set_target_position(id, self.cur_ball[X] - 0.25, self.goal[Y] / 2, 1.4, 3.5, 0.4, False)
# ball is on our left
else:
self.set_target_position(id, self.cur_ball[X] - 0.25, -self.goal[Y] / 2, 1.4, 3.5, 0.4, False)
else:
# ball is on right side
if (self.cur_ball[Y] < 0):
self.set_target_position(id, -0.1 * self.field[X] / 2,
min(-self.cur_ball[Y] - 0.5, self.field[Y] / 2 - self.robot_size[id] / 2), 1.4,
3.5, 0.4, False)
# ball is on left side
else:
self.set_target_position(id, -0.1 * self.field[X] / 2,
max(-self.cur_ball[Y] + 0.5, -self.field[Y] / 2 + self.robot_size[id] / 2), 1.4,
3.5, 0.4, False)
def default_rulebased(self, player_list):
for p in player_list:
# Add actions instead of default rulebase(goalkeeper, defender, forward) actions
# If this robot is stuck at field sides, move forward the center
if pow(self.prev_posture[p][X] - self.cur_posture[p][X],2) + pow(self.prev_posture[p][Y] - self.cur_posture[p][Y],2) < 5e-6:
if self.cur_posture[p][Y] > 0 :
self.set_target_position(p, 0, 0, 1.4, 3.5, 0.4, False)
continue
if p == 0:
goalkeeper(self, 0)
continue
if p == 1 or p == 2:
defender(self, p)
continue
if p == 3 or p == 4:
forward(self, p)
continue
def passing_play(self, player_list):
def find_active_player(self, ids):
_ids = []
for i in ids:
if self.cur_posture[i][ACTIVE] :
_ids.append(i)
return _ids
# select only alive player
_player_list = find_active_player(self, player_list)
self.cur_count = round(self.received_frame.time * 20) # count = 50 ms
if self.end_count == self.cur_count :
self.end_count = 0
if self.reset_condition() :
self.sender = None
self.sender_touch = False
self.receiver = None
# check if sender exists
if self.set_sender_condition() :
self.sender = self.set_sender( _player_list)
# check if receiver exists
if self.set_receiver_condition():
self.receiver = self.set_receiver(_player_list)
if (self.sender != None and self.receiver != None):
self.pass_ball()
# if player is sender
if self.sender in _player_list:
_player_list.remove(self.sender)
# if player is receiver
if self.receiver in _player_list:
_player_list.remove(self.receiver)
default_rulebased(self, _player_list)
return
# initiate empty frame
if (self.end_of_frame):
self.received_frame = Frame()
self.end_of_frame = False
received_subimages = []
if 'time' in f:
self.received_frame.time = f['time']
if 'score' in f:
self.received_frame.score = f['score']
if 'reset_reason' in f:
self.received_frame.reset_reason = f['reset_reason']
if 'game_state' in f:
self.received_frame.game_state = f['game_state']
if 'ball_ownership' in f:
self.received_frame.ball_ownership = f['ball_ownership']
if 'half_passed' in f:
self.received_frame.half_passed = f['half_passed']
if 'subimages' in f:
self.received_frame.subimages = f['subimages']
for s in self.received_frame.subimages:
received_subimages.append(SubImage(s['x'],
s['y'],
s['w'],
s['h'],
s['base64'].encode('utf8')))
self.image.update_image(received_subimages)
if 'coordinates' in f:
self.received_frame.coordinates = f['coordinates']
if 'EOF' in f:
self.end_of_frame = f['EOF']
if (self.end_of_frame):
# to get the image at the end of each frame use the variable:
# self.image.ImageBuffer
if (self.received_frame.reset_reason != NONE):
self.previous_frame = self.received_frame
self.get_coord()
self.find_closest_robot()
if (self.received_frame.reset_reason == EPISODE_END):
# EPISODE_END is sent instead of GAME_END when 'repeat' option is set to 'true'
# to mark the end of episode
# you can reinitialize the parameters, count the number of episodes done, etc. here
# this example does not do anything at episode end
pass
if (self.received_frame.reset_reason == HALFTIME):
# halftime is met - from next frame, self.received_frame.half_passed will be set to True
# although the simulation switches sides,
# coordinates and images given to your AI soccer algorithm will stay the same
# that your team is red and located on left side whether it is 1st half or 2nd half
# this example does not do anything at halftime
pass
##############################################################################
if (self.received_frame.game_state == STATE_DEFAULT):
# robot functions in STATE_DEFAULT
# goalkeeper simply executes goalkeeper algorithm on its own
goalkeeper(self, 0)
# defenders and forwards can pass ball to each other if necessary
passing_play(self, [1, 2, 3, 4])
set_wheel(self, self.wheels)
##############################################################################
elif (self.received_frame.game_state == STATE_KICKOFF):
# if the ball belongs to my team, initiate kickoff
if (self.received_frame.ball_ownership):
self.set_target_position(4, 0, 0, 1.4, 3.0, 0.4, False)
set_wheel(self, self.wheels)
##############################################################################
elif (self.received_frame.game_state == STATE_GOALKICK):
# if the ball belongs to my team,
# drive the goalkeeper to kick the ball
if (self.received_frame.ball_ownership):
self.set_wheel_velocity(0, self.max_linear_velocity[0], self.max_linear_velocity[0], True)
set_wheel(self, self.wheels)
##############################################################################
elif (self.received_frame.game_state == STATE_CORNERKICK):
# just play as simple as possible
goalkeeper(self, 0)
defender(self, 1)
defender(self, 2)
forward(self, 3)
forward(self, 4)
set_wheel(self, self.wheels)
##############################################################################
elif (self.received_frame.game_state == STATE_PENALTYKICK):
# if the ball belongs to my team,
# drive the forward to kick the ball
if (self.received_frame.ball_ownership):
self.set_wheel_velocity(4, self.max_linear_velocity[0], self.max_linear_velocity[0], True)
set_wheel(self, self.wheels)
##############################################################################
if (self.received_frame.reset_reason == GAME_END):
# (virtual finish() in random_walk.cpp)
# save your data
with open(args.datapath + '/result.txt', 'w') as output:
# output.write('yourvariables')
output.close()
# unsubscribe; reset or leave
yield self.sub.unsubscribe()
try:
yield self.leave()
except Exception as e:
self.printConsole("Error: {}".format(e))
##############################################################################
self.end_of_frame = False
self.previous_frame = self.received_frame
def onDisconnect(self):
if reactor.running:
reactor.stop()
if __name__ == '__main__':
try:
unicode
except NameError:
# Define 'unicode' for Python 3
def unicode(s, *_):
return s
def to_unicode(s):
return unicode(s, "utf-8")
parser = argparse.ArgumentParser()
parser.add_argument("server_ip", type=to_unicode)
parser.add_argument("port", type=to_unicode)
parser.add_argument("realm", type=to_unicode)
parser.add_argument("key", type=to_unicode)
parser.add_argument("datapath", type=to_unicode)
args = parser.parse_args()
ai_sv = "rs://" + args.server_ip + ":" + args.port
ai_realm = args.realm
# create a Wamp session object
session = Component(ComponentConfig(ai_realm, {}))
# initialize the msgpack serializer
serializer = MsgPackSerializer()
# use Wamp-over-rawsocket
runner = ApplicationRunner(ai_sv, ai_realm, serializers=[serializer])
runner.run(session, auto_reconnect=False)
|
#ifndef CX_SOLVES_HPP
#define CX_SOLVES_HPP
#include "print.hpp"
//#include "cx_modify.hpp"
#include "sub.hpp"
#include "../tools.hpp"
// #include "cx_multiply.hpp"
// #include "cx_special.hpp"
#include <mkl.h>
#include <boost/timer/timer.hpp>
#include <boost/chrono.hpp>
#include <vector>
#include <utility>
#include <complex>
namespace dqmc {
namespace la {
inline void solve_qr_col_piv(cx_mat&__restrict__ A,
const cx_mat&__restrict__ B,
cx_mat&__restrict__ X) {
using namespace std;
using namespace Eigen;
cx_vec_t taus(A.cols());
ivec iwork(A.cols()); iwork.setZero();
int lwork = -1;
int M = A.rows();
int N = A.cols();
perm_mat row_sort_perm = cx_row_sort(A, X);
lapack_int info = LAPACKE_zgeqp3( LAPACK_COL_MAJOR, M, N, X.data(),
M, iwork.data(), taus.data() );
ivec col_ids(A.cols());
for (int i = 0; i < A.cols(); ++i) { col_ids(i) = iwork(i) - 1; }
Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> lapack_col_perm(col_ids);
cx_mat_t upper = X.triangularView<Upper>();
lwork = -1;
info = LAPACKE_zungqr( LAPACK_COL_MAJOR, M, N, N,
X.data(), M, taus.data() );
// cout << "Reconstructed matrix " << endl
// << row_sort_perm.transpose() * X * upper * lapack_col_perm.transpose() << endl << endl;
// solving
A = X.adjoint() * row_sort_perm * B;
X = lapack_col_perm * upper.triangularView<Upper>().solve(A);
}
}
}
#endif
|
pdf("output.splice_events.pdf")
events=c(25.0,25.0,25.0)
pie(events,col=c(2,3,4),init.angle=30,angle=c(60,120,150),density=c(70,70,70),main="splicing events",labels=c("partial_novel 25%","complete_novel 25%","known 25%"))
dev.off()
pdf("output.splice_junction.pdf")
junction=c(33.3333333333,33.3333333333,33.3333333333)
pie(junction,col=c(2,3,4),init.angle=30,angle=c(60,120,150),density=c(70,70,70),main="splicing junctions",labels=c("partial_novel 33%","complete_novel 33%","known 33%"))
dev.off()
|
\documentclass[english]{article}
\usepackage[T1]{fontenc}
\usepackage[latin9]{inputenc}
\usepackage{geometry}
\usepackage{url}
\geometry{verbose,tmargin=3cm,bmargin=3cm,lmargin=3cm,rmargin=3cm}
\makeatletter
\usepackage{url}
\makeatother
\usepackage{babel}
\title{Research Plan for Practical Verification of QuadTrees}
\author{Jonathan Brouwer}
\date{April 19, 2021}
\begin{document}
\maketitle
%\begin{namelist}{xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
%\item[{\bf Title:}]
% A Very Good Thesis
%\item[{\bf Author:}]
% Gosia Migut
%\item[{\bf Responsible Professor:}]
% Mathijs de Weerdt
%\item[{\bf (Optionally) Other Supervisor:}]
% Eva
%\item[{\bf (Required for final version) Examiner:}]
% Another Professor (\emph{interested, but not involved})
%\item[{\bf Peer group members:}]
% John Appleseed (MSc), Harry Btree (BSc), Mike C3PO (PhD)
%(\emph{i.e., at least 3 other BSc/MSc/PhD students})
%\end{namelist}
\section*{Background of the research}
Haskell \cite{haskell} is a strongly typed purely functional programming language. A big advantage of this is that it makes reasoning about the correctness of algorithms and data structures relatively easy. This is demonstrated in Chapter 16 of the Programming in Haskell by Graham Hutton, where he proofs certain properties of Haskell code. However, these proofs are all done on paper, and making a mistake in these proofs is notoriously easy. There is also always the risk that the proof is no longer valid after the code changes.
Agda \cite{agda} is a dependently typed programming language and interactive theorem prover. Using Agda and the Curry-Howard correspondence \cite{chc}, we can write a formal proof about the code in the language itself, and use the compiler to verify the correctness of the proof \cite{schwaab}\cite{van}. The compiler also verifies that the proof is still valid each time the code changes, and will refuse to compile the code if it is not.
Agda2hs \cite{agda2hs} is a project that identifies a common subset of Agda and Haskell, and provides a tool that automatically translates code from this subset of Agda to Haskell. This lets you write your program in the subset, using full Agda to prove properties about it, and then translate it to nice looking readable Haskell code. However agda2hs is not finished yet, it still lacks some Agda features that it can not compile to Haskell.
QuadTree \cite{quadtree} is a Haskell library that provides discrete region quadtrees that can be used as simple functional alternatives to 2D arrays.
\section*{Research Question}
The goal of this research project is to investigate \textbf{whether agda2hs \cite{agda2hs} can be used to produce a verified implementation of QuadTree \cite{quadtree}}.
We want to investigate this in order to get an insight into how difficult it is to prove properties of relatively complex libraries.
In particular, we ask the following questions:
\begin{itemize}
\item Does the implementation of this library fall within the common subset of Haskell and Agda as identified by agda2hs? If not, is there an alternative implementation possible that does? Or else, what extensions to agda2hs are needed to implement the full functionality of the library?
\item What kind of properties and invariants does the library guarantee? Do the functions in the library require certain preconditions? Are there any ways the internal invariants of the library can be violated?
\item Is it possible to formally state and prove the correctness of Haskell libraries that are ported to Agda? How much time and effort does it take to verify the implementation compared to implementing the algorithm itself? What kind of simplifications could be made to reduce the cost of verification?
\end{itemize}
\section*{Method}
In order to accomplish this goal, I will perform the following tasks:
\begin{enumerate}
\item Create notes on the inner workings of the QuadTree library
\item Create notes on how to use Agda2hs
\item Create an implementation of QuadTree in the common subset of Haskell and Agda (depends on 1 and 2)
\item Find invariants and preconditions in the QuadTree library (depends on 1)
\item State these invariants and preconditions in the new implementation of QuadTree (depends on 3 and 4)
\item Attempt to prove these invariants and preconditions in the new implementation of QuadTree (depends on 5)
\item Find ways to reduce the cost of proving invariants and preconditions (depends on 6)
\end{enumerate}
For steps 2 and 7 I will collaborate with my peer group, while the other steps will done myself alone.
\section*{Planning of the research project}
The timetable for the research project is: \\
Note: I am using "Due" for my own deadlines and "Deadline" for course deadlines.
\begin{center}
\begin{tabular}{| p{0.25\textwidth} | p{0.65\textwidth} | }
\hline
Day & Tasks \\
\hline
\multicolumn{2}{l}{Week 1} \\
\hline
19-04-2021 Monday &
\begin{minipage}[t]{0.65\textwidth} \begin{itemize}
\item Create week 1 planning
\item DEADLINE: Week 1 planning
\item Install environment (Agda, Haskell, Agda2hs)
\end{itemize} \end{minipage} \\
\hline
20-04-2021 Tuesday &
\begin{minipage}[t]{0.65\textwidth} \begin{itemize}
\item DEADLINE: Information Literacy
\end{itemize} \end{minipage} \\
\hline
21-04-2021 Wednesday &
\begin{minipage}[t]{0.65\textwidth} \begin{itemize}
\item Due: (Task 1) Create notes on the inner workings of the QuadTree library
\end{itemize} \end{minipage} \\
\hline
23-04-2021 Friday &
\begin{minipage}[t]{0.65\textwidth} \begin{itemize}
\item Due: (Task 2) Create notes on how to use Agda2hs
\end{itemize} \end{minipage} \\
\hline
25-04-2021 Sunday &
\begin{minipage}[t]{0.65\textwidth} \begin{itemize}
\item DEADLINE: Finish the research plan
\end{itemize} \end{minipage} \\
\hline
\multicolumn{2}{l}{Week 2} \\
\hline
\multicolumn{2}{l}{Week 3} \\
\hline
Entire week &
\begin{minipage}[t]{0.65\textwidth} \begin{itemize}
\item Write first 300 words of research paper
\end{itemize} \end{minipage} \\
\hline
09-05-2021 Sunday &
\begin{minipage}[t]{0.65\textwidth} \begin{itemize}
\item Due: (Task 3) Create an implementation of QuadTree in the common subset of Haskell and Agda
\item Due: (Task 4) Find invariants and preconditions in the QuadTree library
\end{itemize} \end{minipage} \\
\hline
\multicolumn{2}{l}{Week 4} \\
\hline
Entire week &
\begin{minipage}[t]{0.65\textwidth} \begin{itemize}
\item Write "Methodology" of research paper
\item Work on midterm presentation
\end{itemize} \end{minipage} \\
\hline
16-05-2021 Sunday &
\begin{minipage}[t]{0.65\textwidth} \begin{itemize}
\item Due: (Task 5) State these invariants and preconditions in the new implementation of QuadTree
\end{itemize} \end{minipage} \\
\hline
\multicolumn{2}{l}{Week 5} \\
\hline
Entire week &
\begin{minipage}[t]{0.65\textwidth} \begin{itemize}
\item Write "Your Contribution" of research paper
\end{itemize} \end{minipage} \\
\hline
19-05-2021 Wednesday &
\begin{minipage}[t]{0.65\textwidth} \begin{itemize}
\item DEADLINE: Midterm presentation
\end{itemize} \end{minipage} \\
\hline
\multicolumn{2}{l}{Week 6} \\
\hline
Entire week &
\begin{minipage}[t]{0.65\textwidth} \begin{itemize}
\item Write "Experimental Setup and Results" of research paper
\end{itemize} \end{minipage} \\
\hline
30-05-2021 Sunday &
\begin{minipage}[t]{0.65\textwidth} \begin{itemize}
\item Due (Task 6) Attempt to prove these invariants and preconditions in the new implementation of QuadTree
\item Due (Task 7) Find ways to reduce the cost of proving invariants and preconditions
\end{itemize} \end{minipage} \\
\hline
\multicolumn{2}{l}{Week 7} \\
\hline
Entire week &
\begin{minipage}[t]{0.65\textwidth} \begin{itemize}
\item Write "Responsible Research" of research paper
\item Start working exclusively on the research paper. (Code freeze)
\item Extra time if needed
\end{itemize} \end{minipage} \\
\hline
\multicolumn{2}{l}{Week 8} \\
\hline
07-06-2021 Monday &
\begin{minipage}[t]{0.65\textwidth} \begin{itemize}
\item DEADLINE: Paper Draft V1
\end{itemize} \end{minipage} \\
\hline
10-06-2021 Thursday &
\begin{minipage}[t]{0.65\textwidth} \begin{itemize}
\item DEADLINE: Peer Review Draft V1
\end{itemize} \end{minipage} \\
\hline
\multicolumn{2}{l}{Week 9} \\
\hline
16-06-2021 Wednesday &
\begin{minipage}[t]{0.65\textwidth} \begin{itemize}
\item DEADLINE: Paper Draft V2
\end{itemize} \end{minipage} \\
\hline
\multicolumn{2}{l}{Week 10} \\
\hline
27-06-2021 Sunday &
\begin{minipage}[t]{0.65\textwidth} \begin{itemize}
\item DEADLINE: Final paper
\end{itemize} \end{minipage} \\
\hline
\multicolumn{2}{l}{Week 11} \\
\hline
29-06-2021 Tuesday &
\begin{minipage}[t]{0.65\textwidth} \begin{itemize}
\item DEADLINE: Poster
\end{itemize} \end{minipage} \\
\hline
01-07-2021 Thursday &
\begin{minipage}[t]{0.65\textwidth} \begin{itemize}
\item DEADLINE: Presentation
\end{itemize} \end{minipage} \\
\hline
02-07-2021 Friday &
\begin{minipage}[t]{0.65\textwidth} \begin{itemize}
\item DEADLINE: Presentation
\end{itemize} \end{minipage} \\
\hline
\end{tabular}
\end{center}
All planned meetings are:
\begin{center}
\begin{tabular}{|p{0.4\linewidth} | c | c|}
\hline
Purpose & With & Date and time \\ [1ex]
\hline
Initial Meeting & Professor + Peers & 1 April 2021 10:00 \\
\hline
\hline
Improve research plan & Everyone & 20 April 2021 10:00 \\
\hline
Recurring meeting & Everyone & 29 April 2021 10:00 \\
\hline
Recurring meeting & Everyone & 4 May 2021 10:00 \\
\hline
Recurring meeting & Everyone & 11 May 2021 10:00 \\
\hline
Recurring meeting & Everyone & 18 May 2021 10:00 \\
\hline
Recurring meeting & Everyone & 25 May 2021 10:00 \\
\hline
Recurring meeting & Everyone & 1 June 2021 10:00 \\
\hline
Recurring meeting & Everyone & 8 June 2021 10:00 \\
\hline
Recurring meeting & Everyone & 15 June 2021 10:00 \\
\hline
Recurring meeting & Everyone & 22 June 2021 10:00 \\
\hline
Recurring meeting & Everyone & 29 June 2021 10:00 \\
\hline
\end{tabular}
\end{center}
\bibliographystyle{unsrt}
\bibliography{bibliography}
\end{document}
|
/-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
! This file was ported from Lean 3 source module algebra.group_with_zero.power
! leanprover-community/mathlib commit 46a64b5b4268c594af770c44d9e502afc6a515cb
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathlib.Algebra.GroupPower.Lemmas
import Mathlib.Data.Int.Bitwise
/-!
# Powers of elements of groups with an adjoined zero element
In this file we define integer power functions for groups with an adjoined zero element.
This generalises the integer power function on a division ring.
-/
section GroupWithZero
variable {G₀ : Type _} [GroupWithZero G₀] {a : G₀} {m n : ℕ}
section NatPow
theorem pow_sub₀ (a : G₀) {m n : ℕ} (ha : a ≠ 0) (h : n ≤ m) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ := by
have h1 : m - n + n = m := tsub_add_cancel_of_le h
have h2 : a ^ (m - n) * a ^ n = a ^ m := by rw [← pow_add, h1]
simpa only [div_eq_mul_inv] using eq_div_of_mul_eq (pow_ne_zero _ ha) h2
#align pow_sub₀ pow_sub₀
theorem pow_sub_of_lt (a : G₀) {m n : ℕ} (h : n < m) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ := by
obtain rfl | ha := eq_or_ne a 0
· rw [zero_pow (tsub_pos_of_lt h), zero_pow (n.zero_le.trans_lt h), zero_mul]
· exact pow_sub₀ _ ha h.le
#align pow_sub_of_lt pow_sub_of_lt
theorem pow_inv_comm₀ (a : G₀) (m n : ℕ) : a⁻¹ ^ m * a ^ n = a ^ n * a⁻¹ ^ m :=
(Commute.refl a).inv_left₀.pow_pow m n
#align pow_inv_comm₀ pow_inv_comm₀
theorem inv_pow_sub₀ (ha : a ≠ 0) (h : n ≤ m) : a⁻¹ ^ (m - n) = (a ^ m)⁻¹ * a ^ n := by
rw [pow_sub₀ _ (inv_ne_zero ha) h, inv_pow, inv_pow, inv_inv]
#align inv_pow_sub₀ inv_pow_sub₀
theorem inv_pow_sub_of_lt (a : G₀) (h : n < m) : a⁻¹ ^ (m - n) = (a ^ m)⁻¹ * a ^ n := by
rw [pow_sub_of_lt a⁻¹ h, inv_pow, inv_pow, inv_inv]
#align inv_pow_sub_of_lt inv_pow_sub_of_lt
end NatPow
end GroupWithZero
section ZPow
open Int
variable {G₀ : Type _} [GroupWithZero G₀]
-- Porting note: removed `attribute [local ematch] le_of_lt`
theorem zero_zpow : ∀ z : ℤ, z ≠ 0 → (0 : G₀) ^ z = 0
| (n : ℕ), h => by
rw [zpow_ofNat, zero_pow']
simpa using h
| -[n+1], _ => by simp
#align zero_zpow zero_zpow
theorem zero_zpow_eq (n : ℤ) : (0 : G₀) ^ n = if n = 0 then 1 else 0 := by
split_ifs with h
· rw [h, zpow_zero]
· rw [zero_zpow _ h]
#align zero_zpow_eq zero_zpow_eq
theorem zpow_add_one₀ {a : G₀} (ha : a ≠ 0) : ∀ n : ℤ, a ^ (n + 1) = a ^ n * a
| (n : ℕ) => by simp only [← Int.ofNat_succ, zpow_ofNat, pow_succ']
| -[0+1] => by erw [zpow_zero, zpow_negSucc, pow_one, inv_mul_cancel ha]
| -[n + 1+1] => by
rw [Int.negSucc_eq, zpow_neg, neg_add, neg_add_cancel_right, zpow_neg, ← Int.ofNat_succ,
zpow_ofNat, zpow_ofNat, pow_succ _ (n + 1), mul_inv_rev, mul_assoc, inv_mul_cancel ha,
mul_one]
#align zpow_add_one₀ zpow_add_one₀
theorem zpow_sub_one₀ {a : G₀} (ha : a ≠ 0) (n : ℤ) : a ^ (n - 1) = a ^ n * a⁻¹ :=
calc
a ^ (n - 1) = a ^ (n - 1) * a * a⁻¹ := by rw [mul_assoc, mul_inv_cancel ha, mul_one]
_ = a ^ n * a⁻¹ := by rw [← zpow_add_one₀ ha, sub_add_cancel]
#align zpow_sub_one₀ zpow_sub_one₀
theorem zpow_add₀ {a : G₀} (ha : a ≠ 0) (m n : ℤ) : a ^ (m + n) = a ^ m * a ^ n := by
induction' n using Int.induction_on with n ihn n ihn
· simp
· simp only [← add_assoc, zpow_add_one₀ ha, ihn, mul_assoc]
· rw [zpow_sub_one₀ ha, ← mul_assoc, ← ihn, ← zpow_sub_one₀ ha, add_sub_assoc]
#align zpow_add₀ zpow_add₀
theorem zpow_add' {a : G₀} {m n : ℤ} (h : a ≠ 0 ∨ m + n ≠ 0 ∨ m = 0 ∧ n = 0) :
a ^ (m + n) = a ^ m * a ^ n := by
by_cases hm : m = 0
· simp [hm]
by_cases hn : n = 0
· simp [hn]
by_cases ha : a = 0
· subst a
simp only [false_or_iff, eq_self_iff_true, not_true, Ne.def, hm, hn, false_and_iff,
or_false_iff] at h
rw [zero_zpow _ h, zero_zpow _ hm, zero_mul]
· exact zpow_add₀ ha m n
#align zpow_add' zpow_add'
theorem zpow_one_add₀ {a : G₀} (h : a ≠ 0) (i : ℤ) : a ^ (1 + i) = a * a ^ i := by
rw [zpow_add₀ h, zpow_one]
#align zpow_one_add₀ zpow_one_add₀
theorem SemiconjBy.zpow_right₀ {a x y : G₀} (h : SemiconjBy a x y) :
∀ m : ℤ, SemiconjBy a (x ^ m) (y ^ m)
| (n : ℕ) => by simp [h.pow_right n]
| -[n+1] => by simp only [zpow_negSucc, (h.pow_right (n + 1)).inv_right₀]
#align semiconj_by.zpow_right₀ SemiconjBy.zpow_right₀
theorem Commute.zpow_right₀ {a b : G₀} (h : Commute a b) : ∀ m : ℤ, Commute a (b ^ m) :=
SemiconjBy.zpow_right₀ h
#align commute.zpow_right₀ Commute.zpow_right₀
theorem Commute.zpow_left₀ {a b : G₀} (h : Commute a b) (m : ℤ) : Commute (a ^ m) b :=
(h.symm.zpow_right₀ m).symm
#align commute.zpow_left₀ Commute.zpow_left₀
theorem Commute.zpow_zpow₀ {a b : G₀} (h : Commute a b) (m n : ℤ) : Commute (a ^ m) (b ^ n) :=
(h.zpow_left₀ m).zpow_right₀ n
#align commute.zpow_zpow₀ Commute.zpow_zpow₀
theorem Commute.zpow_self₀ (a : G₀) (n : ℤ) : Commute (a ^ n) a :=
(Commute.refl a).zpow_left₀ n
#align commute.zpow_self₀ Commute.zpow_self₀
theorem Commute.self_zpow₀ (a : G₀) (n : ℤ) : Commute a (a ^ n) :=
(Commute.refl a).zpow_right₀ n
#align commute.self_zpow₀ Commute.self_zpow₀
theorem Commute.zpow_zpow_self₀ (a : G₀) (m n : ℤ) : Commute (a ^ m) (a ^ n) :=
(Commute.refl a).zpow_zpow₀ m n
#align commute.zpow_zpow_self₀ Commute.zpow_zpow_self₀
set_option linter.deprecated false in
theorem zpow_bit1₀ (a : G₀) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a := by
rw [← zpow_bit0, bit1, zpow_add', zpow_one]
right; left
apply bit1_ne_zero
#align zpow_bit1₀ zpow_bit1₀
theorem zpow_ne_zero_of_ne_zero {a : G₀} (ha : a ≠ 0) : ∀ z : ℤ, a ^ z ≠ 0
| (_ : ℕ) => by
rw [zpow_ofNat]
exact pow_ne_zero _ ha
| -[_+1] => by
rw [zpow_negSucc]
exact inv_ne_zero (pow_ne_zero _ ha)
#align zpow_ne_zero_of_ne_zero zpow_ne_zero_of_ne_zero
theorem zpow_sub₀ {a : G₀} (ha : a ≠ 0) (z1 z2 : ℤ) : a ^ (z1 - z2) = a ^ z1 / a ^ z2 := by
rw [sub_eq_add_neg, zpow_add₀ ha, zpow_neg, div_eq_mul_inv]
#align zpow_sub₀ zpow_sub₀
set_option linter.deprecated false in
theorem zpow_bit1' (a : G₀) (n : ℤ) : a ^ bit1 n = (a * a) ^ n * a := by
rw [zpow_bit1₀, (Commute.refl a).mul_zpow]
#align zpow_bit1' zpow_bit1'
theorem zpow_eq_zero {x : G₀} {n : ℤ} (h : x ^ n = 0) : x = 0 :=
by_contradiction fun hx => zpow_ne_zero_of_ne_zero hx n h
#align zpow_eq_zero zpow_eq_zero
theorem zpow_eq_zero_iff {a : G₀} {n : ℤ} (hn : n ≠ 0) : a ^ n = 0 ↔ a = 0 :=
⟨zpow_eq_zero, fun ha => ha.symm ▸ zero_zpow _ hn⟩
#align zpow_eq_zero_iff zpow_eq_zero_iff
theorem zpow_ne_zero {x : G₀} (n : ℤ) : x ≠ 0 → x ^ n ≠ 0 :=
mt zpow_eq_zero
#align zpow_ne_zero zpow_ne_zero
theorem zpow_neg_mul_zpow_self (n : ℤ) {x : G₀} (h : x ≠ 0) : x ^ (-n) * x ^ n = 1 := by
rw [zpow_neg]
exact inv_mul_cancel (zpow_ne_zero n h)
#align zpow_neg_mul_zpow_self zpow_neg_mul_zpow_self
end ZPow
section
variable {G₀ : Type _} [CommGroupWithZero G₀]
theorem div_sq_cancel (a b : G₀) : a ^ 2 * b / a = a * b := by
by_cases ha : a = 0
· simp [ha]
rw [sq, mul_assoc, mul_div_cancel_left _ ha]
#align div_sq_cancel div_sq_cancel
end
/-- If a monoid homomorphism `f` between two `GroupWithZero`s maps `0` to `0`, then it maps `x^n`,
`n : ℤ`, to `(f x)^n`. -/
@[simp]
theorem map_zpow₀ {F G₀ G₀' : Type _} [GroupWithZero G₀] [GroupWithZero G₀']
[MonoidWithZeroHomClass F G₀ G₀'] (f : F) (x : G₀) (n : ℤ) : f (x ^ n) = f x ^ n :=
map_zpow' f (map_inv₀ f) x n
#align map_zpow₀ map_zpow₀
|
/-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Michael Howes
-/
import group_theory.commutator
import group_theory.quotient_group
/-!
# The abelianization of a group
This file defines the commutator and the abelianization of a group. It furthermore prepares for the
result that the abelianization is left adjoint to the forgetful functor from abelian groups to
groups, which can be found in `algebra/category/Group/adjunctions`.
## Main definitions
* `commutator`: defines the commutator of a group `G` as a subgroup of `G`.
* `abelianization`: defines the abelianization of a group `G` as the quotient of a group by its
commutator subgroup.
* `abelianization.map`: lifts a group homomorphism to a homomorphism between the abelianizations
* `mul_equiv.abelianization_congr`: Equivalent groups have equivalent abelianizations
-/
universes u v w
-- Let G be a group.
variables (G : Type u) [group G]
/-- The commutator subgroup of a group G is the normal subgroup
generated by the commutators [p,q]=`p*q*p⁻¹*q⁻¹`. -/
@[derive subgroup.normal]
def commutator : subgroup G :=
⁅(⊤ : subgroup G), ⊤⁆
lemma commutator_def : commutator G = ⁅(⊤ : subgroup G), ⊤⁆ := rfl
lemma commutator_eq_closure : commutator G = subgroup.closure {g | ∃ g₁ g₂ : G, ⁅g₁, g₂⁆ = g} :=
by simp_rw [commutator, subgroup.commutator_def, subgroup.mem_top, exists_true_left]
lemma commutator_eq_normal_closure :
commutator G = subgroup.normal_closure {g | ∃ g₁ g₂ : G, ⁅g₁, g₂⁆ = g} :=
by simp_rw [commutator, subgroup.commutator_def', subgroup.mem_top, exists_true_left]
instance commutator_characteristic : (commutator G).characteristic :=
subgroup.commutator_characteristic ⊤ ⊤
lemma commutator_centralizer_commutator_le_center :
⁅(commutator G).centralizer, (commutator G).centralizer⁆ ≤ subgroup.center G :=
begin
rw [←subgroup.centralizer_top, ←subgroup.commutator_eq_bot_iff_le_centralizer],
suffices : ⁅⁅⊤, (commutator G).centralizer⁆, (commutator G).centralizer⁆ = ⊥,
{ refine subgroup.commutator_commutator_eq_bot_of_rotate _ this,
rwa subgroup.commutator_comm (commutator G).centralizer },
rw [subgroup.commutator_comm, subgroup.commutator_eq_bot_iff_le_centralizer],
exact set.centralizer_subset (subgroup.commutator_mono le_top le_top),
end
/-- The abelianization of G is the quotient of G by its commutator subgroup. -/
def abelianization : Type u :=
G ⧸ (commutator G)
namespace abelianization
local attribute [instance] quotient_group.left_rel
instance : comm_group (abelianization G) :=
{ mul_comm := λ x y, quotient.induction_on₂' x y $ λ a b, quotient.sound' $
subgroup.subset_closure ⟨b⁻¹, subgroup.mem_top b⁻¹, a⁻¹, subgroup.mem_top a⁻¹, by group⟩,
.. quotient_group.quotient.group _ }
instance : inhabited (abelianization G) := ⟨1⟩
instance [fintype G] [decidable_pred (∈ commutator G)] :
fintype (abelianization G) :=
quotient_group.fintype (commutator G)
variable {G}
/-- `of` is the canonical projection from G to its abelianization. -/
def of : G →* abelianization G :=
{ to_fun := quotient_group.mk,
map_one' := rfl,
map_mul' := λ x y, rfl }
@[simp] lemma mk_eq_of (a : G) : quot.mk _ a = of a := rfl
section lift
-- So far we have built Gᵃᵇ and proved it's an abelian group.
-- Furthremore we defined the canonical projection `of : G → Gᵃᵇ`
-- Let `A` be an abelian group and let `f` be a group homomorphism from `G` to `A`.
variables {A : Type v} [comm_group A] (f : G →* A)
lemma commutator_subset_ker : commutator G ≤ f.ker :=
begin
rw [commutator_eq_closure, subgroup.closure_le],
rintros x ⟨p, q, rfl⟩,
simp [monoid_hom.mem_ker, mul_right_comm (f p) (f q), commutator_element_def],
end
/-- If `f : G → A` is a group homomorphism to an abelian group, then `lift f` is the unique map from
the abelianization of a `G` to `A` that factors through `f`. -/
def lift : (G →* A) ≃ (abelianization G →* A) :=
{ to_fun := λ f, quotient_group.lift _ f (λ x h, f.mem_ker.2 $ commutator_subset_ker _ h),
inv_fun := λ F, F.comp of,
left_inv := λ f, monoid_hom.ext $ λ x, rfl,
right_inv := λ F, monoid_hom.ext $ λ x, quotient_group.induction_on x $ λ z, rfl }
@[simp] lemma lift.of (x : G) : lift f (of x) = f x :=
rfl
theorem lift.unique
(φ : abelianization G →* A)
-- hφ : φ agrees with f on the image of G in Gᵃᵇ
(hφ : ∀ (x : G), φ (of x) = f x)
{x : abelianization G} :
φ x = lift f x :=
quotient_group.induction_on x hφ
@[simp] lemma lift_of : lift of = monoid_hom.id (abelianization G) :=
lift.apply_symm_apply $ monoid_hom.id _
end lift
variables {A : Type v} [monoid A]
/-- See note [partially-applied ext lemmas]. -/
@[ext]
theorem hom_ext (φ ψ : abelianization G →* A)
(h : φ.comp of = ψ.comp of) : φ = ψ :=
monoid_hom.ext $ λ x, quotient_group.induction_on x $ monoid_hom.congr_fun h
section map
variables {H : Type v} [group H] (f : G →* H)
/-- The map operation of the `abelianization` functor -/
def map : abelianization G →* abelianization H := lift (of.comp f)
@[simp]
lemma map_of (x : G) : map f (of x) = of (f x) := rfl
@[simp]
lemma map_id : map (monoid_hom.id G) = monoid_hom.id (abelianization G) := hom_ext _ _ rfl
@[simp]
lemma map_comp {I : Type w} [group I] (g : H →* I) :
(map g).comp (map f) = map (g.comp f) := hom_ext _ _ rfl
@[simp]
lemma map_map_apply {I : Type w} [group I] {g : H →* I} {x : abelianization G}:
map g (map f x) = map (g.comp f) x := monoid_hom.congr_fun (map_comp _ _) x
end map
end abelianization
section abelianization_congr
variables {G} {H : Type v} [group H] (e : G ≃* H)
/-- Equivalent groups have equivalent abelianizations -/
def mul_equiv.abelianization_congr : abelianization G ≃* abelianization H :=
{ to_fun := abelianization.map e.to_monoid_hom,
inv_fun := abelianization.map e.symm.to_monoid_hom,
left_inv := by { rintros ⟨a⟩, simp },
right_inv := by { rintros ⟨a⟩, simp },
map_mul' := monoid_hom.map_mul _ }
@[simp]
lemma abelianization_congr_of (x : G) :
(e.abelianization_congr) (abelianization.of x) = abelianization.of (e x) := rfl
@[simp]
lemma abelianization_congr_refl :
(mul_equiv.refl G).abelianization_congr = mul_equiv.refl (abelianization G) :=
mul_equiv.to_monoid_hom_injective abelianization.lift_of
@[simp]
lemma abelianization_congr_symm :
e.abelianization_congr.symm = e.symm.abelianization_congr := rfl
@[simp]
lemma abelianization_congr_trans {I : Type v} [group I] (e₂ : H ≃* I) :
e.abelianization_congr.trans e₂.abelianization_congr = (e.trans e₂).abelianization_congr :=
mul_equiv.to_monoid_hom_injective (abelianization.hom_ext _ _ rfl)
end abelianization_congr
/-- An Abelian group is equivalent to its own abelianization. -/
@[simps] def abelianization.equiv_of_comm {H : Type*} [comm_group H] :
H ≃* abelianization H :=
{ to_fun := abelianization.of,
inv_fun := abelianization.lift (monoid_hom.id H),
left_inv := λ a, rfl,
right_inv := by { rintros ⟨a⟩, refl, },
.. abelianization.of }
|
[GOAL]
α : Type u_1
inst✝¹ : PartialOrder α
inst✝ : OrderBot α
a b c d : α
ha : a ≠ ⊥
hab : Disjoint a b
h : a = b
⊢ Disjoint a a
[PROOFSTEP]
rwa [← h] at hab
[GOAL]
α : Type u_1
inst✝¹ : SemilatticeInf α
inst✝ : OrderBot α
a b c d : α
⊢ Disjoint (a ⊓ b) c ↔ Disjoint a (b ⊓ c)
[PROOFSTEP]
rw [disjoint_iff_inf_le, disjoint_iff_inf_le, inf_assoc]
[GOAL]
α : Type u_1
inst✝¹ : SemilatticeInf α
inst✝ : OrderBot α
a b c d : α
⊢ Disjoint a (b ⊓ c) ↔ Disjoint b (a ⊓ c)
[PROOFSTEP]
simp_rw [disjoint_iff_inf_le, inf_left_comm]
[GOAL]
α : Type u_1
inst✝¹ : SemilatticeInf α
inst✝ : OrderBot α
a b c d : α
⊢ Disjoint (a ⊓ b) c ↔ Disjoint (a ⊓ c) b
[PROOFSTEP]
simp_rw [disjoint_iff_inf_le, inf_right_comm]
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : OrderBot α
a b c : α
⊢ Disjoint (a ⊔ b) c ↔ Disjoint a c ∧ Disjoint b c
[PROOFSTEP]
simp only [disjoint_iff, inf_sup_right, sup_eq_bot_iff]
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : OrderBot α
a b c : α
⊢ Disjoint a (b ⊔ c) ↔ Disjoint a b ∧ Disjoint a c
[PROOFSTEP]
simp only [disjoint_iff, inf_sup_left, sup_eq_bot_iff]
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : OrderBot α
a b c : α
h : a ≤ c ⊔ b
hd : Disjoint a c
⊢ a ≤ b ⊔ c
[PROOFSTEP]
rwa [sup_comm]
[GOAL]
α : Type u_1
inst✝¹ : PartialOrder α
inst✝ : OrderTop α
a b c d : α
ha : a ≠ ⊤
hab : Codisjoint a b
h : a = b
⊢ Codisjoint a a
[PROOFSTEP]
rwa [← h] at hab
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : OrderTop α
a b c : α
⊢ Codisjoint (a ⊓ b) c ↔ Codisjoint a c ∧ Codisjoint b c
[PROOFSTEP]
simp only [codisjoint_iff, sup_inf_right, inf_eq_top_iff]
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : OrderTop α
a b c : α
⊢ Codisjoint a (b ⊓ c) ↔ Codisjoint a b ∧ Codisjoint a c
[PROOFSTEP]
simp only [codisjoint_iff, sup_inf_left, inf_eq_top_iff]
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : OrderTop α
a b c : α
h : b ⊓ a ≤ c
hd : Codisjoint b c
⊢ a ⊓ b ≤ c
[PROOFSTEP]
rwa [inf_comm]
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : BoundedOrder α
a b c : α
hab : Disjoint a b
hbc : Codisjoint b c
⊢ a ≤ c
[PROOFSTEP]
rw [← @inf_top_eq _ _ _ a, ← @bot_sup_eq _ _ _ c, ← hab.eq_bot, ← hbc.eq_top, sup_inf_right]
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : BoundedOrder α
a b c : α
hab : Disjoint a b
hbc : Codisjoint b c
⊢ a ⊓ (b ⊔ c) ≤ (a ⊔ c) ⊓ (b ⊔ c)
[PROOFSTEP]
exact inf_le_inf_right _ le_sup_left
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : BoundedOrder α
a b x y z : α
h : IsCompl x y
hle : a ≤ b ⊔ y
⊢ b ⊓ x ⊔ y ⊓ x = b ⊓ x
[PROOFSTEP]
rw [h.symm.inf_eq_bot, sup_bot_eq]
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : BoundedOrder α
a b x y z : α
h : IsCompl y z
⊢ x ⊓ y = ⊥ ↔ x ≤ z
[PROOFSTEP]
rw [← le_bot_iff, ← h.le_sup_right_iff_inf_left_le, bot_sup_eq]
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : BoundedOrder α
a b x y z : α
h : IsCompl y z
⊢ Disjoint x y ↔ x ≤ z
[PROOFSTEP]
rw [disjoint_iff]
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : BoundedOrder α
a b x y z : α
h : IsCompl y z
⊢ x ⊓ y = ⊥ ↔ x ≤ z
[PROOFSTEP]
exact h.inf_left_eq_bot_iff
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : BoundedOrder α
a b x y z x' y' : α
h : IsCompl x y
h' : IsCompl x' y'
⊢ (x ⊔ x') ⊓ (y ⊓ y') = ⊥
[PROOFSTEP]
rw [inf_sup_right, ← inf_assoc, h.inf_eq_bot, bot_inf_eq, bot_sup_eq, inf_left_comm, h'.inf_eq_bot, inf_bot_eq]
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : BoundedOrder α
a b x y z x' y' : α
h : IsCompl x y
h' : IsCompl x' y'
⊢ x ⊔ x' ⊔ y ⊓ y' = ⊤
[PROOFSTEP]
rw [sup_inf_left, @sup_comm _ _ x, sup_assoc, h.sup_eq_top, sup_top_eq, top_inf_eq, sup_assoc, sup_left_comm,
h'.sup_eq_top, sup_top_eq]
[GOAL]
α : Type u_1
β : Type u_2
inst✝³ : PartialOrder α
inst✝² : PartialOrder β
inst✝¹ : OrderBot α
inst✝ : OrderBot β
x y : α × β
⊢ Disjoint x y ↔ Disjoint x.fst y.fst ∧ Disjoint x.snd y.snd
[PROOFSTEP]
constructor
[GOAL]
case mp
α : Type u_1
β : Type u_2
inst✝³ : PartialOrder α
inst✝² : PartialOrder β
inst✝¹ : OrderBot α
inst✝ : OrderBot β
x y : α × β
⊢ Disjoint x y → Disjoint x.fst y.fst ∧ Disjoint x.snd y.snd
[PROOFSTEP]
intro h
[GOAL]
case mp
α : Type u_1
β : Type u_2
inst✝³ : PartialOrder α
inst✝² : PartialOrder β
inst✝¹ : OrderBot α
inst✝ : OrderBot β
x y : α × β
h : Disjoint x y
⊢ Disjoint x.fst y.fst ∧ Disjoint x.snd y.snd
[PROOFSTEP]
refine' ⟨fun a hx hy ↦ (@h (a, ⊥) ⟨hx, _⟩ ⟨hy, _⟩).1, fun b hx hy ↦ (@h (⊥, b) ⟨_, hx⟩ ⟨_, hy⟩).2⟩
[GOAL]
case mp.refine'_1
α : Type u_1
β : Type u_2
inst✝³ : PartialOrder α
inst✝² : PartialOrder β
inst✝¹ : OrderBot α
inst✝ : OrderBot β
x y : α × β
h : Disjoint x y
a : α
hx : a ≤ x.fst
hy : a ≤ y.fst
⊢ (a, ⊥).snd ≤ x.snd
case mp.refine'_2
α : Type u_1
β : Type u_2
inst✝³ : PartialOrder α
inst✝² : PartialOrder β
inst✝¹ : OrderBot α
inst✝ : OrderBot β
x y : α × β
h : Disjoint x y
a : α
hx : a ≤ x.fst
hy : a ≤ y.fst
⊢ (a, ⊥).snd ≤ y.snd
case mp.refine'_3
α : Type u_1
β : Type u_2
inst✝³ : PartialOrder α
inst✝² : PartialOrder β
inst✝¹ : OrderBot α
inst✝ : OrderBot β
x y : α × β
h : Disjoint x y
b : β
hx : b ≤ x.snd
hy : b ≤ y.snd
⊢ (⊥, b).fst ≤ x.fst
case mp.refine'_4
α : Type u_1
β : Type u_2
inst✝³ : PartialOrder α
inst✝² : PartialOrder β
inst✝¹ : OrderBot α
inst✝ : OrderBot β
x y : α × β
h : Disjoint x y
b : β
hx : b ≤ x.snd
hy : b ≤ y.snd
⊢ (⊥, b).fst ≤ y.fst
[PROOFSTEP]
all_goals exact bot_le
[GOAL]
case mp.refine'_1
α : Type u_1
β : Type u_2
inst✝³ : PartialOrder α
inst✝² : PartialOrder β
inst✝¹ : OrderBot α
inst✝ : OrderBot β
x y : α × β
h : Disjoint x y
a : α
hx : a ≤ x.fst
hy : a ≤ y.fst
⊢ (a, ⊥).snd ≤ x.snd
[PROOFSTEP]
exact bot_le
[GOAL]
case mp.refine'_2
α : Type u_1
β : Type u_2
inst✝³ : PartialOrder α
inst✝² : PartialOrder β
inst✝¹ : OrderBot α
inst✝ : OrderBot β
x y : α × β
h : Disjoint x y
a : α
hx : a ≤ x.fst
hy : a ≤ y.fst
⊢ (a, ⊥).snd ≤ y.snd
[PROOFSTEP]
exact bot_le
[GOAL]
case mp.refine'_3
α : Type u_1
β : Type u_2
inst✝³ : PartialOrder α
inst✝² : PartialOrder β
inst✝¹ : OrderBot α
inst✝ : OrderBot β
x y : α × β
h : Disjoint x y
b : β
hx : b ≤ x.snd
hy : b ≤ y.snd
⊢ (⊥, b).fst ≤ x.fst
[PROOFSTEP]
exact bot_le
[GOAL]
case mp.refine'_4
α : Type u_1
β : Type u_2
inst✝³ : PartialOrder α
inst✝² : PartialOrder β
inst✝¹ : OrderBot α
inst✝ : OrderBot β
x y : α × β
h : Disjoint x y
b : β
hx : b ≤ x.snd
hy : b ≤ y.snd
⊢ (⊥, b).fst ≤ y.fst
[PROOFSTEP]
exact bot_le
[GOAL]
case mpr
α : Type u_1
β : Type u_2
inst✝³ : PartialOrder α
inst✝² : PartialOrder β
inst✝¹ : OrderBot α
inst✝ : OrderBot β
x y : α × β
⊢ Disjoint x.fst y.fst ∧ Disjoint x.snd y.snd → Disjoint x y
[PROOFSTEP]
rintro ⟨ha, hb⟩ z hza hzb
[GOAL]
case mpr.intro
α : Type u_1
β : Type u_2
inst✝³ : PartialOrder α
inst✝² : PartialOrder β
inst✝¹ : OrderBot α
inst✝ : OrderBot β
x y : α × β
ha : Disjoint x.fst y.fst
hb : Disjoint x.snd y.snd
z : α × β
hza : z ≤ x
hzb : z ≤ y
⊢ z ≤ ⊥
[PROOFSTEP]
refine' ⟨ha hza.1 hzb.1, hb hza.2 hzb.2⟩
[GOAL]
α : Type u_1
β : Type u_2
inst✝³ : PartialOrder α
inst✝² : PartialOrder β
inst✝¹ : BoundedOrder α
inst✝ : BoundedOrder β
x y : α × β
⊢ IsCompl x y ↔ IsCompl x.fst y.fst ∧ IsCompl x.snd y.snd
[PROOFSTEP]
simp_rw [isCompl_iff, Prod.disjoint_iff, Prod.codisjoint_iff, and_and_and_comm]
[GOAL]
α : Type u_1
inst✝¹ : Lattice α
inst✝ : BoundedOrder α
a b : Complementeds α
⊢ ↑a ≤ ↑b ↔ a ≤ b
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : BoundedOrder α
a b : Complementeds α
⊢ Disjoint ↑a ↑b ↔ Disjoint a b
[PROOFSTEP]
rw [disjoint_iff, disjoint_iff, ← coe_inf, ← coe_bot, coe_inj]
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : BoundedOrder α
a b : Complementeds α
⊢ Codisjoint ↑a ↑b ↔ Codisjoint a b
[PROOFSTEP]
rw [codisjoint_iff, codisjoint_iff, ← coe_sup, ← coe_top, coe_inj]
[GOAL]
α : Type u_1
inst✝¹ : DistribLattice α
inst✝ : BoundedOrder α
a b : Complementeds α
⊢ IsCompl ↑a ↑b ↔ IsCompl a b
[PROOFSTEP]
simp_rw [isCompl_iff, disjoint_coe, codisjoint_coe]
|
module Main (
main,
StatisticsSuite (..),
runSuite
) where
import Prelude
import Statistics (runFold)
import qualified TextStatistics as TS
import Control.Applicative
import Data.Text.Lazy as T
import qualified Data.Text.Lazy.Encoding as E
import qualified Data.ByteString.Lazy as B
data StatisticsSuite = StatisticsSuite {
wordCount :: Int,
lineCount :: Int,
averageWordLength :: Maybe Float,
mostCommonLetter :: Maybe Char
} deriving (Eq, Ord, Show)
statisticsSuite :: TS.TextStatistics StatisticsSuite
statisticsSuite = StatisticsSuite <$> TS.wordCount <*> TS.lineCount <*> TS.averageWordLength <*> TS.mostCommonLetter
runSuite :: T.Text -> StatisticsSuite
runSuite = runFold foldl' statisticsSuite
main :: IO ()
main = do
content <- fmap E.decodeUtf8 B.getContents
print $ runSuite $ content
|
[STATEMENT]
lemma (in group) inj_on_g:
"\<lbrakk>H \<subseteq> carrier G; a \<in> carrier G\<rbrakk> \<Longrightarrow> inj_on (\<lambda>y. y \<otimes> a) H"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>H \<subseteq> carrier G; a \<in> carrier G\<rbrakk> \<Longrightarrow> inj_on (\<lambda>y. y \<otimes> a) H
[PROOF STEP]
by (force simp add: inj_on_def subsetD) |
-- Andreas, 2018-06-14, issue #2513, surviving shape-irrelevance annotations.
data Wrap (A : Set) : Set where
@shape-irrelevant wrap : A → Wrap A
|
State Before: E : Type u
inst✝² : NormedAddCommGroup E
inst✝¹ : NormedSpace ℂ E
inst✝ : CompleteSpace E
f : ℂ → E
z w : ℂ
s : Set ℂ
hs : Set.Countable s
Hc : ContinuousOn f ([[z.re, w.re]] ×ℂ [[z.im, w.im]])
Hd :
∀ (x : ℂ), x ∈ Ioo (min z.re w.re) (max z.re w.re) ×ℂ Ioo (min z.im w.im) (max z.im w.im) \ s → DifferentiableAt ℂ f x
⊢ ((((∫ (x : ℝ) in z.re..w.re, f (↑x + ↑z.im * I)) - ∫ (x : ℝ) in z.re..w.re, f (↑x + ↑w.im * I)) +
I • ∫ (y : ℝ) in z.im..w.im, f (↑w.re + ↑y * I)) -
I • ∫ (y : ℝ) in z.im..w.im, f (↑z.re + ↑y * I)) =
0 State After: E : Type u
inst✝² : NormedAddCommGroup E
inst✝¹ : NormedSpace ℂ E
inst✝ : CompleteSpace E
f : ℂ → E
z w : ℂ
s : Set ℂ
hs : Set.Countable s
Hc : ContinuousOn f ([[z.re, w.re]] ×ℂ [[z.im, w.im]])
Hd :
∀ (x : ℂ), x ∈ Ioo (min z.re w.re) (max z.re w.re) ×ℂ Ioo (min z.im w.im) (max z.im w.im) \ s → DifferentiableAt ℂ f x
this :
∀ (z : ℂ),
I • ↑(ContinuousLinearMap.restrictScalars ℝ (fderiv ℂ f z)) 1 =
↑(ContinuousLinearMap.restrictScalars ℝ (fderiv ℂ f z)) I
⊢ ((((∫ (x : ℝ) in z.re..w.re, f (↑x + ↑z.im * I)) - ∫ (x : ℝ) in z.re..w.re, f (↑x + ↑w.im * I)) +
I • ∫ (y : ℝ) in z.im..w.im, f (↑w.re + ↑y * I)) -
I • ∫ (y : ℝ) in z.im..w.im, f (↑z.re + ↑y * I)) =
0 Tactic: have : ∀ z, I • (fderiv ℂ f z).restrictScalars ℝ 1 = (fderiv ℂ f z).restrictScalars ℝ I := fun z ↦
by rw [(fderiv ℂ f _).coe_restrictScalars', ← (fderiv ℂ f _).map_smul, smul_eq_mul, mul_one] State Before: E : Type u
inst✝² : NormedAddCommGroup E
inst✝¹ : NormedSpace ℂ E
inst✝ : CompleteSpace E
f : ℂ → E
z w : ℂ
s : Set ℂ
hs : Set.Countable s
Hc : ContinuousOn f ([[z.re, w.re]] ×ℂ [[z.im, w.im]])
Hd :
∀ (x : ℂ), x ∈ Ioo (min z.re w.re) (max z.re w.re) ×ℂ Ioo (min z.im w.im) (max z.im w.im) \ s → DifferentiableAt ℂ f x
this :
∀ (z : ℂ),
I • ↑(ContinuousLinearMap.restrictScalars ℝ (fderiv ℂ f z)) 1 =
↑(ContinuousLinearMap.restrictScalars ℝ (fderiv ℂ f z)) I
⊢ ((((∫ (x : ℝ) in z.re..w.re, f (↑x + ↑z.im * I)) - ∫ (x : ℝ) in z.re..w.re, f (↑x + ↑w.im * I)) +
I • ∫ (y : ℝ) in z.im..w.im, f (↑w.re + ↑y * I)) -
I • ∫ (y : ℝ) in z.im..w.im, f (↑z.re + ↑y * I)) =
0 State After: no goals Tactic: refine (integral_boundary_rect_of_hasFDerivAt_real_off_countable f
(fun z => (fderiv ℂ f z).restrictScalars ℝ) z w s hs Hc
(fun x hx => (Hd x hx).hasFDerivAt.restrictScalars ℝ) ?_).trans ?_ <;> simp [this] State Before: E : Type u
inst✝² : NormedAddCommGroup E
inst✝¹ : NormedSpace ℂ E
inst✝ : CompleteSpace E
f : ℂ → E
z✝ w : ℂ
s : Set ℂ
hs : Set.Countable s
Hc : ContinuousOn f ([[z✝.re, w.re]] ×ℂ [[z✝.im, w.im]])
Hd :
∀ (x : ℂ),
x ∈ Ioo (min z✝.re w.re) (max z✝.re w.re) ×ℂ Ioo (min z✝.im w.im) (max z✝.im w.im) \ s → DifferentiableAt ℂ f x
z : ℂ
⊢ I • ↑(ContinuousLinearMap.restrictScalars ℝ (fderiv ℂ f z)) 1 =
↑(ContinuousLinearMap.restrictScalars ℝ (fderiv ℂ f z)) I State After: no goals Tactic: rw [(fderiv ℂ f _).coe_restrictScalars', ← (fderiv ℂ f _).map_smul, smul_eq_mul, mul_one] |
lemma multiplicity_one_nat [simp]: "multiplicity p (Suc 0) = 0" |
"""
Request object for the internal server of the engine.
"""
mutable struct InternalRequest
operation::Symbol
query::String
max_matches::Int
search_method::Symbol
searchable_filters::Vector{Symbol}
max_suggestions::Int
return_fields::Vector{Symbol}
custom_weights::Dict{Symbol}
request_id_key::Symbol
sort_fields::Vector{Symbol}
sort_reverse::Bool
response_size::Int
response_page::Int
input_parser::Symbol
ranker::Symbol
recommender::Symbol
end
# Keyword argument constructor
InternalRequest(;operation=:uninitialized_request,
query="",
max_matches=DEFAULT_MAX_MATCHES,
search_method=DEFAULT_SEARCH_METHOD,
searchable_filters=Symbol[],
max_suggestions=DEFAULT_MAX_SUGGESTIONS,
return_fields=Symbol[],
custom_weights=DEFAULT_CUSTOM_WEIGHTS,
request_id_key=Symbol(""),
sort_fields=DEFAULT_SORT_FIELDS,
sort_reverse=DEFAULT_SORT_REVERSE,
response_size=DEFAULT_RESPONSE_SIZE,
response_page=DEFAULT_RESPONSE_PAGE,
input_parser=DEFAULT_INPUT_PARSER_NAME,
ranker=DEFAULT_RANKER_NAME,
recommender=DEFAULT_RECOMMENDER_NAME)=
InternalRequest(operation,
query,
max_matches,
search_method,
searchable_filters,
max_suggestions,
return_fields,
custom_weights,
request_id_key,
sort_fields,
sort_reverse,
response_size,
response_page,
input_parser,
ranker,
recommender)
#=
Converts an InternalRequest to Dict - the latter will have
String keys with names identical to the request type fields
=#
convert(::Type{Dict}, request::T) where {T<:InternalRequest}= begin
returned_dict = Dict{Symbol, Any}()
for field in fieldnames(T)
push!(returned_dict, field => getproperty(request, field))
end
return returned_dict
end
request2dict(request::T) where {T<:InternalRequest} =
Dict(field => getproperty(request, field) for field in fieldnames(T))
request2json(request::T) where {T<:InternalRequest} =
JSON.json(request2dict(request))
"""
Default request.
"""
const UNINITIALIZED_REQUEST = InternalRequest(operation=:uninitialized_request)
"""
Request corresponding to an error i.e. in parsing.
"""
const ERRORED_REQUEST = InternalRequest(operation=:error)
"""
Request corresponding to a kill server command.
"""
const KILL_REQUEST = InternalRequest(operation=:kill)
"""
Request corresponding to a searcher read configuration command.
"""
const READCONFIGS_REQUEST = InternalRequest(operation=:read_configs)
"""
Request corresponding to an environment operation command.
"""
const ENVOP_REQUEST = InternalRequest(operation=:envop, query="{}")
"""
parse(::Type{InternalRequest}, request::AbstractString)
Parses an outside request received from a client
into an `InternalRequest` usable by the search server.
"""
function parse(::Type{T}, outside_request::AbstractString) where {T<:InternalRequest}
request = T()
try
data = JSON.parse(outside_request, dicttype=Dict{Symbol,Any})
datafields = keys(data)
fields = fieldnames(T)
ftypes = fieldtypes(T)
missing_fields = setdiff(fields, datafields)
!isempty(missing_fields) &&
@warn "Possibly malformed request, missing fields: $missing_fields"
for (ft, field) in zip(ftypes, fields)
in(field, datafields) &&
setproperty!(request, field, __parse(ft, data[field]))
end
catch e
@debug "Request parse error: $e. Returning ERRORED_REQUEST..."
request = ERRORED_REQUEST
end
return request
end
"""
Standard response terminator. It is used in the client-server
communication mark the end of sent and received messages.
"""
const RESPONSE_TERMINATOR="\n"
|
[STATEMENT]
lemma filter_M_subset_2: "h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys \<Longrightarrow> h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'
\<Longrightarrow> (\<And>x. pure (P x) h) \<Longrightarrow> (\<And>x. pure (P x) h')
\<Longrightarrow> (\<forall>b. \<forall>x \<in> set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r b \<longrightarrow> b)
\<Longrightarrow> set ys \<subseteq> set ys'"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; \<forall>b. \<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r b \<longrightarrow> b\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; \<forall>b. \<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r b \<longrightarrow> b\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'
[PROOF STEP]
assume 1: "h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys" and 2: "h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'"
and 3: "(\<And>x. pure (P x) h)" and "(\<And>x. pure (P x) h')"
and 4: "\<forall>b. \<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r b \<longrightarrow> b"
[PROOF STATE]
proof (state)
this:
h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys
h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'
pure (P ?x) h
pure (P ?x) h'
\<forall>b. \<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r b \<longrightarrow> b
goal (1 subgoal):
1. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; \<forall>b. \<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r b \<longrightarrow> b\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'
[PROOF STEP]
have h1: "\<forall>x \<in> set xs. h' \<turnstile> ok (P x)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>x\<in>set xs. h' \<turnstile> ok P x
[PROOF STEP]
using 2 3 \<open>(\<And>x. pure (P x) h')\<close>
[PROOF STATE]
proof (prove)
using this:
h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'
pure (P ?x) h
pure (P ?x) h'
goal (1 subgoal):
1. \<forall>x\<in>set xs. h' \<turnstile> ok P x
[PROOF STEP]
apply(induct xs arbitrary: ys')
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>ys'. \<lbrakk>h' \<turnstile> filter_M P [] \<rightarrow>\<^sub>r ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'\<rbrakk> \<Longrightarrow> \<forall>x\<in>set []. h' \<turnstile> ok P x
2. \<And>a xs ys'. \<lbrakk>\<And>ys'. \<lbrakk>h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'\<rbrakk> \<Longrightarrow> \<forall>x\<in>set xs. h' \<turnstile> ok P x; h' \<turnstile> filter_M P (a # xs) \<rightarrow>\<^sub>r ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'\<rbrakk> \<Longrightarrow> \<forall>x\<in>set (a # xs). h' \<turnstile> ok P x
[PROOF STEP]
by(auto elim!: bind_returns_result_E2)
[PROOF STATE]
proof (state)
this:
\<forall>x\<in>set xs. h' \<turnstile> ok P x
goal (1 subgoal):
1. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; \<forall>b. \<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r b \<longrightarrow> b\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
\<forall>x\<in>set xs. h' \<turnstile> ok P x
[PROOF STEP]
have 5: "\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True"
[PROOF STATE]
proof (prove)
using this:
\<forall>x\<in>set xs. h' \<turnstile> ok P x
goal (1 subgoal):
1. \<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True
[PROOF STEP]
using 4
[PROOF STATE]
proof (prove)
using this:
\<forall>x\<in>set xs. h' \<turnstile> ok P x
\<forall>b. \<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r b \<longrightarrow> b
goal (1 subgoal):
1. \<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True
[PROOF STEP]
apply(auto)[1]
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>x. \<lbrakk>\<forall>x\<in>set xs. h' \<turnstile> ok P x; \<forall>b. \<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r b \<longrightarrow> b; x \<in> set xs; h \<turnstile> P x \<rightarrow>\<^sub>r True\<rbrakk> \<Longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True
[PROOF STEP]
by (metis is_OK_returns_result_E)
[PROOF STATE]
proof (state)
this:
\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True
goal (1 subgoal):
1. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; \<forall>b. \<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r b \<longrightarrow> b\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. set ys \<subseteq> set ys'
[PROOF STEP]
using 1 2 3 5 \<open>(\<And>x. pure (P x) h')\<close>
[PROOF STATE]
proof (prove)
using this:
h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys
h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'
pure (P ?x) h
\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True
pure (P ?x) h'
goal (1 subgoal):
1. set ys \<subseteq> set ys'
[PROOF STEP]
apply(induct xs arbitrary: ys ys')
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P [] \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P [] \<rightarrow>\<^sub>r ys'; \<And>x. pure (P x) h; \<forall>x\<in>set []. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; \<And>x. pure (P x) h'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'
2. \<And>a xs ys ys'. \<lbrakk>\<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'; \<And>x. pure (P x) h; \<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; \<And>x. pure (P x) h'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; h \<turnstile> filter_M P (a # xs) \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P (a # xs) \<rightarrow>\<^sub>r ys'; \<And>x. pure (P x) h; \<forall>x\<in>set (a # xs). h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; \<And>x. pure (P x) h'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'
[PROOF STEP]
apply(auto)[1]
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>a xs ys ys'. \<lbrakk>\<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'; \<And>x. pure (P x) h; \<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; \<And>x. pure (P x) h'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; h \<turnstile> filter_M P (a # xs) \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P (a # xs) \<rightarrow>\<^sub>r ys'; \<And>x. pure (P x) h; \<forall>x\<in>set (a # xs). h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; \<And>x. pure (P x) h'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'
[PROOF STEP]
apply(auto elim!: bind_returns_result_E2 split: if_splits)[1]
[PROOF STATE]
proof (prove)
goal (7 subgoals):
1. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r False; h' \<turnstile> P a \<rightarrow>\<^sub>r True; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; \<not> h \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; \<not> xa; x \<in> set xc; xb; x \<notin> set xd\<rbrakk> \<Longrightarrow> x = a
2. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r False; h' \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; \<not> h \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; \<not> xa; x \<in> set xc; \<not> xb\<rbrakk> \<Longrightarrow> x \<in> set xd
3. \<And>a xs xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r True; h' \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; xa; \<not> xb\<rbrakk> \<Longrightarrow> a \<in> set xd
4. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r True; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; xa; x \<in> set xc; xb; x \<notin> set xd\<rbrakk> \<Longrightarrow> x = a
5. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r True; h' \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; xa; x \<in> set xc; \<not> xb\<rbrakk> \<Longrightarrow> x \<in> set xd
6. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; \<not> xa; x \<in> set xc; xb; x \<notin> set xd\<rbrakk> \<Longrightarrow> x = a
7. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r False; h' \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; \<not> xa; x \<in> set xc; \<not> xb\<rbrakk> \<Longrightarrow> x \<in> set xd
[PROOF STEP]
apply auto[1]
[PROOF STATE]
proof (prove)
goal (6 subgoals):
1. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r False; h' \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; \<not> h \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; \<not> xa; x \<in> set xc; \<not> xb\<rbrakk> \<Longrightarrow> x \<in> set xd
2. \<And>a xs xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r True; h' \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; xa; \<not> xb\<rbrakk> \<Longrightarrow> a \<in> set xd
3. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r True; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; xa; x \<in> set xc; xb; x \<notin> set xd\<rbrakk> \<Longrightarrow> x = a
4. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r True; h' \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; xa; x \<in> set xc; \<not> xb\<rbrakk> \<Longrightarrow> x \<in> set xd
5. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; \<not> xa; x \<in> set xc; xb; x \<notin> set xd\<rbrakk> \<Longrightarrow> x = a
6. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r False; h' \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; \<not> xa; x \<in> set xc; \<not> xb\<rbrakk> \<Longrightarrow> x \<in> set xd
[PROOF STEP]
apply auto[1]
[PROOF STATE]
proof (prove)
goal (5 subgoals):
1. \<And>a xs xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r True; h' \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; xa; \<not> xb\<rbrakk> \<Longrightarrow> a \<in> set xd
2. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r True; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; xa; x \<in> set xc; xb; x \<notin> set xd\<rbrakk> \<Longrightarrow> x = a
3. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r True; h' \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; xa; x \<in> set xc; \<not> xb\<rbrakk> \<Longrightarrow> x \<in> set xd
4. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; \<not> xa; x \<in> set xc; xb; x \<notin> set xd\<rbrakk> \<Longrightarrow> x = a
5. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r False; h' \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; \<not> xa; x \<in> set xc; \<not> xb\<rbrakk> \<Longrightarrow> x \<in> set xd
[PROOF STEP]
apply(metis returns_result_eq)
[PROOF STATE]
proof (prove)
goal (4 subgoals):
1. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r True; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; xa; x \<in> set xc; xb; x \<notin> set xd\<rbrakk> \<Longrightarrow> x = a
2. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r True; h' \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; xa; x \<in> set xc; \<not> xb\<rbrakk> \<Longrightarrow> x \<in> set xd
3. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; \<not> xa; x \<in> set xc; xb; x \<notin> set xd\<rbrakk> \<Longrightarrow> x = a
4. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r False; h' \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; \<not> xa; x \<in> set xc; \<not> xb\<rbrakk> \<Longrightarrow> x \<in> set xd
[PROOF STEP]
apply auto[1]
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r True; h' \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; xa; x \<in> set xc; \<not> xb\<rbrakk> \<Longrightarrow> x \<in> set xd
2. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; \<not> xa; x \<in> set xc; xb; x \<notin> set xd\<rbrakk> \<Longrightarrow> x = a
3. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r False; h' \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; \<not> xa; x \<in> set xc; \<not> xb\<rbrakk> \<Longrightarrow> x \<in> set xd
[PROOF STEP]
apply auto[1]
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; \<not> xa; x \<in> set xc; xb; x \<notin> set xd\<rbrakk> \<Longrightarrow> x = a
2. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r False; h' \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; \<not> xa; x \<in> set xc; \<not> xb\<rbrakk> \<Longrightarrow> x \<in> set xd
[PROOF STEP]
apply auto[1]
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>a xs x xa xb xc xd. \<lbrakk>\<forall>x\<in>set xs. h \<turnstile> P x \<rightarrow>\<^sub>r True \<longrightarrow> h' \<turnstile> P x \<rightarrow>\<^sub>r True; h \<turnstile> P a \<rightarrow>\<^sub>r False; h' \<turnstile> P a \<rightarrow>\<^sub>r False; h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xc; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r xd; h' \<turnstile> P a \<rightarrow>\<^sub>r True; \<And>ys ys'. \<lbrakk>h \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys; h' \<turnstile> filter_M P xs \<rightarrow>\<^sub>r ys'\<rbrakk> \<Longrightarrow> set ys \<subseteq> set ys'; \<And>x. pure (P x) h; \<And>x. pure (P x) h'; \<not> xa; x \<in> set xc; \<not> xb\<rbrakk> \<Longrightarrow> x \<in> set xd
[PROOF STEP]
by(auto)
[PROOF STATE]
proof (state)
this:
set ys \<subseteq> set ys'
goal:
No subgoals!
[PROOF STEP]
qed |
[STATEMENT]
lemma squarefree_nat_code_naive [code]:
"squarefree_nat n \<longleftrightarrow> n \<noteq> 0 \<and> (\<forall>k\<in>{2..n}. \<not>k ^ 2 dvd n)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. squarefree_nat n = (n \<noteq> 0 \<and> (\<forall>k\<in>{2..n}. \<not> k\<^sup>2 dvd n))
[PROOF STEP]
proof safe
[PROOF STATE]
proof (state)
goal (3 subgoals):
1. squarefree_nat n \<Longrightarrow> 0 < n
2. \<And>k. \<lbrakk>squarefree_nat n; k \<in> {2..n}; k\<^sup>2 dvd n\<rbrakk> \<Longrightarrow> False
3. \<lbrakk>\<forall>k\<in>{2..n}. \<not> k\<^sup>2 dvd n; 0 < n\<rbrakk> \<Longrightarrow> squarefree_nat n
[PROOF STEP]
assume *: "\<forall>k\<in>{2..n}. \<not> k\<^sup>2 dvd n" and n: "n > 0"
[PROOF STATE]
proof (state)
this:
\<forall>k\<in>{2..n}. \<not> k\<^sup>2 dvd n
0 < n
goal (3 subgoals):
1. squarefree_nat n \<Longrightarrow> 0 < n
2. \<And>k. \<lbrakk>squarefree_nat n; k \<in> {2..n}; k\<^sup>2 dvd n\<rbrakk> \<Longrightarrow> False
3. \<lbrakk>\<forall>k\<in>{2..n}. \<not> k\<^sup>2 dvd n; 0 < n\<rbrakk> \<Longrightarrow> squarefree_nat n
[PROOF STEP]
show "squarefree_nat n"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. squarefree_nat n
[PROOF STEP]
unfolding squarefree_nat_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. squarefree n
[PROOF STEP]
proof (rule squarefreeI)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x. x\<^sup>2 dvd n \<Longrightarrow> is_unit x
[PROOF STEP]
fix k
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x. x\<^sup>2 dvd n \<Longrightarrow> is_unit x
[PROOF STEP]
assume k: "k ^ 2 dvd n"
[PROOF STATE]
proof (state)
this:
k\<^sup>2 dvd n
goal (1 subgoal):
1. \<And>x. x\<^sup>2 dvd n \<Longrightarrow> is_unit x
[PROOF STEP]
have "k dvd n"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. k dvd n
[PROOF STEP]
by (rule dvd_trans[OF _ k]) auto
[PROOF STATE]
proof (state)
this:
k dvd n
goal (1 subgoal):
1. \<And>x. x\<^sup>2 dvd n \<Longrightarrow> is_unit x
[PROOF STEP]
with n
[PROOF STATE]
proof (chain)
picking this:
0 < n
k dvd n
[PROOF STEP]
have "k \<le> n"
[PROOF STATE]
proof (prove)
using this:
0 < n
k dvd n
goal (1 subgoal):
1. k \<le> n
[PROOF STEP]
by (intro dvd_imp_le)
[PROOF STATE]
proof (state)
this:
k \<le> n
goal (1 subgoal):
1. \<And>x. x\<^sup>2 dvd n \<Longrightarrow> is_unit x
[PROOF STEP]
with bspec[OF *, of k] k
[PROOF STATE]
proof (chain)
picking this:
k \<in> {2..n} \<Longrightarrow> \<not> k\<^sup>2 dvd n
k\<^sup>2 dvd n
k \<le> n
[PROOF STEP]
have "\<not>k > 1"
[PROOF STATE]
proof (prove)
using this:
k \<in> {2..n} \<Longrightarrow> \<not> k\<^sup>2 dvd n
k\<^sup>2 dvd n
k \<le> n
goal (1 subgoal):
1. \<not> 1 < k
[PROOF STEP]
by (intro notI) auto
[PROOF STATE]
proof (state)
this:
\<not> 1 < k
goal (1 subgoal):
1. \<And>x. x\<^sup>2 dvd n \<Longrightarrow> is_unit x
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
\<not> 1 < k
goal (1 subgoal):
1. \<And>x. x\<^sup>2 dvd n \<Longrightarrow> is_unit x
[PROOF STEP]
from k and n
[PROOF STATE]
proof (chain)
picking this:
k\<^sup>2 dvd n
0 < n
[PROOF STEP]
have "k \<noteq> 0"
[PROOF STATE]
proof (prove)
using this:
k\<^sup>2 dvd n
0 < n
goal (1 subgoal):
1. k \<noteq> 0
[PROOF STEP]
by (intro notI) auto
[PROOF STATE]
proof (state)
this:
k \<noteq> 0
goal (1 subgoal):
1. \<And>x. x\<^sup>2 dvd n \<Longrightarrow> is_unit x
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
\<not> 1 < k
k \<noteq> 0
[PROOF STEP]
have "k = 1"
[PROOF STATE]
proof (prove)
using this:
\<not> 1 < k
k \<noteq> 0
goal (1 subgoal):
1. k = 1
[PROOF STEP]
by presburger
[PROOF STATE]
proof (state)
this:
k = 1
goal (1 subgoal):
1. \<And>x. x\<^sup>2 dvd n \<Longrightarrow> is_unit x
[PROOF STEP]
thus "is_unit k"
[PROOF STATE]
proof (prove)
using this:
k = 1
goal (1 subgoal):
1. is_unit k
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
is_unit k
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
squarefree_nat n
goal (2 subgoals):
1. squarefree_nat n \<Longrightarrow> 0 < n
2. \<And>k. \<lbrakk>squarefree_nat n; k \<in> {2..n}; k\<^sup>2 dvd n\<rbrakk> \<Longrightarrow> False
[PROOF STEP]
qed (auto simp: squarefree_nat_def squarefree_def intro!: Nat.gr0I) |
theory PointedSetFactorization
imports Main
PointedSet
begin
locale pointed_set_factorization =
S: set_category S +
F: "functor" C S F
for S :: "'s comp"
and C :: "'c comp"
and F :: "'c \<Rightarrow> 's"
and basepoint :: "'c \<Rightarrow> 's" +
assumes pointed_obj : "\<And>c. F.A.ide c \<Longrightarrow> pointed_set.Obj' ((basepoint c) , S.set (F c))"
and pointed_arr : "\<And>c. F.A.arr c \<Longrightarrow> S.Fun (F c) (basepoint (F.A.dom c)) = basepoint (F.A.cod c)"
begin
interpretation P : pointed_set.
interpretation PC : category P.pointed_set_comp
using P.is_category.
definition FOb where
"FOb c = (basepoint c, S.set (F c))"
definition map where
"map = MkFunctor C P.pointed_set_comp
(\<lambda>c. Some (S.Fun (F c) , FOb (F.A.dom c) , FOb (F.A.cod c) ))"
lemma is_functor: "functor C P.pointed_set_comp map"
unfolding functor_def
apply (simp add: F.A.category_axioms P.is_category)
unfolding functor_axioms_def
apply auto
apply (simp add: map_def)
proof-
show arr: "\<And>f. F.A.arr f \<Longrightarrow> PC.arr (local.map f)"
unfolding map_def apply simp
unfolding P.arr_char apply simp
unfolding P.Arr'_def apply auto
proof-
fix f
assume arr_f : "F.A.arr f"
show "setcat.Arr (S.Fun (F f), snd (FOb (F.A.dom f)), snd (FOb (F.A.cod f)))"
unfolding FOb_def apply simp
unfolding setcat.Arr_def
using S.Fun_mapsto [OF F.preserves_arr [OF arr_f]]
unfolding F.preserves_dom [OF arr_f]
unfolding F.preserves_cod [OF arr_f]
by simp
show "P.Obj' (FOb (F.A.dom f))"
unfolding FOb_def
apply (rule_tac pointed_obj)
using F.A.ide_dom [OF arr_f].
show "P.Obj' (FOb (F.A.cod f))"
unfolding FOb_def
apply (rule_tac pointed_obj)
using F.A.ide_cod [OF arr_f].
show "S.Fun (F f) (fst (FOb (F.A.dom f))) = fst (FOb (F.A.cod f))"
unfolding FOb_def apply simp
using pointed_arr [OF arr_f].
qed
show dom : "\<And>f. F.A.arr f \<Longrightarrow> PC.dom (local.map f) = local.map (F.A.dom f)"
unfolding P.dom_char [OF arr]
unfolding map_def apply simp
unfolding P.Id'_def apply simp
unfolding FOb_def by simp
show cod : "\<And>f. F.A.arr f \<Longrightarrow> PC.cod (local.map f) = local.map (F.A.cod f)"
unfolding P.cod_char [OF arr]
unfolding map_def apply simp
unfolding P.Id'_def apply simp
unfolding FOb_def by simp
fix g f
assume arr_gf : "F.A.seq g f"
have arr_mgf : "PC.seq (map g) (map f)"
apply (rule_tac F.A.seqE [OF arr_gf])
apply (rule_tac PC.seqI)
unfolding dom cod
using arr by simp_all
show "local.map (C g f) = P.pointed_set_comp (local.map g) (local.map f)"
apply (rule_tac reverse_equality)
apply (rule_tac P.comp_eq_char2)
apply (rule_tac arr_mgf)
apply (rule_tac arr [OF arr_gf])
apply (subst dom)
using arr_gf apply blast
apply (subst dom [OF arr_gf])
using F.A.dom_comp [OF arr_gf] apply simp
apply (subst cod)
using arr_gf apply blast
apply (subst cod [OF arr_gf])
using F.A.cod_comp [OF arr_gf] apply simp
proof-
fix x
assume "x \<in> snd (fst (snd (the (local.map f))))"
then have x_in_dom : "x \<in> S.set (F (F.A.dom f))"
apply (rule_tac F.A.seqE [OF arr_gf])
unfolding map_def
apply simp
unfolding FOb_def by simp
show "fst (the (local.map g)) (fst (the (local.map f)) x) = fst (the (local.map (C g f))) x"
apply (rule_tac F.A.seqE [OF arr_gf])
unfolding map_def
by (simp add: x_in_dom)
qed
qed
end
end
|
(*-------------------------------------------*
| |
| Liveness of Specifications |
| |
*-------------------------------------------*)
theory SeqCtrl_all
imports MBP_spec
begin
(*************************************************************
1. ParaAlgo
2.
3.
4.
*************************************************************)
(* ----------------------------------------- *
| deadlock free |
* ----------------------------------------- *)
theorem SeqCtrl_DeadlockFree:
"finite Blks ==> dag Blks Deps
==> DeadlockFree (SeqCtrl Blks Deps) (obsEvent Blks) finish"
apply (simp add: DeadlockFree_def)
apply (simp add: failures_def)
apply (intro allI impI)
apply (elim exE conjE)
apply (simp add: SeqCtrl_def)
apply (insert Seq_trns[of Blks Deps])
apply (drule_tac x="s" in spec)
apply (drule_tac x="{}" in spec)
apply (drule_tac x="P'" in spec)
apply (simp)
apply (elim exE conjE disjE)
(* 1 *)
apply (simp)
apply (simp add: refs_def)
apply (rotate_tac 5)
apply (erule contrapos_pp)
apply (simp (no_asm) add: subset_iff)
apply (case_tac "S' = Blks")
(* finish *)
apply (rule_tac x="finish" in exI)
apply (simp add: obsEvent_def)
apply (simp add: trn_ex_def)
apply (rule_tac x="STOP" in exI)
apply (simp add: Seq_trn_finish)
(* blk *)
apply (insert enable_nonempty_all[of Blks Deps])
apply (drule_tac x="S'" in spec)
apply (simp)
apply (drule mp)
apply (force)
apply (subgoal_tac "EX n. n : enable Blks Deps S'")
apply (erule exE)
apply (rule_tac x="blk n" in exI)
apply (simp add: obsEvent_def)
apply (rule conjI)
apply (simp add: enable_def)
apply (simp add: trn_ex_def)
apply (rule_tac x="$Seq Blks Deps (insert n S')" in exI)
apply (simp add: Seq_trn_blk)
apply (simp add: enable_def)
apply (force)
apply (simp add: rem_tau_append)
done
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.