Datasets:
AI4M
/

text
stringlengths
0
3.34M
lemma open_Collect_positive: fixes f :: "'a::topological_space \<Rightarrow> real" assumes f: "continuous_on s f" shows "\<exists>A. open A \<and> A \<inter> s = {x\<in>s. 0 < f x}"
module TypeSerializers import Serialization: serialize, deserialize export AbstractTypeSerializer, SerializationTypeSerializer, serialize, deserialize abstract type AbstractTypeSerializer{T} end abstract type SerializationTypeSerializer{T} <: AbstractTypeSerializer{T} end function serialize(::Type{TSerializer}, value::T)::IO where {T, TSerializer <: SerializationTypeSerializer{T}} stream = IOBuffer(UInt8[], read = true, write = true) serialize(stream, value) return stream end function deserialize(::Type{TSerializer}, stream::IO)::T where {T, TSerializer <: SerializationTypeSerializer{T}} value = deserialize(stream) return value end end # module
Formal statement is: lemma locally_open_subset: assumes "locally P S" "openin (top_of_set S) t" shows "locally P t" Informal statement is: If $S$ is locally $P$ and $t$ is an open subset of $S$, then $t$ is locally $P$.
@testset "Active Set Core" begin # ActiveSetCore N = 10 p = 3 model = UnicycleGame(p=p) probsize = ProblemSize(N,model) ascore = ActiveSetCore(probsize) @test typeof(ascore) <: ActiveSetCore end
[STATEMENT] lemma rev_shiftl: "word_reverse w << n = word_reverse (w >> n)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. word_reverse w << n = word_reverse (w >> n) [PROOF STEP] by (simp add: shiftl_rev)
!------------------------------------------------------------------------------ !------------------------------------------------------------------------------ ! frc : A periodically forced system !------------------------------------------------------------------------------ !------------------------------------------------------------------------------ SUBROUTINE FUNC(NDIM,U,ICP,PAR,IJAC,F,DFDU,DFDP) ! ---------- ---- IMPLICIT NONE INTEGER, INTENT(IN) :: NDIM, ICP(*), IJAC DOUBLE PRECISION, INTENT(IN) :: U(NDIM), PAR(*) DOUBLE PRECISION, INTENT(OUT) :: F(NDIM) DOUBLE PRECISION, INTENT(INOUT) :: DFDU(NDIM,NDIM), DFDP(NDIM,*) DOUBLE PRECISION a,b,c,amp,beta,x,y,sn,cs,ss ! FHN parameters a = PAR(1) b = PAR(2) c = PAR(3) ! Forcing parameters amp = PAR(4) beta= PAR(5) ! FHN variables x=U(1) y=U(2) ! Forcing variables sn=U(3) cs=U(4) ss = sn**2 + cs**2 ! FHN equations F(1)= c * ( x - x**3/3 + y - amp*cs ) F(2)=-( x - a + b*y ) / c ! Oscillator F(3) = sn + beta*cs - sn*ss F(4) = -beta*sn + cs - cs*ss END SUBROUTINE FUNC SUBROUTINE STPNT(NDIM,U,PAR,t) ! ---------- ----- IMPLICIT NONE INTEGER, INTENT(IN) :: NDIM DOUBLE PRECISION, INTENT(INOUT) :: U(NDIM),PAR(*) DOUBLE PRECISION, INTENT(IN) :: t DOUBLE PRECISION a,b,c,amp,beta,TPI ! FHN parameters a = 0. b = 0.8 c = 3. PAR(1)=a PAR(2)=b PAR(3)=c ! Forcing parameters amp=0. beta=10 PAR(4)=amp PAR(5)=beta TPI=8*ATAN(1.d0) PAR(11)=TPI/beta ! Initial FHB stationary solution (assuming a=0) U(1)= 0. U(2)= 0. ! Initialize the oscillator U(3)=SIN(TPI*t) U(4)=COS(TPI*t) END SUBROUTINE STPNT SUBROUTINE BCND END SUBROUTINE BCND SUBROUTINE ICND END SUBROUTINE ICND SUBROUTINE FOPT END SUBROUTINE FOPT SUBROUTINE PVLS END SUBROUTINE PVLS
State Before: α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 a : α s✝ t✝ : Multiset α f✝ g✝ : α → Multiset β r : α → β → Prop p : γ → δ → Prop s : Multiset α t : Multiset β f : α → Multiset γ g : β → Multiset δ h : (r ⇒ Rel p) f g hst : Rel r s t ⊢ Rel p (bind s f) (bind t g) State After: case h α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 a : α s✝ t✝ : Multiset α f✝ g✝ : α → Multiset β r : α → β → Prop p : γ → δ → Prop s : Multiset α t : Multiset β f : α → Multiset γ g : β → Multiset δ h : (r ⇒ Rel p) f g hst : Rel r s t ⊢ Rel (Rel p) (map f s) (map g t) Tactic: apply rel_join State Before: case h α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 a : α s✝ t✝ : Multiset α f✝ g✝ : α → Multiset β r : α → β → Prop p : γ → δ → Prop s : Multiset α t : Multiset β f : α → Multiset γ g : β → Multiset δ h : (r ⇒ Rel p) f g hst : Rel r s t ⊢ Rel (Rel p) (map f s) (map g t) State After: case h α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 a : α s✝ t✝ : Multiset α f✝ g✝ : α → Multiset β r : α → β → Prop p : γ → δ → Prop s : Multiset α t : Multiset β f : α → Multiset γ g : β → Multiset δ h : (r ⇒ Rel p) f g hst : Rel r s t ⊢ Rel (fun a b => Rel p (f a) (g b)) s t Tactic: rw [rel_map] State Before: case h α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 a : α s✝ t✝ : Multiset α f✝ g✝ : α → Multiset β r : α → β → Prop p : γ → δ → Prop s : Multiset α t : Multiset β f : α → Multiset γ g : β → Multiset δ h : (r ⇒ Rel p) f g hst : Rel r s t ⊢ Rel (fun a b => Rel p (f a) (g b)) s t State After: no goals Tactic: exact hst.mono fun a _ b _ hr => h hr
theory T49 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) " nitpick[card nat=4,timeout=86400] oops end
module InsertInput import State import Cursor import Document %default total public export data InsertInput : Type where InsertChar : Char -> InsertInput InsertNormal : InsertInput InsertNewLine : InsertInput InsertBackspace : InsertInput parseChar : Char -> InsertInput parseChar c = case (ord c) of 127 => InsertBackspace 13 => InsertNewLine 27 => InsertNormal _ => InsertChar c export getInsertInput : IO InsertInput getInsertInput = parseChar <$> getChar
import json from moto.core.responses import BaseResponse from tests.deployment.sagemaker.sagemaker_moto.model import sagemaker_backends class SageMakerResponse(BaseResponse): """SageMaker response for moto mock. References API operations and result from https://docs.aws.amazon.com/sagemaker/latest/dg/API_Operations.html """ @property def request_body(self): return json.loads(self.body) @property def backend(self): return sagemaker_backends[self.region] def create_model(self): model_name = self.request_body['ModelName'] tags = self.request_body.get('Tags', []) primary_container = self.request_body['PrimaryContainer'] execution_role_arn = self.request_body['ExecutionRoleArn'] result = self.backend.create_model( model_name, tags, primary_container, execution_role_arn, self.region ) return json.dumps({'ModelArn': result['arn']}) def create_endpoint_config(self): config_name = self.request_body['EndpointConfigName'] production_variants = self.request_body['ProductionVariants'] result = self.backend.create_endpoint_config( config_name, production_variants, self.region ) return json.dumps({'EndpointConfigArn': result['arn']}) def create_endpoint(self): endpoint_name = self.request_body['EndpointName'] config_name = self.request_body['EndpointConfigName'] result = self.backend.create_endpoint(endpoint_name, config_name, self.region) return json.dumps({'EndpointArn': result['arn']}) def describe_endpoint(self): endpoint_name = self.request_body['EndpointName'] endpoint_description = self.backend.describe_endpoint(endpoint_name) return json.dumps(endpoint_description) def delete_model(self): model_name = self.request_body['ModelName'] self.backend.delete_model(model_name) return '' def delete_endpoint_config(self): config_name = self.request_body['EndpointConfigName'] self.backend.delete_endpoint_config(config_name) return '' def delete_endpoint(self): endpoint_name = self.request_body['EndpointName'] self.backend.delete_endpoint(endpoint_name) return '' def update_endpoint(self): endpoint_name = self.request_body['EndpointName'] config_name = self.request_body['EndpointConfigName'] result = self.backend.update_endpoint(endpoint_name, config_name) return json.dumps({'EndpointArn': result['arn']})
// [===========================================================================] // [ M o n e t a ] // [---------------------------------------------------------------------------] // [ ] // [ Copyright (C) 2005-2015 ] // [ Rodrigo Madera <[email protected]> ] // [ ] // [---------------------------------------------------------------------------] // [ Distributed under the Boost Software License, Version 1.0 ] // [ Read accompanying LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt ] // [===========================================================================] #pragma once #include "soci_includes.hxx" #include "../../../make_entity.hxx" #include "../../../traits/is_entity.hxx" #include "../../../traits/rtuple.hxx" #include <boost/fusion/view/zip_view.hpp> #include <boost/fusion/tuple.hpp> namespace moneta { namespace serialization { namespace soci { namespace detail { class fufu { ::soci::session& _session; public: fufu(::soci::session& session) : _session(session) { } template <typename T> typename boost::enable_if< traits::is_entity< typename boost::mpl::at_c<T, 0>::type >, void >::type operator()(T& pair) const { BOOST_MPL_ASSERT((boost::mpl::equal_to<boost::mpl::size<T>::type, boost::mpl::int_<2> >)); /* XXX */ const int id = boost::fusion::get<1>(pair); // XXX XXX XXX XXX XXX boost::fusion::get<0>(pair) = soci_read< typename traits::pure_type<typename boost::mpl::at_c<T, 0>::type>::type >(_session, id); } template <typename T> typename boost::enable_if< boost::mpl::not_< traits::is_entity< typename boost::mpl::at_c<T, 0>::type > >, void >::type operator()(T& pair) const { BOOST_MPL_ASSERT((boost::mpl::equal_to<boost::mpl::size<T>::type, boost::mpl::int_<2> >)); boost::fusion::get<0>(pair) = boost::fusion::get<1>(pair); } }; template <class Entity> Entity soci_xlate_read( ::soci::session& session, typename moneta::traits::rtuple<Entity>::type& rtuple ) { typedef boost::fusion::vector< traits::tuple<Entity>::type&, traits::rtuple<Entity>::type& > zip_vector_type; typename traits::tuple<Entity>::type tuple = make_tuple<Entity>(); boost::fusion::zip_view<zip_vector_type> zip(zip_vector_type(tuple, rtuple)); boost::fusion::for_each(zip, fufu(session)); Entity result; moneta::traits::to_tie(result) = tuple; return result; } }}}}
Alaska Airlines (AS, Seattle Tacoma Int'l) has outlined tentative deployment plans for its incoming fleet of thirty-two B737-9s due from Boeing (BOE, Chicago O'Hare). San Diego Int'l (1x daily starts August 15). Further revisions to the plan remain possible. Alaska Airlines is an existing B737 operator with eleven B737-700s, sixty-one B737-800s, twelve B737-900s, and seventy-five -900(ER)s currently in service for its passenger mainline unit.
imm.data <- read.table ("ESTIMATE_and_neo_antigens.txt", sep = "\t", header = TRUE, check.names = FALSE) nrow.df <- ncol (imm.data) - 6 mat.res <- data.frame () for (i in 1:nrow.df) { res1 <- anova (lm (ESTIMATE ~ Tissue + imm.data[,i+6], data = imm.data)) res2 <- anova (lm (ESTIMATE ~ Tissue + Neo + imm.data[,i+6], data = imm.data)) mat.res[i,1] <- colnames (imm.data)[i+6] mat.res[i,2] <- as.numeric(as.character(res1$'Pr(>F)'[2])) mat.res[i,3] <- as.numeric(as.character(res2$'Pr(>F)'[3])) } colnames (mat.res) <- c ("Region", "domainXplorer", "AdjNeo") write.table (mat.res, file = "results_adjusting_neoags.txt", sep = "\t", quote = FALSE, row.names = FALSE, col.names = TRUE)
lemma nonzero_of_real_divide: "y \<noteq> 0 \<Longrightarrow> of_real (x / y) = (of_real x / of_real y :: 'a::real_field)"
[STATEMENT] lemma image_poly_eval_indexed_var: assumes "indexed_const \<in> ring_hom R L" and "q \<in> carrier (poly_ring L)" and "degree q > 1" and "pirreducible\<^bsub>L\<^esub> (carrier L) q" shows "(ring.eval (image_poly q)) q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_poly q\<^esub>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ring.eval (image_ring (eval_pmod q) (poly_ring L)) q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. ring.eval (image_ring (eval_pmod q) (poly_ring L)) q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] let ?surj = "L.rupture_surj (carrier L) q" [PROOF STATE] proof (state) goal (1 subgoal): 1. ring.eval (image_ring (eval_pmod q) (poly_ring L)) q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] let ?Rupt = "Rupt\<^bsub>L\<^esub> (carrier L) q" [PROOF STATE] proof (state) goal (1 subgoal): 1. ring.eval (image_ring (eval_pmod q) (poly_ring L)) q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] let ?f = "eval_pmod q" [PROOF STATE] proof (state) goal (1 subgoal): 1. ring.eval (image_ring (eval_pmod q) (poly_ring L)) q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] interpret UP: ring "poly_ring L" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ring (poly_ring L) [PROOF STEP] using L.univ_poly_is_ring[OF L.carrier_is_subring] [PROOF STATE] proof (prove) using this: ring (poly_ring L) goal (1 subgoal): 1. ring (poly_ring L) [PROOF STEP] . [PROOF STATE] proof (state) goal (1 subgoal): 1. ring.eval (image_ring (eval_pmod q) (poly_ring L)) q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] from \<open>pirreducible\<^bsub>L\<^esub> (carrier L) q\<close> [PROOF STATE] proof (chain) picking this: pirreducible\<^bsub>L\<^esub> (carrier L) q [PROOF STEP] interpret Rupt: field ?Rupt [PROOF STATE] proof (prove) using this: pirreducible\<^bsub>L\<^esub> (carrier L) q goal (1 subgoal): 1. field (Rupt\<^bsub>L\<^esub> (carrier L) q) [PROOF STEP] using L.rupture_is_field_iff_pirreducible[OF L.carrier_is_subfield assms(2)] [PROOF STATE] proof (prove) using this: pirreducible\<^bsub>L\<^esub> (carrier L) q field (Rupt\<^bsub>L\<^esub> (carrier L) q) = pirreducible\<^bsub>L\<^esub> (carrier L) q goal (1 subgoal): 1. field (Rupt\<^bsub>L\<^esub> (carrier L) q) [PROOF STEP] by simp [PROOF STATE] proof (state) goal (1 subgoal): 1. ring.eval (image_ring (eval_pmod q) (poly_ring L)) q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] have weak_morphism: "weak_ring_morphism ?f (PIdl\<^bsub>poly_ring L\<^esub> q) (poly_ring L)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. weak_ring_morphism (eval_pmod q) (PIdl\<^bsub>poly_ring L\<^esub> q) (poly_ring L) [PROOF STEP] using indexed_eval_is_weak_ring_morphism[OF assms(2)] [PROOF STATE] proof (prove) using this: weak_ring_morphism (eval_pmod q) (PIdl\<^bsub>poly_ring L\<^esub> q) (poly_ring L) goal (1 subgoal): 1. weak_ring_morphism (eval_pmod q) (PIdl\<^bsub>poly_ring L\<^esub> q) (poly_ring L) [PROOF STEP] . [PROOF STATE] proof (state) this: weak_ring_morphism (eval_pmod q) (PIdl\<^bsub>poly_ring L\<^esub> q) (poly_ring L) goal (1 subgoal): 1. ring.eval (image_ring (eval_pmod q) (poly_ring L)) q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] then [PROOF STATE] proof (chain) picking this: weak_ring_morphism (eval_pmod q) (PIdl\<^bsub>poly_ring L\<^esub> q) (poly_ring L) [PROOF STEP] interpret I: ideal "PIdl\<^bsub>poly_ring L\<^esub> q" "poly_ring L" [PROOF STATE] proof (prove) using this: weak_ring_morphism (eval_pmod q) (PIdl\<^bsub>poly_ring L\<^esub> q) (poly_ring L) goal (1 subgoal): 1. ideal (PIdl\<^bsub>poly_ring L\<^esub> q) (poly_ring L) [PROOF STEP] using weak_ring_morphism.axioms(1) [PROOF STATE] proof (prove) using this: weak_ring_morphism (eval_pmod q) (PIdl\<^bsub>poly_ring L\<^esub> q) (poly_ring L) weak_ring_morphism ?f ?I ?R \<Longrightarrow> ideal ?I ?R goal (1 subgoal): 1. ideal (PIdl\<^bsub>poly_ring L\<^esub> q) (poly_ring L) [PROOF STEP] by auto [PROOF STATE] proof (state) goal (1 subgoal): 1. ring.eval (image_ring (eval_pmod q) (poly_ring L)) q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] interpret Hom: ring_hom_ring ?Rupt "image_poly q" "\<lambda>x. the_elem (?f ` x)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ring_hom_ring (Rupt\<^bsub>L\<^esub> (carrier L) q) (image_ring (eval_pmod q) (poly_ring L)) (\<lambda>x. the_elem (eval_pmod q ` x)) [PROOF STEP] using ring_hom_ring.intro[OF I.quotient_is_ring UP.image_ring_is_ring[OF weak_morphism]] UP.weak_ring_morphism_is_iso[OF weak_morphism] [PROOF STATE] proof (prove) using this: ring_hom_ring_axioms (poly_ring L Quot PIdl\<^bsub>poly_ring L\<^esub> q) (image_ring (eval_pmod q) (poly_ring L)) ?h \<Longrightarrow> ring_hom_ring (poly_ring L Quot PIdl\<^bsub>poly_ring L\<^esub> q) (image_ring (eval_pmod q) (poly_ring L)) ?h (\<lambda>x. the_elem (eval_pmod q ` x)) \<in> ring_iso (poly_ring L Quot PIdl\<^bsub>poly_ring L\<^esub> q) (image_ring (eval_pmod q) (poly_ring L)) goal (1 subgoal): 1. ring_hom_ring (Rupt\<^bsub>L\<^esub> (carrier L) q) (image_ring (eval_pmod q) (poly_ring L)) (\<lambda>x. the_elem (eval_pmod q ` x)) [PROOF STEP] unfolding ring_iso_def symmetric[OF ring_hom_ring_axioms_def] rupture_def [PROOF STATE] proof (prove) using this: ring_hom_ring_axioms (poly_ring L Quot PIdl\<^bsub>poly_ring L\<^esub> q) (image_ring (eval_pmod q) (poly_ring L)) ?h \<Longrightarrow> ring_hom_ring (poly_ring L Quot PIdl\<^bsub>poly_ring L\<^esub> q) (image_ring (eval_pmod q) (poly_ring L)) ?h (\<lambda>x. the_elem (eval_pmod q ` x)) \<in> {h. ring_hom_ring_axioms (poly_ring L Quot PIdl\<^bsub>poly_ring L\<^esub> q) (image_ring (eval_pmod q) (poly_ring L)) h \<and> bij_betw h (carrier (poly_ring L Quot PIdl\<^bsub>poly_ring L\<^esub> q)) (carrier (image_ring (eval_pmod q) (poly_ring L)))} goal (1 subgoal): 1. ring_hom_ring (poly_ring L Quot PIdl\<^bsub>poly_ring L\<^esub> q) (image_ring (eval_pmod q) (poly_ring L)) (\<lambda>x. the_elem (eval_pmod q ` x)) [PROOF STEP] by auto [PROOF STATE] proof (state) goal (1 subgoal): 1. Hom.eval q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] have "set q \<subseteq> carrier L" and lc: "q \<noteq> [] \<Longrightarrow> lead_coeff q \<in> carrier L - { \<zero>\<^bsub>L\<^esub> }" [PROOF STATE] proof (prove) goal (1 subgoal): 1. set q \<subseteq> carrier L &&& (q \<noteq> [] \<Longrightarrow> lead_coeff q \<in> carrier L - {\<zero>\<^bsub>L\<^esub>}) [PROOF STEP] using assms(2) [PROOF STATE] proof (prove) using this: q \<in> carrier (poly_ring L) goal (1 subgoal): 1. set q \<subseteq> carrier L &&& (q \<noteq> [] \<Longrightarrow> lead_coeff q \<in> carrier L - {\<zero>\<^bsub>L\<^esub>}) [PROOF STEP] unfolding sym[OF univ_poly_carrier] polynomial_def [PROOF STATE] proof (prove) using this: q = [] \<or> set q \<subseteq> carrier L \<and> lead_coeff q \<noteq> \<zero>\<^bsub>L\<^esub> goal (1 subgoal): 1. set q \<subseteq> carrier L &&& (q \<noteq> [] \<Longrightarrow> lead_coeff q \<in> carrier L - {\<zero>\<^bsub>L\<^esub>}) [PROOF STEP] by auto [PROOF STATE] proof (state) this: set q \<subseteq> carrier L q \<noteq> [] \<Longrightarrow> lead_coeff q \<in> carrier L - {\<zero>\<^bsub>L\<^esub>} goal (1 subgoal): 1. Hom.eval q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] have map_surj: "set (map (?surj \<circ> L.poly_of_const) q) \<subseteq> carrier ?Rupt" [PROOF STATE] proof (prove) goal (1 subgoal): 1. set (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) \<subseteq> carrier (Rupt\<^bsub>L\<^esub> (carrier L) q) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. set (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) \<subseteq> carrier (Rupt\<^bsub>L\<^esub> (carrier L) q) [PROOF STEP] have "L.poly_of_const a \<in> carrier (poly_ring L)" if "a \<in> carrier L" for a [PROOF STATE] proof (prove) goal (1 subgoal): 1. L.poly_of_const a \<in> carrier (poly_ring L) [PROOF STEP] using that L.normalize_gives_polynomial[of "[ a ]"] [PROOF STATE] proof (prove) using this: a \<in> carrier L set [a] \<subseteq> ?K \<Longrightarrow> polynomial\<^bsub>L\<^esub> ?K (L.normalize [a]) goal (1 subgoal): 1. L.poly_of_const a \<in> carrier (poly_ring L) [PROOF STEP] unfolding univ_poly_carrier ring.poly_of_const_def[OF L.ring_axioms] [PROOF STATE] proof (prove) using this: a \<in> carrier L set [a] \<subseteq> ?K \<Longrightarrow> L.normalize [a] \<in> carrier (?K [X]\<^bsub>L\<^esub>) goal (1 subgoal): 1. L.normalize [a] \<in> carrier (poly_ring L) [PROOF STEP] by simp [PROOF STATE] proof (state) this: ?a18 \<in> carrier L \<Longrightarrow> L.poly_of_const ?a18 \<in> carrier (poly_ring L) goal (1 subgoal): 1. set (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) \<subseteq> carrier (Rupt\<^bsub>L\<^esub> (carrier L) q) [PROOF STEP] hence "(?surj \<circ> L.poly_of_const) a \<in> carrier ?Rupt" if "a \<in> carrier L" for a [PROOF STATE] proof (prove) using this: ?a18 \<in> carrier L \<Longrightarrow> L.poly_of_const ?a18 \<in> carrier (poly_ring L) goal (1 subgoal): 1. (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) a \<in> carrier (Rupt\<^bsub>L\<^esub> (carrier L) q) [PROOF STEP] using ring_hom_memE(1)[OF L.rupture_surj_hom(1)[OF L.carrier_is_subring assms(2)]] that [PROOF STATE] proof (prove) using this: ?a18 \<in> carrier L \<Longrightarrow> L.poly_of_const ?a18 \<in> carrier (poly_ring L) ?x \<in> carrier (poly_ring L) \<Longrightarrow> L.rupture_surj (carrier L) q ?x \<in> carrier (Rupt\<^bsub>L\<^esub> (carrier L) q) a \<in> carrier L goal (1 subgoal): 1. (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) a \<in> carrier (Rupt\<^bsub>L\<^esub> (carrier L) q) [PROOF STEP] by simp [PROOF STATE] proof (state) this: ?a18 \<in> carrier L \<Longrightarrow> (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) ?a18 \<in> carrier (Rupt\<^bsub>L\<^esub> (carrier L) q) goal (1 subgoal): 1. set (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) \<subseteq> carrier (Rupt\<^bsub>L\<^esub> (carrier L) q) [PROOF STEP] with \<open>set q \<subseteq> carrier L\<close> [PROOF STATE] proof (chain) picking this: set q \<subseteq> carrier L ?a18 \<in> carrier L \<Longrightarrow> (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) ?a18 \<in> carrier (Rupt\<^bsub>L\<^esub> (carrier L) q) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: set q \<subseteq> carrier L ?a18 \<in> carrier L \<Longrightarrow> (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) ?a18 \<in> carrier (Rupt\<^bsub>L\<^esub> (carrier L) q) goal (1 subgoal): 1. set (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) \<subseteq> carrier (Rupt\<^bsub>L\<^esub> (carrier L) q) [PROOF STEP] by (induct q) (auto) [PROOF STATE] proof (state) this: set (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) \<subseteq> carrier (Rupt\<^bsub>L\<^esub> (carrier L) q) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: set (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) \<subseteq> carrier (Rupt\<^bsub>L\<^esub> (carrier L) q) goal (1 subgoal): 1. Hom.eval q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] have "?surj X\<^bsub>L\<^esub> \<in> carrier ?Rupt" [PROOF STATE] proof (prove) goal (1 subgoal): 1. L.rupture_surj (carrier L) q X\<^bsub>L\<^esub> \<in> carrier (Rupt\<^bsub>L\<^esub> (carrier L) q) [PROOF STEP] using ring_hom_memE(1)[OF L.rupture_surj_hom(1)[OF _ assms(2)] L.var_closed(1)] L.carrier_is_subring [PROOF STATE] proof (prove) using this: \<lbrakk>subring (carrier L) L; subring (carrier L) L\<rbrakk> \<Longrightarrow> L.rupture_surj (carrier L) q X\<^bsub>L\<^esub> \<in> carrier (Rupt\<^bsub>L\<^esub> (carrier L) q) subring (carrier L) L goal (1 subgoal): 1. L.rupture_surj (carrier L) q X\<^bsub>L\<^esub> \<in> carrier (Rupt\<^bsub>L\<^esub> (carrier L) q) [PROOF STEP] by simp [PROOF STATE] proof (state) this: L.rupture_surj (carrier L) q X\<^bsub>L\<^esub> \<in> carrier (Rupt\<^bsub>L\<^esub> (carrier L) q) goal (1 subgoal): 1. Hom.eval q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] moreover [PROOF STATE] proof (state) this: L.rupture_surj (carrier L) q X\<^bsub>L\<^esub> \<in> carrier (Rupt\<^bsub>L\<^esub> (carrier L) q) goal (1 subgoal): 1. Hom.eval q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] have "map (\<lambda>x. the_elem (?f ` x)) (map (?surj \<circ> L.poly_of_const) q) = q" [PROOF STATE] proof (prove) goal (1 subgoal): 1. map (\<lambda>x. the_elem (eval_pmod q ` x)) (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) = q [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. map (\<lambda>x. the_elem (eval_pmod q ` x)) (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) = q [PROOF STEP] define g where "g = (?surj \<circ> L.poly_of_const)" [PROOF STATE] proof (state) this: g = L.rupture_surj (carrier L) q \<circ> L.poly_of_const goal (1 subgoal): 1. map (\<lambda>x. the_elem (eval_pmod q ` x)) (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) = q [PROOF STEP] define f where "f = (\<lambda>x. the_elem (?f ` x))" [PROOF STATE] proof (state) this: f = (\<lambda>x. the_elem (eval_pmod q ` x)) goal (1 subgoal): 1. map (\<lambda>x. the_elem (eval_pmod q ` x)) (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) = q [PROOF STEP] have "the_elem (?f ` ((?surj \<circ> L.poly_of_const) a)) = ((eval_pmod q) \<circ> L.poly_of_const) a" if "a \<in> carrier L" for a [PROOF STATE] proof (prove) goal (1 subgoal): 1. the_elem (eval_pmod q ` (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) a) = (eval_pmod q \<circ> L.poly_of_const) a [PROOF STEP] using that L.normalize_gives_polynomial[of "[ a ]"] UP.weak_ring_morphism_range[OF weak_morphism] [PROOF STATE] proof (prove) using this: a \<in> carrier L set [a] \<subseteq> ?K \<Longrightarrow> polynomial\<^bsub>L\<^esub> ?K (L.normalize [a]) ?a \<in> carrier (poly_ring L) \<Longrightarrow> eval_pmod q ` L.rupture_surj (carrier L) q ?a = {eval_pmod q ?a} goal (1 subgoal): 1. the_elem (eval_pmod q ` (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) a) = (eval_pmod q \<circ> L.poly_of_const) a [PROOF STEP] unfolding univ_poly_carrier ring.poly_of_const_def[OF L.ring_axioms] [PROOF STATE] proof (prove) using this: a \<in> carrier L set [a] \<subseteq> ?K \<Longrightarrow> L.normalize [a] \<in> carrier (?K [X]\<^bsub>L\<^esub>) ?a \<in> carrier (poly_ring L) \<Longrightarrow> eval_pmod q ` L.rupture_surj (carrier L) q ?a = {eval_pmod q ?a} goal (1 subgoal): 1. the_elem (eval_pmod q ` (L.rupture_surj (carrier L) q \<circ> (\<lambda>k. L.normalize [k])) a) = (eval_pmod q \<circ> (\<lambda>k. L.normalize [k])) a [PROOF STEP] by auto [PROOF STATE] proof (state) this: ?a18 \<in> carrier L \<Longrightarrow> the_elem (eval_pmod q ` (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) ?a18) = (eval_pmod q \<circ> L.poly_of_const) ?a18 goal (1 subgoal): 1. map (\<lambda>x. the_elem (eval_pmod q ` x)) (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) = q [PROOF STEP] hence "the_elem (?f ` ((?surj \<circ> L.poly_of_const) a)) = a" if "a \<in> carrier L" for a [PROOF STATE] proof (prove) using this: ?a18 \<in> carrier L \<Longrightarrow> the_elem (eval_pmod q ` (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) ?a18) = (eval_pmod q \<circ> L.poly_of_const) ?a18 goal (1 subgoal): 1. the_elem (eval_pmod q ` (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) a) = a [PROOF STEP] using eval_norm_eq_id[OF assms(2)] that assms(3) [PROOF STATE] proof (prove) using this: ?a18 \<in> carrier L \<Longrightarrow> the_elem (eval_pmod q ` (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) ?a18) = (eval_pmod q \<circ> L.poly_of_const) ?a18 \<lbrakk>0 < degree q; ?a \<in> carrier L\<rbrakk> \<Longrightarrow> (eval_pmod q \<circ> L.poly_of_const) ?a = ?a a \<in> carrier L 1 < degree q goal (1 subgoal): 1. the_elem (eval_pmod q ` (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) a) = a [PROOF STEP] by simp [PROOF STATE] proof (state) this: ?a18 \<in> carrier L \<Longrightarrow> the_elem (eval_pmod q ` (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) ?a18) = ?a18 goal (1 subgoal): 1. map (\<lambda>x. the_elem (eval_pmod q ` x)) (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) = q [PROOF STEP] hence "f (g a) = a" if "a \<in> carrier L" for a [PROOF STATE] proof (prove) using this: ?a18 \<in> carrier L \<Longrightarrow> the_elem (eval_pmod q ` (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) ?a18) = ?a18 goal (1 subgoal): 1. f (g a) = a [PROOF STEP] using that [PROOF STATE] proof (prove) using this: ?a18 \<in> carrier L \<Longrightarrow> the_elem (eval_pmod q ` (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) ?a18) = ?a18 a \<in> carrier L goal (1 subgoal): 1. f (g a) = a [PROOF STEP] unfolding f_def g_def [PROOF STATE] proof (prove) using this: ?a18 \<in> carrier L \<Longrightarrow> the_elem (eval_pmod q ` (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) ?a18) = ?a18 a \<in> carrier L goal (1 subgoal): 1. the_elem (eval_pmod q ` (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) a) = a [PROOF STEP] by simp [PROOF STATE] proof (state) this: ?a18 \<in> carrier L \<Longrightarrow> f (g ?a18) = ?a18 goal (1 subgoal): 1. map (\<lambda>x. the_elem (eval_pmod q ` x)) (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) = q [PROOF STEP] with \<open>set q \<subseteq> carrier L\<close> [PROOF STATE] proof (chain) picking this: set q \<subseteq> carrier L ?a18 \<in> carrier L \<Longrightarrow> f (g ?a18) = ?a18 [PROOF STEP] have "map f (map g q) = q" [PROOF STATE] proof (prove) using this: set q \<subseteq> carrier L ?a18 \<in> carrier L \<Longrightarrow> f (g ?a18) = ?a18 goal (1 subgoal): 1. map f (map g q) = q [PROOF STEP] by (induct q) (auto) [PROOF STATE] proof (state) this: map f (map g q) = q goal (1 subgoal): 1. map (\<lambda>x. the_elem (eval_pmod q ` x)) (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) = q [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: map f (map g q) = q goal (1 subgoal): 1. map (\<lambda>x. the_elem (eval_pmod q ` x)) (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) = q [PROOF STEP] unfolding f_def g_def [PROOF STATE] proof (prove) using this: map (\<lambda>x. the_elem (eval_pmod q ` x)) (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) = q goal (1 subgoal): 1. map (\<lambda>x. the_elem (eval_pmod q ` x)) (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) = q [PROOF STEP] by simp [PROOF STATE] proof (state) this: map (\<lambda>x. the_elem (eval_pmod q ` x)) (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) = q goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: map (\<lambda>x. the_elem (eval_pmod q ` x)) (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) = q goal (1 subgoal): 1. Hom.eval q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] moreover [PROOF STATE] proof (state) this: map (\<lambda>x. the_elem (eval_pmod q ` x)) (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) = q goal (1 subgoal): 1. Hom.eval q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] have "(\<lambda>x. the_elem (?f ` x)) (?surj X\<^bsub>L\<^esub>) = \<X>\<^bsub>i\<^esub>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. the_elem (eval_pmod q ` L.rupture_surj (carrier L) q X\<^bsub>L\<^esub>) = \<X>\<^bsub>i\<^esub> [PROOF STEP] using UP.weak_ring_morphism_range[OF weak_morphism L.var_closed(1)[OF L.carrier_is_subring]] [PROOF STATE] proof (prove) using this: eval_pmod q ` L.rupture_surj (carrier L) q X\<^bsub>L\<^esub> = {eval_pmod q X\<^bsub>L\<^esub>} goal (1 subgoal): 1. the_elem (eval_pmod q ` L.rupture_surj (carrier L) q X\<^bsub>L\<^esub>) = \<X>\<^bsub>i\<^esub> [PROOF STEP] unfolding eval_pmod_var(1)[OF assms(1-3)] [PROOF STATE] proof (prove) using this: eval_pmod q ` L.rupture_surj (carrier L) q X\<^bsub>L\<^esub> = {\<X>\<^bsub>i\<^esub>} goal (1 subgoal): 1. the_elem (eval_pmod q ` L.rupture_surj (carrier L) q X\<^bsub>L\<^esub>) = \<X>\<^bsub>i\<^esub> [PROOF STEP] by simp [PROOF STATE] proof (state) this: the_elem (eval_pmod q ` L.rupture_surj (carrier L) q X\<^bsub>L\<^esub>) = \<X>\<^bsub>i\<^esub> goal (1 subgoal): 1. Hom.eval q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: L.rupture_surj (carrier L) q X\<^bsub>L\<^esub> \<in> carrier (Rupt\<^bsub>L\<^esub> (carrier L) q) map (\<lambda>x. the_elem (eval_pmod q ` x)) (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) = q the_elem (eval_pmod q ` L.rupture_surj (carrier L) q X\<^bsub>L\<^esub>) = \<X>\<^bsub>i\<^esub> [PROOF STEP] have "Hom.S.eval q \<X>\<^bsub>i\<^esub> = (\<lambda>x. the_elem (?f ` x)) (Rupt.eval (map (?surj \<circ> L.poly_of_const) q) (?surj X\<^bsub>L\<^esub>))" [PROOF STATE] proof (prove) using this: L.rupture_surj (carrier L) q X\<^bsub>L\<^esub> \<in> carrier (Rupt\<^bsub>L\<^esub> (carrier L) q) map (\<lambda>x. the_elem (eval_pmod q ` x)) (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) = q the_elem (eval_pmod q ` L.rupture_surj (carrier L) q X\<^bsub>L\<^esub>) = \<X>\<^bsub>i\<^esub> goal (1 subgoal): 1. Hom.eval q \<X>\<^bsub>i\<^esub> = the_elem (eval_pmod q ` Rupt.eval (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) (L.rupture_surj (carrier L) q X\<^bsub>L\<^esub>)) [PROOF STEP] using Hom.eval_hom'[OF _ map_surj] [PROOF STATE] proof (prove) using this: L.rupture_surj (carrier L) q X\<^bsub>L\<^esub> \<in> carrier (Rupt\<^bsub>L\<^esub> (carrier L) q) map (\<lambda>x. the_elem (eval_pmod q ` x)) (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) = q the_elem (eval_pmod q ` L.rupture_surj (carrier L) q X\<^bsub>L\<^esub>) = \<X>\<^bsub>i\<^esub> ?a \<in> carrier (Rupt\<^bsub>L\<^esub> (carrier L) q) \<Longrightarrow> the_elem (eval_pmod q ` Rupt.eval (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) ?a) = Hom.eval (map (\<lambda>x. the_elem (eval_pmod q ` x)) (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q)) (the_elem (eval_pmod q ` ?a)) goal (1 subgoal): 1. Hom.eval q \<X>\<^bsub>i\<^esub> = the_elem (eval_pmod q ` Rupt.eval (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) (L.rupture_surj (carrier L) q X\<^bsub>L\<^esub>)) [PROOF STEP] by auto [PROOF STATE] proof (state) this: Hom.eval q \<X>\<^bsub>i\<^esub> = the_elem (eval_pmod q ` Rupt.eval (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) (L.rupture_surj (carrier L) q X\<^bsub>L\<^esub>)) goal (1 subgoal): 1. Hom.eval q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] moreover [PROOF STATE] proof (state) this: Hom.eval q \<X>\<^bsub>i\<^esub> = the_elem (eval_pmod q ` Rupt.eval (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) (L.rupture_surj (carrier L) q X\<^bsub>L\<^esub>)) goal (1 subgoal): 1. Hom.eval q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] have "\<zero>\<^bsub>?Rupt\<^esub> = ?surj \<zero>\<^bsub>poly_ring L\<^esub>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<zero>\<^bsub>Rupt\<^bsub>L\<^esub> (carrier L) q\<^esub> = L.rupture_surj (carrier L) q \<zero>\<^bsub>poly_ring L\<^esub> [PROOF STEP] unfolding rupture_def FactRing_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<zero>\<^bsub>\<lparr>carrier = a_rcosets\<^bsub>poly_ring L\<^esub> (PIdl\<^bsub>poly_ring L\<^esub> q), monoid.mult = rcoset_mult (poly_ring L) (PIdl\<^bsub>poly_ring L\<^esub> q), one = L.rupture_surj (carrier L) q \<one>\<^bsub>poly_ring L\<^esub>, zero = PIdl\<^bsub>poly_ring L\<^esub> q, add = (<+>\<^bsub>poly_ring L\<^esub>)\<rparr>\<^esub> = L.rupture_surj (carrier L) q \<zero>\<^bsub>poly_ring L\<^esub> [PROOF STEP] by (simp add: I.a_rcos_const) [PROOF STATE] proof (state) this: \<zero>\<^bsub>Rupt\<^bsub>L\<^esub> (carrier L) q\<^esub> = L.rupture_surj (carrier L) q \<zero>\<^bsub>poly_ring L\<^esub> goal (1 subgoal): 1. Hom.eval q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] hence "the_elem (?f ` \<zero>\<^bsub>?Rupt\<^esub>) = \<zero>\<^bsub>image_poly q\<^esub>" [PROOF STATE] proof (prove) using this: \<zero>\<^bsub>Rupt\<^bsub>L\<^esub> (carrier L) q\<^esub> = L.rupture_surj (carrier L) q \<zero>\<^bsub>poly_ring L\<^esub> goal (1 subgoal): 1. the_elem (eval_pmod q ` \<zero>\<^bsub>Rupt\<^bsub>L\<^esub> (carrier L) q\<^esub>) = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] using UP.weak_ring_morphism_range[OF weak_morphism UP.zero_closed] [PROOF STATE] proof (prove) using this: \<zero>\<^bsub>Rupt\<^bsub>L\<^esub> (carrier L) q\<^esub> = L.rupture_surj (carrier L) q \<zero>\<^bsub>poly_ring L\<^esub> eval_pmod q ` L.rupture_surj (carrier L) q \<zero>\<^bsub>poly_ring L\<^esub> = {eval_pmod q \<zero>\<^bsub>poly_ring L\<^esub>} goal (1 subgoal): 1. the_elem (eval_pmod q ` \<zero>\<^bsub>Rupt\<^bsub>L\<^esub> (carrier L) q\<^esub>) = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] unfolding image_ring_zero [PROOF STATE] proof (prove) using this: \<zero>\<^bsub>Rupt\<^bsub>L\<^esub> (carrier L) q\<^esub> = L.rupture_surj (carrier L) q \<zero>\<^bsub>poly_ring L\<^esub> eval_pmod q ` L.rupture_surj (carrier L) q \<zero>\<^bsub>poly_ring L\<^esub> = {eval_pmod q \<zero>\<^bsub>poly_ring L\<^esub>} goal (1 subgoal): 1. the_elem (eval_pmod q ` \<zero>\<^bsub>Rupt\<^bsub>L\<^esub> (carrier L) q\<^esub>) = eval_pmod q \<zero>\<^bsub>poly_ring L\<^esub> [PROOF STEP] by simp [PROOF STATE] proof (state) this: the_elem (eval_pmod q ` \<zero>\<^bsub>Rupt\<^bsub>L\<^esub> (carrier L) q\<^esub>) = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> goal (1 subgoal): 1. Hom.eval q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] hence "(\<lambda>x. the_elem (?f ` x)) (Rupt.eval (map (?surj \<circ> L.poly_of_const) q) (?surj X\<^bsub>L\<^esub>)) = \<zero>\<^bsub>image_poly q\<^esub>" [PROOF STATE] proof (prove) using this: the_elem (eval_pmod q ` \<zero>\<^bsub>Rupt\<^bsub>L\<^esub> (carrier L) q\<^esub>) = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> goal (1 subgoal): 1. the_elem (eval_pmod q ` Rupt.eval (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) (L.rupture_surj (carrier L) q X\<^bsub>L\<^esub>)) = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] using L.polynomial_rupture[OF L.carrier_is_subring assms(2)] [PROOF STATE] proof (prove) using this: the_elem (eval_pmod q ` \<zero>\<^bsub>Rupt\<^bsub>L\<^esub> (carrier L) q\<^esub>) = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> Rupt.eval (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) (L.rupture_surj (carrier L) q X\<^bsub>L\<^esub>) = \<zero>\<^bsub>Rupt\<^bsub>L\<^esub> (carrier L) q\<^esub> goal (1 subgoal): 1. the_elem (eval_pmod q ` Rupt.eval (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) (L.rupture_surj (carrier L) q X\<^bsub>L\<^esub>)) = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] by simp [PROOF STATE] proof (state) this: the_elem (eval_pmod q ` Rupt.eval (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) (L.rupture_surj (carrier L) q X\<^bsub>L\<^esub>)) = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> goal (1 subgoal): 1. Hom.eval q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: Hom.eval q \<X>\<^bsub>i\<^esub> = the_elem (eval_pmod q ` Rupt.eval (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) (L.rupture_surj (carrier L) q X\<^bsub>L\<^esub>)) the_elem (eval_pmod q ` Rupt.eval (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) (L.rupture_surj (carrier L) q X\<^bsub>L\<^esub>)) = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: Hom.eval q \<X>\<^bsub>i\<^esub> = the_elem (eval_pmod q ` Rupt.eval (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) (L.rupture_surj (carrier L) q X\<^bsub>L\<^esub>)) the_elem (eval_pmod q ` Rupt.eval (map (L.rupture_surj (carrier L) q \<circ> L.poly_of_const) q) (L.rupture_surj (carrier L) q X\<^bsub>L\<^esub>)) = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> goal (1 subgoal): 1. Hom.eval q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> [PROOF STEP] by simp [PROOF STATE] proof (state) this: Hom.eval q \<X>\<^bsub>i\<^esub> = \<zero>\<^bsub>image_ring (eval_pmod q) (poly_ring L)\<^esub> goal: No subgoals! [PROOF STEP] qed
State Before: α : Type u_1 α' : Type ?u.2423125 β : Type u_2 β' : Type ?u.2423131 γ : Type ?u.2423134 E : Type u_3 inst✝¹² : MeasurableSpace α inst✝¹¹ : MeasurableSpace α' inst✝¹⁰ : MeasurableSpace β inst✝⁹ : MeasurableSpace β' inst✝⁸ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝⁷ : NormedAddCommGroup E inst✝⁶ : SigmaFinite ν inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E inst✝³ : SigmaFinite μ E' : Type ?u.2423399 inst✝² : NormedAddCommGroup E' inst✝¹ : CompleteSpace E' inst✝ : NormedSpace ℝ E' f g : α × β → E F : E → ℝ≥0∞ hf : Integrable f hg : Integrable g ⊢ (∫⁻ (x : α), F (∫ (y : β), f (x, y) - g (x, y) ∂ν) ∂μ) = ∫⁻ (x : α), F ((∫ (y : β), f (x, y) ∂ν) - ∫ (y : β), g (x, y) ∂ν) ∂μ State After: α : Type u_1 α' : Type ?u.2423125 β : Type u_2 β' : Type ?u.2423131 γ : Type ?u.2423134 E : Type u_3 inst✝¹² : MeasurableSpace α inst✝¹¹ : MeasurableSpace α' inst✝¹⁰ : MeasurableSpace β inst✝⁹ : MeasurableSpace β' inst✝⁸ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝⁷ : NormedAddCommGroup E inst✝⁶ : SigmaFinite ν inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E inst✝³ : SigmaFinite μ E' : Type ?u.2423399 inst✝² : NormedAddCommGroup E' inst✝¹ : CompleteSpace E' inst✝ : NormedSpace ℝ E' f g : α × β → E F : E → ℝ≥0∞ hf : Integrable f hg : Integrable g ⊢ (fun x => F (∫ (y : β), f (x, y) - g (x, y) ∂ν)) =ᶠ[ae μ] fun x => F ((∫ (y : β), f (x, y) ∂ν) - ∫ (y : β), g (x, y) ∂ν) Tactic: refine' lintegral_congr_ae _ State Before: α : Type u_1 α' : Type ?u.2423125 β : Type u_2 β' : Type ?u.2423131 γ : Type ?u.2423134 E : Type u_3 inst✝¹² : MeasurableSpace α inst✝¹¹ : MeasurableSpace α' inst✝¹⁰ : MeasurableSpace β inst✝⁹ : MeasurableSpace β' inst✝⁸ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝⁷ : NormedAddCommGroup E inst✝⁶ : SigmaFinite ν inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E inst✝³ : SigmaFinite μ E' : Type ?u.2423399 inst✝² : NormedAddCommGroup E' inst✝¹ : CompleteSpace E' inst✝ : NormedSpace ℝ E' f g : α × β → E F : E → ℝ≥0∞ hf : Integrable f hg : Integrable g ⊢ (fun x => F (∫ (y : β), f (x, y) - g (x, y) ∂ν)) =ᶠ[ae μ] fun x => F ((∫ (y : β), f (x, y) ∂ν) - ∫ (y : β), g (x, y) ∂ν) State After: case h α : Type u_1 α' : Type ?u.2423125 β : Type u_2 β' : Type ?u.2423131 γ : Type ?u.2423134 E : Type u_3 inst✝¹² : MeasurableSpace α inst✝¹¹ : MeasurableSpace α' inst✝¹⁰ : MeasurableSpace β inst✝⁹ : MeasurableSpace β' inst✝⁸ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝⁷ : NormedAddCommGroup E inst✝⁶ : SigmaFinite ν inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E inst✝³ : SigmaFinite μ E' : Type ?u.2423399 inst✝² : NormedAddCommGroup E' inst✝¹ : CompleteSpace E' inst✝ : NormedSpace ℝ E' f g : α × β → E F : E → ℝ≥0∞ hf : Integrable f hg : Integrable g a✝ : α h2f : Integrable fun y => f (a✝, y) h2g : Integrable fun y => g (a✝, y) ⊢ F (∫ (y : β), f (a✝, y) - g (a✝, y) ∂ν) = F ((∫ (y : β), f (a✝, y) ∂ν) - ∫ (y : β), g (a✝, y) ∂ν) Tactic: filter_upwards [hf.prod_right_ae, hg.prod_right_ae] with _ h2f h2g State Before: case h α : Type u_1 α' : Type ?u.2423125 β : Type u_2 β' : Type ?u.2423131 γ : Type ?u.2423134 E : Type u_3 inst✝¹² : MeasurableSpace α inst✝¹¹ : MeasurableSpace α' inst✝¹⁰ : MeasurableSpace β inst✝⁹ : MeasurableSpace β' inst✝⁸ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝⁷ : NormedAddCommGroup E inst✝⁶ : SigmaFinite ν inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E inst✝³ : SigmaFinite μ E' : Type ?u.2423399 inst✝² : NormedAddCommGroup E' inst✝¹ : CompleteSpace E' inst✝ : NormedSpace ℝ E' f g : α × β → E F : E → ℝ≥0∞ hf : Integrable f hg : Integrable g a✝ : α h2f : Integrable fun y => f (a✝, y) h2g : Integrable fun y => g (a✝, y) ⊢ F (∫ (y : β), f (a✝, y) - g (a✝, y) ∂ν) = F ((∫ (y : β), f (a✝, y) ∂ν) - ∫ (y : β), g (a✝, y) ∂ν) State After: no goals Tactic: simp [integral_sub h2f h2g]
-- --------------------------------------------------------------- [ Error.idr ] -- Module : Error.idr -- Copyright : (c) Jan de Muijnck-Hughes -- License : see LICENSE -- --------------------------------------------------------------------- [ EOH ] module Toolkit.Options.ArgParse.Error import Data.String import System.File import Toolkit.Data.Location import Toolkit.Options.ArgParse.Model import Toolkit.Options.ArgParse.Lexer import Toolkit.Options.ArgParse.Parser %default total public export data ArgParseError : Type where InvalidOption : Arg -> ArgParseError MalformedOption : ParseError Token -> ArgParseError export (Show Arg) => Show ArgParseError where show (InvalidOption o) = "Invalid Option " ++ show o show (MalformedOption (PError (MkParseFail error location rest))) = unlines [show location, error] show (MalformedOption (LError (MkLexFail l i))) = unwords [show l, ":\n" <+> i] show (MalformedOption (FError x)) = unlines ["File Error:", show x] -- --------------------------------------------------------------------- [ EOF ]
# Unit Commitment _**[Power Systems Optimization](https://github.com/east-winds/power-systems-optimization)**_ _by Michael R. Davidson and Jesse D. Jenkins (last updated: September 29, 2020)_ This notebook will build on the economic dispatch (ED) model by introducing binary startup (called "commitment") decisions, constraints, and costs of thermal generators. Similar to ED, it minimizes the short-run production costs of meeting electricity demand, but these additions are necessary for operating systems with large amounts of (inflexible) thermal generation. They also entail significant computational trade-offs. **** We build up the model in several stages. We first start with the simplest model that incorporates unit commitment decisions in order to understand the logic of three-variable commitment formulations. Next, we introduce moderate complexity through the addition of ramp constraints&mdash;which we need to be modified from the ED to account for startups and shutdowns. Finally, we model a more realistic unit commitment that includes reserves&mdash;an important feature of day-ahead scheduling in power systems. ## Introduction to unit commitment Engineering considerations severely limit the possible output ranges of power plants. System operators need to be aware of these limitations when scheduling generation to meet demand. Thermal power plants, in particular, due to their complex designs, thermodynamic cycles, and material properties, can be particularly challenging. In practice, due to the times involved in bringing these power plants online, much of this scheduling is done day-ahead, which gives rise to the need for a day-ahead market. **Unit commitment** (UC) is the problem of minimizing short-run costs of production inclusive of production and startup costs, in order to meet a given demand and considering relevant engineering constraints of the generators. It is built on the ED model in that it typically considers all of the same variables in addition to the new startup-related variables and constraints&mdash;hence, it is also sometimes called unit commitment and economic dispatch (UCED). This notebook, for simplicity, only considers a single-bus case, while typical formulations usually include a simplified network representation. ## Simple unit commitment We start with the simplest case that incorporates unit commitment, building on the `economic_dispatch_multi` problem of the [Economic Dispatch notebook](04-Economic-Dispatch.ipynb). $$ \begin{align} \min \ & \sum_{g \in G, t \in T} VarCost_g \times GEN_{g,t} + \sum_{g \in G_{thermal}, t \in T} StartUpCost_g \times START_{g,t} \\ \end{align} $$ $$ \begin{align} \text{s.t.} & \\ & \sum_{g} GEN_{g,t} = Demand_t & \forall \quad t \in T \\ & GEN_{g,t} \leq Pmax_{g,t} & \forall \quad g \notin G_{thermal} , t \in T \\ & GEN_{g,t} \geq Pmin_{g,t} & \forall \quad g \notin G_{thermal} , t \in T \\ & GEN_{g,t} \leq Pmax_{g,t} \times COMMIT_{g,t} & \forall \quad g \in G_{thermal} , t \in T \\ & GEN_{g,t} \geq Pmin_{g,t} \times COMMIT_{g,t} & \forall \quad g \in G_{thermal} , t \in T \\ & COMMIT_{g,t} \geq \sum_{t'≥t-MinUp_g}^{t} START_{g,t} & \forall \quad g \in G_{thermal} , t \in T \\ & 1-COMMIT_{g,t} \geq \sum_{t'≥t-MinDown_g}^{t} SHUT_{g,t} &\forall \quad g \in G_{thermal} , t \in T \\ & COMMIT_{g,t+1} - COMMIT_{g,t} =&\\ & \quad START_{g,t+1} - SHUT_{g,t+1} &\forall \quad G_{thermal} \in G , t = 1..T-1 \end{align} $$ The **decision variables** in the above problem: - $GEN_{g}$, generation (in MW) produced by each generator, $g$ - $START_{g,t}$, startup decision (binary) of thermal generator $g$ at time $t$ - $SHUT_{g,t}$, shutdown decision (binary) of thermal generator $g$ at time $t$ - $COMMIT_{g,t}$, commitment status (binary) of generator $g$ at time $t$ The **parameters** are: - $Pmin_g$, the minimum operating bounds for generator $g$ (based on engineering or natural resource constraints) - $Pmax_g$, the maximum operating bounds for generator $g$ (based on engineering or natural resource constraints) - $Demand$, the demand (in MW) - $VarCost_g = VarOM_g + HeatRate_g \times FuelCost_g$, the variable cost of generator $g$ - $StartUpCost_g$, the startup cost of generator $g$ - $MinUp_g$, the minimum up time of generator $g$, or the minimum time after start-up before a unit can shut down - $MinDown_g$, the minimum down time of generator $g$, or the minimum time after shut-down before a unit can start again In addition, we introduce a few different sets: - $G$, the set of all generators - $G_{thermal} \subset G$, the subset of thermal generators for which commitment is necessary - $T$, the set of all time periods over which we are optimizing commitment and dispatch decisions Finally, the **three-variable commitment equations** capture the basic logic of commitment: - Units incur costs when they startup (not when they shutdown) - Units must stay on (and off) for a minimum period of time&mdash;in lieu of explicitly enforcing a startup trajectory - Some summations (simplified here) will need to be modified near the beginning of the time period There are some further resources at the bottom for alternative and/or more complex formulations of the UC. Now, let's implement UC. ### 1. Load packages ```julia using JuMP, GLPK using Plots; plotly(); using VegaLite # to make some nice plots using DataFrames, CSV, PrettyTables ENV["COLUMNS"]=120; # Set so all columns of DataFrames and Matrices are displayed ``` ┌ Info: For saving to png with the Plotly backend ORCA has to be installed. └ @ Plots /Users/jdj2/.julia/packages/Plots/M1wcx/src/backends.jl:373 ### 2. Load and format data We will use data loosely based on San Diego Gas and Electric (SDG&E, via the [PowerGenome](https://github.com/gschivley/PowerGenome) data platform) including a few neighboring generators and adjustments to make the problem easy to solve, consisting of: - 33 generators (we added a few more to ensure we can provide enough reserves) - estimated hourly demand for 2020 (net load at the transmission substation level after subtracting 600MW of behind-the-meter solar from original demand) - variable generation capacity factors - estimated natural gas fuel costs In order to demonstrate the impacts of unit commitment, we will keep our high solar sensitivity case from the [Economic Dispatch notebook](04-Economic-Dispatch.ipynb) (with 3,500 MW of solar PV) to produce large variations in net load (demand less available renewable supply) required to meet demand (similar to [California's infamous "Duck Curve"](https://www.caiso.com/Documents/FlexibleResourcesHelpRenewables_FastFacts.pdf)). ```julia datadir = joinpath("uc_data") gen_info = CSV.read(joinpath(datadir,"Generators_data.csv"), DataFrame); fuels = CSV.read(joinpath(datadir,"Fuels_data.csv"), DataFrame); loads = CSV.read(joinpath(datadir,"Demand.csv"), DataFrame); gen_variable = CSV.read(joinpath(datadir,"Generators_variability.csv"), DataFrame); # Rename all columns to lowercase (by convention) for f in [gen_info, fuels, loads, gen_variable] rename!(f,lowercase.(names(f))) end ``` **Construct generator dataframe** ```julia # Keep columns relevant to our UC model select!(gen_info, 1:26) # columns 1:26 gen_df = outerjoin(gen_info, fuels, on = :fuel) # load in fuel costs and add to data frame rename!(gen_df, :cost_per_mmbtu => :fuel_cost) # rename column for fuel cost gen_df.fuel_cost[ismissing.(gen_df[:,:fuel_cost])] .= 0 # create "is_variable" column to indicate if this is a variable generation source (e.g. wind, solar): gen_df.is_variable = false gen_df[in(["onshore_wind_turbine","small_hydroelectric","solar_photovoltaic"]).(gen_df.resource), :is_variable] .= true; # create full name of generator (including geographic location and cluster number) # for use with variable generation dataframe gen_df.gen_full = lowercase.(gen_df.region .* "_" .* gen_df.resource .* "_" .* string.(gen_df.cluster) .* ".0"); # remove generators with no capacity (e.g. new build options that we'd use if this was capacity expansion problem) gen_df = gen_df[gen_df.existing_cap_mw .> 0,:]; ``` **Modify load and variable generation dataframes** ```julia # 1. Convert from GMT to GMT-8 gen_variable.hour = mod.(gen_variable.hour .- 9, 8760) .+ 1 sort!(gen_variable, :hour) loads.hour = mod.(loads.hour .- 9, 8760) .+ 1 sort!(loads, :hour); # 2. Convert from "wide" to "long" format gen_variable_long = stack(gen_variable, Not(:hour), variable_name=:gen_full, value_name=:cf); # Now we have a "long" dataframe; ``` ### 3. Create solver function As a utility function, since we do this alot, we'll create a function to convert JuMP AxisArray outputs with two indexes to DataFrames. ```julia #= Function to convert JuMP outputs (technically, AxisArrays) with two-indexes to a dataframe Inputs: var -- JuMP AxisArray (e.g., value.(GEN)) Reference: https://jump.dev/JuMP.jl/v0.19/containers/ =# function value_to_df_2dim(var) solution = DataFrame(var.data) ax1 = var.axes[1] ax2 = var.axes[2] cols = names(solution) insertcols!(solution, 1, :r_id => ax1) solution = stack(solution, Not(:r_id), variable_name=:hour) solution.hour = foldl(replace, [cols[i] => ax2[i] for i in 1:length(ax2)], init=solution.hour) rename!(solution, :value => :gen) solution.hour = convert.(Int64,solution.hour) return solution end ``` value_to_df_2dim (generic function with 1 method) Then we'll create a function to create and solve a simple unit commitment problem with specified input data. ```julia #= Function to solve simple unit commitment problem (commitment equations) Inputs: gen_df -- dataframe with generator info loads -- load by time gen_variable -- capacity factors of variable generators (in "long" format) =# function unit_commitment_simple(gen_df, loads, gen_variable) UC = Model(GLPK.Optimizer) # We reduce the MIP gap tolerance threshold here to increase tractability # Here we set it to a 1% gap, meaning that we will terminate once we have # a feasible integer solution guaranteed to be within 1% of the objective # function value of the optimal solution. # Note that GLPK's default MIP gap is 0.0, meaning that it tries to solve # the integer problem to optimality, which can take a LONG time for # any complex problem. So it is important to set this to a realistic value. set_optimizer_attribute(UC, "mip_gap", 0.01) # Define sets based on data # Note the creation of several different sets of generators for use in # different equations. # Thermal resources for which unit commitment constraints apply G_thermal = gen_df[gen_df[!,:up_time] .> 0,:r_id] # Non-thermal resources for which unit commitment constraints do NOT apply G_nonthermal = gen_df[gen_df[!,:up_time] .== 0,:r_id] # Variable renewable resources G_var = gen_df[gen_df[!,:is_variable] .== 1,:r_id] # Non-variable (dispatchable) resources G_nonvar = gen_df[gen_df[!,:is_variable] .== 0,:r_id] # Non-variable and non-thermal resources G_nt_nonvar = intersect(G_nonvar, G_nonthermal) # Set of all generators (above are all subsets of this) G = gen_df.r_id # All time periods (hours) over which we are optimizing T = loads.hour # A subset of time periods that excludes the last time period T_red = loads.hour[1:end-1] # reduced time periods without last one # Generator capacity factor time series for variable generators gen_var_cf = innerjoin(gen_variable, gen_df[gen_df.is_variable .== 1 , [:r_id, :gen_full, :existing_cap_mw]], on = :gen_full) # Decision variables @variables(UC, begin # Continuous decision variables GEN[G, T] >= 0 # generation # Bin = binary variables; # the following are all binary decisions that # can ONLY take the values 0 or 1 # The presence of these discrete decisions makes this an MILP COMMIT[G_thermal, T], Bin # commitment status (Bin=binary) START[G_thermal, T], Bin # startup decision SHUT[G_thermal, T], Bin # shutdown decision end) # Objective function # Sum of variable costs + start-up costs for all generators and time periods @objective(UC, Min, sum( (gen_df[gen_df.r_id .== i,:heat_rate_mmbtu_per_mwh][1] * gen_df[gen_df.r_id .== i,:fuel_cost][1] + gen_df[gen_df.r_id .== i,:var_om_cost_per_mwh][1]) * GEN[i,t] for i in G_nonvar for t in T) + sum(gen_df[gen_df.r_id .== i,:var_om_cost_per_mwh][1] * GEN[i,t] for i in G_var for t in T) + sum(gen_df[gen_df.r_id .== i,:start_cost_per_mw][1] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * START[i,t] for i in G_thermal for t in T) ) # Demand balance constraint (supply must = demand in all time periods) @constraint(UC, cDemand[t in T], sum(GEN[i,t] for i in G) == loads[loads.hour .== t,:demand][1]) # Capacity constraints # 1. thermal generators requiring commitment @constraint(UC, Cap_thermal_min[i in G_thermal, t in T], GEN[i,t] >= COMMIT[i, t] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:min_power][1]) @constraint(UC, Cap_thermal_max[i in G_thermal, t in T], GEN[i,t] <= COMMIT[i, t] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1]) # 2. non-variable generation not requiring commitment @constraint(UC, Cap_nt_nonvar[i in G_nt_nonvar, t in T], GEN[i,t] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1]) # 3. variable generation, accounting for hourly capacity factor @constraint(UC, Cap_var[i in 1:nrow(gen_var_cf)], GEN[gen_var_cf[i,:r_id], gen_var_cf[i,:hour] ] <= gen_var_cf[i,:cf] * gen_var_cf[i,:existing_cap_mw]) # Unit commitment constraints # 1. Minimum up time @constraint(UC, Startup[i in G_thermal, t in T], COMMIT[i, t] >= sum(START[i, tt] for tt in intersect(T, (t-gen_df[gen_df.r_id .== i,:up_time][1]):t))) # 2. Minimum down time @constraint(UC, Shutdown[i in G_thermal, t in T], 1-COMMIT[i, t] >= sum(SHUT[i, tt] for tt in intersect(T, (t-gen_df[gen_df.r_id .== i,:down_time][1]):t))) # 3. Commitment state @constraint(UC, CommitmentStatus[i in G_thermal, t in T_red], COMMIT[i,t+1] - COMMIT[i,t] == START[i,t+1] - SHUT[i,t+1]) # Solve statement (! indicates runs in place) optimize!(UC) # Generation solution and convert to data frame # with our helper function defined above gen = value_to_df_2dim(value.(GEN)) # Commitment status solution and convert to data frame commit = value_to_df_2dim(value.(COMMIT)) # Calculate curtailment = available wind and/or solar output that # had to be wasted due to operating constraints curtail = innerjoin(gen_var_cf, gen, on = [:r_id, :hour]) curtail.curt = curtail.cf .* curtail.existing_cap_mw - curtail.gen # Return the solution parameters and objective return ( gen, commit, curtail, cost = objective_value(UC), status = termination_status(UC) ) end ``` unit_commitment_simple (generic function with 1 method) ### 4. Solve a day's unit commitment ```julia # A spring day n=100 T_period = (n*24+1):((n+1)*24) # High solar case: 3,500 MW gen_df_sens = copy(gen_df) gen_df_sens[gen_df_sens.resource .== "solar_photovoltaic", :existing_cap_mw] = 3500 loads_multi = loads[in.(loads.hour,Ref(T_period)),:] gen_variable_multi = gen_variable_long[in.(gen_variable_long.hour,Ref(T_period)),:] solution = unit_commitment_simple(gen_df_sens, loads_multi, gen_variable_multi); ``` ```julia # Add in BTM solar and curtailment and plot results sol_gen = innerjoin(solution.gen, gen_df[!, [:r_id, :resource]], on = :r_id) sol_gen = combine(groupby(sol_gen, [:resource, :hour]), :gen => sum) # Rename generators (for plotting purposes) sol_gen[sol_gen.resource .== "solar_photovoltaic", :resource] .= "_solar_photovoltaic" sol_gen[sol_gen.resource .== "onshore_wind_turbine", :resource] .= "_onshore_wind_turbine" sol_gen[sol_gen.resource .== "small_hydroelectric", :resource] .= "_small_hydroelectric" # BTM solar btm = DataFrame(resource = repeat(["_solar_photovoltaic_btm"]; outer=length(T_period)), hour = T_period, gen_sum = gen_variable_multi[gen_variable_multi.gen_full .== "wec_sdge_solar_photovoltaic_1.0",:cf] * 600) append!(sol_gen, btm) # Curtailment curtail = combine(groupby(solution.curtail, [:hour]), :curt => sum) curtail.resource = "_curtailment" rename!(curtail, :curt_sum => :gen_sum) append!(sol_gen, curtail[:,[:resource, :hour, :gen_sum]]) # Rescale hours sol_gen.hour = sol_gen.hour .- T_period[1] sol_gen |> @vlplot(:area, x=:hour, y={:gen_sum, stack=:zero}, color={"resource:n", scale={scheme="category10"}}) ``` Notice that the combined cycle plants flatten out during the day, but don't shut down due to the need for ramping capabilities in the late afternoon/evening, when solar output falls off and evening demand remains strong. This leads to some curtailment of solar from 11:00 - 16:00, which was not present in the Economic Dispatch model. All curtailment is lumped together as the model does not accurately distinguish between whether wind, solar or hydro is curtailed, which in practice is up to the system operator and depends on a variety of factors such as location, interconnection voltage, etc. We can examine the commitment status of various units by examining the results in `solution.commit`. ```julia sol_commit = innerjoin(solution.commit, gen_df[!, [:r_id, :resource]], on = :r_id) sol_commit = combine(groupby(sol_commit, [:resource, :hour]), :gen => sum) sol_commit.hour = sol_commit.hour .- T_period[1] sol_commit |> @vlplot(:area, x=:hour, y={:gen_sum, stack=:zero}, color={"resource:n", scale={scheme="category10"}}) ``` Note that units shutdown during the solar period and startup for the evening peak. However, due to the commitment constraints, not all natural gas plants can be decommitted, resulting in the observed curtailment. A large number of combustion turbines turn on to meet the evening peak. ## Moderate complexity unit commitment We expand the above unit commitment with ramp equations. These must be modified to prevent ramp violations during the startup process. In order to accommodate this, we introduce an **auxiliary variable** $GENAUX_{g,t}$ defined as the generation above the minimum output (if committed). $GENAUX_{g,t} = GEN_{g,t} = 0$ if the unit is not committed. Auxiliary variables are for convenience (we could always write the whole problem in terms of the original decision variables), but they help de-clutter the model and in general won't add too much computational penalty. The following constraints are added: $$ \begin{align} & GENAUX_{g,t} = GEN_{g,t} - Pmin_{g,t}COMMIT_{g,t} & \forall \quad g \in G_{thermal} , t \in T \\ & GENAUX_{g,t+1} - GENAUX_{g,t} \leq RampUp_{g} & \forall \quad g \in G_{thermal} , t = 1..T-1 \\ & GENAUX_{g,t} - GENAUX_{g,t+1} \leq RampDn_{g} & \forall \quad g \in G_{thermal} , t = 1..T-1 \\ & GEN_{g,t+1} - GEN_{g,t} \leq RampUp_{g} & \forall \quad g \notin G_{thermal} , t = 1..T-1 \\ & GEN_{g,t} - GEN_{g,t+1} \leq RampDn_{g} & \forall \quad g \notin G_{thermal} , t = 1..T-1 \end{align} $$ The creation of this auxiliary variable $GENAUX$ helps us avoid violating ramping constraints when we start up our units and their generation immediately jumps up to their minium output level or during shut-down when a unit drops from minimum output (or above) to zero. Note you may encounter alternative formulations in the literature to address this start-up and shut-down that modify the right-hand side of the traditional ramping constraint on total generation to account for the additional step change in output during start-up or shut-down periods. The above formulation is conceptually simple and works well. ### 3. Create solver function (We reuse steps 1 and 2 above to load packages and data.) ```julia #= Function to solve moderate complexity unit commitment problem (commitment and ramp equations) Inputs: gen_df -- dataframe with generator info loads -- load by time gen_variable -- capacity factors of variable generators (in "long" format) =# function unit_commitment_ramp(gen_df, loads, gen_variable) UC = Model(GLPK.Optimizer) set_optimizer_attribute(UC, "mip_gap", 0.01) #1% MIP gap # Define sets based on data # Note the creation of several different sets of generators for use in # different equations. G_thermal = gen_df[gen_df[!,:up_time] .> 0,:r_id] G_nonthermal = gen_df[gen_df[!,:up_time] .== 0,:r_id] G_var = gen_df[gen_df[!,:is_variable] .== 1,:r_id] G_nonvar = gen_df[gen_df[!,:is_variable] .== 0,:r_id] G_nt_nonvar = intersect(G_nonvar, G_nonthermal) G = gen_df.r_id T = loads.hour T_red = loads.hour[1:end-1] # reduced time periods without last one # Generator capacity factor time series for variable generators gen_var_cf = innerjoin(gen_variable, gen_df[gen_df.is_variable .== 1 , [:r_id, :gen_full, :existing_cap_mw]], on = :gen_full) # Decision variables @variables(UC, begin GEN[G, T] >= 0 # generation GENAUX[G_thermal, T] >= 0 # auxiliary generation variable COMMIT[G_thermal, T], Bin # commitment status (Bin=binary) START[G_thermal, T], Bin # startup decision SHUT[G_thermal, T], Bin # shutdown decision end) # Objective function @objective(UC, Min, sum( (gen_df[gen_df.r_id .== i,:heat_rate_mmbtu_per_mwh][1] * gen_df[gen_df.r_id .== i,:fuel_cost][1] + gen_df[gen_df.r_id .== i,:var_om_cost_per_mwh][1]) * GEN[i,t] for i in G_nonvar for t in T) + sum(gen_df[gen_df.r_id .== i,:var_om_cost_per_mwh][1] * GEN[i,t] for i in G_var for t in T) + sum(gen_df[gen_df.r_id .== i,:start_cost_per_mw][1] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * START[i,t] for i in G_thermal for t in T) ) # Demand constraint @constraint(UC, cDemand[t in T], sum(GEN[i,t] for i in G) == loads[loads.hour .== t,:demand][1]) # Capacity constraints (thermal generators requiring commitment) @constraint(UC, Cap_thermal_min[i in G_thermal, t in T], GEN[i,t] >= COMMIT[i, t] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:min_power][1]) @constraint(UC, Cap_thermal_max[i in G_thermal, t in T], GEN[i,t] <= COMMIT[i, t] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1]) # Capacity constraints (non-variable generation not requiring commitment) @constraint(UC, Cap_nt_nonvar[i in G_nt_nonvar, t in T], GEN[i,t] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1]) # Capacity constraints (variable generation) @constraint(UC, Cap_var[i in 1:nrow(gen_var_cf)], GEN[gen_var_cf[i,:r_id], gen_var_cf[i,:hour] ] <= gen_var_cf[i,:cf] * gen_var_cf[i,:existing_cap_mw]) # Unit commitment constraints @constraint(UC, Startup[i in G_thermal, t in T], COMMIT[i, t] >= sum(START[i, tt] for tt in intersect(T, (t-gen_df[gen_df.r_id .== i,:up_time][1]):t))) @constraint(UC, Shutdown[i in G_thermal, t in T], 1-COMMIT[i, t] >= sum(SHUT[i, tt] for tt in intersect(T, (t-gen_df[gen_df.r_id .== i,:down_time][1]):t))) @constraint(UC, CommitmentStatus[i in G_thermal, t in T_red], COMMIT[i,t+1] - COMMIT[i,t] == START[i,t+1] - SHUT[i,t+1]) # New auxiliary variable GENAUX for generation above the minimum output level # for committed thermal units (only created for thermal generators) @constraint(UC, AuxGen[i in G_thermal, t in T], GENAUX[i,t] == GEN[i,t] - COMMIT[i, t] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:min_power][1]) # Ramp equations for thermal generators (constraining GENAUX) @constraint(UC, RampUp_thermal[i in G_thermal, t in T_red], GENAUX[i,t+1] - GENAUX[i,t] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:ramp_up_percentage][1] ) @constraint(UC, RampDn_thermal[i in G_thermal, t in T_red], GENAUX[i,t] - GENAUX[i,t+1] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:ramp_dn_percentage][1] ) # Ramp equations for non-thermal generators (constraining total generation GEN) @constraint(UC, RampUp_nonthermal[i in G_nonthermal, t in T_red], GEN[i,t+1] - GEN[i,t] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:ramp_up_percentage][1] ) @constraint(UC, RampDn[i in G, t in T_red], GEN[i,t] - GEN[i,t+1] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:ramp_dn_percentage][1] ) # Solve statement (! indicates runs in place) optimize!(UC) # Generation solution gen = value_to_df_2dim(value.(GEN)) # Commitment status solution commit = value_to_df_2dim(value.(COMMIT)) # Calculate curtailment curtail = innerjoin(gen_var_cf, gen, on = [:r_id, :hour]) curtail.curt = curtail.cf .* curtail.existing_cap_mw - curtail.gen # Return the solution and objective as named tuple return ( gen, commit, curtail, cost = objective_value(UC), status = termination_status(UC) ) end ``` unit_commitment_ramp (generic function with 1 method) ### 4. Solve a day's unit commitment ```julia solution = unit_commitment_ramp(gen_df_sens, loads_multi, gen_variable_multi); # Add in BTM solar and curtailment and plot results sol_gen = innerjoin(solution.gen, gen_df[!, [:r_id, :resource]], on = :r_id) sol_gen = combine(groupby(sol_gen, [:resource, :hour]), :gen => sum) # Rename generators (for plotting purposes) sol_gen[sol_gen.resource .== "solar_photovoltaic", :resource] .= "_solar_photovoltaic" sol_gen[sol_gen.resource .== "onshore_wind_turbine", :resource] .= "_onshore_wind_turbine" sol_gen[sol_gen.resource .== "small_hydroelectric", :resource] .= "_small_hydroelectric" # BTM solar btm = DataFrame(resource = repeat(["_solar_photovoltaic_btm"]; outer=length(T_period)), hour = T_period, gen_sum = gen_variable_multi[gen_variable_multi.gen_full .== "wec_sdge_solar_photovoltaic_1.0",:cf] * 600) append!(sol_gen, btm) # Curtailment curtail = combine(groupby(solution.curtail, [:hour]), :curt => sum) curtail.resource = "_curtailment" rename!(curtail, :curt_sum => :gen_sum) append!(sol_gen, curtail[:,[:resource, :hour, :gen_sum]]) # Rescale hours sol_gen.hour = sol_gen.hour .- T_period[1] sol_gen |> @vlplot(:area, x=:hour, y={:gen_sum, stack=:zero}, color={"resource:n", scale={scheme="category10"}}) ``` In contrast to when we added ramp constraints to the Economic Dispatch problem, adding ramp constraints to our Unit Commitment formulation does not change the solution as much (at least in this case). Much of the inflexibility here arises from the unit commitment constraints, and once committed, there is ample ramping capability. We do however get relatively more combustion turbines running to meet the evening ramp, given their faster ramp rates. ```julia sol_commit = innerjoin(solution.commit, gen_df[!, [:r_id, :resource]], on = :r_id) sol_commit = combine(groupby(sol_commit, [:resource, :hour]), :gen => sum) sol_commit.hour = sol_commit.hour .- T_period[1] sol_commit |> @vlplot(:area, x=:hour, y={:gen_sum, stack=:zero}, color={"resource:n", scale={scheme="category10"}}) ``` A case involving more large coal or nuclear units with slower ramping limits than gas turbines or combined cycle plants might find ramp constraints more limiting. As in many cases, the impact of constraints is case dependent, and models must exercise some judicious application of domain knowledge (and experimentation with alternative formulations) to decide how complex your model should be to reflect important *binding* constraints that actually shape your outcomes of interest. Where constraints are non-binding or second order, it may be more practical to omit them entirely, reducing the computational intensity (solve time) of your model... ## Unit commitment with ramping and reserves We now add spinning reserve requirements to the model. Spinning reserves refer to generation capacity that is online and able to generate (e.g., within 10-30 minutes) if needed by the system operator. (Note: in Europe, these are referred to as tertiary reserves.) The SO will establish reserve requirements to maintain sufficient capacity to respond to demand or supply forecast errors or in case of "contingencies," such as the unplanned and sudden loss of a generating station or a transmission line. The SO then typically operates a reserve market to competitively procure this available capacity. Most SO's actually define several classes of reserve products defined by their response time and period over which they may be activated. Here we will focus on spinning reserve requirements and establish a simple set of reserve requirements for reserves up (ability to quickly increase output) and reserves down (ability to quickly reduce output): $$ \begin{align} & ResReqUp_t = 300 MW + 5\% \times Demand_t &\forall \quad t \in T \\ & ResReqDn_t = 5\% \times Demand_t & \forall \quad t \in T \end{align} $$ Here, $300 MW$ is our contigency reserves, meant to ensure we have sufficient upwards ramping capability online and available to cover the unexpected loss of 300 MW worth of generation. The 5% of demand term in the constraints above is meant to provide sufficient reserves in either upwards or downwards direction to cover errors in the demand forecast. For simplicity, we ignore solar PV and wind production in our reserve calculation, though in practice, we would want to consider solar and wind forecast errors in calculating up reserve requirements as well. In our simple system, only thermal generators provide reserves. (This can be easily adjusted by changing the sets and defining the potential reserve contributions for different sets of resources differently, such as storage or hydro resources). The contribution of each generators to meeting reserves and the overall reserve constraint are thus given by: $$ \begin{align} & RESUP_{g,t} \leq Pmax_{g,t}COMMIT_{g,t} - GEN_{g,t} & \forall \quad g \in G_{thermal} , t \in T \\ & RESDN_{g,t} \leq GEN_{g,t} - Pmin_{g,t}COMMIT_{g,t} & \forall \quad g \in G_{thermal} , t \in T \\ & RESUP_{g,t} \leq RampUp_{g} & \forall \quad g \in G_{thermal}, t \in T\\ & RESDN_{g,t} \leq RampDn_{g} & \forall \quad g \in G_{thermal}, t \in T \\ & \sum_{g \in G_{thermal}} RESUP_{g,t} \geq ResReqUp_t & \forall \quad t \in T \\ & \sum_{g \in G_{thermal}} RESDN_{g,t} \geq ResReqDn_t & \forall \quad t \in T \end{align} $$ We have added two new **decision variables**: - $RESUP_{g,t}$, up-reserve capacity (in MW) of generator $g$ at time $t$ - $RESDN_{g,t}$, down-reserve capacity (in MW) of generator $g$ at time $t$ Note that in this case, we constrain the reserve contribution for each thermal generator to be the same as their hourly ramp rates, $RampUp_{g}, RampDown_{g}$. In practice, reserve products typically require a faster response time, on the order of 10-30 minutes for "tertiary" reserves (aka spinning reserves or contingency reserves), and 5-15 minutes for "secondary" reserves (regulation reserves). Thus, depending on the reserve requirements being modeled, one might specify a distinct maximum reserve contribution for each unit that reflects their ramping capabilities over shorter time periods. ### 3. Create solver function (We reuse steps 1 and 2 above to load packages and data.) ```julia #= Function to solve full unit commitment problem (commitment, ramp, reserve equations) Inputs: gen_df -- dataframe with generator info loads -- load by time gen_variable -- capacity factors of variable generators (in "long" format) =# function unit_commitment_full(gen_df, loads, gen_variable) UC = Model(GLPK.Optimizer) # To keep solve times to a few minutes, we increase the MIP gap tolerance # in this more complex case to 2%. You can play with this setting to see # how the MIP gap affects solve times on your computer. set_optimizer_attribute(UC, "mip_gap", 0.02) # Define sets based on data # Note the creation of several different sets of generators for use in # different equations. G_thermal = gen_df[gen_df[!,:up_time] .> 0,:r_id] G_nonthermal = gen_df[gen_df[!,:up_time] .== 0,:r_id] G_var = gen_df[gen_df[!,:is_variable] .== 1,:r_id] G_nonvar = gen_df[gen_df[!,:is_variable] .== 0,:r_id] G_nt_nonvar = intersect(G_nonvar, G_nonthermal) G = gen_df.r_id T = loads.hour T_red = loads.hour[1:end-1] # reduced time periods without last one # Generator capacity factor time series for variable generators gen_var_cf = innerjoin(gen_variable, gen_df[gen_df.is_variable .== 1 , [:r_id, :gen_full, :existing_cap_mw, :resource]], on = :gen_full) gen_var_cf.max_gen = gen_var_cf.cf .* gen_var_cf.existing_cap_mw # Compute reserve requirements ResReqUp = Dict(T[i] => 300 + 0.05 * loads[loads.hour .== T[i],:demand][1] for i in 1:length(T)) ResReqDn = Dict(T[i] => 0 + 0.05 * loads[loads.hour .== T[i],:demand][1] for i in 1:length(T)) # Decision variables @variables(UC, begin GEN[G, T] >= 0 # generation GENAUX[G_thermal, T] >= 0 # auxiliary generation variable COMMIT[G_thermal, T], Bin # commitment status (Bin=binary) START[G_thermal, T], Bin # startup decision SHUT[G_thermal, T], Bin # shutdown decision RESUP[G_thermal, T] # up reserve capacity RESDN[G_thermal, T] # down reserve capacity end) # Objective function @objective(UC, Min, sum( (gen_df[gen_df.r_id .== i,:heat_rate_mmbtu_per_mwh][1] * gen_df[gen_df.r_id .== i,:fuel_cost][1] + gen_df[gen_df.r_id .== i,:var_om_cost_per_mwh][1]) * GEN[i,t] for i in G_nonvar for t in T) + sum(gen_df[gen_df.r_id .== i,:var_om_cost_per_mwh][1] * GEN[i,t] for i in G_var for t in T) + sum(gen_df[gen_df.r_id .== i,:start_cost_per_mw][1] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * START[i,t] for i in G_thermal for t in T) ) # Demand constraint @constraint(UC, cDemand[t in T], sum(GEN[i,t] for i in G) == loads[loads.hour .== t,:demand][1]) # Capacity constraints (thermal generators requiring commitment) @constraint(UC, Cap_thermal_min[i in G_thermal, t in T], GEN[i,t] >= COMMIT[i, t] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:min_power][1]) @constraint(UC, Cap_thermal_max[i in G_thermal, t in T], GEN[i,t] <= COMMIT[i, t] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1]) # Capacity constraints (non-variable generation not requiring commitment) @constraint(UC, Cap_nt_nonvar[i in G_nt_nonvar, t in T], GEN[i,t] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1]) # Capacity constraints (variable generation) @constraint(UC, Cap_var[i in 1:nrow(gen_var_cf)], GEN[gen_var_cf[i,:r_id], gen_var_cf[i,:hour] ] <= gen_var_cf[i,:max_gen]) # Unit commitment constraints @constraint(UC, Startup[i in G_thermal, t in T], COMMIT[i, t] >= sum(START[i, tt] for tt in intersect(T, (t-gen_df[gen_df.r_id .== i,:up_time][1]):t))) @constraint(UC, Shutdown[i in G_thermal, t in T], 1-COMMIT[i, t] >= sum(SHUT[i, tt] for tt in intersect(T, (t-gen_df[gen_df.r_id .== i,:down_time][1]):t))) @constraint(UC, CommitmentStatus[i in G_thermal, t in T_red], COMMIT[i,t+1] - COMMIT[i,t] == START[i,t+1] - SHUT[i,t+1]) # Auxiliary variable @constraint(UC, AuxGen[i in G_thermal, t in T], GENAUX[i,t] == GEN[i,t] - COMMIT[i, t] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:min_power][1]) # Ramp equations (thermal generators) @constraint(UC, RampUp_thermal[i in G_thermal, t in T_red], GENAUX[i,t+1] - GENAUX[i,t] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:ramp_up_percentage][1] ) @constraint(UC, RampDn_thermal[i in G_thermal, t in T_red], GENAUX[i,t] - GENAUX[i,t+1] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:ramp_dn_percentage][1] ) # Ramp equations (non-thermal generators) @constraint(UC, RampUp_nonthermal[i in G_nonthermal, t in T_red], GEN[i,t+1] - GEN[i,t] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:ramp_up_percentage][1] ) @constraint(UC, RampDn[i in G, t in T_red], GEN[i,t] - GEN[i,t+1] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:ramp_dn_percentage][1] ) # Reserve equations # (1) Reserves limited by committed capacity of generator @constraint(UC, ResUpCap[i in G_thermal, t in T], RESUP[i,t] <= COMMIT[i, t] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1] - GEN[i,t]) @constraint(UC, ResDnCap[i in G_thermal, t in T], RESDN[i,t] <= GEN[i,t] - COMMIT[i, t] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:min_power][1]) # (2) Reserves limited by ramp rates @constraint(UC, ResUpRamp[i in G_thermal, t in T], RESUP[i,t] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:ramp_up_percentage][1]) @constraint(UC, ResDnRamp[i in G_thermal, t in T], RESDN[i,t] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:ramp_dn_percentage][1]) # (3) Overall reserve requirements @constraint(UC, ResUpRequirement[t in T], sum(RESUP[i,t] for i in G_thermal) >= ResReqUp[t]) @constraint(UC, ResDnRequirement[t in T], sum(RESDN[i,t] for i in G_thermal) >= ResReqDn[t]) # Solve statement (! indicates runs in place) optimize!(UC) # Generation solution gen = value_to_df_2dim(value.(GEN)) # Commitment status solution commit = value_to_df_2dim(value.(COMMIT)) # Calculate curtailment curtail = innerjoin(gen_var_cf, gen, on = [:r_id, :hour]) curtail.curt = curtail.cf .* curtail.existing_cap_mw - curtail.gen # Return the solution and objective as named tuple return ( gen, commit, curtail, cost = objective_value(UC), status = termination_status(UC) ) end ``` unit_commitment_full (generic function with 1 method) ### 4. Solve the model and plot results **Note: this might take a little while depending on your machine.** ```julia solution = unit_commitment_full(gen_df_sens, loads_multi, gen_variable_multi); # Add in BTM solar and curtailment and plot results sol_gen = innerjoin(solution.gen, gen_df[!, [:r_id, :resource]], on = :r_id) sol_gen = combine(groupby(sol_gen, [:resource, :hour]), :gen => sum) # Rename generators (for plotting purposes) sol_gen[sol_gen.resource .== "solar_photovoltaic", :resource] .= "_solar_photovoltaic" sol_gen[sol_gen.resource .== "onshore_wind_turbine", :resource] .= "_onshore_wind_turbine" sol_gen[sol_gen.resource .== "small_hydroelectric", :resource] .= "_small_hydroelectric" # BTM solar btm = DataFrame(resource = repeat(["_solar_photovoltaic_btm"]; outer=length(T_period)), hour = T_period, gen_sum = gen_variable_multi[gen_variable_multi.gen_full .== "wec_sdge_solar_photovoltaic_1.0",:cf] * 600) append!(sol_gen, btm) # Curtailment curtail = combine(groupby(solution.curtail, [:hour]), :curt => sum) curtail.resource = "_curtailment" rename!(curtail, :curt_sum => :gen_sum) append!(sol_gen, curtail[:,[:resource, :hour, :gen_sum]]) # Rescale hours sol_gen.hour = sol_gen.hour .- T_period[1] sol_gen |> @vlplot(:area, x=:hour, y={:gen_sum, stack=:zero}, color={"resource:n", scale={scheme="category10"}}) ``` We can now see that the need to maintain reserve requirements leads to greater commitment of natural gas units throughout the day. The addition of CCGTs and GTs to meet reserve requirements leads to greater curtailment of wind and solar in the afternoon hours. We also see more CT units committed during the morning ramp as well as the afternoon hours to help provide reserves. ```julia sol_commit = innerjoin(solution.commit, gen_df[!, [:r_id, :resource]], on = :r_id) sol_commit = combine(groupby(sol_commit, [:resource, :hour]), :gen => sum) sol_commit.hour = sol_commit.hour .- T_period[1] sol_commit |> @vlplot(:area, x=:hour, y={:gen_sum, stack=:zero}, color={"resource:n", scale={scheme="category10"}}) ``` ### Further resources Knueven, B., Ostrowski, J., & Watson, J.-P. (2019). On Mixed Integer Programming Formulations for the Unit Commitment Problem. Optimization Online, 91. http://www.optimization-online.org/DB_FILE/2018/11/6930.pdf Morales-Espana, G., Latorre, J. M., & Ramos, A. (2013). Tight and Compact MILP Formulation of Start-Up and Shut-Down Ramping in Unit Commitment. IEEE Transactions on Power Systems, 28(2), 1288–1296. https://doi.org/10.1109/TPWRS.2012.2222938 Morales-España, G., Ramírez-Elizondo, L., & Hobbs, B. F. (2017). Hidden power system inflexibilities imposed by traditional unit commitment formulations. Applied Energy, 191, 223–238. https://doi.org/10.1016/j.apenergy.2017.01.089 Ostrowski, J., Anjos, M. F., & Vannelli, A. (2012). Tight Mixed Integer Linear Programming Formulations for the Unit Commitment Problem. IEEE Transactions on Power Systems, 27(1), 39–46. https://doi.org/10.1109/TPWRS.2011.2162008
lemma real_affinity_lt: "0 < m \<Longrightarrow> m * x + c < y \<longleftrightarrow> x < inverse m * y + - (c / m)" for m :: "'a::linordered_field"
From NaturalNumbers Require Export Base Tutorial. (* Given statements in Natural Numbers Game in Lean. They just write that Peano gave these. If we really wanted we could have just Admitted. them *) Fact add_zero (n : mynat) : n + 0 = n. Proof. trivial. Qed. Fact add_succ (m n : mynat) : n + (S m) = S (n + m). Proof. trivial. Qed. (* Level 0 data *) (* name The `induction` tactic *) (* tactics induction *) (* theorems add_succ *) (* Level 0 prologue *) (* Alright, so now that we know the basics, let's get started with addition. Just as a reminder, these are the things we have and know: <ul> <li>a type `mynat`</li> <li>a term `0 : mynat`, the number zero</li> <li>a function `S: mynat -> mynat` taking a number `n` to its successor</li> <li>addition, with the usual notation `a + b`</li> <li>a theorem `add_zero (n : mynat) : n + 0 = n.`</li> <li>a theorem `add_succ (m n : mynat) : n + (S m) = S (n + m).`</li> <li>the principle of mathematical induction, used with the `induction` tactic, see below.</li> </ul> Okay, so in this first level we will prove ``` #Lemma zero_add (n : mynat) : 0 + n = n. ``` Strange right, it seems so simple knowing our theorem ``` #Fact add_zero (n : mynat) : n + 0 = n. ``` but commutativity is not a given! To prove the lemma for this level, just `rewrite` and `reflexivity` are not enough, we need something stronger. There is a tactic called `induction`, which we can use on inductive types like our type `mynat`. Suppose we have a `n : mynat` in our assumptions, then we can write ``` induction n s [| ? h]. ``` to start our induction proof. When you type this, Coq will start two "subgoals", one for the base case (`n = 0`), and one for the induction step. It is common practice to "select" the subgoal explicitly by typing a dash `-` on the next line. Doing this you will only see one goal again. Once you are done proving this goal, the interpreter will tell you ```plaintext This subproof is complete, but there are some unfocused goals. Focus next goal with bullet -. 1 subgoal subgoal 1 is: ... ``` Now you might wonder what the `[| ? h]` means. To be very precise, in our inductive type `mynat` we have two constructors (`0` and `S n`), so `induction` will produce two paths. In the first path, we don't get any (new) hypotheses, so we don't have to name any variables. In the second path, we get a number and an induction hypothesis. The `?` is the name for the number, indicating we don't really care what it is called, we well see it in the subgoal (it will be `n`, the same name as the variable we are doing induction over). The second hypothesis is the induction hypothesis. I always like to call it `h`, I think by default it is `IHn`. This variable will be the induction hypothesis, saying `h : 0 + n = n`. In short, the proof will look something like this: ``` induction n as [| ? h]. - rewrite ... ... reflexivity. - rewrite ... ... reflexivity. ``` Try it out below! *) Lemma zero_add (n : mynat) : 0 + n = n. Proof. induction n as [| ? H]. - rewrite add_zero. reflexivity. - rewrite add_succ. rewrite H. reflexivity. Qed. (* Level epilogue *) (* Level end *) (* Level 1 data *) (* name `add_assoc` -- associativity of addition *) (* tactics induction *) (* theorems add_succ *) (* Level 1 prologue *) (* The next step is to prove that addition is associative, i.e. that `(a + b) + c = a + (b + c)`. Note that in the goals, the left hand side of the equation will show up as `a + b + c` instead of `(a + b) + c`. This is simply because Coq knows that addition is left-binding. *) Lemma add_assoc (a b c : mynat) : (a + b) + c = a + (b + c). Proof. induction c as [| ? H]. - repeat rewrite add_zero. reflexivity. (* This only works if we do induction on C, otherwise we would want succ_add *) - repeat rewrite add_succ. rewrite H. reflexivity. Qed. (* Level epilogue *) (* Level end *) (* Level 2 data *) (* name `succ_add` *) (* tactics repeat *) (* theorems add_succ *) (* Level 2 prologue *) (* It is almost time for the boss level of this world. Before that, let us first prove the counterpart to `add_succ`: `succ_add`. Just as a tip, instead of repeatedly writing `rewrite add_zero.`, it is also possible to use the `repeat` tactic, allowing you to write ``` repeat rewrite add_zero. ``` When using the `rewrite` tactic, Coq guesses which parameters to use in the theorem. It is also possible to do this explicitly by writing ``` rewrite (add_zero a) ``` to rewrite a subterm `a + 0` into `a`. *) Lemma succ_add (a b : mynat) : S a + b = S (a + b). Proof. induction b as [| ? H]. - repeat rewrite add_zero. reflexivity. - repeat rewrite add_succ. rewrite H. reflexivity. Qed. (* Level epilogue *) (* Level end *) (* Level 3 data *) (* name `add_comm` (boss level) *) (* tactics repeat *) (* theorems add_succ *) (* Level 3 prologue *) (* <b>*boss music*</b> Check the side menu to remember the theorems you have shown so far, you should be prepared to prove this lemma. *) Lemma add_comm (a b : mynat) : a + b = b + a. Proof. induction b as [| ? H]. - now rewrite add_zero, zero_add. - rewrite add_succ, succ_add. now rewrite H. Qed. (* Level epilogue *) (* Level end *) (* Given in natural numbers game *) Definition I := S 0. Notation "1" := I. Fact one_eq_succ_zero : 1 = S 0. Proof. trivial. Qed. (* Level 4 data *) (* name `succ_eq_add_one` *) (* tactics repeat *) (* theorems one_eq_succ_zero *) (* Level 4 prologue *) (* I have just defined the number `1`, in the way you would expect: `1 = S 0`, and added a theorem ``` #Fact one_eq_succ_zero : 1 = S 0. ``` that witnesses this. Use it to prove the following theorem. *) Lemma succ_eq_add_one (n : mynat) : S n = n + 1. Proof. rewrite one_eq_succ_zero. rewrite add_succ. rewrite add_zero. reflexivity. Qed. (* Level epilogue *) (* Level end *) (* Level 5 data *) (* name `add_right_comm` *) (* tactics repeat *) (* theorems one_eq_succ_zero *) (* Level 5 prologue *) (* Alright, time for the last level in Addition World. Here it might be useful to use the strategy I mentioned before: rewriting a specific term in the equation. Remember you can do this with the `rewrite` tactic by using it like this: ``` rewrite (add_comm b c). ``` *) Lemma add_right_comm (a b c : mynat) : a + b + c = a + c + b. Proof. rewrite add_assoc. rewrite (add_comm b c). (* Can just use the forward direction but whatever *) rewrite <- add_assoc. reflexivity. Qed. (* Level epilogue *) (* With all these statements about addition, we have shown that `mynat` is a commutative monoid. In Lean (the proof checker from the original Natural Numbers Game) we could tell the proof checker that `mynat` is indeed a commutative monoid. Sadly such a structure does not exist, but I have come up with a (rather hacky) solution for this, so that we can still use some more advanced tactics to make your life easier. Basically, I added a "fake" multiplication operation, and added some `Axiom`s (basically theorems which we just assume to be true, do this at your own risk!). With these, I was able to convince Coq that `mynat` is a semiring with this fake multiplication. For now this will suffice, and it allows us to use the powerful `ring` tactic, allowing us to prove simple statements about expressions in one line, such as ``` #Lemma test (a b c d e : mynat) : (((a+b)+c)+d)+e=(c+((b+e)+a))+d. #Proof. # ring. #Qed. ``` It is now time to move on to Multiplication World! Though if you wish, you could also go to Function World, as we know enough to get started there too. You can do this by going back to the main menu and clicking Function World in the graph! *) (* Level end *)
Formal statement is: lemma continuous_on_open_avoid: fixes f :: "'a::metric_space \<Rightarrow> 'b::t1_space" assumes "continuous_on s f" and "open s" and "x \<in> s" and "f x \<noteq> a" shows "\<exists>e>0. \<forall>y. dist x y < e \<longrightarrow> f y \<noteq> a" Informal statement is: If $f$ is a continuous function on an open set $S$, and $f(x) \neq a$ for some $x \in S$, then there exists an $\epsilon > 0$ such that $f(y) \neq a$ for all $y$ with $|x - y| < \epsilon$.
x <- read.table("Picoides_pubescens.RepeatMasker.out", sep="", fill=T, stringsAsFactors=F) # remove header and white space lines x <- x[grep("*caffold*", x[,5]), ] # read in scaffolds and keep those at least one Mbp y <- read.table("Picoides_pubescens.fa.fai", stringsAsFactors=F) y <- y[y[,2] >= 1000000, ] y <- sort(y[,1]) # subset the repeats file by the large scaffolds x <- x[x[,5] %in% y, ] # simplify for analyses x2 <- x[,5:7] write.table(x2, "repeatmask.txt", sep="\t", quote=F, col.names=F, row.names=F) # simplify for analyses x2 <- x[,c(5,6,7,10)] write.table(x2, "repeatmask2.txt", sep="\t", quote=F, col.names=F, row.names=F) # filter for only CR1 superfamily (there will still be some non-CR1s in there) x3 <- x[x[,11] == "LINE/CR1", ] # further refine CR1s x3 <- x3[grep("^CR1", x3[,10]), ] write(c("#scaffold", "5'", "3'"), file="repeats_cr1s.txt", ncolumns=3, sep="\t") # loop for each cr1 for(a in 1:nrow(x3)) { a_rep <- x3[a,] a_rep2 <- as.character(a_rep[1,12:14]) a_rep2 <- as.numeric(a_rep2[-grep("\\(", a_rep2)]) if(a_rep2[2] > a_rep2[1]) { a_out <- c(a_rep[1,5], a_rep[1,6], a_rep[1,7]) } else if(a_rep2[1] > a_rep2[2]) { a_out <- c(a_rep[1,5], a_rep[1,7], a_rep[1,6]) } else { a_out <- c("error", "error", "error") } write(a_out, file="repeats_cr1s.txt", ncolumns=3, sep="\t", append=T) }
(* Title: HOL/HOLCF/IOA/meta_theory/Automata.thy Author: Olaf Müller, Konrad Slind, Tobias Nipkow *) section {* The I/O automata of Lynch and Tuttle in HOLCF *} theory Automata imports Asig begin default_sort type type_synonym ('a, 's) transition = "'s * 'a * 's" type_synonym ('a, 's) ioa = "'a signature * 's set * ('a,'s)transition set * ('a set set) * ('a set set)" consts (* IO automata *) asig_of ::"('a,'s)ioa => 'a signature" starts_of ::"('a,'s)ioa => 's set" trans_of ::"('a,'s)ioa => ('a,'s)transition set" wfair_of ::"('a,'s)ioa => ('a set) set" sfair_of ::"('a,'s)ioa => ('a set) set" is_asig_of ::"('a,'s)ioa => bool" is_starts_of ::"('a,'s)ioa => bool" is_trans_of ::"('a,'s)ioa => bool" input_enabled ::"('a,'s)ioa => bool" IOA ::"('a,'s)ioa => bool" (* constraints for fair IOA *) fairIOA ::"('a,'s)ioa => bool" input_resistant::"('a,'s)ioa => bool" (* enabledness of actions and action sets *) enabled ::"('a,'s)ioa => 'a => 's => bool" Enabled ::"('a,'s)ioa => 'a set => 's => bool" (* action set keeps enabled until probably disabled by itself *) en_persistent :: "('a,'s)ioa => 'a set => bool" (* post_conditions for actions and action sets *) was_enabled ::"('a,'s)ioa => 'a => 's => bool" set_was_enabled ::"('a,'s)ioa => 'a set => 's => bool" (* invariants *) invariant :: "[('a,'s)ioa, 's=>bool] => bool" (* binary composition of action signatures and automata *) asig_comp ::"['a signature, 'a signature] => 'a signature" compatible ::"[('a,'s)ioa, ('a,'t)ioa] => bool" par ::"[('a,'s)ioa, ('a,'t)ioa] => ('a,'s*'t)ioa" (infixr "||" 10) (* hiding and restricting *) hide_asig :: "['a signature, 'a set] => 'a signature" hide :: "[('a,'s)ioa, 'a set] => ('a,'s)ioa" restrict_asig :: "['a signature, 'a set] => 'a signature" restrict :: "[('a,'s)ioa, 'a set] => ('a,'s)ioa" (* renaming *) rename_set :: "'a set => ('c => 'a option) => 'c set" rename :: "('a, 'b)ioa => ('c => 'a option) => ('c,'b)ioa" notation (xsymbols) par (infixr "\<parallel>" 10) inductive reachable :: "('a, 's) ioa => 's => bool" for C :: "('a, 's) ioa" where reachable_0: "s : starts_of C ==> reachable C s" | reachable_n: "[| reachable C s; (s, a, t) : trans_of C |] ==> reachable C t" abbreviation trans_of_syn ("_ -_--_-> _" [81,81,81,81] 100) where "s -a--A-> t == (s,a,t):trans_of A" notation (xsymbols) trans_of_syn ("_ \<midarrow>_\<midarrow>_\<longrightarrow> _" [81,81,81,81] 100) abbreviation "act A == actions (asig_of A)" abbreviation "ext A == externals (asig_of A)" abbreviation int where "int A == internals (asig_of A)" abbreviation "inp A == inputs (asig_of A)" abbreviation "out A == outputs (asig_of A)" abbreviation "local A == locals (asig_of A)" defs (* --------------------------------- IOA ---------------------------------*) asig_of_def: "asig_of == fst" starts_of_def: "starts_of == (fst o snd)" trans_of_def: "trans_of == (fst o snd o snd)" wfair_of_def: "wfair_of == (fst o snd o snd o snd)" sfair_of_def: "sfair_of == (snd o snd o snd o snd)" is_asig_of_def: "is_asig_of A == is_asig (asig_of A)" is_starts_of_def: "is_starts_of A == (~ starts_of A = {})" is_trans_of_def: "is_trans_of A == (!triple. triple:(trans_of A) --> fst(snd(triple)):actions(asig_of A))" input_enabled_def: "input_enabled A == (!a. (a:inputs(asig_of A)) --> (!s1. ? s2. (s1,a,s2):(trans_of A)))" ioa_def: "IOA A == (is_asig_of A & is_starts_of A & is_trans_of A & input_enabled A)" invariant_def: "invariant A P == (!s. reachable A s --> P(s))" (* ------------------------- parallel composition --------------------------*) compatible_def: "compatible A B == (((out A Int out B) = {}) & ((int A Int act B) = {}) & ((int B Int act A) = {}))" asig_comp_def: "asig_comp a1 a2 == (((inputs(a1) Un inputs(a2)) - (outputs(a1) Un outputs(a2)), (outputs(a1) Un outputs(a2)), (internals(a1) Un internals(a2))))" par_def: "(A || B) == (asig_comp (asig_of A) (asig_of B), {pr. fst(pr):starts_of(A) & snd(pr):starts_of(B)}, {tr. let s = fst(tr); a = fst(snd(tr)); t = snd(snd(tr)) in (a:act A | a:act B) & (if a:act A then (fst(s),a,fst(t)):trans_of(A) else fst(t) = fst(s)) & (if a:act B then (snd(s),a,snd(t)):trans_of(B) else snd(t) = snd(s))}, wfair_of A Un wfair_of B, sfair_of A Un sfair_of B)" (* ------------------------ hiding -------------------------------------------- *) restrict_asig_def: "restrict_asig asig actns == (inputs(asig) Int actns, outputs(asig) Int actns, internals(asig) Un (externals(asig) - actns))" (* Notice that for wfair_of and sfair_of nothing has to be changed, as changes from the outputs to the internals does not touch the locals as a whole, which is of importance for fairness only *) restrict_def: "restrict A actns == (restrict_asig (asig_of A) actns, starts_of A, trans_of A, wfair_of A, sfair_of A)" hide_asig_def: "hide_asig asig actns == (inputs(asig) - actns, outputs(asig) - actns, internals(asig) Un actns)" hide_def: "hide A actns == (hide_asig (asig_of A) actns, starts_of A, trans_of A, wfair_of A, sfair_of A)" (* ------------------------- renaming ------------------------------------------- *) rename_set_def: "rename_set A ren == {b. ? x. Some x = ren b & x : A}" rename_def: "rename ioa ren == ((rename_set (inp ioa) ren, rename_set (out ioa) ren, rename_set (int ioa) ren), starts_of ioa, {tr. let s = fst(tr); a = fst(snd(tr)); t = snd(snd(tr)) in ? x. Some(x) = ren(a) & (s,x,t):trans_of ioa}, {rename_set s ren | s. s: wfair_of ioa}, {rename_set s ren | s. s: sfair_of ioa})" (* ------------------------- fairness ----------------------------- *) fairIOA_def: "fairIOA A == (! S : wfair_of A. S<= local A) & (! S : sfair_of A. S<= local A)" input_resistant_def: "input_resistant A == ! W : sfair_of A. ! s a t. reachable A s & reachable A t & a:inp A & Enabled A W s & s -a--A-> t --> Enabled A W t" enabled_def: "enabled A a s == ? t. s-a--A-> t" Enabled_def: "Enabled A W s == ? w:W. enabled A w s" en_persistent_def: "en_persistent A W == ! s a t. Enabled A W s & a ~:W & s -a--A-> t --> Enabled A W t" was_enabled_def: "was_enabled A a t == ? s. s-a--A-> t" set_was_enabled_def: "set_was_enabled A W t == ? w:W. was_enabled A w t" declare split_paired_Ex [simp del] lemmas ioa_projections = asig_of_def starts_of_def trans_of_def wfair_of_def sfair_of_def subsection "asig_of, starts_of, trans_of" lemma ioa_triple_proj: "((asig_of (x,y,z,w,s)) = x) & ((starts_of (x,y,z,w,s)) = y) & ((trans_of (x,y,z,w,s)) = z) & ((wfair_of (x,y,z,w,s)) = w) & ((sfair_of (x,y,z,w,s)) = s)" apply (simp add: ioa_projections) done lemma trans_in_actions: "[| is_trans_of A; (s1,a,s2):trans_of(A) |] ==> a:act A" apply (unfold is_trans_of_def actions_def is_asig_def) apply (erule allE, erule impE, assumption) apply simp done lemma starts_of_par: "starts_of(A || B) = {p. fst(p):starts_of(A) & snd(p):starts_of(B)}" apply (simp add: par_def ioa_projections) done lemma trans_of_par: "trans_of(A || B) = {tr. let s = fst(tr); a = fst(snd(tr)); t = snd(snd(tr)) in (a:act A | a:act B) & (if a:act A then (fst(s),a,fst(t)):trans_of(A) else fst(t) = fst(s)) & (if a:act B then (snd(s),a,snd(t)):trans_of(B) else snd(t) = snd(s))}" apply (simp add: par_def ioa_projections) done subsection "actions and par" lemma actions_asig_comp: "actions(asig_comp a b) = actions(a) Un actions(b)" apply (simp (no_asm) add: actions_def asig_comp_def asig_projections) apply blast done lemma asig_of_par: "asig_of(A || B) = asig_comp (asig_of A) (asig_of B)" apply (simp add: par_def ioa_projections) done lemma externals_of_par: "ext (A1||A2) = (ext A1) Un (ext A2)" apply (simp add: externals_def asig_of_par asig_comp_def asig_inputs_def asig_outputs_def Un_def set_diff_eq) apply blast done lemma actions_of_par: "act (A1||A2) = (act A1) Un (act A2)" apply (simp add: actions_def asig_of_par asig_comp_def asig_inputs_def asig_outputs_def asig_internals_def Un_def set_diff_eq) apply blast done lemma inputs_of_par: "inp (A1||A2) = ((inp A1) Un (inp A2)) - ((out A1) Un (out A2))" apply (simp add: actions_def asig_of_par asig_comp_def asig_inputs_def asig_outputs_def Un_def set_diff_eq) done lemma outputs_of_par: "out (A1||A2) = (out A1) Un (out A2)" apply (simp add: actions_def asig_of_par asig_comp_def asig_outputs_def Un_def set_diff_eq) done lemma internals_of_par: "int (A1||A2) = (int A1) Un (int A2)" apply (simp add: actions_def asig_of_par asig_comp_def asig_inputs_def asig_outputs_def asig_internals_def Un_def set_diff_eq) done subsection "actions and compatibility" lemma compat_commute: "compatible A B = compatible B A" apply (simp add: compatible_def Int_commute) apply auto done lemma ext1_is_not_int2: "[| compatible A1 A2; a:ext A1|] ==> a~:int A2" apply (unfold externals_def actions_def compatible_def) apply simp apply blast done (* just commuting the previous one: better commute compatible *) lemma ext2_is_not_int1: "[| compatible A2 A1 ; a:ext A1|] ==> a~:int A2" apply (unfold externals_def actions_def compatible_def) apply simp apply blast done lemmas ext1_ext2_is_not_act2 = ext1_is_not_int2 [THEN int_and_ext_is_act] lemmas ext1_ext2_is_not_act1 = ext2_is_not_int1 [THEN int_and_ext_is_act] lemma intA_is_not_extB: "[| compatible A B; x:int A |] ==> x~:ext B" apply (unfold externals_def actions_def compatible_def) apply simp apply blast done lemma intA_is_not_actB: "[| compatible A B; a:int A |] ==> a ~: act B" apply (unfold externals_def actions_def compatible_def is_asig_def asig_of_def) apply simp apply blast done (* the only one that needs disjointness of outputs and of internals and _all_ acts *) lemma outAactB_is_inpB: "[| compatible A B; a:out A ;a:act B|] ==> a : inp B" apply (unfold asig_outputs_def asig_internals_def actions_def asig_inputs_def compatible_def is_asig_def asig_of_def) apply simp apply blast done (* needed for propagation of input_enabledness from A,B to A||B *) lemma inpAAactB_is_inpBoroutB: "[| compatible A B; a:inp A ;a:act B|] ==> a : inp B | a: out B" apply (unfold asig_outputs_def asig_internals_def actions_def asig_inputs_def compatible_def is_asig_def asig_of_def) apply simp apply blast done subsection "input_enabledness and par" (* ugly case distinctions. Heart of proof: 1. inpAAactB_is_inpBoroutB ie. internals are really hidden. 2. inputs_of_par: outputs are no longer inputs of par. This is important here *) lemma input_enabled_par: "[| compatible A B; input_enabled A; input_enabled B|] ==> input_enabled (A||B)" apply (unfold input_enabled_def) apply (simp add: Let_def inputs_of_par trans_of_par) apply (tactic "safe_tac (Context.raw_transfer @{theory} @{theory_context Fun})") apply (simp add: inp_is_act) prefer 2 apply (simp add: inp_is_act) (* a: inp A *) apply (case_tac "a:act B") (* a:act B *) apply (erule_tac x = "a" in allE) apply simp apply (drule inpAAactB_is_inpBoroutB) apply assumption apply assumption apply (erule_tac x = "a" in allE) apply simp apply (erule_tac x = "aa" in allE) apply (erule_tac x = "b" in allE) apply (erule exE) apply (erule exE) apply (rule_tac x = " (s2,s2a) " in exI) apply (simp add: inp_is_act) (* a~: act B*) apply (simp add: inp_is_act) apply (erule_tac x = "a" in allE) apply simp apply (erule_tac x = "aa" in allE) apply (erule exE) apply (rule_tac x = " (s2,b) " in exI) apply simp (* a:inp B *) apply (case_tac "a:act A") (* a:act A *) apply (erule_tac x = "a" in allE) apply (erule_tac x = "a" in allE) apply (simp add: inp_is_act) apply (frule_tac A1 = "A" in compat_commute [THEN iffD1]) apply (drule inpAAactB_is_inpBoroutB) back apply assumption apply assumption apply simp apply (erule_tac x = "aa" in allE) apply (erule_tac x = "b" in allE) apply (erule exE) apply (erule exE) apply (rule_tac x = " (s2,s2a) " in exI) apply (simp add: inp_is_act) (* a~: act B*) apply (simp add: inp_is_act) apply (erule_tac x = "a" in allE) apply (erule_tac x = "a" in allE) apply simp apply (erule_tac x = "b" in allE) apply (erule exE) apply (rule_tac x = " (aa,s2) " in exI) apply simp done subsection "invariants" lemma invariantI: "[| !!s. s:starts_of(A) ==> P(s); !!s t a. [|reachable A s; P(s)|] ==> (s,a,t): trans_of(A) --> P(t) |] ==> invariant A P" apply (unfold invariant_def) apply (rule allI) apply (rule impI) apply (rule_tac x = "s" in reachable.induct) apply assumption apply blast apply blast done lemma invariantI1: "[| !!s. s : starts_of(A) ==> P(s); !!s t a. reachable A s ==> P(s) --> (s,a,t):trans_of(A) --> P(t) |] ==> invariant A P" apply (blast intro: invariantI) done lemma invariantE: "[| invariant A P; reachable A s |] ==> P(s)" apply (unfold invariant_def) apply blast done subsection "restrict" lemmas reachable_0 = reachable.reachable_0 and reachable_n = reachable.reachable_n lemma cancel_restrict_a: "starts_of(restrict ioa acts) = starts_of(ioa) & trans_of(restrict ioa acts) = trans_of(ioa)" apply (simp add: restrict_def ioa_projections) done lemma cancel_restrict_b: "reachable (restrict ioa acts) s = reachable ioa s" apply (rule iffI) apply (erule reachable.induct) apply (simp add: cancel_restrict_a reachable_0) apply (erule reachable_n) apply (simp add: cancel_restrict_a) (* <-- *) apply (erule reachable.induct) apply (rule reachable_0) apply (simp add: cancel_restrict_a) apply (erule reachable_n) apply (simp add: cancel_restrict_a) done lemma acts_restrict: "act (restrict A acts) = act A" apply (simp (no_asm) add: actions_def asig_internals_def asig_outputs_def asig_inputs_def externals_def asig_of_def restrict_def restrict_asig_def) apply auto done lemma cancel_restrict: "starts_of(restrict ioa acts) = starts_of(ioa) & trans_of(restrict ioa acts) = trans_of(ioa) & reachable (restrict ioa acts) s = reachable ioa s & act (restrict A acts) = act A" apply (simp (no_asm) add: cancel_restrict_a cancel_restrict_b acts_restrict) done subsection "rename" lemma trans_rename: "s -a--(rename C f)-> t ==> (? x. Some(x) = f(a) & s -x--C-> t)" apply (simp add: Let_def rename_def trans_of_def) done lemma reachable_rename: "[| reachable (rename C g) s |] ==> reachable C s" apply (erule reachable.induct) apply (rule reachable_0) apply (simp add: rename_def ioa_projections) apply (drule trans_rename) apply (erule exE) apply (erule conjE) apply (erule reachable_n) apply assumption done subsection "trans_of(A||B)" lemma trans_A_proj: "[|(s,a,t):trans_of (A||B); a:act A|] ==> (fst s,a,fst t):trans_of A" apply (simp add: Let_def par_def trans_of_def) done lemma trans_B_proj: "[|(s,a,t):trans_of (A||B); a:act B|] ==> (snd s,a,snd t):trans_of B" apply (simp add: Let_def par_def trans_of_def) done lemma trans_A_proj2: "[|(s,a,t):trans_of (A||B); a~:act A|] ==> fst s = fst t" apply (simp add: Let_def par_def trans_of_def) done lemma trans_B_proj2: "[|(s,a,t):trans_of (A||B); a~:act B|] ==> snd s = snd t" apply (simp add: Let_def par_def trans_of_def) done lemma trans_AB_proj: "(s,a,t):trans_of (A||B) ==> a :act A | a :act B" apply (simp add: Let_def par_def trans_of_def) done lemma trans_AB: "[|a:act A;a:act B; (fst s,a,fst t):trans_of A;(snd s,a,snd t):trans_of B|] ==> (s,a,t):trans_of (A||B)" apply (simp add: Let_def par_def trans_of_def) done lemma trans_A_notB: "[|a:act A;a~:act B; (fst s,a,fst t):trans_of A;snd s=snd t|] ==> (s,a,t):trans_of (A||B)" apply (simp add: Let_def par_def trans_of_def) done lemma trans_notA_B: "[|a~:act A;a:act B; (snd s,a,snd t):trans_of B;fst s=fst t|] ==> (s,a,t):trans_of (A||B)" apply (simp add: Let_def par_def trans_of_def) done lemmas trans_of_defs1 = trans_AB trans_A_notB trans_notA_B and trans_of_defs2 = trans_A_proj trans_B_proj trans_A_proj2 trans_B_proj2 trans_AB_proj lemma trans_of_par4: "((s,a,t) : trans_of(A || B || C || D)) = ((a:actions(asig_of(A)) | a:actions(asig_of(B)) | a:actions(asig_of(C)) | a:actions(asig_of(D))) & (if a:actions(asig_of(A)) then (fst(s),a,fst(t)):trans_of(A) else fst t=fst s) & (if a:actions(asig_of(B)) then (fst(snd(s)),a,fst(snd(t))):trans_of(B) else fst(snd(t))=fst(snd(s))) & (if a:actions(asig_of(C)) then (fst(snd(snd(s))),a,fst(snd(snd(t)))):trans_of(C) else fst(snd(snd(t)))=fst(snd(snd(s)))) & (if a:actions(asig_of(D)) then (snd(snd(snd(s))),a,snd(snd(snd(t)))):trans_of(D) else snd(snd(snd(t)))=snd(snd(snd(s)))))" apply (simp (no_asm) add: par_def actions_asig_comp prod_eq_iff Let_def ioa_projections) done subsection "proof obligation generator for IOA requirements" (* without assumptions on A and B because is_trans_of is also incorporated in ||def *) lemma is_trans_of_par: "is_trans_of (A||B)" apply (unfold is_trans_of_def) apply (simp add: Let_def actions_of_par trans_of_par) done lemma is_trans_of_restrict: "is_trans_of A ==> is_trans_of (restrict A acts)" apply (unfold is_trans_of_def) apply (simp add: cancel_restrict acts_restrict) done lemma is_trans_of_rename: "is_trans_of A ==> is_trans_of (rename A f)" apply (unfold is_trans_of_def restrict_def restrict_asig_def) apply (simp add: Let_def actions_def trans_of_def asig_internals_def asig_outputs_def asig_inputs_def externals_def asig_of_def rename_def rename_set_def) apply blast done lemma is_asig_of_par: "[| is_asig_of A; is_asig_of B; compatible A B|] ==> is_asig_of (A||B)" apply (simp add: is_asig_of_def asig_of_par asig_comp_def compatible_def asig_internals_def asig_outputs_def asig_inputs_def actions_def is_asig_def) apply (simp add: asig_of_def) apply auto done lemma is_asig_of_restrict: "is_asig_of A ==> is_asig_of (restrict A f)" apply (unfold is_asig_of_def is_asig_def asig_of_def restrict_def restrict_asig_def asig_internals_def asig_outputs_def asig_inputs_def externals_def o_def) apply simp apply auto done lemma is_asig_of_rename: "is_asig_of A ==> is_asig_of (rename A f)" apply (simp add: is_asig_of_def rename_def rename_set_def asig_internals_def asig_outputs_def asig_inputs_def actions_def is_asig_def asig_of_def) apply auto apply (drule_tac [!] s = "Some ?x" in sym) apply auto done lemmas [simp] = is_asig_of_par is_asig_of_restrict is_asig_of_rename is_trans_of_par is_trans_of_restrict is_trans_of_rename lemma compatible_par: "[|compatible A B; compatible A C |]==> compatible A (B||C)" apply (unfold compatible_def) apply (simp add: internals_of_par outputs_of_par actions_of_par) apply auto done (* better derive by previous one and compat_commute *) lemma compatible_par2: "[|compatible A C; compatible B C |]==> compatible (A||B) C" apply (unfold compatible_def) apply (simp add: internals_of_par outputs_of_par actions_of_par) apply auto done lemma compatible_restrict: "[| compatible A B; (ext B - S) Int ext A = {}|] ==> compatible A (restrict B S)" apply (unfold compatible_def) apply (simp add: ioa_triple_proj asig_triple_proj externals_def restrict_def restrict_asig_def actions_def) apply auto done declare split_paired_Ex [simp] end
(* Author: Alexander Katovsky *) header "Functor" theory Functors imports Category begin record ('o1, 'o2, 'm1, 'm2, 'a, 'b) Functor = CatDom :: "('o1,'m1,'a)Category_scheme" CatCod :: "('o2,'m2,'b)Category_scheme" MapM :: "'m1 \<Rightarrow> 'm2" abbreviation FunctorMorApp :: "('o1, 'o2, 'm1, 'm2, 'a1, 'a2, 'a) Functor_scheme \<Rightarrow> 'm1 \<Rightarrow> 'm2" (infixr "##" 70) where "FunctorMorApp F m \<equiv> (MapM F) m" definition MapO :: "('o1, 'o2, 'm1, 'm2, 'a1, 'a2, 'a) Functor_scheme \<Rightarrow> 'o1 \<Rightarrow> 'o2" where "MapO F X \<equiv> THE Y . Y \<in> Obj(CatCod F) \<and> F ## (Id (CatDom F) X) = Id (CatCod F) Y" abbreviation FunctorObjApp :: "('o1, 'o2, 'm1, 'm2, 'a1, 'a2, 'a) Functor_scheme \<Rightarrow> 'o1 \<Rightarrow> 'o2" (infixr "@@" 70) where "FunctorObjApp F X \<equiv> (MapO F X)" locale PreFunctor = fixes F :: "('o1, 'o2, 'm1, 'm2, 'a1, 'a2, 'a) Functor_scheme" (structure) assumes FunctorComp: "f \<approx>>\<^bsub>CatDom F\<^esub> g \<Longrightarrow> F ## (f ;;\<^bsub>CatDom F\<^esub> g) = (F ## f) ;;\<^bsub>CatCod F\<^esub> (F ## g)" and FunctorId: "X \<in> obj\<^bsub>CatDom F\<^esub> \<Longrightarrow> \<exists> Y \<in> obj\<^bsub>CatCod F\<^esub> . F ## (id\<^bsub>CatDom F\<^esub> X) = id\<^bsub>CatCod F\<^esub> Y" and CatDom[simp]: "Category(CatDom F)" and CatCod[simp]: "Category(CatCod F)" locale FunctorM = PreFunctor + assumes FunctorCompM: "f maps\<^bsub>CatDom F\<^esub> X to Y \<Longrightarrow> (F ## f) maps\<^bsub>CatCod F\<^esub> (F @@ X) to (F @@ Y)" locale FunctorExt = fixes F :: "('o1, 'o2, 'm1, 'm2, 'a1, 'a2, 'a) Functor_scheme" (structure) assumes FunctorMapExt: "(MapM F) \<in> extensional (Mor (CatDom F))" locale Functor = FunctorM + FunctorExt definition MakeFtor :: "('o1, 'o2, 'm1, 'm2, 'a, 'b,'r) Functor_scheme \<Rightarrow> ('o1, 'o2, 'm1, 'm2, 'a, 'b,'r) Functor_scheme" where "MakeFtor F \<equiv> \<lparr> CatDom = CatDom F , CatCod = CatCod F , MapM = restrict (MapM F) (Mor (CatDom F)) , \<dots> = Functor.more F \<rparr>" lemma PreFunctorFunctor[simp]: "Functor F \<Longrightarrow> PreFunctor F" by (simp add: Functor_def FunctorM_def) lemmas functor_simps = PreFunctor.FunctorComp PreFunctor.FunctorId definition functor_abbrev ("Ftor _ : _ \<longrightarrow> _" [81]) where "Ftor F : A \<longrightarrow> B \<equiv> (Functor F) \<and> (CatDom F = A) \<and> (CatCod F = B)" lemma functor_abbrevE[elim]: "\<lbrakk>Ftor F : A \<longrightarrow> B ; \<lbrakk>(Functor F) ; (CatDom F = A) ; (CatCod F = B)\<rbrakk> \<Longrightarrow> R\<rbrakk> \<Longrightarrow> R" by (auto simp add: functor_abbrev_def) definition functor_comp_def ("_ \<approx>>;;; _" [81]) where "functor_comp_def F G \<equiv> (Functor F) \<and> (Functor G) \<and> (CatDom G = CatCod F)" lemma functor_comp_def[elim]: "\<lbrakk>F \<approx>>;;; G ; \<lbrakk>Functor F ; Functor G ; CatDom G = CatCod F\<rbrakk> \<Longrightarrow> R\<rbrakk> \<Longrightarrow> R" by (auto simp add: functor_comp_def_def) lemma (in Functor) FunctorMapsTo: assumes "f \<in> mor\<^bsub>CatDom F\<^esub>" shows "F ## f maps\<^bsub>CatCod F\<^esub> (F @@ (dom\<^bsub>CatDom F\<^esub> f)) to (F @@ (cod\<^bsub>CatDom F\<^esub> f))" proof- have "f maps\<^bsub>CatDom F\<^esub> (dom\<^bsub>CatDom F\<^esub> f) to (cod\<^bsub>CatDom F\<^esub> f)" using assms by auto thus ?thesis by (simp add: FunctorCompM[of f "dom\<^bsub>CatDom F\<^esub> f" "cod\<^bsub>CatDom F\<^esub> f"]) qed lemma (in Functor) FunctorCodDom: assumes "f \<in> mor\<^bsub>CatDom F\<^esub>" shows "dom\<^bsub>CatCod F\<^esub>(F ## f) = F @@ (dom\<^bsub>CatDom F\<^esub> f)" and "cod\<^bsub>CatCod F\<^esub>(F ## f) = F @@ (cod\<^bsub>CatDom F\<^esub> f)" proof- have "F ## f maps\<^bsub>CatCod F\<^esub> (F @@ (dom\<^bsub>CatDom F\<^esub> f)) to (F @@ (cod\<^bsub>CatDom F\<^esub> f))" using assms by (simp add: FunctorMapsTo) thus "dom\<^bsub>CatCod F\<^esub>(F ## f) = F @@ (dom\<^bsub>CatDom F\<^esub> f)" and "cod\<^bsub>CatCod F\<^esub>(F ## f) = F @@ (cod\<^bsub>CatDom F\<^esub> f)" by auto qed lemma (in Functor) FunctorCompPreserved: "f \<in> mor\<^bsub>CatDom F\<^esub> \<Longrightarrow> F ## f \<in> mor\<^bsub>CatCod F\<^esub>" by (auto dest:FunctorMapsTo) lemma (in Functor) FunctorCompDef: assumes "f \<approx>>\<^bsub>CatDom F\<^esub> g" shows "(F ## f) \<approx>>\<^bsub>CatCod F\<^esub> (F ## g)" proof(auto simp add: CompDefined_def) show "F ## f \<in> mor\<^bsub>CatCod F\<^esub>" and "F ## g \<in> mor\<^bsub>CatCod F\<^esub>" using assms by (auto simp add: FunctorCompPreserved) have "f \<in> mor\<^bsub>CatDom F\<^esub>" and "g \<in> mor\<^bsub>CatDom F\<^esub>" using assms by auto hence a: "cod\<^bsub>CatCod F\<^esub> (F ## f) = F @@ (cod\<^bsub>CatDom F\<^esub> f)" and b: "dom\<^bsub>CatCod F\<^esub>(F ## g) = F @@ (dom\<^bsub>CatDom F\<^esub> g)" by (simp add: FunctorCodDom)+ have "cod\<^bsub>CatCod F\<^esub> (F ## f) = F @@ (dom\<^bsub>CatDom F\<^esub> g)" using assms a by auto also have "... = dom\<^bsub>CatCod F\<^esub> (F ## g)" using b by simp finally show "cod\<^bsub>CatCod F\<^esub> (F ## f) = dom\<^bsub>CatCod F\<^esub> (F ## g)" . qed lemma FunctorComp: "\<lbrakk>Ftor F : A \<longrightarrow> B ; f \<approx>>\<^bsub>A\<^esub> g\<rbrakk> \<Longrightarrow> F ## (f ;;\<^bsub>A\<^esub> g) = (F ## f) ;;\<^bsub>B\<^esub> (F ## g)" by (auto simp add: PreFunctor.FunctorComp) lemma FunctorCompDef: "\<lbrakk>Ftor F : A \<longrightarrow> B ; f \<approx>>\<^bsub>A\<^esub> g\<rbrakk> \<Longrightarrow> (F ## f) \<approx>>\<^bsub>B\<^esub> (F ## g)" by (auto simp add: Functor.FunctorCompDef) lemma FunctorMapsTo: assumes "Ftor F : A \<longrightarrow> B" and "f maps\<^bsub>A\<^esub> X to Y" shows "(F ## f) maps\<^bsub>B\<^esub> (F @@ X) to (F @@ Y)" proof- have b: "CatCod F = B" and a: "CatDom F = A" and ff: "Functor F" using assms by auto have df: "(dom\<^bsub>CatDom F\<^esub> f) = X" and cf: "(cod\<^bsub>CatDom F\<^esub> f) = Y" using a assms by auto have "f \<in> mor\<^bsub>CatDom F\<^esub>" using assms by auto hence "F ## f maps\<^bsub>CatCod F\<^esub> (F @@ (dom\<^bsub>CatDom F\<^esub> f)) to (F @@ (cod\<^bsub>CatDom F\<^esub> f))" using ff by (simp add: Functor.FunctorMapsTo) thus ?thesis using df cf b by simp qed lemma (in PreFunctor) FunctorId2: assumes "X \<in> obj\<^bsub>CatDom F\<^esub>" shows "F @@ X \<in> obj\<^bsub>CatCod F\<^esub> \<and> F ## (id\<^bsub>CatDom F\<^esub> X) = id\<^bsub>CatCod F\<^esub> (F @@ X)" proof- let ?Q = "\<lambda> E Y . Y \<in> obj\<^bsub>CatCod F\<^esub> \<and> E = id\<^bsub>CatCod F\<^esub> Y" let ?P = "?Q (F ## (id\<^bsub>CatDom F\<^esub> X))" from assms FunctorId obtain Y where "?P Y" by auto moreover { fix y e z have "\<lbrakk>?Q e y ; ?Q e z\<rbrakk> \<Longrightarrow> y = z" by (auto intro: Category.IdInj[of "CatCod F" y z]) } ultimately have "\<exists>! Z . ?P Z" by auto hence "?P (THE Y . ?P Y)" by (rule theI') thus ?thesis by (auto simp add: MapO_def) qed lemma FunctorId: assumes "Ftor F : C \<longrightarrow> D" and "X \<in> Obj C" shows "F ## (Id C X) = Id D (F @@ X)" proof- have "CatDom F = C" and "CatCod F = D" and "PreFunctor F" using assms by auto thus ?thesis using assms PreFunctor.FunctorId2[of F X] by simp qed lemma (in Functor) DomFunctor: "f \<in> mor\<^bsub>CatDom F\<^esub> \<Longrightarrow> dom\<^bsub>CatCod F\<^esub> (F ## f) = F @@ (dom\<^bsub>CatDom F\<^esub> f)" by (simp add: FunctorCodDom) lemma (in Functor) FunctorId3Dom: assumes "f \<in> mor\<^bsub>CatDom F\<^esub>" shows "F ## (id\<^bsub>CatDom F\<^esub> (dom\<^bsub>CatDom F\<^esub> f)) = id\<^bsub>CatCod F\<^esub> (dom\<^bsub>CatCod F\<^esub> (F ## f))" proof- have "(dom\<^bsub>CatDom F\<^esub> f) \<in> obj\<^bsub>CatDom F\<^esub>" using assms by (simp add: Category.Cdom) hence "F ## (id\<^bsub>CatDom F\<^esub> (dom\<^bsub>CatDom F\<^esub> f)) = id\<^bsub>CatCod F\<^esub> (F @@ (dom\<^bsub>CatDom F\<^esub> f))" by (simp add: FunctorId2) also have "... = id\<^bsub>CatCod F\<^esub> (dom\<^bsub>CatCod F\<^esub> (F ## f))" using assms by (simp add: DomFunctor) finally show ?thesis by simp qed lemma (in Functor) FunctorId3Cod: assumes "f \<in> mor\<^bsub>CatDom F\<^esub>" shows "F ## (id\<^bsub>CatDom F\<^esub> (cod\<^bsub>CatDom F\<^esub> f)) = id\<^bsub>CatCod F\<^esub> (cod\<^bsub>CatCod F\<^esub> (F ## f))" proof- have "(cod\<^bsub>CatDom F\<^esub> f) \<in> obj\<^bsub>CatDom F\<^esub>" using assms by (simp add: Category.Ccod) hence "F ## (id\<^bsub>CatDom F\<^esub> (cod\<^bsub>CatDom F\<^esub> f)) = id\<^bsub>CatCod F\<^esub> (F @@ (cod\<^bsub>CatDom F\<^esub> f))" by (simp add: FunctorId2) also have "... = id\<^bsub>CatCod F\<^esub> (cod\<^bsub>CatCod F\<^esub> (F ## f))" using assms by (simp add: CodFunctor) finally show ?thesis by simp qed lemma (in PreFunctor) FmToFo: "\<lbrakk>X \<in> obj\<^bsub>CatDom F\<^esub> ; Y \<in> obj\<^bsub>CatCod F\<^esub> ; F ## (id\<^bsub>CatDom F\<^esub> X) = id\<^bsub>CatCod F\<^esub> Y\<rbrakk> \<Longrightarrow> F @@ X = Y" by (auto simp add: FunctorId2 intro: Category.IdInj[of "CatCod F" "F @@ X" Y]) lemma MakeFtorPreFtor: assumes "PreFunctor F" shows "PreFunctor (MakeFtor F)" proof- { fix X assume a: "X \<in> obj\<^bsub>CatDom F\<^esub>" have "id\<^bsub>CatDom F \<^esub>X \<in> mor\<^bsub>CatDom F\<^esub>" proof- have "Category (CatDom F)" using assms by (simp add: PreFunctor_def) hence "id\<^bsub>CatDom F \<^esub>X maps\<^bsub>CatDom F\<^esub> X to X" using a by (simp add: Category.Cidm) thus ?thesis using a by (auto) qed } thus "PreFunctor (MakeFtor F)" using assms by(auto simp add: PreFunctor_def MakeFtor_def Category.MapsToMorDomCod) qed lemma MakeFtorMor: "f \<in> mor\<^bsub>CatDom F\<^esub> \<Longrightarrow> MakeFtor F ## f = F ## f" by(simp add: MakeFtor_def) lemma MakeFtorObj: assumes "PreFunctor F" and "X \<in> obj\<^bsub>CatDom F\<^esub>" shows "MakeFtor F @@ X = F @@ X" proof- have "X \<in> obj\<^bsub>CatDom (MakeFtor F)\<^esub>" using assms(2) by (simp add: MakeFtor_def) moreover have "(F @@ X) \<in> obj\<^bsub>CatCod (MakeFtor F)\<^esub>" using assms by (simp add: PreFunctor.FunctorId2 MakeFtor_def) moreover have "MakeFtor F ## id\<^bsub>CatDom (MakeFtor F) \<^esub>X = id\<^bsub>CatCod (MakeFtor F) \<^esub>(F @@ X)" proof- have "Category (CatDom F)" using assms(1) by (simp add: PreFunctor_def) hence "id\<^bsub>CatDom F \<^esub>X maps\<^bsub>CatDom F\<^esub> X to X" using assms(2) by (auto simp add: Category.Cidm) hence "id\<^bsub>CatDom F \<^esub>X \<in> mor\<^bsub>CatDom F\<^esub>" by auto hence "MakeFtor F ## id\<^bsub>CatDom (MakeFtor F) \<^esub>X = F ## id\<^bsub>CatDom F \<^esub>X" by (simp add: MakeFtor_def) also have "... = id\<^bsub>CatCod F \<^esub>(F @@ X)" using assms by (simp add: PreFunctor.FunctorId2) finally show ?thesis by (simp add: MakeFtor_def) qed moreover have "PreFunctor (MakeFtor F)" using assms(1) by (simp add: MakeFtorPreFtor) ultimately show ?thesis by (simp add: PreFunctor.FmToFo) qed lemma MakeFtor: assumes "FunctorM F" shows "Functor (MakeFtor F)" proof(intro_locales) show "PreFunctor (MakeFtor F)" using assms by (simp add: MakeFtorPreFtor FunctorM_def) show "FunctorM_axioms (MakeFtor F)" proof(auto simp add: FunctorM_axioms_def) { fix f X Y assume aa: "f maps\<^bsub>CatDom (MakeFtor F)\<^esub> X to Y" show "((MakeFtor F) ## f) maps\<^bsub>CatCod (MakeFtor F)\<^esub> ((MakeFtor F) @@ X) to ((MakeFtor F) @@ Y)" proof- have "((MakeFtor F) ## f) = F ## f" using aa by (auto simp add: MakeFtor_def) moreover have "((MakeFtor F) @@ X) = F @@ X" and "((MakeFtor F) @@ Y) = F @@ Y" proof- have "Category (CatDom F)" using assms by (simp add: FunctorM_def PreFunctor_def) hence "X \<in> obj\<^bsub>CatDom F\<^esub>" and "Y \<in> obj\<^bsub>CatDom F\<^esub>" using aa by (auto simp add: Category.MapsToObj MakeFtor_def) moreover have "PreFunctor F" using assms(1) by (simp add: FunctorM_def) ultimately show "((MakeFtor F) @@ X) = F @@ X" and "((MakeFtor F) @@ Y) = F @@ Y" by (simp add: MakeFtorObj)+ qed moreover have "F ## f maps\<^bsub>CatCod F\<^esub> (F @@ X) to (F @@ Y)" using assms(1) aa by (simp add: FunctorM.FunctorCompM MakeFtor_def) ultimately show ?thesis by (simp add: MakeFtor_def) qed } qed show "FunctorExt (MakeFtor F)" by(simp add: FunctorExt_def MakeFtor_def) qed definition IdentityFunctor' :: "('o,'m,'a) Category_scheme \<Rightarrow> ('o,'o,'m,'m,'a,'a) Functor" ("FId' _" [70]) where "IdentityFunctor' C \<equiv> \<lparr>CatDom = C , CatCod = C , MapM = (\<lambda> f . f) \<rparr>" definition IdentityFunctor ("FId _" [70]) where "IdentityFunctor C \<equiv> MakeFtor(IdentityFunctor' C)" lemma IdFtor'PreFunctor: "Category C \<Longrightarrow> PreFunctor (FId' C)" by(auto simp add: PreFunctor_def IdentityFunctor'_def) lemma IdFtor'Obj: assumes "Category C" and "X \<in> obj\<^bsub>CatDom (FId' C)\<^esub>" shows "(FId' C) @@ X = X" proof- have "(FId' C) ## id\<^bsub>CatDom (FId' C)\<^esub> X = id\<^bsub>CatCod (FId' C)\<^esub> X" by(simp add: IdentityFunctor'_def) moreover have "X \<in> obj\<^bsub>CatCod (FId' C)\<^esub>" using assms by (simp add: IdentityFunctor'_def) ultimately show ?thesis using assms by (simp add: PreFunctor.FmToFo IdFtor'PreFunctor) qed lemma IdFtor'FtorM: assumes "Category C" shows "FunctorM (FId' C)" proof(auto simp add: FunctorM_def IdFtor'PreFunctor assms FunctorM_axioms_def) { fix f X Y assume a: "f maps\<^bsub>CatDom (FId' C)\<^esub> X to Y" show "((FId' C) ## f) maps\<^bsub>CatCod (FId' C)\<^esub> ((FId' C) @@ X) to ((FId' C) @@ Y)" proof- have "X \<in> obj\<^bsub>CatDom (FId' C)\<^esub>" and "Y \<in> obj\<^bsub>CatDom (FId' C)\<^esub>" using a assms by (simp add: Category.MapsToObj IdentityFunctor'_def)+ moreover have "(FId' C) ## f = f" and "CatDom (FId' C) = CatCod (FId' C)" by (simp add: IdentityFunctor'_def)+ ultimately show ?thesis using assms a by(simp add: IdFtor'Obj) qed } qed lemma IdFtorFtor: "Category C \<Longrightarrow> Functor (FId C)" by (auto simp add: IdentityFunctor_def IdFtor'FtorM intro: MakeFtor) definition ConstFunctor' :: "('o1,'m1,'a) Category_scheme \<Rightarrow> ('o2,'m2,'b) Category_scheme \<Rightarrow> 'o2 \<Rightarrow> ('o1,'o2,'m1,'m2,'a,'b) Functor" where "ConstFunctor' A B b \<equiv> \<lparr> CatDom = A , CatCod = B , MapM = (\<lambda> f . (Id B) b) \<rparr>" definition "ConstFunctor A B b \<equiv> MakeFtor(ConstFunctor' A B b)" lemma ConstFtor' : assumes "Category A" "Category B" "b \<in> (Obj B)" shows "PreFunctor (ConstFunctor' A B b)" and "FunctorM (ConstFunctor' A B b)" proof- show "PreFunctor (ConstFunctor' A B b)" using assms apply (subst PreFunctor_def) apply (rule conjI)+ by (auto simp add: ConstFunctor'_def Category.Simps Category.CatIdCompId) moreover { fix X assume "X \<in> obj\<^bsub>A\<^esub>" "b \<in> obj\<^bsub>B\<^esub>" "PreFunctor (ConstFunctor' A B b)" hence "(ConstFunctor' A B b) @@ X = b" by (auto simp add: ConstFunctor'_def PreFunctor.FmToFo Category.Simps) } ultimately show "FunctorM (ConstFunctor' A B b)" using assms by (intro_locales, auto simp add: ConstFunctor'_def Category.Simps FunctorM_axioms_def) qed lemma ConstFtor: assumes "Category A" "Category B" "b \<in> (Obj B)" shows "Functor (ConstFunctor A B b)" by (auto simp add: assms ConstFtor' ConstFunctor_def MakeFtor) definition UnitFunctor :: "('o,'m,'a) Category_scheme \<Rightarrow> ('o,unit,'m,unit,'a,unit) Functor" where "UnitFunctor C \<equiv> ConstFunctor C UnitCategory ()" lemma UnitFtor: assumes "Category C" shows "Functor(UnitFunctor C)" proof- have "() \<in> obj\<^bsub>UnitCategory\<^esub>" by (simp add: UnitCategory_def MakeCatObj) hence "Functor(ConstFunctor C UnitCategory ())" using assms by (simp add: ConstFtor) thus ?thesis by (simp add: UnitFunctor_def) qed definition FunctorComp' :: "('o1,'o2,'m1,'m2,'a1,'a2) Functor \<Rightarrow> ('o2,'o3,'m2,'m3,'b1,'b2) Functor \<Rightarrow> ('o1,'o3,'m1,'m3,'a1,'b2) Functor" (infixl ";;:" 71) where "FunctorComp' F G \<equiv> \<lparr> CatDom = CatDom F , CatCod = CatCod G , MapM = \<lambda> f . (MapM G)((MapM F) f) \<rparr>" definition FunctorComp (infixl ";;;" 71) where "FunctorComp F G \<equiv> MakeFtor (FunctorComp' F G)" lemma FtorCompComp': assumes "f \<approx>>\<^bsub>CatDom F\<^esub> g" and "F \<approx>>;;; G" shows "G ## (F ## (f ;;\<^bsub>CatDom F\<^esub> g)) = (G ## (F ## f)) ;;\<^bsub>CatCod G\<^esub> (G ## (F ## g))" proof- have [simp]: "PreFunctor G \<and> PreFunctor F" using assms by auto have [simp]: "(F ## f) \<approx>>\<^bsub>CatDom G\<^esub> (F ## g)" using assms by (auto simp add: Functor.FunctorCompDef[of F f g]) have "F ## (f ;;\<^bsub>CatDom F\<^esub> g) = (F ## f) ;;\<^bsub>CatCod F\<^esub> (F ## g)" using assms by (auto simp add: PreFunctor.FunctorComp) hence "G ## (F ## (f ;;\<^bsub>CatDom F\<^esub> g)) = G ## ((F ## f) ;;\<^bsub>CatCod F\<^esub> (F ## g))" by simp also have "... = G ## ((F ## f) ;;\<^bsub>CatDom G\<^esub> (F ## g))" using assms by auto also have "... = (G ## (F ## f)) ;;\<^bsub>CatCod G\<^esub> (G ## (F ## g))" by (simp add: PreFunctor.FunctorComp[of G "(F ## f)" "(F ## g)"]) finally show ?thesis by simp qed lemma FtorCompId: assumes a: "X \<in> (Obj (CatDom F))" and "F \<approx>>;;; G" shows "G ## (F ## (id\<^bsub>CatDom F \<^esub>X)) = id\<^bsub>CatCod G\<^esub>(G @@ (F @@ X)) \<and> G @@ (F @@ X) \<in> (Obj (CatCod G))" proof- have [simp]: "PreFunctor G \<and> PreFunctor F" using assms by auto have b: "(F @@ X) \<in> obj\<^bsub>CatDom G\<^esub>" using assms by (auto simp add: PreFunctor.FunctorId2) have "G ## F ## (id\<^bsub>CatDom F \<^esub>X) = G ## (id\<^bsub>CatCod F\<^esub>(F @@ X))" using b a by (simp add: PreFunctor.FunctorId2[of F "X"]) also have "... = G ## (id\<^bsub>CatDom G\<^esub>(F @@ X))" using assms by auto also have "... = id\<^bsub>CatCod G\<^esub>(G @@ (F @@ X)) \<and> G @@ (F @@ X) \<in> (Obj (CatCod G))" using b by (simp add: PreFunctor.FunctorId2[of G "(F @@ X)"]) finally show ?thesis by simp qed lemma FtorCompIdDef: assumes a: "X \<in> (Obj (CatDom F))" and b: "PreFunctor (F ;;: G)" and "F \<approx>>;;; G" shows "(F ;;: G) @@ X = (G @@ (F @@ X))" proof- have "(F ;;: G) ## (id\<^bsub>CatDom (F ;;: G)\<^esub>(X)) = G ## (F ## (id\<^bsub>CatDom F\<^esub>(X)))" using assms by (simp add: FunctorComp'_def) also have "... = id\<^bsub>CatCod G\<^esub>(G @@ (F @@ (X)))" using assms a by(auto simp add: FtorCompId[of _ F G]) finally have "(F ;;: G) ## (id\<^bsub>CatDom (F ;;: G)\<^esub>(X)) = id\<^bsub>CatCod (F ;;: G)\<^esub>(G @@ (F @@ X))" using assms by (simp add: FunctorComp'_def) moreover have "G @@ (F @@ (X)) \<in> (Obj (CatCod (F ;;: G)))" using assms a by(auto simp add: FtorCompId[of _ F G] FunctorComp'_def) moreover have "X \<in> obj\<^bsub>CatDom (F ;;: G)\<^esub>" using a by (simp add: FunctorComp'_def) ultimately show ?thesis using b by (simp add: PreFunctor.FmToFo[of "F ;;: G" X "G @@ (F @@ X)"]) qed lemma FunctorCompMapsTo: assumes "f \<in> mor\<^bsub>CatDom (F ;;: G)\<^esub>" and "F \<approx>>;;; G" shows "(G ## (F ## f)) maps\<^bsub>CatCod G\<^esub> (G @@ (F @@ (dom\<^bsub>CatDom F\<^esub> f))) to (G @@ (F @@ (cod\<^bsub>CatDom F\<^esub> f)))" proof- have "f \<in> mor\<^bsub>CatDom F \<^esub>\<and> Functor F" using assms by (auto simp add: FunctorComp'_def) hence "(F ## f) maps\<^bsub>CatDom G\<^esub> (F @@ (dom\<^bsub>CatDom F\<^esub> f)) to (F @@ (cod\<^bsub>CatDom F\<^esub> f))" using assms by (auto simp add: Functor.FunctorMapsTo[of F f]) moreover have "FunctorM G" using assms by (auto simp add: FunctorComp_def Functor_def) ultimately show ?thesis by(simp add: FunctorM.FunctorCompM[of G "F ## f" "F @@ (dom\<^bsub>CatDom F\<^esub> f)" "F @@ (cod\<^bsub>CatDom F\<^esub> f)"]) qed lemma FunctorCompMapsTo2: assumes "f \<in> mor\<^bsub>CatDom (F ;;: G)\<^esub>" and "F \<approx>>;;; G" and "PreFunctor (F ;;: G)" shows "((F ;;: G) ## f) maps\<^bsub>CatCod (F ;;: G)\<^esub> ((F ;;: G) @@ (dom\<^bsub>CatDom (F ;;: G)\<^esub> f)) to ((F ;;: G) @@ (cod\<^bsub>CatDom (F ;;: G)\<^esub> f))" proof- have "Category (CatDom (F ;;: G))" using assms by (simp add: PreFunctor_def) hence 1: "(dom\<^bsub>CatDom (F ;;: G)\<^esub> f) \<in> obj\<^bsub>CatDom F \<^esub>\<and> (cod\<^bsub>CatDom (F ;;: G)\<^esub> f) \<in> obj\<^bsub>CatDom F\<^esub>" using assms by (auto simp add: Category.Simps FunctorComp'_def) have "(G ## (F ## f)) maps\<^bsub>CatCod G\<^esub> (G @@ (F @@ (dom\<^bsub>CatDom F\<^esub> f))) to (G @@ (F @@ (cod\<^bsub>CatDom F\<^esub> f)))" using assms by (auto simp add: FunctorCompMapsTo[of f F G]) moreover have "CatDom F = CatDom(F ;;: G) \<and> CatCod G = CatCod(F ;;: G) \<and> (G ## (F ## f)) = ((F ;;: G) ## f)" using assms by (simp add: FunctorComp'_def) moreover have "(F ;;: G) @@ (dom\<^bsub>CatDom (F ;;: G)\<^esub> f) = (G @@ (F @@ (dom\<^bsub>CatDom(F ;;: G)\<^esub> f))) \<and> (F ;;: G) @@ (cod\<^bsub>CatDom (F ;;: G)\<^esub> f) = (G @@ (F @@ (cod\<^bsub>CatDom(F ;;: G)\<^esub> f)))" by (auto simp add: FtorCompIdDef[of _ F G] 1 assms) ultimately show ?thesis by auto qed lemma FunctorCompMapsTo3: assumes "f maps\<^bsub>CatDom (F ;;: G)\<^esub> X to Y" and "F \<approx>>;;; G" and "PreFunctor (F ;;: G)" shows "F ;;: G ## f maps\<^bsub>CatCod (F ;;: G)\<^esub> F ;;: G @@ X to F ;;: G @@ Y" proof- have "f \<in> mor\<^bsub>CatDom (F ;;: G)\<^esub>" and "dom\<^bsub>CatDom (F ;;: G)\<^esub> f = X" and "cod\<^bsub>CatDom (F ;;: G)\<^esub> f = Y" using assms by auto thus ?thesis using assms by (auto intro: FunctorCompMapsTo2) qed lemma FtorCompPreFtor: assumes "F \<approx>>;;; G" shows "PreFunctor (F ;;: G)" proof- have 1: "PreFunctor G \<and> PreFunctor F" using assms by auto show "PreFunctor (F ;;: G)" using assms proof(auto simp add: PreFunctor_def FunctorComp'_def Category.Simps FtorCompId[of _ F G] intro:FtorCompComp') show "Category (CatDom F)" and "Category (CatCod G)" using assms 1 by (auto simp add: PreFunctor_def) qed qed lemma FtorCompM : assumes "F \<approx>>;;; G" shows "FunctorM (F ;;: G)" proof(auto simp only: FunctorM_def) show 1: "PreFunctor (F ;;: G)" using assms by (rule FtorCompPreFtor) { fix X Y f assume a: "f maps\<^bsub>CatDom (F ;;: G)\<^esub> X to Y" have "F ;;: G ## f maps\<^bsub>CatCod (F ;;: G)\<^esub> F ;;: G @@ X to F ;;: G @@ Y" using a assms 1 by (rule FunctorCompMapsTo3) } thus "FunctorM_axioms (F ;;: G)" by(auto simp add: 1 FunctorM_axioms_def) qed lemma FtorComp: assumes "F \<approx>>;;; G" shows "Functor (F ;;; G)" proof- have "FunctorM (F ;;: G)" using assms by (rule FtorCompM) thus ?thesis by (simp add: FunctorComp_def MakeFtor) qed lemma (in Functor) FunctorPreservesIso: assumes "ciso\<^bsub>CatDom F\<^esub> k" shows "ciso\<^bsub>CatCod F\<^esub> (F ## k)" proof- have [simp]: "k \<in> mor\<^bsub>CatDom F\<^esub>" using assms by (simp add: Category.IsoIsMor) have "cinv\<^bsub>CatCod F\<^esub> (F ## k) (F ## (Cinv\<^bsub>CatDom F\<^esub> k))" proof(rule Category.Inverse_relI) show "Category (CatCod F)" by simp show "(F ## k) \<approx>>\<^bsub>CatCod F\<^esub> (F ## (Cinv\<^bsub>CatDom F\<^esub> k))" by (rule FunctorCompDef, simp add: Category.IsoCompInv assms) show "(F ## k) ;;\<^bsub>CatCod F\<^esub> (F ## (Cinv\<^bsub>CatDom F\<^esub> k)) = id\<^bsub>CatCod F\<^esub> (dom\<^bsub>CatCod F\<^esub> (F ## k))" proof- have "(F ## k) ;;\<^bsub>CatCod F\<^esub> (F ## (Cinv\<^bsub>CatDom F\<^esub> k)) = F ## (k ;;\<^bsub>CatDom F\<^esub> (Cinv\<^bsub>CatDom F\<^esub> k))" using assms by(auto simp add: FunctorComp Category.IsoCompInv) also have "... = F ## (id\<^bsub>CatDom F\<^esub> (dom\<^bsub>CatDom F\<^esub> k))" using assms by (simp add: Category.IsoInvId2) also have "... = id\<^bsub>CatCod F\<^esub> (dom\<^bsub>CatCod F\<^esub> (F ## k))" by (simp add: FunctorId3Dom) finally show ?thesis by simp qed show "(F ## (Cinv\<^bsub>CatDom F\<^esub> k)) ;;\<^bsub>CatCod F\<^esub> (F ## k) = id\<^bsub>CatCod F\<^esub> (cod\<^bsub>CatCod F\<^esub> (F ## k))" proof- have "(F ## (Cinv\<^bsub>CatDom F\<^esub> k)) ;;\<^bsub>CatCod F\<^esub> (F ## k) = F ## ((Cinv\<^bsub>CatDom F\<^esub> k) ;;\<^bsub>CatDom F\<^esub> k)" using assms by(auto simp add: FunctorComp Category.InvCompIso) also have "... = F ## (id\<^bsub>CatDom F\<^esub> (cod\<^bsub>CatDom F\<^esub> k))" using assms by (simp add: Category.IsoInvId1) also have "... = id\<^bsub>CatCod F\<^esub> (cod\<^bsub>CatCod F\<^esub> (F ## k))" using assms by (simp add: FunctorId3Cod) finally show ?thesis by simp qed qed thus ?thesis by(auto simp add: isomorphism_def) qed declare PreFunctor.CatDom[simp] PreFunctor.CatCod [simp] lemma FunctorMFunctor[simp]: "Functor F \<Longrightarrow> FunctorM F" by (simp add: Functor_def) locale Equivalence = Functor + assumes Full: "\<lbrakk>A \<in> Obj (CatDom F) ; B \<in> Obj (CatDom F) ; h maps\<^bsub>CatCod F\<^esub> (F @@ A) to (F @@ B)\<rbrakk> \<Longrightarrow> \<exists> f . (f maps\<^bsub>CatDom F\<^esub> A to B) \<and> (F ## f = h)" and Faithful: "\<lbrakk>f maps\<^bsub>CatDom F\<^esub> A to B ; g maps\<^bsub>CatDom F\<^esub> A to B ; F ## f = F ## g\<rbrakk> \<Longrightarrow> f = g" and IsoDense: "C \<in> Obj (CatCod F) \<Longrightarrow> \<exists> A \<in> Obj (CatDom F) . ObjIso (CatCod F) (F @@ A) C" end
-- @@stderr -- dtrace: failed to compile script test/unittest/arithmetic/err.D_SYNTAX.addmin.d: [D_SYNTAX] line 23: syntax error near ";"
[STATEMENT] lemma skl1_inv1_init [iff]: "init skl1 \<subseteq> skl1_inv1" [PROOF STATE] proof (prove) goal (1 subgoal): 1. init skl1 \<subseteq> skl1_inv1 [PROOF STEP] by (auto simp add: skl1_def skl1_init_def skl1_inv1_def)
theory Matrix_LinPoly imports Jordan_Normal_Form.Matrix_Impl Farkas.Simplex_for_Reals Farkas.Matrix_Farkas begin text \<open> Add this to linear polynomials in Simplex \<close> lemma eval_poly_with_sum: "(v \<lbrace> X \<rbrace>) = (\<Sum>x\<in> vars v. coeff v x * X x)" using linear_poly_sum sum.cong by fastforce lemma eval_poly_with_sum_superset: assumes "finite S" assumes "S \<supseteq> vars v" shows "(v \<lbrace>X\<rbrace>) = (\<Sum>x\<in>S. coeff v x * X x)" proof - define D where D: "D = S - vars v" have zeros: "\<forall>x \<in> D. coeff v x = 0" using D coeff_zero by auto have fnt: "finite (vars v)" using finite_vars by auto have "(v \<lbrace>X\<rbrace>) = (\<Sum>x\<in> vars v. coeff v x * X x)" using linear_poly_sum sum.cong by fastforce also have "... = (\<Sum>x\<in> vars v. coeff v x * X x) + (\<Sum>x\<in>D. coeff v x * X x)" using zeros by auto also have "... = (\<Sum>x\<in> vars v \<union> D. coeff v x * X x)" using assms(1) fnt Diff_partition[of "vars v" S, OF assms(2)] sum.subset_diff[of "vars v" S, OF assms(2) assms(1)] by (simp add: \<open>\<And>g. sum g S = sum g (S - vars v) + sum g (vars v)\<close> D) also have "... = (\<Sum>x\<in>S. coeff v x * X x)" using D Diff_partition assms(2) by fastforce finally show ?thesis . qed text \<open> Get rid of these synonyms \<close> section \<open> Translations of Jordan Normal Forms Matrix Library to Simplex polynomials \<close> subsection \<open> Vectors \<close> (* Translate rat list to linear polynomial with same coefficients *) definition list_to_lpoly where "list_to_lpoly cs = sum_list (map2 (\<lambda> i c. lp_monom c i) [0..<length cs] cs)" lemma empty_list_0poly: shows "list_to_lpoly [] = 0" unfolding list_to_lpoly_def by simp lemma sum_list_map_upto_coeff_limit: assumes "i \<ge> length L" shows "coeff (list_to_lpoly L) i = 0" using assms by (induction L rule: rev_induct) (auto simp: list_to_lpoly_def) lemma rl_lpoly_coeff_nth_non_empty: assumes "i < length cs" assumes "cs \<noteq> []" shows "coeff (list_to_lpoly cs) i = cs!i" using assms(2) assms(1) proof (induction cs rule: rev_nonempty_induct) fix x ::rat assume "i < length [x]" have "(list_to_lpoly [x]) = lp_monom x 0" by (simp add: list_to_lpoly_def) then show "coeff (list_to_lpoly [x]) i = [x] ! i" using \<open>i < length [x]\<close> list_to_lpoly_def by auto next fix x :: rat fix xs :: "rat list" assume "xs \<noteq> []" assume IH: "i < length xs \<Longrightarrow> coeff (list_to_lpoly xs) i = xs ! i" assume "i < length (xs @ [x])" consider (le) "i < length xs" | (eq) "i = length xs" using \<open>i < length (xs @ [x])\<close> less_Suc_eq by auto then show "coeff (list_to_lpoly (xs @ [x])) i = (xs @ [x]) ! i" proof (cases) case le have "coeff (lp_monom x (length xs)) i = 0" using le by auto have "coeff (sum_list (map2 (\<lambda>x y. lp_monom y x) [0..<length (xs @ [x])] (xs @ [x]))) i = (xs @ [x]) ! i" apply(simp add: IH le nth_append) using IH le list_to_lpoly_def by auto then show ?thesis unfolding list_to_lpoly_def by simp next case eq then have *: "coeff (sum_list (map2 (\<lambda>x y. lp_monom y x) [0..<length xs] xs)) i = 0" using sum_list_map_upto_coeff_limit[of xs i] by (simp add: list_to_lpoly_def) have **: "(sum_list (map2 (\<lambda> x y. lp_monom y x) [0..<length (xs @ [x])] (xs @ [x]))) = sum_list (map (\<lambda>(x,y). lp_monom y x) (zip [0..<length xs] xs)) + lp_monom x (length xs)" by simp have "coeff ((list_to_lpoly xs) + lp_monom x (length xs)) i = x" unfolding list_to_lpoly_def using * ** by (simp add: eq) then show ?thesis by (simp add: eq list_to_lpoly_def) qed qed lemma list_to_lpoly_coeff_nth: assumes "i < length cs " shows "coeff (list_to_lpoly cs) i = cs ! i" using gr_implies_not0 rl_lpoly_coeff_nth_non_empty assms by fastforce lemma rat_list_outside_zero: assumes "length cs \<le> i" shows "coeff (list_to_lpoly cs) i = 0" using sum_list_map_upto_coeff_limit[of cs i, OF assms] by simp text \<open> Transform linear polynomials to rational vectors \<close> fun dim_poly where "dim_poly p = (if (vars p) = {} then 0 else Max (vars p)+1)" (* 0, 0, 0, 3, 0, 0, \<dots> has dimension 4 , consistent with dim vec *) definition max_dim_poly_list where "max_dim_poly_list lst = Max {Max (vars p) |p. p \<in> set lst}" fun lpoly_to_vec where "lpoly_to_vec p = vec (dim_poly p) (coeff p)" lemma all_greater_dim_poly_zero[simp]: assumes "x \<ge> dim_poly p" shows "coeff p x = 0" using Max_ge[of "vars p" x, OF finite_vars[of p]] coeff_zero[of p x] by (metis add_cancel_left_right assms dim_poly.elims empty_iff leD le_eq_less_or_eq trans_less_add1 zero_neq_one_class.zero_neq_one) lemma lpoly_to_vec_0_iff_zero_poly [iff]: shows "(lpoly_to_vec p) = 0\<^sub>v 0 \<longleftrightarrow> p = 0" proof(standard) show "lpoly_to_vec p = 0\<^sub>v 0 \<Longrightarrow> p = 0" proof (rule contrapos_pp) assume "p \<noteq> 0" then have "vars p \<noteq> {}" by (simp add: vars_empty_zero) then have "dim_poly p > 0" by (simp) then show "lpoly_to_vec p \<noteq> 0\<^sub>v 0" using vec_of_dim_0[of "lpoly_to_vec p"] by simp qed next qed (auto simp: vars_empty_zero) lemma dim_poly_dim_vec_equiv: "dim_vec (lpoly_to_vec p) = dim_poly p" using lpoly_to_vec.simps by auto lemma dim_poly_greater_ex_coeff: "dim_poly x > d \<Longrightarrow> \<exists>i\<ge>d. coeff x i \<noteq> 0" by (simp split: if_splits) (meson Max_in coeff_zero finite_vars less_Suc_eq_le) lemma dimpoly_all_zero_limit: assumes "\<And>i. i \<ge> d \<Longrightarrow> coeff x i = 0" shows "dim_poly x \<le> d" proof - have "(\<forall>i\<ge> d. coeff x i = 0) \<Longrightarrow> dim_poly x \<le> d " proof (rule contrapos_pp) assume "\<not> dim_poly x \<le> d" then have "dim_poly x > d" by linarith then have "\<exists>i \<ge> d. coeff x i \<noteq> 0" using dim_poly_greater_ex_coeff[of d x] by blast then show "\<not> (\<forall>i\<ge>d. coeff x i = 0)" by blast qed then show ?thesis using assms by blast qed lemma construct_poly_from_lower_dim_poly: assumes "dim_poly x = d+1" obtains p c where "dim_poly p \<le> d" "x = p + lp_monom c d" proof - define c' where c': "c' = coeff x d" have f: "\<forall>i>d. coeff x i = 0" using assms by auto have *: "x = x - (lp_monom c' d) + (lp_monom c' d)" by simp have "coeff (x - (lp_monom c' d)) d = 0" using c' by simp then have "\<forall>i\<ge>d. coeff (x - (lp_monom c' d)) i = 0" using f by auto then have **: "dim_poly (x - (lp_monom c' d)) \<le> d" using dimpoly_all_zero_limit[of d "(x - (lp_monom c' d))"] by auto define p' where p': "p' = x - (lp_monom c' d)" have "\<exists>p c. dim_poly p \<le> d \<and> x = p + lp_monom c d" using "*" "**" by blast then show ?thesis using * p' c' that by blast qed lemma vars_subset_0_dim_poly: "vars z \<subseteq> {0..<dim_poly z}" by (simp add: finite_vars less_Suc_eq_le subsetI) lemma in_dim_and_not_var_zero: "x \<in> {0..<dim_poly z} - vars z \<Longrightarrow> coeff z x = 0" using coeff_zero by auto lemma valuate_with_dim_poly: "z \<lbrace> X \<rbrace> = (\<Sum>i\<in>{0..<dim_poly z}. coeff z i * X i)" using eval_poly_with_sum_superset[of "{0..<dim_poly z}" z X] using vars_subset_0_dim_poly by blast lemma lin_poly_to_vec_coeff_access: assumes "x < dim_poly y" shows "(lpoly_to_vec y) $ x = coeff y x" proof - have "x < dim_vec (lpoly_to_vec y)" using dim_poly_dim_vec_equiv[of y] assms by auto then show ?thesis by (simp add: coeff_def) qed lemma addition_over_lin_poly_to_vec: fixes x y assumes "a < dim_poly x" assumes "dim_poly x = dim_poly y" shows "(lpoly_to_vec x + lpoly_to_vec y) $ a = coeff (x + y) a" using assms(1) assms(2) lin_poly_to_vec_coeff_access by (simp add: dim_poly_dim_vec_equiv) lemma list_to_lpoly_dim_less: "length cs \<ge> dim_poly (list_to_lpoly cs)" using dimpoly_all_zero_limit sum_list_map_upto_coeff_limit by blast text \<open> Transform rational vectors to linear polynomials \<close> fun vec_to_lpoly where "vec_to_lpoly rv = list_to_lpoly (list_of_vec rv)" lemma vec_to_lin_poly_coeff_access: assumes "x < dim_vec y" shows "y $ x = coeff (vec_to_lpoly y) x" by (simp add: assms list_to_lpoly_coeff_nth) lemma addition_over_vec_to_lin_poly: fixes x y assumes "a < dim_vec x" assumes "dim_vec x = dim_vec y" shows "(x + y) $ a = coeff (vec_to_lpoly x + vec_to_lpoly y) a" using assms(1) assms(2) coeff_plus index_add_vec(1) by (metis vec_to_lin_poly_coeff_access) lemma outside_list_coeff0: assumes "i \<ge> dim_vec xs" shows "coeff (vec_to_lpoly xs) i = 0" by (simp add: assms sum_list_map_upto_coeff_limit) lemma vec_to_poly_dim_less: "dim_poly (vec_to_lpoly x) \<le> dim_vec x" using list_to_lpoly_dim_less[of "list_of_vec x"] by simp lemma vec_to_lpoly_from_lpoly_coeff_dual1: "coeff (vec_to_lpoly (lpoly_to_vec p)) i = coeff p i" by (metis all_greater_dim_poly_zero dim_poly_dim_vec_equiv lin_poly_to_vec_coeff_access not_less outside_list_coeff0 vec_to_lin_poly_coeff_access) lemma vec_to_lpoly_from_lpoly_coeff_dual2: assumes "i < dim_vec (lpoly_to_vec (vec_to_lpoly v))" shows "(lpoly_to_vec (vec_to_lpoly v)) $ i = v $ i" by (metis assms dim_poly_dim_vec_equiv less_le_trans lin_poly_to_vec_coeff_access vec_to_lin_poly_coeff_access vec_to_poly_dim_less) lemma vars_subset_dim_vec_to_lpoly_dim: "vars (vec_to_lpoly v) \<subseteq> {0..<dim_vec v}" by (meson ivl_subset le_numeral_extra(3) order.trans vec_to_poly_dim_less vars_subset_0_dim_poly) lemma sum_dim_vec_equals_sum_dim_poly: shows "(\<Sum>a = 0..<dim_vec A. coeff (vec_to_lpoly A) a * X a) = (\<Sum>a = 0..<dim_poly (vec_to_lpoly A). coeff (vec_to_lpoly A) a * X a)" proof - consider (eq) "dim_vec A = dim_poly (vec_to_lpoly A)" | (le) "dim_vec A > dim_poly (vec_to_lpoly A)" using vec_to_poly_dim_less[of "A"] by fastforce then show ?thesis proof (cases) case le define dp where dp: "dp = dim_poly (vec_to_lpoly A)" have "(\<Sum>a = 0..<dim_vec A. coeff (vec_to_lpoly A) a * X a) = (\<Sum>a = 0..<dp. coeff (vec_to_lpoly A) a * X a) + (\<Sum>a = dp..<dim_vec A. coeff (vec_to_lpoly A) a * X a)" by (metis (no_types, lifting) dp vec_to_poly_dim_less sum.atLeastLessThan_concat zero_le) also have "... = (\<Sum>a = 0..<dp. coeff (vec_to_lpoly A) a * X a)" using all_greater_dim_poly_zero by (simp add: dp) also have "... = (\<Sum>a = 0..<dim_poly (vec_to_lpoly A).coeff (vec_to_lpoly A) a * X a)" using dp by auto finally show ?thesis by blast qed (auto) qed lemma vec_to_lpoly_vNil [simp]: "vec_to_lpoly vNil = 0" by (simp add: empty_list_0poly) lemma zero_vector_is_zero_poly: "coeff (vec_to_lpoly (0\<^sub>v n)) i = 0" by (metis index_zero_vec(1) index_zero_vec(2) not_less outside_list_coeff0 vec_to_lin_poly_coeff_access) lemma coeff_nonzero_dim_vec_non_zero: assumes "coeff (vec_to_lpoly v) i \<noteq> 0" shows "v $ i \<noteq> 0" "i < dim_vec v" apply (metis assms leI outside_list_coeff0 vec_to_lin_poly_coeff_access) using assms leI outside_list_coeff0 by blast lemma lpoly_of_v_equals_v_append0: "vec_to_lpoly v = vec_to_lpoly (v @\<^sub>v 0\<^sub>v a)" (is "?lhs = ?rhs") proof - have "\<forall>i. coeff ?lhs i = coeff ?rhs i" proof fix i consider (le) "i < dim_vec v" | (ge) "i \<ge> dim_vec v" using leI by blast then show "coeff (vec_to_lpoly v) i = coeff (vec_to_lpoly (v @\<^sub>v 0\<^sub>v a)) i" proof (cases) case le then show ?thesis using vec_to_lin_poly_coeff_access[of i v] index_append_vec(1) by (metis index_append_vec(2) vec_to_lin_poly_coeff_access trans_less_add1) next case ge then have "coeff (vec_to_lpoly v) i = 0" using outside_list_coeff0 by blast moreover have "coeff (vec_to_lpoly (v @\<^sub>v 0\<^sub>v a)) i = 0" proof (rule ccontr) assume na: "\<not> coeff (vec_to_lpoly (v @\<^sub>v 0\<^sub>v a)) i = 0" define va where v: "va = coeff (vec_to_lpoly (v @\<^sub>v 0\<^sub>v a)) i" have "i < dim_vec (v @\<^sub>v 0\<^sub>v a)" using coeff_nonzero_dim_vec_non_zero[of "(v @\<^sub>v 0\<^sub>v a)" i] na by blast moreover have "(0\<^sub>v a) $ (i - dim_vec v) = va" by (metis ge diff_is_0_eq' index_append_vec(1) index_append_vec(2) not_less_zero vec_to_lin_poly_coeff_access v zero_less_diff calculation) moreover have "va \<noteq> 0" using v na by linarith ultimately show False using ge by auto qed then show "coeff (vec_to_lpoly v) i = coeff (vec_to_lpoly (v @\<^sub>v 0\<^sub>v a)) i" using not_less using calculation by linarith qed qed then show ?thesis using Abstract_Linear_Poly.poly_eqI by blast qed lemma vec_to_lpoly_eval_dot_prod: "(vec_to_lpoly v) \<lbrace> x \<rbrace> = v \<bullet> (vec (dim_vec v) x)" proof - have "(vec_to_lpoly v) \<lbrace> x \<rbrace> = (\<Sum>i\<in>{0..<dim_vec v}. coeff (vec_to_lpoly v) i * x i)" using eval_poly_with_sum_superset[of "{0..<dim_vec v}" "vec_to_lpoly v" x] vars_subset_dim_vec_to_lpoly_dim by blast also have "... = (\<Sum>i\<in>{0..<dim_vec v}. v$i * x i)" using list_to_lpoly_coeff_nth by auto also have "... = v \<bullet> (vec (dim_vec v) x)" unfolding scalar_prod_def by auto finally show ?thesis . qed lemma vec_coeff_append1: "i \<in> {0..<dim_vec a} \<Longrightarrow> coeff (vec_to_lpoly (a@\<^sub>vb)) i = a$i" by (metis atLeastLessThan_iff index_append_vec(1) index_append_vec(2) vec_to_lin_poly_coeff_access trans_less_add1) lemma vec_coeff_append2: "i \<in> {dim_vec a..<dim_vec (a@\<^sub>vb)} \<Longrightarrow> coeff (vec_to_lpoly (a@\<^sub>vb)) i = b$(i-dim_vec a)" by (metis atLeastLessThan_iff index_append_vec(1) index_append_vec(2) leD vec_to_lin_poly_coeff_access) text \<open> Maybe Code Equation \<close> lemma vec_to_lpoly_poly_of_vec_eq: "vec_to_lpoly v = poly_of_vec v" proof - have "\<And>i. i < dim_vec v \<Longrightarrow> coeff (poly_of_vec v) i = v $ i" by (simp add: coeff.rep_eq poly_of_vec.rep_eq) moreover have "\<And>i. i < dim_vec v \<Longrightarrow> coeff (vec_to_lpoly v) i = v $ i" by (simp add: vec_to_lin_poly_coeff_access) moreover have "\<And>i. i \<ge> dim_vec v \<Longrightarrow> coeff (poly_of_vec v) i = 0" by (simp add: coeff.rep_eq poly_of_vec.rep_eq) moreover have "\<And>i. i \<ge> dim_vec v \<Longrightarrow> coeff (vec_to_lpoly v) i = 0" using outside_list_coeff0 by blast ultimately show ?thesis by (metis Abstract_Linear_Poly.poly_eq_iff le_less_linear) qed lemma vars_vec_append_subset: "vars (vec_to_lpoly (0\<^sub>v n @\<^sub>v v)) \<subseteq> {n..<n+dim_vec v}" proof - let ?p = "(vec_to_lpoly (0\<^sub>v n @\<^sub>v v))" have "dim_poly ?p \<le> n+dim_vec v" using dim_poly_of_append_vec[of "0\<^sub>v n" "v"] by auto have "vars (vec_to_lpoly (0\<^sub>v n @\<^sub>v v)) \<subseteq> {0..<n+dim_vec v}" using vars_subset_dim_vec_to_lpoly_dim[of "(0\<^sub>v n @\<^sub>v v)"] by auto moreover have "\<forall>i < n. coeff ?p i = 0" using vec_coeff_append1[of _ "0\<^sub>v n" v] by auto ultimately show "vars (vec_to_lpoly (0\<^sub>v n @\<^sub>v v)) \<subseteq> {n..<n+dim_vec v}" by (meson atLeastLessThan_iff coeff_zero not_le subsetCE subsetI) qed section \<open> Matrices \<close> (* \<open> From \<open> mat \<close> to \<open> linear_poly list \<close> *) fun matrix_to_lpolies where "matrix_to_lpolies A = map vec_to_lpoly (rows A)" lemma matrix_to_lpolies_vec_of_row: "i <dim_row A \<Longrightarrow> matrix_to_lpolies A ! i = vec_to_lpoly (row A i)" using matrix_to_lpolies.simps[of A] by simp lemma outside_of_col_range_is_0: assumes "i < dim_row A" and "j \<ge> dim_col A" shows "coeff ((matrix_to_lpolies A)!i) j = 0" using outside_list_coeff0[of "col A i" j] by (metis assms(1) assms(2) index_row(2) length_rows matrix_to_lpolies.simps nth_map nth_rows outside_list_coeff0) lemma polys_greater_col_zero: assumes "x \<in> set (matrix_to_lpolies A)" assumes "j \<ge> dim_col A" shows "coeff x j = 0" using assms(1) assms(2) outside_of_col_range_is_0[of _ A j] assms(2) matrix_to_lpolies.simps by (metis in_set_conv_nth length_map length_rows) lemma matrix_to_lp_vec_to_lpoly_row [simp]: assumes "i < dim_row A" shows "(matrix_to_lpolies A)!i = vec_to_lpoly (row A i)" by (simp add: assms) lemma matrix_to_lpolies_coeff_access: assumes "i < dim_row A" and "j < dim_col A" shows "coeff (matrix_to_lpolies A ! i) j = A $$ (i,j)" using matrix_to_lp_vec_to_lpoly_row[of i A, OF assms(1)] by (metis assms(1) assms(2) index_row(1) index_row(2) vec_to_lin_poly_coeff_access) text \<open> From linear polynomial list to matrix \<close> definition lin_polies_to_mat where "lin_polies_to_mat lst = mat (length lst) (max_dim_poly_list lst) (\<lambda>(x,y).coeff (lst!x) y)" lemma lin_polies_to_rat_mat_coeff_index: assumes "i < length L" and "j < (max_dim_poly_list L)" shows "coeff (L ! i) j = (lin_polies_to_mat L) $$ (i,j)" unfolding lin_polies_to_mat_def by (simp add: assms(1) assms(2)) lemma vec_to_lpoly_valuate_equiv_dot_prod: assumes "dim_vec y = dim_vec x" (* Can be \<ge> *) shows "(vec_to_lpoly y) \<lbrace> ($)x \<rbrace> = y \<bullet> x" proof - let ?p = "vec_to_lpoly y" have 2: "?p\<lbrace> ($)x \<rbrace> = (\<Sum>j\<in>vars?p. coeff ?p j * x$j)" using eval_poly_with_sum[of ?p "($)x"] by blast have "vars ?p \<subseteq> {0..<dim_vec y}" using vars_subset_dim_vec_to_lpoly_dim by blast have 2: "?p\<lbrace> ($)x \<rbrace> = (\<Sum>j\<in>vars?p. coeff ?p j * x$j)" using eval_poly_with_sum[of ?p "($)x"] by blast also have *: "... = (\<Sum>i\<in>{0..<dim_poly ?p}. coeff ?p i * x$i)" using valuate_with_dim_poly by (metis (no_types, lifting) calculation sum.cong) also have "... = y \<bullet> x" proof - have "\<And>j. j < dim_vec x \<Longrightarrow> coeff (vec_to_lpoly y) j = y $ j" using assms vec_to_lin_poly_coeff_access by auto then show ?thesis using vec_to_lpoly_eval_dot_prod[of "y" "($)x"] by (metis assms calculation dim_vec index_vec vec_eq_iff) qed finally show ?thesis unfolding scalar_prod_def . qed lemma matrix_to_lpolies_valuate_scalarP: assumes "i < dim_row A" assumes "dim_col A = dim_vec x" shows "(matrix_to_lpolies A!i) \<lbrace> ($)x \<rbrace> = (row A i) \<bullet> x" using vec_to_lpoly_valuate_equiv_dot_prod[of "row A i" x] by (simp add: assms(1) assms(2)) end
Cory Williams Programmer Script Project 4 R-verion 3.6.0 #loading necessary downstream packages library(dplyr) library(Seurat) library(patchwork) #all packages and scripts were obtained from the publishing website and ran in an interactive R-studio envrironment provided by BU clustering computing network #assigns the location of the alevin output file to a variable to be called on files <- "/projectnb/bf528/users/group_8/project_4/programmer/GSM2230760__salmon_quant/alevin/quants_mat.gz" #loads the package needed to import alevin data library("tximport", lib.loc="~/R/x86_64-pc-linux-gnu-library/3.6") #uses txiport to import alevin file ad txi variable txi <- tximport(files, type="alevin") #crearting Seurat object using txi$counts which is the cell count and assinging it to vairable "pbmc" pbmc <- CreateSeuratObject(counts = txi$counts , min.cells = 3, min.features = 200, project = "10X_PBMC") #plot initial numbers of cell count and gene expression count per cell pre filtering and noramlization VlnPlot(pbmc, features = c("nFeature_RNA", "nCount_RNA"), ncol = 3 #filtering out genes higher than 200 but lower than 2500 and applying it to pbmc <- subset(pbmc, subset = nFeature_RNA > 200 & nFeature_RNA < 2500 & percent.mt < 5) #normalize data pbmc <- NormalizeData(pbmc, normalization.method = "LogNormalize", scale.factor = 10000) #account for variation pbmc <- FindVariableFeatures(pbmc, selection.method = "vst", nfeatures = 2000) #set a standard for gene variation all.genes <- rownames(pbmc) pbmc <- ScaleData(pbmc, features = all.genes) #cluster cells pbmc <- FindNeighbors(pbmc, dims = 1:10) pbmc <- FindClusters(pbmc, resolution = 0.5)
lemma isCont_has_Ub: fixes f :: "real \<Rightarrow> 'a::linorder_topology" shows "a \<le> b \<Longrightarrow> \<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> isCont f x \<Longrightarrow> \<exists>M. (\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> f x \<le> M) \<and> (\<forall>N. N < M \<longrightarrow> (\<exists>x. a \<le> x \<and> x \<le> b \<and> N < f x))"
function T = multiply_pots(T1, T2) % MULTIPLY_POTS Multiply a pair of dpots together pointwise (cgpot) % T = multiply_pots(pots) ddom = myunion(T1.ddom, T2.ddom); cdom = myunion(T1.cdom, T2.cdom); dom = myunion(ddom, cdom); ns = zeros(1, max(dom)); ns(T1.ddom) = T1.dsizes; ns(T2.ddom) = T2.dsizes; ns(T1.cdom) = T1.csizes; ns(T2.cdom) = T2.csizes; T = cgpot(ddom, cdom, ns); T = multiply_by_pot(T, T1); T = multiply_by_pot(T, T2);
\section{Abstract} In this report we analysed the \emph{mID} in order to search for vulnerabilities that may affect it's operation. To do so, we used a mix of different strategies including Threat Modelling, Risk Analysis and CVE. We also included some suggestions to fix or mitigate the problems we listed. Given the constraints related to resources and time, we also specified which problems should be addressed first. \pagebreak
(* See github.com/andrejbaur for more details on getting started. *) Definition P (A : Type) := A -> Prop. Notation "{ x : A | P }" := (fun x : A => P). Definition singleton {A : Type} (x : A) := {y:A | x = y}. Definition subset {A : Type} (u v : P A) := forall x : A, u x -> v x. Notation "u <= v" := (subset u v). Definition disjoint {A : Type} (u v : P A) := forall x, ~(u x /\ v x). Notation "'all' x : U , P" := (forall x, U x -> P) (at level 20, x at level 99). Notation "'some' x : U , P" := (exists x, U x /\ P) (at level 20, x at level 99). Definition union {A : Type} (S : P (P A)) := {x : A | some U : S, U x }. Definition inter {A : Type} (u v : P A) := {x : A | u x /\ v x}. Notation "u * v" := (inter u v). Definition empty {A : Type} := { x : A | False}. Definition full {A : Type} := { x : A | True}. Structure topology (A : Type) := { open :> P A -> Prop ; empty_open : open empty ; full_open : open full; inter_open : all u : open, all v :open, open (u * v); union_open : forall S, S<= open -> open (union S) }. Definition discrete (A : Type) : topology A. Proof. exists full ; firstorder. Defined. Definition T1 {A : Type} (T : topology A) := forall x y : A, x <> y -> some u : T, (u x /\ ~(u y)). Definition hausdorff {A : Type} (T : topology A) := forall x y : A, x <> y -> some u : T, some v : T, (u x /\ v y /\ disjoint u v). Lemma discrete_hausdorff {A : Type} : hausdorff (discrete A). Proof. intros x y N. exists { z : A | x = z}; split ; [exact I | idtac]. exists { z : A | y = z}; split ; [exact I | idtac]. repeat split ; auto. intros z [? ?]. absurd (x = y); auto. transitivity z ; auto. Qed. Lemma hausdorff_is_T1 {A : Type} (T : topology A): hausdorff T -> T1 T. Proof. intros H x y N. destruct (H x y N) as [u [? [v [? [? [? G]]]]]]. exists u ; repeat split ; auto. intro. absurd (u y /\ v y); auto. Qed. Definition indiscrete (A : Type) : topology A. Proof. exists { u : P A | forall x : A, u x -> (forall y : A, u y) }; firstorder. Defined. Lemma indiscrete_least (A : Type) (T : topology A) : (forall (X : Type) (s t : P X), s <= t -> t <= s -> s = t) -> indiscrete A <= T. Proof. intros ext u H. assert (G : (u = union { v : P A | T v /\ some x : v, u x })). - apply ext. + intros x ?. exists full; firstorder using full_open. + intros x [v [[? [y [? ?]]] ?]] ; now apply (H y). - rewrite G ; apply union_open ; firstorder. Qed. Definition particular {A : Type} (x : A) : topology A. Proof. exists { u : P A | (exists y, u y) -> u x } ; firstorder. Qed. (* the topology generated by a family B of subsets that are closed under finite intersections. *) Definition base {A : Type} (B : P (P A)) : B full -> (all u : B, all v : B, B (u * v)) -> topology A. Proof. intros H G. exists { u : P A | forall x, u x <-> some v : B, (v x /\ v <= u) }. - firstorder. - firstorder. - intros u Hu v Hv x. split. + intros [Gu Gv]. destruct (proj1 (Hu x) Gu) as [u' [? [? ?]]]. destruct (proj1 (Hv x) Gv) as [v' [? [? ?]]]. exists (u' * v') ; firstorder. + intros [w [? [? ?]]]. split ; now apply H2. - intros S K x. split. + intros [u [H1 H2]]. destruct (K u H1 x) as [L1 _]. destruct (L1 H2) as [v ?]. exists v; firstorder. + firstorder. Defined. Require Import List. (* The intersection of a finite list of subsets. *) Definition inters {A : Type} (us : list (P A)) : P A := {x : A | Forall (fun u => u x) us }. (* The closure of a family of sets by finite intersections. *) Definition inter_close {A : Type} (S : P (P A)) := { v : P A | some us : Forall S, (forall x, v x <-> inters us x) }. Lemma Forall_app {A : Type} (l1 l2 : list A) (P : A -> Prop): Forall P l1 -> Forall P l2 -> Forall P (l1 ++ l2). Proof. induction l1 ; simpl ; auto. intro H. inversion H; auto. Qed. Lemma Forall_app1 {A : Type} (l1 l2 : list A) (P : A -> Prop) : Forall P (l1 ++ l2) -> Forall P l1. Proof. induction l1; simpl ; auto. intro H. inversion H; auto. Qed. Lemma Forall_app2 {A : Type} (l1 l2 : list A) (P : A -> Prop): Forall P (l1 ++ l2) -> Forall P l2. Proof. induction l1; simpl ; auto. intros H. inversion H; auto. Qed. (* The topology generated by a subbase S. *) Definition subbase {A : Type} (S : P (P A)) : topology A. Proof. apply (base (inter_close S)). - exists nil ; firstorder using Forall_nil. - intros u [us [Hu Gu]] v [vs [Hv Gv]]. exists (us ++ vs). split ; [ (now apply Forall_app) | idtac ]. split. + intros [? ?]. apply Forall_app ; firstorder. + intro K; split. * apply Gu. apply (Forall_app1 _ _ _ K). * apply Gv. apply (Forall_app2 _ _ _ K). Defined. Lemma subbase_open {A : Type} (S : P (P A)) (u : P A) : S u -> (subbase S) u. Proof. intros H x. split. - intro G. exists u ; split ; [ idtac | firstorder ]. exists (u :: nil). split ; [now constructor | idtac]. intro y; split. + intro ; now constructor. + intro K. inversion K; auto. - firstorder. Qed. Definition cofinite (A: Type) : topology A := subbase { u : P A | exists x, forall y, (u y <-> y <> x) }. Lemma cofinite_T1 (A : Type) : T1 (cofinite A). Proof. intros x y N. exists {z : A | z<>y}. split ; auto. apply subbase_open. exists y; firstorder. Qed.
// All content Copyright (C) 2018 Genomics plc #define BOOST_TEST_DYN_LINK #include <cstdlib> #include <tuple> #include <boost/test/unit_test.hpp> #include <boost/algorithm/string.hpp> #include "vcf/reader.hpp" #include "io/tabixVCFFile.hpp" #include "vcf/filterDescription.hpp" #include "VCFTestUtils.hpp" using std::string; BOOST_AUTO_TEST_CASE( shouldParseValidVCFFilterHeaderUpperCaseID ) { const std::string line = "##FILTER=<ID=ABCDEFGHIJKLMNOPQRSTUVWXYZ,Description=\"A description of a filter.\">"; wecall::vcf::FilterDesc filterDesc = wecall::io::TabixVCFFile::parseFilterHeaderLine( line ); BOOST_CHECK_EQUAL( filterDesc.id, "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ); BOOST_CHECK_EQUAL( filterDesc.description, "A description of a filter." ); } BOOST_AUTO_TEST_CASE( shouldParseValidVCFFilterHeaderLowerCaseID ) { const std::string line = "##FILTER=<ID=abcdefghijklmnopqrstuvwxyz,Description=\"A description of a filter.\">"; wecall::vcf::FilterDesc filterDesc = wecall::io::TabixVCFFile::parseFilterHeaderLine( line ); BOOST_CHECK_EQUAL( filterDesc.id, "abcdefghijklmnopqrstuvwxyz" ); BOOST_CHECK_EQUAL( filterDesc.description, "A description of a filter." ); } BOOST_AUTO_TEST_CASE( shouldParseValidVCFFilterHeaderDigitsAndPunctuation ) { const std::string line = "##FILTER=<ID=_1234567890,Description=\"A description of a filter.\">"; wecall::vcf::FilterDesc filterDesc = wecall::io::TabixVCFFile::parseFilterHeaderLine( line ); BOOST_CHECK_EQUAL( filterDesc.id, "_1234567890" ); BOOST_CHECK_EQUAL( filterDesc.description, "A description of a filter." ); } BOOST_AUTO_TEST_CASE( shouldRaiseOnINFOHeaderType ) { const std::string line = "##INFO=<ID=AA,Number=A,Type=String,Description=\"Genotype\">"; BOOST_CHECK_THROW( wecall::vcf::FilterDesc filterDesc = wecall::io::TabixVCFFile::parseFilterHeaderLine( line ), wecall::utils::wecall_exception ); } BOOST_AUTO_TEST_CASE( shouldRaiseOnFORMATHeaderType ) { const std::string line = "##FORMAT=<ID=AA,Number=A,Type=String,Description=\"Genotype\">"; BOOST_CHECK_THROW( wecall::vcf::FilterDesc filterDesc = wecall::io::TabixVCFFile::parseFilterHeaderLine( line ), wecall::utils::wecall_exception ); } BOOST_AUTO_TEST_CASE( shouldRaiseOnInvalidVCFFilterHeader ) { const std::string line = "##FILTER=<ID=q10;Description=\"A description of a filter.\">"; BOOST_CHECK_THROW( wecall::vcf::FilterDesc filterDesc = wecall::io::TabixVCFFile::parseFilterHeaderLine( line ), wecall::utils::wecall_exception ); } BOOST_AUTO_TEST_CASE( shouldDetectFilterIdInFilterDescs ) { using namespace wecall::vcf; std::string id1 = "gq1"; std::string id2 = "gq2"; std::set< FilterDesc > filterDescs = {FilterDesc( id1, "Random description" )}; BOOST_CHECK( wecall::io::TabixVCFFile::containsFilterId( filterDescs, id1 ) ); BOOST_CHECK( not wecall::io::TabixVCFFile::containsFilterId( filterDescs, id2 ) ); }
theory poly imports Main HOL begin primrec pow :: "nat \<Rightarrow> nat \<Rightarrow> nat" where "pow x 0 = Suc 0" | "pow x (Suc y) = x * pow x y" lemma add_rule: "pow x (y + z) = pow x y * pow x z" apply(induct z) apply auto done datatype poly = Nat nat | Var nat | Plus poly poly | Times poly poly primrec pval :: "poly \<Rightarrow> (nat \<Rightarrow> nat) \<Rightarrow> nat" where "pval (Nat n) _ = n" | "pval (Var v) f = f v" | "pval (Plus p q) f = (pval p f) + (pval p f)" | "pval (Times p q) f = (pval p f) * (pval p f)"
[GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f g h : α → β ⊢ map id = id [PROOFSTEP] ext ⟨f⟩ [GOAL] case h.mk α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝ g h : α → β x✝ : Germ l β f : α → β ⊢ map id (Quot.mk Setoid.r f) = id (Quot.mk Setoid.r f) [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝ g✝ h : α → β op : β → γ → δ f f' : α → β Hf✝ : Setoid.r f f' g g' : α → γ Hg✝ : Setoid.r g g' x : α Hf : f x = f' x Hg : g x = g' x ⊢ (fun f g x => op (f x) (g x)) f g x = (fun f g x => op (f x) (g x)) f' g' x [PROOFSTEP] simp only [Hf, Hg] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝¹ : Monoid M inst✝ : MulAction M β f✝ : Germ l β f : α → β ⊢ 1 • ↑f = ↑f [PROOFSTEP] norm_cast [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝¹ : Monoid M inst✝ : MulAction M β f✝ : Germ l β f : α → β ⊢ 1 • f =ᶠ[l] f [PROOFSTEP] simp only [one_smul] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝¹ : Monoid M inst✝ : MulAction M β f✝ : Germ l β f : α → β ⊢ f =ᶠ[l] f [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝¹ : Monoid M inst✝ : MulAction M β c₁ c₂ : M f✝ : Germ l β f : α → β ⊢ (c₁ * c₂) • ↑f = c₁ • c₂ • ↑f [PROOFSTEP] norm_cast [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝¹ : Monoid M inst✝ : MulAction M β c₁ c₂ : M f✝ : Germ l β f : α → β ⊢ (c₁ * c₂) • f =ᶠ[l] c₁ • c₂ • f [PROOFSTEP] simp only [mul_smul] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝¹ : Monoid M inst✝ : MulAction M β c₁ c₂ : M f✝ : Germ l β f : α → β ⊢ c₁ • c₂ • f =ᶠ[l] c₁ • c₂ • f [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝¹ : Monoid M inst✝ : MulAction M β f✝ : Germ l β f : α → β ⊢ 1 • ↑f = ↑f [PROOFSTEP] simp only [← coe_one, ← coe_smul', one_smul] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝¹ : Monoid M inst✝ : MulAction M β c₁✝ c₂✝ : Germ l M f✝ : Germ l β c₁ c₂ : α → M f : α → β ⊢ (↑c₁ * ↑c₂) • ↑f = ↑c₁ • ↑c₂ • ↑f [PROOFSTEP] norm_cast [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝¹ : Monoid M inst✝ : MulAction M β c₁✝ c₂✝ : Germ l M f✝ : Germ l β c₁ c₂ : α → M f : α → β ⊢ (c₁ * c₂) • f =ᶠ[l] c₁ • c₂ • f [PROOFSTEP] simp only [mul_smul] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝¹ : Monoid M inst✝ : MulAction M β c₁✝ c₂✝ : Germ l M f✝ : Germ l β c₁ c₂ : α → M f : α → β ⊢ c₁ • c₂ • f =ᶠ[l] c₁ • c₂ • f [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f g h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝² : Monoid M inst✝¹ : AddMonoid N inst✝ : DistribMulAction M N c : M ⊢ c • 0 = 0 [PROOFSTEP] simp only [← coe_zero, ← coe_smul, smul_zero] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g✝¹ h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝² : Monoid M inst✝¹ : AddMonoid N inst✝ : DistribMulAction M N c : M f✝ g✝ : Germ l N f g : α → N ⊢ c • (↑f + ↑g) = c • ↑f + c • ↑g [PROOFSTEP] norm_cast [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g✝¹ h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝² : Monoid M inst✝¹ : AddMonoid N inst✝ : DistribMulAction M N c : M f✝ g✝ : Germ l N f g : α → N ⊢ c • (f + g) =ᶠ[l] c • f + c • g [PROOFSTEP] simp only [smul_add] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g✝¹ h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝² : Monoid M inst✝¹ : AddMonoid N inst✝ : DistribMulAction M N c : M f✝ g✝ : Germ l N f g : α → N ⊢ c • f + c • g =ᶠ[l] c • f + c • g [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f g h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝² : Monoid M inst✝¹ : AddMonoid N inst✝ : DistribMulAction M N c✝ : Germ l M c : α → M ⊢ ↑c • 0 = 0 [PROOFSTEP] simp only [← coe_zero, ← coe_smul', smul_zero] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g✝¹ h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝² : Monoid M inst✝¹ : AddMonoid N inst✝ : DistribMulAction M N c✝ : Germ l M f✝ g✝ : Germ l N c : α → M f g : α → N ⊢ ↑c • (↑f + ↑g) = ↑c • ↑f + ↑c • ↑g [PROOFSTEP] norm_cast [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g✝¹ h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝² : Monoid M inst✝¹ : AddMonoid N inst✝ : DistribMulAction M N c✝ : Germ l M f✝ g✝ : Germ l N c : α → M f g : α → N ⊢ c • (f + g) =ᶠ[l] c • f + c • g [PROOFSTEP] simp only [smul_add] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g✝¹ h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝² : Monoid M inst✝¹ : AddMonoid N inst✝ : DistribMulAction M N c✝ : Germ l M f✝ g✝ : Germ l N c : α → M f g : α → N ⊢ c • f + c • g =ᶠ[l] c • f + c • g [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝² : Semiring R inst✝¹ : AddCommMonoid M inst✝ : Module R M c₁ c₂ : R f✝ : Germ l M f : α → M ⊢ (c₁ + c₂) • ↑f = c₁ • ↑f + c₂ • ↑f [PROOFSTEP] norm_cast [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝² : Semiring R inst✝¹ : AddCommMonoid M inst✝ : Module R M c₁ c₂ : R f✝ : Germ l M f : α → M ⊢ (c₁ + c₂) • f =ᶠ[l] c₁ • f + c₂ • f [PROOFSTEP] simp only [add_smul] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝² : Semiring R inst✝¹ : AddCommMonoid M inst✝ : Module R M c₁ c₂ : R f✝ : Germ l M f : α → M ⊢ c₁ • f + c₂ • f =ᶠ[l] c₁ • f + c₂ • f [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝² : Semiring R inst✝¹ : AddCommMonoid M inst✝ : Module R M f✝ : Germ l M f : α → M ⊢ 0 • ↑f = 0 [PROOFSTEP] norm_cast [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝² : Semiring R inst✝¹ : AddCommMonoid M inst✝ : Module R M f✝ : Germ l M f : α → M ⊢ 0 • f =ᶠ[l] 0 [PROOFSTEP] simp only [zero_smul, coe_zero] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝² : Semiring R inst✝¹ : AddCommMonoid M inst✝ : Module R M f✝ : Germ l M f : α → M ⊢ 0 =ᶠ[l] 0 [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝² : Semiring R inst✝¹ : AddCommMonoid M inst✝ : Module R M c₁✝ c₂✝ : Germ l R f✝ : Germ l M c₁ c₂ : α → R f : α → M ⊢ (↑c₁ + ↑c₂) • ↑f = ↑c₁ • ↑f + ↑c₂ • ↑f [PROOFSTEP] norm_cast [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝² : Semiring R inst✝¹ : AddCommMonoid M inst✝ : Module R M c₁✝ c₂✝ : Germ l R f✝ : Germ l M c₁ c₂ : α → R f : α → M ⊢ (c₁ + c₂) • f =ᶠ[l] c₁ • f + c₂ • f [PROOFSTEP] simp only [add_smul] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝² : Semiring R inst✝¹ : AddCommMonoid M inst✝ : Module R M c₁✝ c₂✝ : Germ l R f✝ : Germ l M c₁ c₂ : α → R f : α → M ⊢ c₁ • f + c₂ • f =ᶠ[l] c₁ • f + c₂ • f [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝¹ g h : α → β M : Type u_5 N : Type u_6 R : Type u_7 inst✝² : Semiring R inst✝¹ : AddCommMonoid M inst✝ : Module R M f✝ : Germ l M f : α → M ⊢ 0 • ↑f = 0 [PROOFSTEP] simp only [← coe_zero, ← coe_smul', zero_smul] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝ g✝ h✝ : α → β inst✝² : Mul β inst✝¹ : LE β inst✝ : ExistsMulOfLE β x y : Germ l β f g : α → β h : f ≤ᶠ[l] g ⊢ ∃ c, ↑g = ↑f * c [PROOFSTEP] classical choose c hc using fun x (hx : f x ≤ g x) ↦ exists_mul_of_le hx refine ⟨ofFun <| fun x ↦ if hx : f x ≤ g x then c x hx else f x, coe_eq.2 ?_⟩ filter_upwards [h] with x hx rw [dif_pos hx, hc] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝ g✝ h✝ : α → β inst✝² : Mul β inst✝¹ : LE β inst✝ : ExistsMulOfLE β x y : Germ l β f g : α → β h : f ≤ᶠ[l] g ⊢ ∃ c, ↑g = ↑f * c [PROOFSTEP] choose c hc using fun x (hx : f x ≤ g x) ↦ exists_mul_of_le hx [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝ g✝ h✝ : α → β inst✝² : Mul β inst✝¹ : LE β inst✝ : ExistsMulOfLE β x y : Germ l β f g : α → β h : f ≤ᶠ[l] g c : (x : α) → f x ≤ g x → β hc : ∀ (x : α) (hx : f x ≤ g x), g x = f x * c x hx ⊢ ∃ c, ↑g = ↑f * c [PROOFSTEP] refine ⟨ofFun <| fun x ↦ if hx : f x ≤ g x then c x hx else f x, coe_eq.2 ?_⟩ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝ g✝ h✝ : α → β inst✝² : Mul β inst✝¹ : LE β inst✝ : ExistsMulOfLE β x y : Germ l β f g : α → β h : f ≤ᶠ[l] g c : (x : α) → f x ≤ g x → β hc : ∀ (x : α) (hx : f x ≤ g x), g x = f x * c x hx ⊢ g =ᶠ[l] (fun f g x => (fun x x_1 => x * x_1) (f x) (g x)) f fun x => if hx : f x ≤ g x then c x hx else f x [PROOFSTEP] filter_upwards [h] with x hx [GOAL] case h α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 l : Filter α f✝ g✝ h✝ : α → β inst✝² : Mul β inst✝¹ : LE β inst✝ : ExistsMulOfLE β x✝ y : Germ l β f g : α → β h : f ≤ᶠ[l] g c : (x : α) → f x ≤ g x → β hc : ∀ (x : α) (hx : f x ≤ g x), g x = f x * c x hx x : α hx : f x ≤ g x ⊢ g x = f x * if hx : f x ≤ g x then c x hx else f x [PROOFSTEP] rw [dif_pos hx, hc]
I want to give a big thank you to everyone at The American Institute of Dental Assisting! Especially Holly, Tammy and Pam. It has been an amazing 13 weeks! I have learned so much and am very excited to start my new career! I am so glad I found this program. It worked right into my life without having to stop working while in school. The classes were very well instructed even though it was fast paced. The instructors were willing to help when we needed it. The clinicals were very fun and it was great to get the hands on training with dentists! Again, thank you all so much!
#= Protected Accessor Function for User. =# # gets the sparse matrix function getadj(A::Assoc) return copy(A.A) end # getcol, getrow, getval return range objects if possible # if not, they return copies of the col, rw, val parts of Assoc's struct function getcol(A::Assoc) if isempty(A) return Union{AbstractString, Number}[] else if isa(A.col[1], AbstractString) || ~(size(A.A,2) == A.col[end]) return copy(A.col) end return 1:size(A.A,2) end end function getrow(A::Assoc) if isempty(A) return Union{AbstractString, Number}[] else if isa(A.row[1], AbstractString) || ~(size(A.A,1) == A.row[end]) return copy(A.row) end return 1:size(A.A,1) end end function getval(A::Assoc) if isempty(A) return Union{AbstractString, Number}[] else if isa(A.val[1], AbstractString) return copy(A.val) end return sort(unique(nonzeros(A.A))) end end #= find : get the triplet of the input Assoc in three array. Similar to findnz for sparse. =# using SparseArrays function find(A::Assoc) if isa(A.A,LinearAlgebra.Adjoint) || isa(A.A, LinearAlgebra.Transpose) row, col, val = findnz(SparseMatrixCSC(A.A)) else row, col, val = findnz(A.A) end val = Array(val) n = nnz(A) #map if the Associative array isn't numerical if ~isempty(A) if isa(A.row[1],AbstractString) row = [ A.row[row[i]] for i in 1:n] end if isa(A.col[1],AbstractString) col = [ A.col[col[i]] for i in 1:n] end if isa(A.val[1],AbstractString) || A.val != [1.0] val = [ A.val[val[i]] for i in 1:n] end end return row, col, val end ######################################################## # D4M: Dynamic Distributed Dimensional Data Model # Architect: Dr. Jeremy Kepner ([email protected]) # Software Engineer: Alexander Chen ([email protected]) ########################################################
module Structure.Category.Action where open import Structure.Category.Functor
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.uniform_space.completion import topology.metric_space.isometry import topology.instances.real /-! # The completion of a metric space Completion of uniform spaces are already defined in `topology.uniform_space.completion`. We show here that the uniform space completion of a metric space inherits a metric space structure, by extending the distance to the completion and checking that it is indeed a distance, and that it defines the same uniformity as the already defined uniform structure on the completion -/ open set filter uniform_space uniform_space.completion open_locale filter noncomputable theory universes u variables {α : Type u} [pseudo_metric_space α] namespace metric /-- The distance on the completion is obtained by extending the distance on the original space, by uniform continuity. -/ instance : has_dist (completion α) := ⟨completion.extension₂ dist⟩ /-- The new distance is uniformly continuous. -/ protected lemma completion.uniform_continuous_dist : uniform_continuous (λp:completion α × completion α, dist p.1 p.2) := uniform_continuous_extension₂ dist /-- The new distance is an extension of the original distance. -/ protected lemma completion.dist_eq (x y : α) : dist (x : completion α) y = dist x y := completion.extension₂_coe_coe uniform_continuous_dist _ _ /- Let us check that the new distance satisfies the axioms of a distance, by starting from the properties on α and extending them to `completion α` by continuity. -/ protected lemma completion.dist_self (x : completion α) : dist x x = 0 := begin apply induction_on x, { refine is_closed_eq _ continuous_const, exact (completion.uniform_continuous_dist.continuous.comp (continuous.prod_mk continuous_id continuous_id : _) : _) }, { assume a, rw [completion.dist_eq, dist_self] } end protected lemma completion.dist_comm (x y : completion α) : dist x y = dist y x := begin apply induction_on₂ x y, { refine is_closed_eq completion.uniform_continuous_dist.continuous _, exact completion.uniform_continuous_dist.continuous.comp (@continuous_swap (completion α) (completion α) _ _) }, { assume a b, rw [completion.dist_eq, completion.dist_eq, dist_comm] } end protected lemma completion.dist_triangle (x y z : completion α) : dist x z ≤ dist x y + dist y z := begin apply induction_on₃ x y z, { refine is_closed_le _ (continuous.add _ _), { have : continuous (λp : completion α × completion α × completion α, (p.1, p.2.2)) := continuous.prod_mk continuous_fst (continuous.comp continuous_snd continuous_snd), exact (completion.uniform_continuous_dist.continuous.comp this : _) }, { have : continuous (λp : completion α × completion α × completion α, (p.1, p.2.1)) := continuous.prod_mk continuous_fst (continuous_fst.comp continuous_snd), exact (completion.uniform_continuous_dist.continuous.comp this : _) }, { have : continuous (λp : completion α × completion α × completion α, (p.2.1, p.2.2)) := continuous.prod_mk (continuous_fst.comp continuous_snd) (continuous.comp continuous_snd continuous_snd), exact (continuous.comp completion.uniform_continuous_dist.continuous this : _) } }, { assume a b c, rw [completion.dist_eq, completion.dist_eq, completion.dist_eq], exact dist_triangle a b c } end /-- Elements of the uniformity (defined generally for completions) can be characterized in terms of the distance. -/ protected lemma completion.mem_uniformity_dist (s : set (completion α × completion α)) : s ∈ uniformity (completion α) ↔ (∃ε>0, ∀{a b}, dist a b < ε → (a, b) ∈ s) := begin split, { /- Start from an entourage `s`. It contains a closed entourage `t`. Its pullback in α is an entourage, so it contains an ε-neighborhood of the diagonal by definition of the entourages in metric spaces. Then `t` contains an ε-neighborhood of the diagonal in `completion α`, as closed properties pass to the completion. -/ assume hs, rcases mem_uniformity_is_closed hs with ⟨t, ht, ⟨tclosed, ts⟩⟩, have A : {x : α × α | (coe (x.1), coe (x.2)) ∈ t} ∈ uniformity α := uniform_continuous_def.1 (uniform_continuous_coe α) t ht, rcases mem_uniformity_dist.1 A with ⟨ε, εpos, hε⟩, refine ⟨ε, εpos, λx y hxy, _⟩, have : ε ≤ dist x y ∨ (x, y) ∈ t, { apply induction_on₂ x y, { have : {x : completion α × completion α | ε ≤ dist (x.fst) (x.snd) ∨ (x.fst, x.snd) ∈ t} = {p : completion α × completion α | ε ≤ dist p.1 p.2} ∪ t, by ext; simp, rw this, apply is_closed.union _ tclosed, exact is_closed_le continuous_const completion.uniform_continuous_dist.continuous }, { assume x y, rw completion.dist_eq, by_cases h : ε ≤ dist x y, { exact or.inl h }, { have Z := hε (not_le.1 h), simp only [set.mem_set_of_eq] at Z, exact or.inr Z }}}, simp only [not_le.mpr hxy, false_or, not_le] at this, exact ts this }, { /- Start from a set `s` containing an ε-neighborhood of the diagonal in `completion α`. To show that it is an entourage, we use the fact that `dist` is uniformly continuous on `completion α × completion α` (this is a general property of the extension of uniformly continuous functions). Therefore, the preimage of the ε-neighborhood of the diagonal in ℝ is an entourage in `completion α × completion α`. Massaging this property, it follows that the ε-neighborhood of the diagonal is an entourage in `completion α`, and therefore this is also the case of `s`. -/ rintros ⟨ε, εpos, hε⟩, let r : set (ℝ × ℝ) := {p | dist p.1 p.2 < ε}, have : r ∈ uniformity ℝ := metric.dist_mem_uniformity εpos, have T := uniform_continuous_def.1 (@completion.uniform_continuous_dist α _) r this, simp only [uniformity_prod_eq_prod, mem_prod_iff, exists_prop, filter.mem_map, set.mem_set_of_eq] at T, rcases T with ⟨t1, ht1, t2, ht2, ht⟩, refine mem_of_superset ht1 _, have A : ∀a b : completion α, (a, b) ∈ t1 → dist a b < ε, { assume a b hab, have : ((a, b), (a, a)) ∈ set.prod t1 t2 := ⟨hab, refl_mem_uniformity ht2⟩, have I := ht this, simp [completion.dist_self, real.dist_eq, completion.dist_comm] at I, exact lt_of_le_of_lt (le_abs_self _) I }, show t1 ⊆ s, { rintros ⟨a, b⟩ hp, have : dist a b < ε := A a b hp, exact hε this }} end /-- If two points are at distance 0, then they coincide. -/ protected lemma completion.eq_of_dist_eq_zero (x y : completion α) (h : dist x y = 0) : x = y := begin /- This follows from the separation of `completion α` and from the description of entourages in terms of the distance. -/ have : separated_space (completion α) := by apply_instance, refine separated_def.1 this x y (λs hs, _), rcases (completion.mem_uniformity_dist s).1 hs with ⟨ε, εpos, hε⟩, rw ← h at εpos, exact hε εpos end /-- Reformulate `completion.mem_uniformity_dist` in terms that are suitable for the definition of the metric space structure. -/ protected lemma completion.uniformity_dist' : uniformity (completion α) = (⨅ε:{ε : ℝ // 0 < ε}, 𝓟 {p | dist p.1 p.2 < ε.val}) := begin ext s, rw mem_infi_of_directed, { simp [completion.mem_uniformity_dist, subset_def] }, { rintro ⟨r, hr⟩ ⟨p, hp⟩, use ⟨min r p, lt_min hr hp⟩, simp [lt_min_iff, (≥)] {contextual := tt} } end protected lemma completion.uniformity_dist : uniformity (completion α) = (⨅ ε>0, 𝓟 {p | dist p.1 p.2 < ε}) := by simpa [infi_subtype] using @completion.uniformity_dist' α _ /-- Metric space structure on the completion of a pseudo_metric space. -/ instance completion.metric_space : metric_space (completion α) := { dist_self := completion.dist_self, eq_of_dist_eq_zero := completion.eq_of_dist_eq_zero, dist_comm := completion.dist_comm, dist_triangle := completion.dist_triangle, to_uniform_space := by apply_instance, uniformity_dist := completion.uniformity_dist } /-- The embedding of a metric space in its completion is an isometry. -/ lemma completion.coe_isometry : isometry (coe : α → completion α) := isometry_emetric_iff_metric.2 completion.dist_eq end metric
Formal statement is: lemma homeomorphic_spheres: fixes a b ::"'a::real_normed_vector" assumes "0 < d" "0 < e" shows "(sphere a d) homeomorphic (sphere b e)" Informal statement is: If $d$ and $e$ are positive real numbers, then the spheres of radius $d$ and $e$ centered at $a$ and $b$ are homeomorphic.
# Binomial Distribution > ***GitHub***: https://github.com/czs108 ## Definition \begin{equation} P(X = r) =\, ^{n}C_{r} \cdot p^{r} \cdot (1 - p)^{n - r} \end{equation} \begin{align} X &= \text{The total number of successes.} \\ p &= \text{The probability of a success on an individual trial.} \\ n &= \text{The number of trials.} \end{align} If a variable $X$ follows a *Binomial Distribution* where the probability of *success* in a trial is $p$, and $n$ is the *total* number of trials. This can be written as \begin{equation} X \sim B(n,\, p) \end{equation} ## Expectation \begin{equation} E(X) = np \end{equation} ## Variance \begin{equation} Var(X) = np \cdot (1 - p) \end{equation} ## Approximation ### Poisson Distribution $X \sim B(n,\, p)$ can be approximated by the *Poisson Distribution* $X \sim Po(np)$ if $n$ is *large* and $p$ is *small*. Because both the *expectation* and *variance* of $X \sim Po(np)$ are $np$. When $n$ is large and $p$ is small, $(1 - p) \approx 1$ and for $X \sim B(n,\, p)$: \begin{equation} E(X) = np \end{equation} \begin{equation} Var(X) \approx np \end{equation} The approximation is typically very close if $n > 50$ and $p < 0.1$. ### Normal Distribution Suppose $q$ is $(1 - p)$. Normally if $np > 5$ and $nq > 5$, $X \sim B(n,\, p)$ also can be approximated by the *Normal Distribution* $X \sim N(np,\, npq)$.
Brato Chakrabarti, CCB, I love Sarod
lemma Bseq_mult: fixes f g :: "nat \<Rightarrow> 'a::real_normed_field" assumes "Bseq f" and "Bseq g" shows "Bseq (\<lambda>x. f x * g x)"
using CUDA using CuCountMap using StatsBase: countmap v = rand(Int16, 100_000_000); using BenchmarkTools @benchmark gpu_countmap = cucountmap($v) # BenchmarkTools.Trial: # memory estimate: 4.17 MiB # allocs estimate: 190 # -------------- # minimum time: 41.275 ms (0.00% GC) # median time: 44.494 ms (0.00% GC) # mean time: 52.756 ms (0.48% GC) # maximum time: 297.796 ms (3.98% GC) # -------------- # samples: 95 # evals/sample: 1 @benchmark cpu_countmap = countmap($v) # BenchmarkTools.Trial: # memory estimate: 4.17 MiB # allocs estimate: 37 # -------------- # minimum time: 132.618 ms (0.00% GC) # median time: 134.176 ms (0.00% GC) # mean time: 134.874 ms (0.19% GC) # maximum time: 145.168 ms (6.76% GC) # -------------- # samples: 38 # evals/sample: 1 cuv = CUDA.cu(v) @benchmark gpu_countmap2 = countmap(cuv) # BenchmarkTools.Trial: # memory estimate: 4.17 MiB # allocs estimate: 97 # -------------- # minimum time: 5.472 ms (0.00% GC) # median time: 5.768 ms (0.00% GC) # mean time: 6.125 ms (3.91% GC) # maximum time: 201.707 ms (96.90% GC) # -------------- # samples: 816 # evals/sample: 1
module Formalization.ClassicalPropositionalLogic.NaturalDeduction.Consistency where import Lvl open import Formalization.ClassicalPropositionalLogic.NaturalDeduction open import Formalization.ClassicalPropositionalLogic.NaturalDeduction.Proofs open import Formalization.ClassicalPropositionalLogic.Syntax open import Functional open import Logic.Propositional as Logic using (_←_) open import Logic.Propositional.Theorems as Logic using () open import Relator.Equals.Proofs.Equiv open import Sets.PredicateSet using (PredSet ; _∈_ ; _∉_ ; _∪_ ; _∪•_ ; _∖_ ; _⊆_ ; _⊇_ ; ∅ ; [≡]-to-[⊆] ; [≡]-to-[⊇]) renaming (•_ to singleton ; _≡_ to _≡ₛ_) open import Type private variable ℓₚ ℓ ℓ₁ ℓ₂ : Lvl.Level private variable P : Type{ℓₚ} private variable Γ Γ₁ Γ₂ : Formulas(P){ℓ} private variable φ ψ : Formula(P) Inconsistent : Formulas(P){ℓ} → Type Inconsistent(Γ) = Γ ⊢ ⊥ Consistent : Formulas(P){ℓ} → Type Consistent(Γ) = Γ ⊬ ⊥ consistency-of-[∪]ₗ : Consistent(Γ₁ ∪ Γ₂) → Consistent(Γ₁) consistency-of-[∪]ₗ con z = con (weaken-union z) [⊢]-derivability-inconsistency : (Γ ⊢ φ) Logic.↔ Inconsistent(Γ ∪ singleton(¬ φ)) [⊢]-derivability-inconsistency = Logic.[↔]-intro [¬]-elim ([¬]-intro-converse ∘ [¬¬]-intro) [⊢]-derivability-consistencyᵣ : Consistent(Γ) → ((Γ ⊢ φ) → Consistent(Γ ∪ singleton(φ))) [⊢]-derivability-consistencyᵣ con Γφ Γφ⊥ = con([⊥]-intro Γφ ([¬]-intro Γφ⊥)) [⊢]-explosion-inconsistency : (∀{φ} → (Γ ⊢ φ)) Logic.↔ Inconsistent(Γ) [⊢]-explosion-inconsistency {Γ} = Logic.[↔]-intro (λ z → [⊥]-elim z) (λ z → z) [⊢]-compose-inconsistency : (Γ ⊢ φ) → Inconsistent(Γ ∪ singleton(φ)) → Inconsistent(Γ) [⊢]-compose-inconsistency Γφ Γφ⊥ = [⊥]-intro Γφ ([¬]-intro Γφ⊥) [⊢]-compose-consistency : (Γ ⊢ φ) → Consistent(Γ) → Consistent(Γ ∪ singleton(φ)) [⊢]-compose-consistency Γφ = Logic.contrapositiveᵣ ([⊢]-compose-inconsistency Γφ) [⊢]-subset-consistency : (Γ₁ ⊆ Γ₂) → (Consistent(Γ₂) → Consistent(Γ₁)) [⊢]-subset-consistency sub con = con ∘ weaken sub [⊢]-subset-inconsistency : (Γ₁ ⊆ Γ₂) → (Inconsistent(Γ₁) → Inconsistent(Γ₂)) [⊢]-subset-inconsistency sub = weaken sub [⊬]-negation-consistency : (Γ ⊬ (¬ φ)) → Consistent(Γ ∪ singleton(φ)) [⊬]-negation-consistency = _∘ [¬]-intro [⊢]-consistent-noncontradicting-membership : Consistent(Γ) → ((¬ φ) ∈ Γ) → (φ ∈ Γ) → Logic.⊥ [⊢]-consistent-noncontradicting-membership con Γ¬φ Γφ = con([⊥]-intro (direct Γφ) (direct Γ¬φ))
module Replica.App.Log import Control.App import Control.App.Console import Replica.App.Replica import Replica.Option.Global import Replica.Other.Decorated %default total export interface Log e where logWithLevel : (lvl : LogLevel) -> (content : String) -> App e () export log : Log e => String -> App e () log = logWithLevel Info export debug : Log e => String -> App e () debug = logWithLevel Debug export warning : Log e => String -> App e () warning = logWithLevel Warning export critical : Log e => String -> App e () critical = logWithLevel Critical export Console e => State GlobalConfig Global e => Log e where logWithLevel lvl content = do Just threshold <- map logLevel $ get GlobalConfig | Nothing => pure () if lvl >= threshold then putStrLn content else pure ()
------------------------------------------------------------------------ -- The Agda standard library -- -- Sums (disjoint unions) ------------------------------------------------------------------------ {-# OPTIONS --without-K --safe #-} module Data.Sum.Base where open import Data.Bool.Base using (true; false) open import Function.Base using (_∘_; _-[_]-_ ; id) open import Relation.Nullary.Reflects using (invert) open import Relation.Nullary using (Dec; yes; no; _because_; ¬_) open import Level using (Level; _⊔_) private variable a b c d : Level A : Set a B : Set b C : Set c D : Set d ------------------------------------------------------------------------ -- Definition infixr 1 _⊎_ data _⊎_ (A : Set a) (B : Set b) : Set (a ⊔ b) where inj₁ : (x : A) → A ⊎ B inj₂ : (y : B) → A ⊎ B ------------------------------------------------------------------------ -- Functions [_,_] : ∀ {C : A ⊎ B → Set c} → ((x : A) → C (inj₁ x)) → ((x : B) → C (inj₂ x)) → ((x : A ⊎ B) → C x) [ f , g ] (inj₁ x) = f x [ f , g ] (inj₂ y) = g y [_,_]′ : (A → C) → (B → C) → (A ⊎ B → C) [_,_]′ = [_,_] fromInj₁ : (B → A) → A ⊎ B → A fromInj₁ = [ id ,_]′ fromInj₂ : (A → B) → A ⊎ B → B fromInj₂ = [_, id ]′ swap : A ⊎ B → B ⊎ A swap (inj₁ x) = inj₂ x swap (inj₂ x) = inj₁ x map : (A → C) → (B → D) → (A ⊎ B → C ⊎ D) map f g = [ inj₁ ∘ f , inj₂ ∘ g ] map₁ : (A → C) → (A ⊎ B → C ⊎ B) map₁ f = map f id map₂ : (B → D) → (A ⊎ B → A ⊎ D) map₂ = map id infixr 1 _-⊎-_ _-⊎-_ : (A → B → Set c) → (A → B → Set d) → (A → B → Set (c ⊔ d)) f -⊎- g = f -[ _⊎_ ]- g -- Conversion back and forth with Dec fromDec : Dec A → A ⊎ ¬ A fromDec ( true because [p]) = inj₁ (invert [p]) fromDec (false because [¬p]) = inj₂ (invert [¬p]) toDec : A ⊎ ¬ A → Dec A toDec (inj₁ p) = yes p toDec (inj₂ ¬p) = no ¬p
Require Import VST.floyd.base2. Require Import VST.floyd.assert_lemmas. Require Import VST.floyd.type_induction. Require Import VST.floyd.jmeq_lemmas. Require Export VST.floyd.fieldlist. Require Export VST.floyd.compact_prod_sum. Require Export VST.floyd.sublist. Definition proj_struct (i : ident) (m : members) {A: ident * type -> Type} (v: compact_prod (map A m)) (d: A (i, field_type i m)): A (i, field_type i m) := proj_compact_prod (i, field_type i m) m v d member_dec. Definition proj_union (i : ident) (m : members) {A: ident * type -> Type} (v: compact_sum (map A m)) (d: A (i, field_type i m)): A (i, field_type i m) := proj_compact_sum (i, field_type i m) m v d member_dec. Definition members_union_inj {m: members} {A} (v: compact_sum (map A m)) (it: ident * type): Prop := compact_sum_inj v it member_dec. Definition upd_sublist {X: Type} (lo hi: Z) (l: list X) (l0: list X) : list X := firstn (Z.to_nat lo) l ++ l0 ++ skipn (Z.to_nat hi) l. (* TODO: We should use the following two definition in replace_refill lemmas in the future. And avoid using compact prod/sum directly. *) Definition upd_struct (i : ident) (m : members) {A: ident * type -> Type} (v: compact_prod (map A m)) (v0: A (i, field_type i m)): compact_prod (map A m) := upd_compact_prod _ v (i, field_type i m) v0 member_dec. Definition upd_union (i : ident) (m : members) {A: ident * type -> Type} (v: compact_sum (map A m)) (v0: A (i, field_type i m)): compact_sum (map A m) := upd_compact_sum _ v (i, field_type i m) v0 member_dec. Lemma proj_struct_JMeq: forall (i: ident) (m : members) {A1 A2: ident * type -> Type} (v1: compact_prod (map A1 m)) (v2: compact_prod (map A2 m)) (d1: A1 (i, field_type i m)) (d2: A2 (i, field_type i m)), (forall i, in_members i m -> @eq Type (A1 (i, field_type i m)) (A2 (i, field_type i m))) -> members_no_replicate m = true -> in_members i m -> JMeq v1 v2 -> JMeq (proj_struct i m v1 d1) (proj_struct i m v2 d2). Proof. intros. apply proj_compact_prod_JMeq; auto. + clear - H H0. intros. pose proof In_field_type _ _ H0 H1. destruct i as [i t]. simpl fst in H2; simpl snd in H2. rewrite <- H2. apply H; auto. apply List.in_map with (f := fst) in H1. auto. + apply in_members_field_type; auto. Qed. Lemma members_union_inj_JMeq: forall (m : members) {A1 A2: ident * type -> Type} (v1: compact_sum (map A1 m)) (v2: compact_sum (map A2 m)), (forall i, in_members i m -> @eq Type (A1 (i, field_type i m)) (A2 (i, field_type i m))) -> members_no_replicate m = true -> JMeq v1 v2 -> (forall it, members_union_inj v1 it <-> members_union_inj v2 it). Proof. intros. apply compact_sum_inj_JMeq; auto. intros [? ?] ?. specialize (H i). spec H. + change i with (fst (i, t)). apply in_map. auto. + apply In_field_type in H2; auto. simpl snd in H2. rewrite <- H2; simpl fst. auto. Qed. Lemma proj_union_JMeq: forall (i: ident) (m : members) {A1 A2: ident * type -> Type} (v1: compact_sum (map A1 m)) (v2: compact_sum (map A2 m)) (d1: A1 (i, field_type i m)) (d2: A2 (i, field_type i m)), (forall i, in_members i m -> @eq Type (A1 (i, field_type i m)) (A2 (i, field_type i m))) -> members_no_replicate m = true -> members_union_inj v1 (i, field_type i m) -> JMeq v1 v2 -> JMeq (proj_union i m v1 d1) (proj_union i m v2 d2). Proof. intros. apply proj_compact_sum_JMeq; auto. + clear - H H0. intros. pose proof In_field_type _ _ H0 H1. destruct i as [i t]. simpl fst in H2; simpl snd in H2. rewrite <- H2. apply H; auto. apply List.in_map with (f := fst) in H1. auto. Qed.
theory T107 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) " nitpick[card nat=4,timeout=86400] oops end
(** * Laws about product categories *) Require Import HoTT.Basics HoTT.Types. Require Import Category.Core Functor.Core InitialTerminalCategory.Core InitialTerminalCategory.Functors Category.Prod Functor.Prod Functor.Composition.Core Functor.Identity Functor.Composition.Laws. Set Universe Polymorphism. Set Implicit Arguments. Generalizable All Variables. Set Asymmetric Patterns. Local Open Scope category_scope. Local Open Scope functor_scope. Local Notation prod_type := Basics.Datatypes.prod. Local Notation fst_type := Basics.Datatypes.fst. Local Notation snd_type := Basics.Datatypes.snd. Local Notation pair_type := Basics.Datatypes.pair. (** ** Swap functor [C × D → D × C] *) Module Swap. Definition functor (C D : PreCategory) : Functor (C * D) (D * C) := Build_Functor (C * D) (D * C) (fun cd => (snd_type cd, fst_type cd)%core) (fun _ _ m => (snd_type m, fst_type m)%core) (fun _ _ _ _ _ => idpath) (fun _ => idpath). Definition law (C D : PreCategory) : functor C D o functor D C = 1 := idpath. End Swap. (** ** [A * (B * C) ≅ (A * B) * C] *) Module Associativity. Section associativity. Variables A B C : PreCategory. Definition functor : Functor (A * (B * C)) ((A * B) * C) := (fst * (fst o snd)) * (snd o snd). Definition inverse : Functor ((A * B) * C) (A * (B * C)) := (fst o fst) * ((snd o fst) * snd). Definition law : functor o inverse = 1 /\ inverse o functor = 1 := (idpath, idpath)%core. End associativity. End Associativity. (** ** Laws about the initial category [0] *) Module Law0. Section law0. Context `{Funext}. Context `{IsInitialCategory zero}. Local Notation "0" := zero : category_scope. Variable C : PreCategory. Global Instance is_initial_category__product : IsInitialCategory (C * 0) := fun P c => initial_category_ind P (snd c). Global Instance is_initial_category__product' : IsInitialCategory (0 * C) := fun P c => initial_category_ind P (fst c). Definition functor : Functor (C * 0) 0 := Functors.from_initial _. Definition functor' : Functor (0 * C) 0 := Functors.from_initial _. Definition inverse : Functor 0 (C * 0) := Functors.from_initial _. Definition inverse' : Functor 0 (0 * C) := Functors.from_initial _. (** *** [C × 0 ≅ 0] *) Definition law : functor o inverse = 1 /\ inverse o functor = 1 := center _. (** *** [0 × C ≅ 0] *) Definition law' : functor' o inverse' = 1 /\ inverse' o functor' = 1 := center _. End law0. End Law0. (** ** Laws about the terminal category [1] *) Module Law1. Section law1. Context `{Funext}. Context `{IsTerminalCategory one}. Local Notation "1" := one : category_scope. Variable C : PreCategory. Definition functor : Functor (C * 1) C := fst. Definition functor' : Functor (1 * C) C := snd. Definition inverse : Functor C (C * 1) := 1 * Functors.to_terminal _. Definition inverse' : Functor C (1 * C) := Functors.to_terminal _ * 1. (** We could throw this in a [repeat match goal with ... end], but we know the order, so we hard-code the order to speed it up by a factor of about 10. *) Local Ltac t_prod := split; try first [ exact (compose_fst_prod _ _) | exact (compose_snd_prod _ _) ]; []; apply Functor.Prod.Universal.path_prod; rewrite <- !Functor.Composition.Laws.associativity by assumption; (rewrite ?compose_fst_prod, ?compose_snd_prod, ?Functor.Composition.Laws.left_identity, ?Functor.Composition.Laws.right_identity by assumption); try (reflexivity || exact (center _)). (** *** [C × 1 ≅ C] *) Lemma law1 : functor o inverse = 1 /\ inverse o functor = 1. Proof. unfold functor, inverse. t_prod. Qed. (** *** [1 × C ≅ C] *) Lemma law1' : functor' o inverse' = 1 /\ inverse' o functor' = 1. Proof. unfold functor', inverse'. t_prod. Qed. End law1. End Law1.
module STLC2 where open import Data.Nat -- open import Data.List open import Data.Empty using (⊥-elim) open import Relation.Binary.PropositionalEquality using (_≡_; refl; sym; trans; cong; cong₂; subst) open import Relation.Nullary open import Data.Product -- de Bruijn indexed lambda calculus infix 5 ƛ_ infixl 7 _∙_ infix 9 var_ data Term : Set where var_ : ℕ → Term ƛ_ : Term → Term _∙_ : Term → Term → Term -- only "shift" the variable when -- 1. it's free -- 2. it will be captured after substitution -- free <= x && x < subst-depth shift : ℕ → ℕ → Term → Term shift free subst-depth (var x) with free >? x shift free subst-depth (var x) | yes p = var x -- bound shift free subst-depth (var x) | no ¬p with subst-depth >? x -- free shift free subst-depth (var x) | no ¬p | yes q = var (suc x) -- will be captured, should increment shift free subst-depth (var x) | no ¬p | no ¬q = var x shift free subst-depth (ƛ M) = ƛ (shift (suc free) (suc subst-depth) M) shift free subst-depth (M ∙ N) = shift free subst-depth M ∙ shift free subst-depth N infixl 10 _[_/_] _[_/_] : Term → Term → ℕ → Term (var x) [ N / n ] with x ≟ n (var x) [ N / n ] | yes p = N (var x) [ N / n ] | no ¬p = var x (ƛ M) [ N / n ] = ƛ ((M [ shift 0 (suc n) N / suc n ])) (L ∙ M) [ N / n ] = L [ N / n ] ∙ M [ N / n ] -- substitution infixl 10 _[_] _[_] : Term → Term → Term M [ N ] = M [ N / zero ] -- β reduction infix 3 _β→_ data _β→_ : Term → Term → Set where β-ƛ-∙ : ∀ {M N} → ((ƛ M) ∙ N) β→ (M [ N ]) β-ƛ : ∀ {M N} → M β→ N → ƛ M β→ ƛ N β-∙-l : ∀ {L M N} → M β→ N → M ∙ L β→ N ∙ L β-∙-r : ∀ {L M N} → M β→ N → L ∙ M β→ L ∙ N -- the reflexive and transitive closure of _β→_ infix 2 _β→*_ infixr 2 _→*_ data _β→*_ : Term → Term → Set where ∎ : ∀ {M} → M β→* M _→*_ : ∀ {L M N} → L β→ M → M β→* N -------------- → L β→* N infixl 3 _<β>_ _<β>_ : ∀ {M N O} → M β→* N → N β→* O → M β→* O _<β>_ {M} {.M} {O} ∎ N→O = N→O _<β>_ {M} {N} {O} (L→M →* M→N) N→O = L→M →* M→N <β> N→O -- infix 2 _-↠_ infixr 2 _→⟨_⟩_ _→⟨_⟩_ : ∀ {M N} → ∀ L → L β→ M → M β→* N -------------- → L β→* N L →⟨ P ⟩ Q = P →* Q infixr 2 _→*⟨_⟩_ _→*⟨_⟩_ : ∀ {M N} → ∀ L → L β→* M → M β→* N -------------- → L β→* N L →*⟨ P ⟩ Q = P <β> Q infix 3 _→∎ _→∎ : ∀ M → M β→* M M →∎ = ∎ jump : ∀ {M N} → M β→ N → M β→* N jump {M} {N} M→N = M→N →* ∎ -- the symmetric closure of _β→*_ infix 1 _β≡_ data _β≡_ : Term → Term → Set where β-sym : ∀ {M N} → M β→* N → N β→* M ------- → M β≡ N infixr 2 _=*⟨_⟩_ _=*⟨_⟩_ : ∀ {M N} → ∀ L → L β≡ M → M β≡ N -------------- → L β≡ N L =*⟨ β-sym A B ⟩ β-sym C D = β-sym (A <β> C) (D <β> B) infixr 2 _=*⟨⟩_ _=*⟨⟩_ : ∀ {N} → ∀ L → L β≡ N -------------- → L β≡ N L =*⟨⟩ β-sym C D = β-sym C D infix 3 _=∎ _=∎ : ∀ M → M β≡ M M =∎ = β-sym ∎ ∎ forward : ∀ {M N} → M β≡ N → M β→* N forward (β-sym A _) = A backward : ∀ {M N} → M β≡ N → N β→* M backward (β-sym _ B) = B -- data Normal : Set where Normal : Term → Set Normal M = ¬ ∃ (λ N → M β→ N) normal : ∀ {M N} → Normal M → M β→* N → M ≡ N normal P ∎ = refl normal P (M→L →* L→N) = ⊥-elim (P (_ , M→L)) normal-ƛ : ∀ {M} → Normal (ƛ M) → Normal M normal-ƛ P (N , M→N) = P ((ƛ N) , (β-ƛ M→N)) normal-ƛ' : ∀ {M} → Normal M → Normal (ƛ M) normal-ƛ' P (.(ƛ N) , β-ƛ {N = N} ƛM→N) = P (N , ƛM→N) normal-∙-r : ∀ {M N} → Normal (M ∙ N) → Normal N normal-∙-r {M} P (O , N→O) = P (M ∙ O , (β-∙-r N→O)) normal-∙-l : ∀ {M N} → Normal (M ∙ N) → Normal M normal-∙-l {_} {N} P (O , M→O) = P (O ∙ N , (β-∙-l M→O)) cong-ƛ : ∀ {M N} → M β→* N → ƛ M β→* ƛ N cong-ƛ ∎ = ∎ cong-ƛ (M→N →* N→O) = β-ƛ M→N →* cong-ƛ N→O cong-∙-l : ∀ {L M N} → M β→* N → M ∙ L β→* N ∙ L cong-∙-l ∎ = ∎ cong-∙-l (M→N →* N→O) = β-∙-l M→N →* cong-∙-l N→O cong-∙-r : ∀ {L M N} → M β→* N → L ∙ M β→* L ∙ N cong-∙-r ∎ = ∎ cong-∙-r (M→N →* N→O) = β-∙-r M→N →* cong-∙-r N→O ∙-dist-r : ∀ M N O → (ƛ (M ∙ N)) ∙ O β→* ((ƛ M) ∙ O) ∙ ((ƛ N) ∙ O) ∙-dist-r (var x) N O = {! !} ∙-dist-r (ƛ M) N O = {! !} ∙-dist-r (M ∙ L) N O = {! !} ∙-dist-r2 : ∀ M N O → (ƛ (M ∙ N)) ∙ O β≡ ((ƛ M) ∙ O) ∙ ((ƛ N) ∙ O) ∙-dist-r2 (var x) N O = {! !} ∙-dist-r2 (ƛ M) N O = {! !} ∙-dist-r2 (M ∙ L) (var x) O = (ƛ (M ∙ L ∙ var x)) ∙ O =*⟨ β-sym (β-ƛ-∙ →* ∎) {! !} ⟩ ((M ∙ L ∙ var x) [ O ]) =*⟨ {! !} ⟩ {! !} =*⟨ {! !} ⟩ (ƛ M ∙ L) ∙ O ∙ ((ƛ var x) ∙ O) =∎ ∙-dist-r2 (M ∙ L) (ƛ N) O = {! !} ∙-dist-r2 (M ∙ L) (N ∙ K) O = {! !} -- {! !} -- →*⟨ {! !} ⟩ -- {! !} -- →*⟨ {! !} ⟩ -- {! !} -- →*⟨ {! !} ⟩ -- {! !} -- →*⟨ {! !} ⟩ -- {! !} -- →∎ -- (ƛ M) [ N / n ] = ƛ ((M [ shift 0 (suc n) N / suc n ])) cong-[]2 : ∀ {M N L n} → M β→ N → (M [ L / n ]) β→* (N [ L / n ]) cong-[]2 (β-ƛ-∙ {var x} {N}) = {! !} cong-[]2 {_} {_} {L} {n} (β-ƛ-∙ {ƛ M} {N}) = (ƛ (ƛ (M [ shift 0 (suc (suc n)) (shift 0 (suc n) L) / suc (suc n) ]))) ∙ (N [ L / n ]) →*⟨ jump β-ƛ-∙ ⟩ ƛ ((M [ shift 0 (suc (suc n)) (shift 0 (suc n) L) / suc (suc n) ]) [ shift 0 1 (N [ L / n ]) / 1 ]) →*⟨ cong-ƛ {! !} ⟩ ƛ {! !} →*⟨ {! !} ⟩ {! !} →*⟨ {! !} ⟩ ƛ ((M [ shift 0 1 N / 1 ]) [ shift 0 (suc n) L / suc n ]) →∎ cong-[]2 {_} {_} {L} {n} (β-ƛ-∙ {M ∙ K} {N}) = (ƛ (M [ shift 0 (suc n) L / suc n ]) ∙ (K [ shift 0 (suc n) L / suc n ])) ∙ (N [ L / n ]) →*⟨ {! !} ⟩ -- →*⟨ forward (∙-dist-r2 (M [ shift zero (suc n) L / suc n ]) (K [ shift zero (suc n) L / suc n ]) (N [ L / n ])) ⟩ (ƛ (M [ shift zero (suc n) L / suc n ])) ∙ (N [ L / n ]) ∙ ((ƛ (K [ shift 0 (suc n) L / suc n ])) ∙ (N [ L / n ])) →*⟨ cong-∙-l (cong-[]2 (β-ƛ-∙ {M} {N})) ⟩ ((M [ N ]) [ L / n ]) ∙ ((ƛ (K [ shift 0 (suc n) L / suc n ])) ∙ (N [ L / n ])) →*⟨ cong-∙-r (cong-[]2 (β-ƛ-∙ {K} {N})) ⟩ ((M [ N ]) [ L / n ]) ∙ ((K [ N ]) [ L / n ]) →∎ cong-[]2 (β-ƛ M→N) = cong-ƛ (cong-[]2 M→N) cong-[]2 (β-∙-l M→N) = cong-∙-l (cong-[]2 M→N) cong-[]2 (β-∙-r M→N) = cong-∙-r (cong-[]2 M→N) cong-∙-l' : ∀ {L M N} → M β→* N → M ∙ L ≡ N ∙ L cong-∙-l' ∎ = refl cong-∙-l' {L} {M} {O} (_→*_ {M = N} M→N N→O) = trans M∙L≡N∙L N∙L≡O∙L where M∙L≡N∙L : M ∙ L ≡ N ∙ L M∙L≡N∙L = {! !} N∙L≡O∙L : N ∙ L ≡ O ∙ L N∙L≡O∙L = cong-∙-l' N→O -- rans (cong-∙-l' (M→N →* ∎)) (cong-∙-l' N→O) cong-[] : ∀ {M N L n} → M β→ N → (M [ L / n ]) ≡ (N [ L / n ]) cong-[] β-ƛ-∙ = {! !} cong-[] (β-ƛ M→N) = {! !} cong-[] (β-∙-l M→N) = cong-∙-l' {! cong-[] M→N !} cong-[] (β-∙-r M→N) = {! !} normal-unique' : ∀ {M N O} → Normal N → Normal O → M β→ N → M β→ O → N ≡ O normal-unique' P Q β-ƛ-∙ β-ƛ-∙ = refl normal-unique' P Q (β-ƛ-∙ {M} {L}) (β-∙-l {N = .(ƛ N)} (β-ƛ {N = N} M→N)) = {! !} -- trans (normal P (cong-[]2 M→N)) N[L]≡ƛN∙L -- trans (normal P (cong-[]2 M→N)) N[L]≡ƛN∙L where N[L]≡ƛN∙L : (N [ L ]) ≡ (ƛ N) ∙ L N[L]≡ƛN∙L = sym (normal Q (jump β-ƛ-∙)) -- β-ƛ-∙ : ∀ {M N} → ((ƛ M) ∙ N) β→ (M [ N ]) normal-unique' P Q (β-ƛ-∙ {M} {L}) (β-∙-r {N = N} L→N) = {! sym (normal Q (jump β-ƛ-∙)) !} -- sym (trans (normal Q (jump β-ƛ-∙)) (cong (λ x → M [ x ]) (sym (normal {! !} (jump N→O))))) -- sym (trans (normal Q (jump β-ƛ-∙)) (cong (λ x → {! M [ x ] !}) {! !})) -- sym (trans {! !} (normal {! P !} (jump β-ƛ-∙))) normal-unique' P Q (β-ƛ M→N) (β-ƛ M→O) = cong ƛ_ (normal-unique' (normal-ƛ P) (normal-ƛ Q) M→N M→O) normal-unique' P Q (β-∙-l M→N) β-ƛ-∙ = {!normal (normal-∙-l P) !} normal-unique' P Q (β-∙-l {L} {N = N} M→N) (β-∙-l {N = O} M→O) = cong (λ x → x ∙ L) (normal-unique' (normal-∙-l P) (normal-∙-l Q) M→N M→O) normal-unique' P Q (β-∙-l M→N) (β-∙-r M→O) = cong₂ _∙_ (sym (normal (normal-∙-l Q) (jump M→N))) (normal (normal-∙-r P) (jump M→O)) normal-unique' {O = O} P Q (β-∙-r {L} {N = N} M→N) M→O = {! !} normal-unique : ∀ {M N O} → Normal N → Normal O → M β→* N → M β→* O → N ≡ O normal-unique P Q ∎ M→O = normal P M→O normal-unique P Q M→N ∎ = sym (normal Q M→N) normal-unique P Q (_→*_ {M = L} M→L L→N) (_→*_ {M = K} M→K K→O) = {! !} -- rewrite (normal-unique' {! !} {! !} M→L M→K) = normal-unique P Q L→N {! K→O !} -- where -- postulate L≡K : L ≡ K -- normal-unique' P Q {! !} {! !} -- ... | U = {! !} -- trans {! !} (normal-unique {! !} {! !} L→N {! !}) -- L≡K = {! !} -- normal-unique P Q {! !} M→O -- normal-unique P Q M→N ∎ = sym (normal Q M→N) -- normal-unique P Q M→N (M→L →* L→O) = {! !} -- β→*-confluent : ∀ {M N O} → (M β→* N) → (M β→* O) → ∃ (λ P → (N β→* P) × (O β→* P)) -- β→*-confluent {M} {.M} {O} ∎ M→O = O , M→O , ∎ -- β→*-confluent {M} {N} {.M} (M→L →* L→N) ∎ = N , ∎ , (M→L →* L→N) -- β→*-confluent {M} {N} {O} (M→L →* L→N) (M→K →* K→O) = {! !} -- lemma-0 : ∀ M N → M [ N ] β→* (ƛ M) ∙ N -- lemma-0 (var zero) (var zero) = (var zero) →⟨ {! !} ⟩ {! !} -- lemma-0 (var zero) (var suc y) = {! !} -- lemma-0 (var suc x) (var y) = {! !} -- lemma-0 (var x) (ƛ O) = {! !} -- lemma-0 (var x) (O ∙ P) = {! !} -- lemma-0 (ƛ M) O = {! !} -- lemma-0 (M ∙ N) O = {! !} -- lemma : ∀ M N O → ((ƛ M) ∙ N β→* O) → M [ N ] β→* O -- lemma (var x) N .((ƛ var x) ∙ N) (.((ƛ var x) ∙ N) ∎) = {! !} -- lemma (ƛ M) N .((ƛ (ƛ M)) ∙ N) (.((ƛ (ƛ M)) ∙ N) ∎) = {! !} -- lemma (M ∙ M₁) N .((ƛ M ∙ M₁) ∙ N) (.((ƛ M ∙ M₁) ∙ N) ∎) = {! !} -- lemma M N O (.((ƛ M) ∙ N) →⟨⟩ redex→O) = lemma M N O redex→O -- lemma M N O (_→⟨_⟩_ .((ƛ M) ∙ N) {P} ƛM∙N→P P→O) = {! !} -- -- lemma M N P (jump ƛM∙N→P) <β> P→O -- lemma-1 : ∀ M N O P → (ƛ M β→* N) → (N ∙ O β→* P) → M [ O ] β→* P -- lemma-1 M .(ƛ M) O P (.(ƛ M) ∎) N∙O→P = lemma M O P N∙O→P -- lemma-1 M N O P (.(ƛ M) →⟨⟩ ƛM→N) N∙O→P = lemma-1 M N O P ƛM→N N∙O→P -- lemma-1 M N O .(N ∙ O) (.(ƛ M) →⟨ x ⟩ ƛM→N) (.(N ∙ O) ∎) = {! !} -- lemma-1 M N O P (.(ƛ M) →⟨ x ⟩ ƛM→N) (.(N ∙ O) →⟨⟩ N∙O→P) = {! !} -- lemma-1 M N O P (.(ƛ M) →⟨ x ⟩ ƛM→N) (.(N ∙ O) →⟨ x₁ ⟩ N∙O→P) = {! !} -- -- (M [ N ]) β→* O -- -- M'→O : P ∙ N β→* O -- -- L→M' : ƛ M β→ P -- -- (M [ N ]) β→* O -- -- M'→O : N₂ ∙ N β→* O -- -- L→M' : ƛ M β→ N₂ -- -- M→N : (M [ N ]) β→* N₁ -- -- that diamond prop -- -- -- -- M -- -- N O -- -- P -- -- -- β→*-confluent : ∀ {M N O} → (M β→* N) → (M β→* O) → ∃ (λ P → (N β→* P) × (O β→* P)) -- β→*-confluent {O = O} (M ∎) M→O = O , M→O , (O ∎) -- β→*-confluent (L →⟨⟩ M→N) M→O = β→*-confluent M→N M→O -- β→*-confluent {N = N} (L →⟨ x ⟩ M→N) (.L ∎) = N , (N ∎) , (L →⟨ x ⟩ M→N) -- β→*-confluent (L →⟨ x ⟩ M→N) (.L →⟨⟩ M→O) = β→*-confluent (L →⟨ x ⟩ M→N) M→O -- β→*-confluent (.((ƛ _) ∙ _) →⟨ β-ƛ-∙ ⟩ M→N) (.((ƛ _) ∙ _) →⟨ β-ƛ-∙ ⟩ M'→O) = β→*-confluent M→N M'→O -- β→*-confluent {N = N} {O} (.((ƛ M) ∙ N₁) →⟨ β-ƛ-∙ {M} {N₁} ⟩ M→N) (.((ƛ M) ∙ N₁) →⟨ β-∙-l {N = N₂} L→M' ⟩ M'→O) = β→*-confluent M→N (lemma-1 M N₂ N₁ O ((ƛ M) →⟨ L→M' ⟩ (N₂ ∎)) M'→O) -- β→*-confluent (.((ƛ _) ∙ _) →⟨ β-ƛ-∙ ⟩ M→N) (.((ƛ _) ∙ _) →⟨ β-∙-r L→M' ⟩ M'→O) = {! !} -- β→*-confluent (.(ƛ _) →⟨ β-ƛ L→M ⟩ M→N) (.(ƛ _) →⟨ L→M' ⟩ M'→O) = {! !} -- β→*-confluent (.(_ ∙ _) →⟨ β-∙-l L→M ⟩ M→N) (.(_ ∙ _) →⟨ L→M' ⟩ M'→O) = {! !} -- β→*-confluent (.(_ ∙ _) →⟨ β-∙-r L→M ⟩ M→N) (.(_ ∙ _) →⟨ L→M' ⟩ M'→O) = {! !} -- L -- M M' -- N O -- P -- -- module Example where -- S : Term -- S = ƛ ƛ ƛ var 2 ∙ var 0 ∙ (var 1 ∙ var 0) -- K : Term -- K = ƛ ƛ var 1 -- I : Term -- I = ƛ (var 0) -- Z : Term -- Z = ƛ ƛ var 0 -- SZ : Term -- SZ = ƛ ƛ var 1 ∙ var 0 -- PLUS : Term -- PLUS = ƛ ƛ ƛ ƛ var 3 ∙ var 1 ∙ (var 2 ∙ var 1 ∙ var 0) -- test-0 : ƛ (ƛ ƛ var 1) ∙ var 0 β→* ƛ ƛ var 1 -- test-0 = -- ƛ (ƛ ƛ var 1) ∙ var 0 -- →⟨ β-ƛ β-ƛ-∙ ⟩ -- ƛ (ƛ var 1) [ var 0 / 0 ] -- →⟨⟩ -- ƛ ƛ ((var 1) [ shift 0 1 (var 0) / 1 ]) -- →⟨⟩ -- ƛ ƛ ((var 1) [ var 1 / 1 ]) -- →⟨⟩ -- ƛ (ƛ var 1) -- ∎ -- test-2 : PLUS ∙ Z ∙ SZ β→* SZ -- test-2 = -- PLUS ∙ Z ∙ SZ -- →⟨⟩ -- (ƛ (ƛ (ƛ (ƛ var 3 ∙ var 1 ∙ (var 2 ∙ var 1 ∙ var zero))))) ∙ Z ∙ SZ -- →⟨ β-∙-l β-ƛ-∙ ⟩ -- ((ƛ (ƛ (ƛ var 3 ∙ var 1 ∙ (var 2 ∙ var 1 ∙ var zero)))) [ Z ]) ∙ SZ -- →⟨⟩ -- ((ƛ (ƛ (ƛ var 3 ∙ var 1 ∙ (var 2 ∙ var 1 ∙ var zero)))) [ Z / 0 ]) ∙ SZ -- →⟨⟩ -- (ƛ ((ƛ (ƛ var 3 ∙ var 1 ∙ (var 2 ∙ var 1 ∙ var zero))) [ shift 0 1 Z / 1 ])) ∙ SZ -- →⟨⟩ -- (ƛ ((ƛ (ƛ var 3 ∙ var 1 ∙ (var 2 ∙ var 1 ∙ var zero))) [ Z / 1 ])) ∙ SZ -- →⟨⟩ -- (ƛ (ƛ ((ƛ var 3 ∙ var 1 ∙ (var 2 ∙ var 1 ∙ var zero)) [ Z / 2 ]))) ∙ SZ -- →⟨⟩ -- (ƛ (ƛ (ƛ ((var 3 ∙ var 1 ∙ (var 2 ∙ var 1 ∙ var zero)) [ Z / 3 ])))) ∙ SZ -- →⟨⟩ -- (ƛ ƛ ƛ Z ∙ var 1 ∙ (var 2 ∙ var 1 ∙ var zero)) ∙ SZ -- →⟨ β-ƛ-∙ ⟩ -- ((ƛ ƛ Z ∙ var 1 ∙ (var 2 ∙ var 1 ∙ var zero)) [ SZ / 0 ]) -- →⟨⟩ -- ƛ ((ƛ Z ∙ var 1 ∙ (var 2 ∙ var 1 ∙ var zero)) [ SZ / 1 ]) -- →⟨⟩ -- ƛ ƛ ((Z ∙ var 1 ∙ (var 2 ∙ var 1 ∙ var zero)) [ SZ / 2 ]) -- →⟨⟩ -- ƛ ƛ Z ∙ var 1 ∙ (SZ ∙ var 1 ∙ var 0) -- →⟨ β-ƛ (β-ƛ (β-∙-r (β-∙-l β-ƛ-∙))) ⟩ -- ƛ ƛ Z ∙ var 1 ∙ (((ƛ var 1 ∙ var 0) [ var 1 ]) ∙ var 0) -- →⟨⟩ -- ƛ ƛ Z ∙ var 1 ∙ (((ƛ var 1 ∙ var 0) [ var 1 / 0 ]) ∙ var 0) -- →⟨⟩ -- ƛ ƛ Z ∙ var 1 ∙ ((ƛ ((var 1 ∙ var 0) [ shift 0 1 (var 1) / 1 ])) ∙ var 0) -- →⟨⟩ -- ƛ ƛ Z ∙ var 1 ∙ ((ƛ ((var 1 ∙ var 0) [ var 1 / 1 ])) ∙ var 0) -- →⟨⟩ -- ƛ ƛ Z ∙ var 1 ∙ ((ƛ var 1 ∙ var 0) ∙ var 0) -- →⟨ β-ƛ (β-ƛ (β-∙-r β-ƛ-∙)) ⟩ -- ƛ ƛ Z ∙ var 1 ∙ ((var 1 ∙ var 0) [ var 0 / 0 ]) -- →⟨⟩ -- ƛ ƛ (ƛ ƛ var 0) ∙ var 1 ∙ (var 1 ∙ var 0) -- →⟨ β-ƛ (β-ƛ (β-∙-l β-ƛ-∙)) ⟩ -- ƛ ƛ ((ƛ var 0) [ var 1 / 0 ]) ∙ (var 1 ∙ var 0) -- →⟨⟩ -- ƛ ƛ (ƛ ((var 0) [ var 1 / 1 ])) ∙ (var 1 ∙ var 0) -- →⟨⟩ -- ƛ ƛ (ƛ var 0) ∙ (var 1 ∙ var 0) -- →⟨ β-ƛ (β-ƛ β-ƛ-∙) ⟩ -- ƛ ƛ ((var 0) [ var 1 ∙ var 0 / 0 ]) -- →⟨⟩ -- SZ -- ∎
Formal statement is: lemma norm_add_less: "norm x < r \<Longrightarrow> norm y < s \<Longrightarrow> norm (x + y) < r + s" Informal statement is: If $x$ and $y$ are complex numbers such that $|x| < r$ and $|y| < s$, then $|x + y| < r + s$.
[STATEMENT] lemma k_wise_indep: "k_wise_indep_vars k (\<lambda>_. discrete) hash (carrier R)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. k_wise_indep_vars k (\<lambda>_. discrete) hash (carrier R) [PROOF STEP] unfolding k_wise_indep_vars_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<forall>J\<subseteq>carrier R. card J \<le> k \<longrightarrow> finite J \<longrightarrow> indep_vars (\<lambda>_. discrete) hash J [PROOF STEP] using indep [PROOF STATE] proof (prove) using this: \<lbrakk>?J \<subseteq> carrier R; card ?J \<le> k\<rbrakk> \<Longrightarrow> indep_vars (\<lambda>_. discrete) hash ?J goal (1 subgoal): 1. \<forall>J\<subseteq>carrier R. card J \<le> k \<longrightarrow> finite J \<longrightarrow> indep_vars (\<lambda>_. discrete) hash J [PROOF STEP] by simp
[STATEMENT] lemma p'_stop_zero: "p' t_stop = (if a = 0 then v else 0)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. p' t_stop = (if a = 0 then v else 0) [PROOF STEP] by (auto simp: p'_def t_stop_def)
[STATEMENT] lemma elements_with_ord_1: "n > 0 \<Longrightarrow> {x\<in>totatives n. ord n x = Suc 0} = {1}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. 0 < n \<Longrightarrow> {x \<in> totatives n. ord n x = Suc 0} = {1} [PROOF STEP] by (auto simp: ord_eq_Suc_0_iff cong_def totatives_less)
-- ------------------------------------------------------------- [ Tibetan.idr ] -- Module : Text.Show.Tibetan -- Description : Parsers for Tibetan numerals. -- --------------------------------------------------------------------- [ EOH ] ||| Module with functions to display Tibetan numerals from Integers. module Text.Show.Tibetan %default total replace : (Eq a) => a -> a -> List a -> List a replace c1 c2 l = map (\c => if c == c1 then c2 else c) l ||| Given an integer, display it using Tibetan numerals, e.g. ||| ||| ```idris example ||| showBo 13 ||| ``` export showBo : (Integral a, Show a) => a -> String showBo i = pack . foldr (.) id fs $ iString where iString = unpack . show $ i fs : List (List Char -> List Char) fs = zipWith replace ['0'..'9'] ['༠','༡','༢','༣','༤','༥','༦','༧','༨','༩'] export showTest : (Integral a, Show a) => a -> String showTest i = pack . foldr (.) id fs $ iString where iString = unpack . show $ i fs : List (List Char -> List Char) fs = zipWith replace ['0'..'9'] ['0'..'9']
module Fmt import Data.String %default total -- From https://gist.github.com/chrisdone/672efcd784528b7d0b7e17ad9c115292 -- TODO: Add showables public export data Format = FInt Format | FString Format | FOther Char Format | FEnd public export format : List Char -> Format format ('%' :: 'd' :: cs) = FInt (format cs) format ('%' :: 's' :: cs) = FString (format cs) format (c :: cs) = FOther c (format cs) format [] = FEnd public export formatString : String -> Format formatString = format . unpack public export interpFormat : Format -> Type interpFormat (FInt f) = Int -> interpFormat f interpFormat (FString f) = String -> interpFormat f interpFormat (FOther _ f) = interpFormat f interpFormat FEnd = String public export toFunction : (fmt : Format) -> String -> interpFormat fmt toFunction (FInt f) a = \i => toFunction f (a ++ show i) toFunction (FString f) a = \s => toFunction f (a ++ s) toFunction (FOther c f) a = toFunction f (a ++ singleton c) toFunction FEnd a = a public export fmt : (s : String) -> interpFormat (formatString s) fmt s = toFunction (formatString s) ""
Formal statement is: lemma isCont_eq_Ub: fixes f :: "real \<Rightarrow> 'a::linorder_topology" shows "a \<le> b \<Longrightarrow> \<forall>x::real. a \<le> x \<and> x \<le> b \<longrightarrow> isCont f x \<Longrightarrow> \<exists>M. (\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> f x \<le> M) \<and> (\<exists>x. a \<le> x \<and> x \<le> b \<and> f x = M)" Informal statement is: If $f$ is continuous on the closed interval $[a,b]$, then $f$ attains its supremum on $[a,b]$.
# Vanilla Gradient Descent This notebook applies the most basic gradient descent to predict `Happiness.Score` from `Economy..GDP.per.Capita.`. The dataset used is the World Happiness Report ```python import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set_style("darkgrid") %matplotlib inline ``` # Import Data ```python df = pd.read_csv('data/2017.csv') ``` ```python economy = df['Economy..GDP.per.Capita.'].values happiness = df['Happiness.Score'].values ``` ```python plt.scatter(economy, happiness) ``` # Gradient Descent **Vanilla Gradient Descent** is used. ```python update = learning_rate * gradient_of_parameters parameters = parameters - update ``` \begin{align} y' &=& mx + c \\ error &=& \frac{1}{N} \sum_{}(y - y') ^ 2 \\ \frac{\partial error}{\partial m} &=& -\frac{2}{N} * (y - y') * x \\ \frac{\partial error}{\partial c} &=& -\frac{2}{N} * (y - y') \\ \end{align} ```python learning_rate = 0.0001 epochs = 200 n = len(happiness) m = 0 c = 0 # a list of mean squared errors through the epochs errors = [] for epoch in range(epochs): error = 0 for x, y in zip(economy, happiness): # mean squared error error += (y - (m * x + c)) ** 2 # gradient of parameters m_delta = -n * 0.5 * (y - (m * x + c)) * x c_delta = -n * 0.5 * (y - (m * x + c)) m_update = learning_rate * m_delta c_update = learning_rate * c_delta m -= m_update c -= c_update errors.append(error) plt.plot(errors) ``` As expected, the mean squared error reduces with epochs. After a few epochs, it is near-constant. # Plotting the line of best fit ```python limit = int(round(np.max(happiness))) plt.plot([m * x + c for x in range(3)]) plt.scatter(economy, happiness) ``` # Result A line of best fit is obtained that describes the correlation between `Happiness.Score` and `Economy..GDP.per.Capita.`.
(* * 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) *) section "Enumeration extensions and alternative definition" theory Enumeration imports "~~/src/HOL/Main" begin abbreviation "enum \<equiv> enum_class.enum" abbreviation "enum_all \<equiv> enum_class.enum_all" abbreviation "enum_ex \<equiv> enum_class.enum_ex" primrec (nonexhaustive) the_index :: "'a list \<Rightarrow> 'a \<Rightarrow> nat" where "the_index (x # xs) y = (if x = y then 0 else Suc (the_index xs y))" lemma the_index_bounded: "x \<in> set xs \<Longrightarrow> the_index xs x < length xs" by (induct xs, clarsimp+) lemma nth_the_index: "x \<in> set xs \<Longrightarrow> xs ! the_index xs x = x" by (induct xs, clarsimp+) lemma distinct_the_index_is_index[simp]: "\<lbrakk> distinct xs ; n < length xs \<rbrakk> \<Longrightarrow> the_index xs (xs ! n) = n" by (meson nth_eq_iff_index_eq nth_mem nth_the_index the_index_bounded) lemma the_index_last_distinct: "distinct xs \<and> xs \<noteq> [] \<Longrightarrow> the_index xs (last xs) = length xs - 1" apply safe apply (subgoal_tac "xs ! (length xs - 1) = last xs") apply (subgoal_tac "xs ! the_index xs (last xs) = last xs") apply (subst nth_eq_iff_index_eq[symmetric]) apply assumption apply (rule the_index_bounded) apply simp_all apply (rule nth_the_index) apply simp apply (induct xs, auto) done context enum begin (* These two are added for historical reasons. *) lemmas enum_surj[simp] = enum_UNIV declare enum_distinct[simp] lemma enum_nonempty[simp]: "(enum :: 'a list) \<noteq> []" using enum_surj by fastforce definition maxBound :: 'a where "maxBound \<equiv> last enum" definition minBound :: 'a where "minBound \<equiv> hd enum" definition toEnum :: "nat \<Rightarrow> 'a" where "toEnum n \<equiv> if n < length (enum :: 'a list) then enum ! n else the None" definition fromEnum :: "'a \<Rightarrow> nat" where "fromEnum x \<equiv> the_index enum x" lemma maxBound_is_length: "fromEnum maxBound = length (enum :: 'a list) - 1" by (simp add: maxBound_def fromEnum_def the_index_last_distinct) lemma maxBound_less_length: "(x \<le> fromEnum maxBound) = (x < length (enum :: 'a list))" unfolding maxBound_is_length by (cases "length enum") auto lemma maxBound_is_bound [simp]: "fromEnum x \<le> fromEnum maxBound" unfolding maxBound_less_length by (fastforce simp: fromEnum_def intro: the_index_bounded) lemma to_from_enum [simp]: fixes x :: 'a shows "toEnum (fromEnum x) = x" proof - have "x \<in> set enum" by simp then show ?thesis by (simp add: toEnum_def fromEnum_def nth_the_index the_index_bounded) qed lemma from_to_enum [simp]: "x \<le> fromEnum maxBound \<Longrightarrow> fromEnum (toEnum x) = x" unfolding maxBound_less_length by (simp add: toEnum_def fromEnum_def) lemma map_enum: fixes x :: 'a shows "map f enum ! fromEnum x = f x" proof - have "fromEnum x \<le> fromEnum (maxBound :: 'a)" by (rule maxBound_is_bound) then have "fromEnum x < length (enum::'a list)" by (simp add: maxBound_less_length) then have "map f enum ! fromEnum x = f (enum ! fromEnum x)" by simp also have "x \<in> set enum" by simp then have "enum ! fromEnum x = x" by (simp add: fromEnum_def nth_the_index) finally show ?thesis . qed definition assocs :: "('a \<Rightarrow> 'b) \<Rightarrow> ('a \<times> 'b) list" where "assocs f \<equiv> map (\<lambda>x. (x, f x)) enum" end (* For historical naming reasons. *) lemmas enum_bool = enum_bool_def lemma fromEnumTrue [simp]: "fromEnum True = 1" by (simp add: fromEnum_def enum_bool) lemma fromEnumFalse [simp]: "fromEnum False = 0" by (simp add: fromEnum_def enum_bool) class enum_alt = fixes enum_alt :: "nat \<Rightarrow> 'a option" class enumeration_alt = enum_alt + assumes enum_alt_one_bound: "enum_alt x = (None :: 'a option) \<Longrightarrow> enum_alt (Suc x) = (None :: 'a option)" assumes enum_alt_surj: "range enum_alt \<union> {None} = UNIV" assumes enum_alt_inj: "(enum_alt x :: 'a option) = enum_alt y \<Longrightarrow> (x = y) \<or> (enum_alt x = (None :: 'a option))" begin lemma enum_alt_inj_2: assumes "enum_alt x = (enum_alt y :: 'a option)" "enum_alt x \<noteq> (None :: 'a option)" shows "x = y" proof - from assms have "(x = y) \<or> (enum_alt x = (None :: 'a option))" by (fastforce intro!: enum_alt_inj) with assms show ?thesis by clarsimp qed lemma enum_alt_surj_2: "\<exists>x. enum_alt x = Some y" proof - have "Some y \<in> range enum_alt \<union> {None}" by (subst enum_alt_surj) simp then have "Some y \<in> range enum_alt" by simp then show ?thesis by auto qed end definition alt_from_ord :: "'a list \<Rightarrow> nat \<Rightarrow> 'a option" where "alt_from_ord L \<equiv> \<lambda>n. if (n < length L) then Some (L ! n) else None" lemma handy_if_lemma: "((if P then Some A else None) = Some B) = (P \<and> (A = B))" by simp class enumeration_both = enum_alt + enum + assumes enum_alt_rel: "enum_alt = alt_from_ord enum" instance enumeration_both < enumeration_alt apply (intro_classes; simp add: enum_alt_rel alt_from_ord_def) apply auto[1] apply (safe; simp)[1] apply (rule rev_image_eqI; simp) apply (rule the_index_bounded; simp) apply (subst nth_the_index; simp) apply (clarsimp simp: handy_if_lemma) apply (subst nth_eq_iff_index_eq[symmetric]; simp) done instantiation bool :: enumeration_both begin definition enum_alt_bool: "enum_alt \<equiv> alt_from_ord [False, True]" instance by (intro_classes, simp add: enum_bool_def enum_alt_bool) end definition toEnumAlt :: "nat \<Rightarrow> ('a :: enum_alt)" where "toEnumAlt n \<equiv> the (enum_alt n)" definition fromEnumAlt :: "('a :: enum_alt) \<Rightarrow> nat" where "fromEnumAlt x \<equiv> THE n. enum_alt n = Some x" definition upto_enum :: "('a :: enumeration_alt) \<Rightarrow> 'a \<Rightarrow> 'a list" ("(1[_.e._])") where "upto_enum n m \<equiv> map toEnumAlt [fromEnumAlt n ..< Suc (fromEnumAlt m)]" lemma fromEnum_alt_red[simp]: "fromEnumAlt = (fromEnum :: ('a :: enumeration_both) \<Rightarrow> nat)" apply (rule ext) apply (simp add: fromEnumAlt_def fromEnum_def enum_alt_rel alt_from_ord_def) apply (rule theI2) apply (rule conjI) apply (clarify, rule nth_the_index, simp) apply (rule the_index_bounded, simp) apply auto done lemma toEnum_alt_red[simp]: "toEnumAlt = (toEnum :: nat \<Rightarrow> 'a :: enumeration_both)" by (rule ext) (simp add: enum_alt_rel alt_from_ord_def toEnum_def toEnumAlt_def) lemma upto_enum_red: "[(n :: ('a :: enumeration_both)) .e. m] = map toEnum [fromEnum n ..< Suc (fromEnum m)]" unfolding upto_enum_def by simp instantiation nat :: enumeration_alt begin definition enum_alt_nat: "enum_alt \<equiv> Some" instance by (intro_classes; simp add: enum_alt_nat UNIV_option_conv) end lemma toEnumAlt_nat[simp]: "toEnumAlt = id" by (rule ext) (simp add: toEnumAlt_def enum_alt_nat) lemma fromEnumAlt_nat[simp]: "fromEnumAlt = id" by (rule ext) (simp add: fromEnumAlt_def enum_alt_nat) lemma upto_enum_nat[simp]: "[n .e. m] = [n ..< Suc m]" by (subst upto_enum_def) simp definition zipE1 :: "'a :: enum_alt \<Rightarrow> 'b list \<Rightarrow> ('a \<times> 'b) list" where "zipE1 x L \<equiv> zip (map toEnumAlt [fromEnumAlt x ..< fromEnumAlt x + length L]) L" definition zipE2 :: "'a :: enum_alt \<Rightarrow> 'a \<Rightarrow> 'b list \<Rightarrow> ('a \<times> 'b) list" where "zipE2 x xn L \<equiv> zip (map (\<lambda>n. toEnumAlt (fromEnumAlt x + (fromEnumAlt xn - fromEnumAlt x) * n)) [0 ..< length L]) L" definition zipE3 :: "'a list \<Rightarrow> 'b :: enum_alt \<Rightarrow> ('a \<times> 'b) list" where "zipE3 L x \<equiv> zip L (map toEnumAlt [fromEnumAlt x ..< fromEnumAlt x + length L])" definition zipE4 :: "'a list \<Rightarrow> 'b :: enum_alt \<Rightarrow> 'b \<Rightarrow> ('a \<times> 'b) list" where "zipE4 L x xn \<equiv> zip L (map (\<lambda>n. toEnumAlt (fromEnumAlt x + (fromEnumAlt xn - fromEnumAlt x) * n)) [0 ..< length L])" lemma to_from_enum_alt[simp]: "toEnumAlt (fromEnumAlt x) = (x :: 'a :: enumeration_alt)" proof - have rl: "\<And>a b. a = Some b \<Longrightarrow> the a = b" by simp show ?thesis unfolding fromEnumAlt_def toEnumAlt_def by (rule rl, rule theI') (metis enum_alt_inj enum_alt_surj_2 not_None_eq) qed lemma upto_enum_triv [simp]: "[x .e. x] = [x]" unfolding upto_enum_def by simp lemma toEnum_eq_to_fromEnum_eq: fixes v :: "'a :: enum" shows "n \<le> fromEnum (maxBound :: 'a) \<Longrightarrow> (toEnum n = v) = (n = fromEnum v)" by auto end
[STATEMENT] lemma is_document_ptr_kind_none: assumes "\<not>is_document_ptr_kind ptr" shows "cast\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>d\<^sub>o\<^sub>c\<^sub>u\<^sub>m\<^sub>e\<^sub>n\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r ptr = None" [PROOF STATE] proof (prove) goal (1 subgoal): 1. cast ptr = None [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: \<not> is_document_ptr_kind ptr goal (1 subgoal): 1. cast ptr = None [PROOF STEP] unfolding is_document_ptr_kind_def cast\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>d\<^sub>o\<^sub>c\<^sub>u\<^sub>m\<^sub>e\<^sub>n\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r_def [PROOF STATE] proof (prove) using this: \<not> (case case ptr of object_ptr.Ext (Inl xa) \<Rightarrow> Map.empty xa | object_ptr.Ext (Inr (Inl x)) \<Rightarrow> Some x | object_ptr.Ext (Inr (Inr x)) \<Rightarrow> Map.empty x of None \<Rightarrow> False | Some x \<Rightarrow> True) goal (1 subgoal): 1. (case ptr of object_ptr.Ext (Inl xa) \<Rightarrow> Map.empty xa | object_ptr.Ext (Inr (Inl x)) \<Rightarrow> Some x | object_ptr.Ext (Inr (Inr x)) \<Rightarrow> Map.empty x) = None [PROOF STEP] by (auto split: object_ptr.splits sum.splits)
Formal statement is: lemma limitin_const_iff [simp]: "limitin X (\<lambda>a. l) l F \<longleftrightarrow> l \<in> topspace X" Informal statement is: A constant sequence converges to a point $l$ if and only if $l$ is in the topological space $X$.
State Before: α : Type ?u.166351 β✝ : Type ?u.166354 γ : Type ?u.166357 δ : Type ?u.166360 β : Type u_1 inst✝ : CommMonoid β u a b : β hu : IsUnit u ⊢ u * a ~ᵤ b ↔ a ~ᵤ b State After: α : Type ?u.166351 β✝ : Type ?u.166354 γ : Type ?u.166357 δ : Type ?u.166360 β : Type u_1 inst✝ : CommMonoid β u a b : β hu : IsUnit u ⊢ a * u ~ᵤ b ↔ a ~ᵤ b Tactic: rw [mul_comm] State Before: α : Type ?u.166351 β✝ : Type ?u.166354 γ : Type ?u.166357 δ : Type ?u.166360 β : Type u_1 inst✝ : CommMonoid β u a b : β hu : IsUnit u ⊢ a * u ~ᵤ b ↔ a ~ᵤ b State After: no goals Tactic: exact associated_mul_isUnit_left_iff hu
subroutine makeplot (lscreen) c****************************************************************************** c This subroutine does the plot-package-specific commands to begin c a plot, then calls the specific plot drawing routine, then ends the c plot. c****************************************************************************** implicit real*8 (a-h,o-z) include 'Atmos.com' include 'Pstuff.com' integer sm_device, lscreen, nchars c open the plot device: screen terminal if (plotroutine(1:4) .eq. 'term') then if (sm_device(smterm) .lt. 0) then write (array,1001) smterm istat = ivwrite(lscreen+1,1,array,79) write (nf1out,1007) array(1:79) stop endif endif c open the plot device: hardcopy sent to printer if (plotroutine(1:4) .eq. 'hard') then if (plotroutine(6:9) .eq. 'land') then if (sm_device('postland') .lt. 0) then write (array,1002) istat = ivwrite(lscreen+1,1,array,34) write (nf1out,1007) array(1:34) stop endif elseif (plotroutine(6:9) .eq. 'port') then if (sm_device('postport') .lt. 0) then write (array,1009) istat = ivwrite(lscreen+1,1,array,34) write (nf1out,1007) array(1:34) write (nf1out,1009) stop endif endif endif c open the plot device: postscript file if (plotroutine(1:4) .eq. 'file') then if (f5out .eq. 'optional_output_file') then array = 'Give the file name for the POSTSRIPT plot image: ' nchars = 49 call getasci (nchars,maxline) f5out = chinfo(1:nchars) else nchars = 80 call getcount (nchars,f5out) endif if (plotroutine(6:9) .eq. 'land') then if (nchars .lt. 10) then write (errmess,1003) nchars else write (errmess,1004) nchars endif elseif (plotroutine(6:9) .eq. 'port') then if (nchars .lt. 10) then write (errmess,1005) nchars else write (errmess,1006) nchars endif endif write (array,errmess) f5out(1:nchars) if (sm_device(array(1:nchars+13)) .lt. 0) then write (nf1out,1007) array(1:nchars+9) istat = ivwrite(lscreen+1,1,array,nchars+9) stop endif endif c issue standard beginning commands call sm_graphics call sm_erase c call the routine that makes the desired plot if (plotroutine(11:14) .eq. 'cog ') then call cogplot elseif (plotroutine(11:14) .eq. 'abun') then call abunplot elseif (plotroutine(11:14) .eq. 'spec') then call specplot elseif (plotroutine(11:14) .eq. 'bin ') then call binplot elseif (plotroutine(11:14) .eq. 'flux') then call fluxplot endif c issue standard ending commands; exit normally if (plotroutine(1:4) .eq. 'file') then f5out = 'optional_output_file' endif call sm_gflush if (plotroutine(1:4).eq.'hard' .or. . plotroutine(1:4).eq.'file') call sm_hardcopy call sm_alpha return c*****format statements 1001 format ('DEVICE OPENING ERROR FOR:',a54) 1002 format ('DEVICE OPENING ERROR FOR: postland') 1009 format ('DEVICE OPENING ERROR FOR: postport') 1007 format (a80) 1003 format ('(13hpostlandfile ,a',i1,'$)') 1004 format ('(13hpostlandfile ,a',i2,'$)') 1005 format ('(13hpostportfile ,a',i1,'$)') 1006 format ('(13hpostportfile ,a',i2,'$)') end
[GOAL] α : Type u β : Type u_1 inst✝⁷ : OrderedSemiring α inst✝⁶ : Zero β inst✝⁵ : One β inst✝⁴ : Add β inst✝³ : Mul β inst✝² : Pow β ℕ inst✝¹ : SMul ℕ β inst✝ : NatCast β f : β → α hf : Injective f zero : f 0 = 0 one : f 1 = 1 add : ∀ (x y : β), f (x + y) = f x + f y mul : ∀ (x y : β), f (x * y) = f x * f y nsmul : ∀ (x : β) (n : ℕ), f (n • x) = n • f x npow : ∀ (x : β) (n : ℕ), f (x ^ n) = f x ^ n nat_cast : ∀ (n : ℕ), f ↑n = ↑n src✝¹ : OrderedAddCommMonoid β := orderedAddCommMonoid f hf zero add nsmul src✝ : Semiring β := Injective.semiring f hf zero one add mul nsmul npow nat_cast ⊢ f 0 ≤ f 1 [PROOFSTEP] simp only [zero, one, zero_le_one] [GOAL] α : Type u β : Type u_1 inst✝⁷ : OrderedSemiring α inst✝⁶ : Zero β inst✝⁵ : One β inst✝⁴ : Add β inst✝³ : Mul β inst✝² : Pow β ℕ inst✝¹ : SMul ℕ β inst✝ : NatCast β f : β → α hf : Injective f zero : f 0 = 0 one : f 1 = 1 add : ∀ (x y : β), f (x + y) = f x + f y mul : ∀ (x y : β), f (x * y) = f x * f y nsmul : ∀ (x : β) (n : ℕ), f (n • x) = n • f x npow : ∀ (x : β) (n : ℕ), f (x ^ n) = f x ^ n nat_cast : ∀ (n : ℕ), f ↑n = ↑n src✝¹ : OrderedAddCommMonoid β := orderedAddCommMonoid f hf zero add nsmul src✝ : Semiring β := Injective.semiring f hf zero one add mul nsmul npow nat_cast a b c : β h : a ≤ b hc : 0 ≤ c ⊢ f (c * a) ≤ f (c * b) [PROOFSTEP] rw [mul, mul] [GOAL] α : Type u β : Type u_1 inst✝⁷ : OrderedSemiring α inst✝⁶ : Zero β inst✝⁵ : One β inst✝⁴ : Add β inst✝³ : Mul β inst✝² : Pow β ℕ inst✝¹ : SMul ℕ β inst✝ : NatCast β f : β → α hf : Injective f zero : f 0 = 0 one : f 1 = 1 add : ∀ (x y : β), f (x + y) = f x + f y mul : ∀ (x y : β), f (x * y) = f x * f y nsmul : ∀ (x : β) (n : ℕ), f (n • x) = n • f x npow : ∀ (x : β) (n : ℕ), f (x ^ n) = f x ^ n nat_cast : ∀ (n : ℕ), f ↑n = ↑n src✝¹ : OrderedAddCommMonoid β := orderedAddCommMonoid f hf zero add nsmul src✝ : Semiring β := Injective.semiring f hf zero one add mul nsmul npow nat_cast a b c : β h : a ≤ b hc : 0 ≤ c ⊢ f c * f a ≤ f c * f b [PROOFSTEP] refine' mul_le_mul_of_nonneg_left h _ [GOAL] α : Type u β : Type u_1 inst✝⁷ : OrderedSemiring α inst✝⁶ : Zero β inst✝⁵ : One β inst✝⁴ : Add β inst✝³ : Mul β inst✝² : Pow β ℕ inst✝¹ : SMul ℕ β inst✝ : NatCast β f : β → α hf : Injective f zero : f 0 = 0 one : f 1 = 1 add : ∀ (x y : β), f (x + y) = f x + f y mul : ∀ (x y : β), f (x * y) = f x * f y nsmul : ∀ (x : β) (n : ℕ), f (n • x) = n • f x npow : ∀ (x : β) (n : ℕ), f (x ^ n) = f x ^ n nat_cast : ∀ (n : ℕ), f ↑n = ↑n src✝¹ : OrderedAddCommMonoid β := orderedAddCommMonoid f hf zero add nsmul src✝ : Semiring β := Injective.semiring f hf zero one add mul nsmul npow nat_cast a b c : β h : a ≤ b hc : 0 ≤ c ⊢ 0 ≤ f c [PROOFSTEP] rwa [← zero] [GOAL] α : Type u β : Type u_1 inst✝⁷ : OrderedSemiring α inst✝⁶ : Zero β inst✝⁵ : One β inst✝⁴ : Add β inst✝³ : Mul β inst✝² : Pow β ℕ inst✝¹ : SMul ℕ β inst✝ : NatCast β f : β → α hf : Injective f zero : f 0 = 0 one : f 1 = 1 add : ∀ (x y : β), f (x + y) = f x + f y mul : ∀ (x y : β), f (x * y) = f x * f y nsmul : ∀ (x : β) (n : ℕ), f (n • x) = n • f x npow : ∀ (x : β) (n : ℕ), f (x ^ n) = f x ^ n nat_cast : ∀ (n : ℕ), f ↑n = ↑n src✝¹ : OrderedAddCommMonoid β := orderedAddCommMonoid f hf zero add nsmul src✝ : Semiring β := Injective.semiring f hf zero one add mul nsmul npow nat_cast a b c : β h : a ≤ b hc : 0 ≤ c ⊢ f (a * c) ≤ f (b * c) [PROOFSTEP] rw [mul, mul] [GOAL] α : Type u β : Type u_1 inst✝⁷ : OrderedSemiring α inst✝⁶ : Zero β inst✝⁵ : One β inst✝⁴ : Add β inst✝³ : Mul β inst✝² : Pow β ℕ inst✝¹ : SMul ℕ β inst✝ : NatCast β f : β → α hf : Injective f zero : f 0 = 0 one : f 1 = 1 add : ∀ (x y : β), f (x + y) = f x + f y mul : ∀ (x y : β), f (x * y) = f x * f y nsmul : ∀ (x : β) (n : ℕ), f (n • x) = n • f x npow : ∀ (x : β) (n : ℕ), f (x ^ n) = f x ^ n nat_cast : ∀ (n : ℕ), f ↑n = ↑n src✝¹ : OrderedAddCommMonoid β := orderedAddCommMonoid f hf zero add nsmul src✝ : Semiring β := Injective.semiring f hf zero one add mul nsmul npow nat_cast a b c : β h : a ≤ b hc : 0 ≤ c ⊢ f a * f c ≤ f b * f c [PROOFSTEP] refine' mul_le_mul_of_nonneg_right h _ [GOAL] α : Type u β : Type u_1 inst✝⁷ : OrderedSemiring α inst✝⁶ : Zero β inst✝⁵ : One β inst✝⁴ : Add β inst✝³ : Mul β inst✝² : Pow β ℕ inst✝¹ : SMul ℕ β inst✝ : NatCast β f : β → α hf : Injective f zero : f 0 = 0 one : f 1 = 1 add : ∀ (x y : β), f (x + y) = f x + f y mul : ∀ (x y : β), f (x * y) = f x * f y nsmul : ∀ (x : β) (n : ℕ), f (n • x) = n • f x npow : ∀ (x : β) (n : ℕ), f (x ^ n) = f x ^ n nat_cast : ∀ (n : ℕ), f ↑n = ↑n src✝¹ : OrderedAddCommMonoid β := orderedAddCommMonoid f hf zero add nsmul src✝ : Semiring β := Injective.semiring f hf zero one add mul nsmul npow nat_cast a b c : β h : a ≤ b hc : 0 ≤ c ⊢ 0 ≤ f c [PROOFSTEP] rwa [← zero] [GOAL] α : Type u β : Type u_1 inst✝¹¹ : OrderedRing α inst✝¹⁰ : Zero β inst✝⁹ : One β inst✝⁸ : Add β inst✝⁷ : Mul β inst✝⁶ : Neg β inst✝⁵ : Sub β inst✝⁴ : SMul ℕ β inst✝³ : SMul ℤ β inst✝² : Pow β ℕ inst✝¹ : NatCast β inst✝ : IntCast β f : β → α hf : Injective f zero : f 0 = 0 one : f 1 = 1 add : ∀ (x y : β), f (x + y) = f x + f y mul : ∀ (x y : β), f (x * y) = f x * f y neg : ∀ (x : β), f (-x) = -f x sub : ∀ (x y : β), f (x - y) = f x - f y nsmul : ∀ (x : β) (n : ℕ), f (n • x) = n • f x zsmul : ∀ (x : β) (n : ℤ), f (n • x) = n • f x npow : ∀ (x : β) (n : ℕ), f (x ^ n) = f x ^ n nat_cast : ∀ (n : ℕ), f ↑n = ↑n int_cast : ∀ (n : ℤ), f ↑n = ↑n src✝¹ : OrderedSemiring β := Injective.orderedSemiring f hf zero one add mul nsmul npow nat_cast src✝ : Ring β := Injective.ring f hf zero one add mul neg sub nsmul zsmul npow nat_cast int_cast a b : β ha : 0 ≤ a hb : 0 ≤ b ⊢ f 0 ≤ f (a * b) [PROOFSTEP] rw [zero, mul] [GOAL] α : Type u β : Type u_1 inst✝¹¹ : OrderedRing α inst✝¹⁰ : Zero β inst✝⁹ : One β inst✝⁸ : Add β inst✝⁷ : Mul β inst✝⁶ : Neg β inst✝⁵ : Sub β inst✝⁴ : SMul ℕ β inst✝³ : SMul ℤ β inst✝² : Pow β ℕ inst✝¹ : NatCast β inst✝ : IntCast β f : β → α hf : Injective f zero : f 0 = 0 one : f 1 = 1 add : ∀ (x y : β), f (x + y) = f x + f y mul : ∀ (x y : β), f (x * y) = f x * f y neg : ∀ (x : β), f (-x) = -f x sub : ∀ (x y : β), f (x - y) = f x - f y nsmul : ∀ (x : β) (n : ℕ), f (n • x) = n • f x zsmul : ∀ (x : β) (n : ℤ), f (n • x) = n • f x npow : ∀ (x : β) (n : ℕ), f (x ^ n) = f x ^ n nat_cast : ∀ (n : ℕ), f ↑n = ↑n int_cast : ∀ (n : ℤ), f ↑n = ↑n src✝¹ : OrderedSemiring β := Injective.orderedSemiring f hf zero one add mul nsmul npow nat_cast src✝ : Ring β := Injective.ring f hf zero one add mul neg sub nsmul zsmul npow nat_cast int_cast a b : β ha : 0 ≤ a hb : 0 ≤ b ⊢ 0 ≤ f a * f b [PROOFSTEP] apply mul_nonneg [GOAL] case ha α : Type u β : Type u_1 inst✝¹¹ : OrderedRing α inst✝¹⁰ : Zero β inst✝⁹ : One β inst✝⁸ : Add β inst✝⁷ : Mul β inst✝⁶ : Neg β inst✝⁵ : Sub β inst✝⁴ : SMul ℕ β inst✝³ : SMul ℤ β inst✝² : Pow β ℕ inst✝¹ : NatCast β inst✝ : IntCast β f : β → α hf : Injective f zero : f 0 = 0 one : f 1 = 1 add : ∀ (x y : β), f (x + y) = f x + f y mul : ∀ (x y : β), f (x * y) = f x * f y neg : ∀ (x : β), f (-x) = -f x sub : ∀ (x y : β), f (x - y) = f x - f y nsmul : ∀ (x : β) (n : ℕ), f (n • x) = n • f x zsmul : ∀ (x : β) (n : ℤ), f (n • x) = n • f x npow : ∀ (x : β) (n : ℕ), f (x ^ n) = f x ^ n nat_cast : ∀ (n : ℕ), f ↑n = ↑n int_cast : ∀ (n : ℤ), f ↑n = ↑n src✝¹ : OrderedSemiring β := Injective.orderedSemiring f hf zero one add mul nsmul npow nat_cast src✝ : Ring β := Injective.ring f hf zero one add mul neg sub nsmul zsmul npow nat_cast int_cast a b : β ha : 0 ≤ a hb : 0 ≤ b ⊢ 0 ≤ f a [PROOFSTEP] rwa [← zero] [GOAL] case hb α : Type u β : Type u_1 inst✝¹¹ : OrderedRing α inst✝¹⁰ : Zero β inst✝⁹ : One β inst✝⁸ : Add β inst✝⁷ : Mul β inst✝⁶ : Neg β inst✝⁵ : Sub β inst✝⁴ : SMul ℕ β inst✝³ : SMul ℤ β inst✝² : Pow β ℕ inst✝¹ : NatCast β inst✝ : IntCast β f : β → α hf : Injective f zero : f 0 = 0 one : f 1 = 1 add : ∀ (x y : β), f (x + y) = f x + f y mul : ∀ (x y : β), f (x * y) = f x * f y neg : ∀ (x : β), f (-x) = -f x sub : ∀ (x y : β), f (x - y) = f x - f y nsmul : ∀ (x : β) (n : ℕ), f (n • x) = n • f x zsmul : ∀ (x : β) (n : ℤ), f (n • x) = n • f x npow : ∀ (x : β) (n : ℕ), f (x ^ n) = f x ^ n nat_cast : ∀ (n : ℕ), f ↑n = ↑n int_cast : ∀ (n : ℤ), f ↑n = ↑n src✝¹ : OrderedSemiring β := Injective.orderedSemiring f hf zero one add mul nsmul npow nat_cast src✝ : Ring β := Injective.ring f hf zero one add mul neg sub nsmul zsmul npow nat_cast int_cast a b : β ha : 0 ≤ a hb : 0 ≤ b ⊢ 0 ≤ f b [PROOFSTEP] rwa [← zero] [GOAL] α : Type u β : Type u_1 inst✝⁷ : StrictOrderedSemiring α inst✝⁶ : Zero β inst✝⁵ : One β inst✝⁴ : Add β inst✝³ : Mul β inst✝² : Pow β ℕ inst✝¹ : SMul ℕ β inst✝ : NatCast β f : β → α hf : Injective f zero : f 0 = 0 one : f 1 = 1 add : ∀ (x y : β), f (x + y) = f x + f y mul : ∀ (x y : β), f (x * y) = f x * f y nsmul : ∀ (x : β) (n : ℕ), f (n • x) = n • f x npow : ∀ (x : β) (n : ℕ), f (x ^ n) = f x ^ n nat_cast : ∀ (n : ℕ), f ↑n = ↑n src✝² : OrderedCancelAddCommMonoid β := orderedCancelAddCommMonoid f hf zero add nsmul src✝¹ : OrderedSemiring β := Injective.orderedSemiring f hf zero one add mul nsmul npow nat_cast src✝ : Nontrivial β := pullback_nonzero f zero one a b c : β h : a < b hc : 0 < c ⊢ f (c * a) < f (c * b) [PROOFSTEP] simpa only [mul, zero] using mul_lt_mul_of_pos_left ‹f a < f b› (by rwa [← zero]) [GOAL] α : Type u β : Type u_1 inst✝⁷ : StrictOrderedSemiring α inst✝⁶ : Zero β inst✝⁵ : One β inst✝⁴ : Add β inst✝³ : Mul β inst✝² : Pow β ℕ inst✝¹ : SMul ℕ β inst✝ : NatCast β f : β → α hf : Injective f zero : f 0 = 0 one : f 1 = 1 add : ∀ (x y : β), f (x + y) = f x + f y mul : ∀ (x y : β), f (x * y) = f x * f y nsmul : ∀ (x : β) (n : ℕ), f (n • x) = n • f x npow : ∀ (x : β) (n : ℕ), f (x ^ n) = f x ^ n nat_cast : ∀ (n : ℕ), f ↑n = ↑n src✝² : OrderedCancelAddCommMonoid β := orderedCancelAddCommMonoid f hf zero add nsmul src✝¹ : OrderedSemiring β := Injective.orderedSemiring f hf zero one add mul nsmul npow nat_cast src✝ : Nontrivial β := pullback_nonzero f zero one a b c : β h : a < b hc : 0 < c ⊢ 0 < f c [PROOFSTEP] rwa [← zero] [GOAL] α : Type u β : Type u_1 inst✝⁷ : StrictOrderedSemiring α inst✝⁶ : Zero β inst✝⁵ : One β inst✝⁴ : Add β inst✝³ : Mul β inst✝² : Pow β ℕ inst✝¹ : SMul ℕ β inst✝ : NatCast β f : β → α hf : Injective f zero : f 0 = 0 one : f 1 = 1 add : ∀ (x y : β), f (x + y) = f x + f y mul : ∀ (x y : β), f (x * y) = f x * f y nsmul : ∀ (x : β) (n : ℕ), f (n • x) = n • f x npow : ∀ (x : β) (n : ℕ), f (x ^ n) = f x ^ n nat_cast : ∀ (n : ℕ), f ↑n = ↑n src✝² : OrderedCancelAddCommMonoid β := orderedCancelAddCommMonoid f hf zero add nsmul src✝¹ : OrderedSemiring β := Injective.orderedSemiring f hf zero one add mul nsmul npow nat_cast src✝ : Nontrivial β := pullback_nonzero f zero one a b c : β h : a < b hc : 0 < c ⊢ f (a * c) < f (b * c) [PROOFSTEP] simpa only [mul, zero] using mul_lt_mul_of_pos_right ‹f a < f b› (by rwa [← zero]) [GOAL] α : Type u β : Type u_1 inst✝⁷ : StrictOrderedSemiring α inst✝⁶ : Zero β inst✝⁵ : One β inst✝⁴ : Add β inst✝³ : Mul β inst✝² : Pow β ℕ inst✝¹ : SMul ℕ β inst✝ : NatCast β f : β → α hf : Injective f zero : f 0 = 0 one : f 1 = 1 add : ∀ (x y : β), f (x + y) = f x + f y mul : ∀ (x y : β), f (x * y) = f x * f y nsmul : ∀ (x : β) (n : ℕ), f (n • x) = n • f x npow : ∀ (x : β) (n : ℕ), f (x ^ n) = f x ^ n nat_cast : ∀ (n : ℕ), f ↑n = ↑n src✝² : OrderedCancelAddCommMonoid β := orderedCancelAddCommMonoid f hf zero add nsmul src✝¹ : OrderedSemiring β := Injective.orderedSemiring f hf zero one add mul nsmul npow nat_cast src✝ : Nontrivial β := pullback_nonzero f zero one a b c : β h : a < b hc : 0 < c ⊢ 0 < f c [PROOFSTEP] rwa [← zero] [GOAL] α : Type u β : Type u_1 inst✝¹¹ : StrictOrderedRing α inst✝¹⁰ : Zero β inst✝⁹ : One β inst✝⁸ : Add β inst✝⁷ : Mul β inst✝⁶ : Neg β inst✝⁵ : Sub β inst✝⁴ : SMul ℕ β inst✝³ : SMul ℤ β inst✝² : Pow β ℕ inst✝¹ : NatCast β inst✝ : IntCast β f : β → α hf : Injective f zero : f 0 = 0 one : f 1 = 1 add : ∀ (x y : β), f (x + y) = f x + f y mul : ∀ (x y : β), f (x * y) = f x * f y neg : ∀ (x : β), f (-x) = -f x sub : ∀ (x y : β), f (x - y) = f x - f y nsmul : ∀ (x : β) (n : ℕ), f (n • x) = n • f x zsmul : ∀ (x : β) (n : ℤ), f (n • x) = n • f x npow : ∀ (x : β) (n : ℕ), f (x ^ n) = f x ^ n nat_cast : ∀ (n : ℕ), f ↑n = ↑n int_cast : ∀ (n : ℤ), f ↑n = ↑n src✝¹ : StrictOrderedSemiring β := Injective.strictOrderedSemiring f hf zero one add mul nsmul npow nat_cast src✝ : Ring β := Injective.ring f hf zero one add mul neg sub nsmul zsmul npow nat_cast int_cast a b : β a0 : 0 < a b0 : 0 < b ⊢ f 0 < f (a * b) [PROOFSTEP] rw [zero, mul] [GOAL] α : Type u β : Type u_1 inst✝¹¹ : StrictOrderedRing α inst✝¹⁰ : Zero β inst✝⁹ : One β inst✝⁸ : Add β inst✝⁷ : Mul β inst✝⁶ : Neg β inst✝⁵ : Sub β inst✝⁴ : SMul ℕ β inst✝³ : SMul ℤ β inst✝² : Pow β ℕ inst✝¹ : NatCast β inst✝ : IntCast β f : β → α hf : Injective f zero : f 0 = 0 one : f 1 = 1 add : ∀ (x y : β), f (x + y) = f x + f y mul : ∀ (x y : β), f (x * y) = f x * f y neg : ∀ (x : β), f (-x) = -f x sub : ∀ (x y : β), f (x - y) = f x - f y nsmul : ∀ (x : β) (n : ℕ), f (n • x) = n • f x zsmul : ∀ (x : β) (n : ℤ), f (n • x) = n • f x npow : ∀ (x : β) (n : ℕ), f (x ^ n) = f x ^ n nat_cast : ∀ (n : ℕ), f ↑n = ↑n int_cast : ∀ (n : ℤ), f ↑n = ↑n src✝¹ : StrictOrderedSemiring β := Injective.strictOrderedSemiring f hf zero one add mul nsmul npow nat_cast src✝ : Ring β := Injective.ring f hf zero one add mul neg sub nsmul zsmul npow nat_cast int_cast a b : β a0 : 0 < a b0 : 0 < b ⊢ 0 < f a * f b [PROOFSTEP] apply mul_pos [GOAL] case ha α : Type u β : Type u_1 inst✝¹¹ : StrictOrderedRing α inst✝¹⁰ : Zero β inst✝⁹ : One β inst✝⁸ : Add β inst✝⁷ : Mul β inst✝⁶ : Neg β inst✝⁵ : Sub β inst✝⁴ : SMul ℕ β inst✝³ : SMul ℤ β inst✝² : Pow β ℕ inst✝¹ : NatCast β inst✝ : IntCast β f : β → α hf : Injective f zero : f 0 = 0 one : f 1 = 1 add : ∀ (x y : β), f (x + y) = f x + f y mul : ∀ (x y : β), f (x * y) = f x * f y neg : ∀ (x : β), f (-x) = -f x sub : ∀ (x y : β), f (x - y) = f x - f y nsmul : ∀ (x : β) (n : ℕ), f (n • x) = n • f x zsmul : ∀ (x : β) (n : ℤ), f (n • x) = n • f x npow : ∀ (x : β) (n : ℕ), f (x ^ n) = f x ^ n nat_cast : ∀ (n : ℕ), f ↑n = ↑n int_cast : ∀ (n : ℤ), f ↑n = ↑n src✝¹ : StrictOrderedSemiring β := Injective.strictOrderedSemiring f hf zero one add mul nsmul npow nat_cast src✝ : Ring β := Injective.ring f hf zero one add mul neg sub nsmul zsmul npow nat_cast int_cast a b : β a0 : 0 < a b0 : 0 < b ⊢ 0 < f a [PROOFSTEP] rwa [← zero] [GOAL] case hb α : Type u β : Type u_1 inst✝¹¹ : StrictOrderedRing α inst✝¹⁰ : Zero β inst✝⁹ : One β inst✝⁸ : Add β inst✝⁷ : Mul β inst✝⁶ : Neg β inst✝⁵ : Sub β inst✝⁴ : SMul ℕ β inst✝³ : SMul ℤ β inst✝² : Pow β ℕ inst✝¹ : NatCast β inst✝ : IntCast β f : β → α hf : Injective f zero : f 0 = 0 one : f 1 = 1 add : ∀ (x y : β), f (x + y) = f x + f y mul : ∀ (x y : β), f (x * y) = f x * f y neg : ∀ (x : β), f (-x) = -f x sub : ∀ (x y : β), f (x - y) = f x - f y nsmul : ∀ (x : β) (n : ℕ), f (n • x) = n • f x zsmul : ∀ (x : β) (n : ℤ), f (n • x) = n • f x npow : ∀ (x : β) (n : ℕ), f (x ^ n) = f x ^ n nat_cast : ∀ (n : ℕ), f ↑n = ↑n int_cast : ∀ (n : ℤ), f ↑n = ↑n src✝¹ : StrictOrderedSemiring β := Injective.strictOrderedSemiring f hf zero one add mul nsmul npow nat_cast src✝ : Ring β := Injective.ring f hf zero one add mul neg sub nsmul zsmul npow nat_cast int_cast a b : β a0 : 0 < a b0 : 0 < b ⊢ 0 < f b [PROOFSTEP] rwa [← zero]
-- import solutions to level 1 import complex.kb_solutions.I /-! # Level 2: Complex conjugation -/ namespace complex -- First complete the definition using `complex.mk` or `⟨x, y⟩` notation /-- The complex conjugate of a complex number -/ def conj (z : ℂ) : ℂ := ⟨re(z), -im(z)⟩ -- Now prove how it interacts with everything else /-! ## Real and imaginary parts -/ @[simp] lemma conj_re (z : ℂ) : re(conj z) = re(z) := rfl -- short for "begin refl end" @[simp] lemma conj_im (z : ℂ) : im(conj z) = -im(z) := rfl /-! ## Behaviour with respect to 0, 1 and I -/ @[simp] lemma conj_zero : conj 0 = 0 := by ext; simp -- short for "begin ext; simp end" @[simp] lemma conj_one : conj 1 = 1 := by ext; simp @[simp] lemma conj_I : conj I = -I := by ext; simp @[simp] lemma conj_neg_I : conj (-I) = I := by ext; simp /-! # Behaviour with respect to +, - and * -/ @[simp] lemma conj_add (z w : ℂ) : conj (z + w) = conj z + conj w := by ext; -- check on real and imag parts simp; -- question becomes to check that a+b=b+a for certain real numbers a and b ring -- true because this is obvious in a ring @[simp] lemma conj_neg (z : ℂ) : conj (-z) = -conj z := by ext; -- check on real and imag parts refl -- happens to be true by definition @[simp] lemma conj_mul (z w : ℂ) : conj (z * w) = conj z * conj w := by ext; -- check on real and imag parts simp; -- it's some random statement involving ring theory of the real numbers ring -- solve it /-! # Properties of the `conj` map -/ @[simp] lemma conj_conj (z : ℂ) : conj (conj z) = z := by ext; -- check on real and imag parts simp -- ext had reduced question to -(-x)=x for reals attribute [simp] ext_iff -- cheeky trick to make the next proof work lemma conj_inj {z w : ℂ} : conj z = conj w ↔ z = w := begin simp * at * end @[simp] lemma conj_eq_zero {z : ℂ} : conj z = 0 ↔ z = 0 := begin simp * at * end /-- the ring homomorphism complex conjugation -/ def Conj : ℂ →+* ℂ := { to_fun := conj, map_zero' := conj_zero, map_one' := conj_one, map_add' := conj_add, map_mul' := conj_mul, } open function lemma conj_involutive : involutive conj := conj_conj lemma conj_bijective : bijective conj := conj_involutive.bijective end complex
#ifndef OPENMC_TALLIES_FILTER_TIME_H #define OPENMC_TALLIES_FILTER_TIME_H #include <gsl/gsl-lite.hpp> #include "openmc/tallies/filter.h" #include "openmc/vector.h" namespace openmc { //============================================================================== //! Bins the incident particle time. //============================================================================== class TimeFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors ~TimeFilter() = default; //---------------------------------------------------------------------------- // Methods std::string type() const override { return "time"; } void from_xml(pugi::xml_node node) override; void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; std::string text_label(int bin) const override; //---------------------------------------------------------------------------- // Accessors const vector<double>& bins() const { return bins_; } void set_bins(gsl::span<const double> bins); protected: //---------------------------------------------------------------------------- // Data members vector<double> bins_; }; } // namespace openmc #endif // OPENMC_TALLIES_FILTER_ENERGY_H
theory T185 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) " nitpick[card nat=8,timeout=86400] oops end
module IdrisScript.Date.Types import IdrisScript.Date.Months import IdrisScript.Date.Days %access public export record Year where constructor MkYear unYear : Int implementation Eq Year where year == year' = unYear year == unYear year' record Date where constructor MkDate unDate : Int implementation Eq Date where date == date' = unDate date == unDate date' record Hours where constructor MkHours unHours : Int implementation Eq Hours where hours == hours' = unHours hours == unHours hours' record Minutes where constructor MkMinutes unMinutes : Int implementation Eq Minutes where mins == mins' = unMinutes mins == unMinutes mins' record Seconds where constructor MkSeconds unSeconds : Int implementation Eq Seconds where secs == secs' = unSeconds secs == unSeconds secs' record Milliseconds where constructor MkMilliseconds unMilliseconds : Int implementation Eq Milliseconds where millis == millis' = unMilliseconds millis == unMilliseconds millis'
#ifndef _PCAP_CONTEXT_ #define _PCAP_CONTEXT_ #include <string> #include <boost/smart_ptr/shared_ptr.hpp> #include <boost/cstdint.hpp> #include <context_db/SccpContext.hpp> class PcapContext { boost::uint32_t tid; SccpContext sccp; public: PcapContext(void); PcapContext(boost::uint32_t tid, SccpContext sccp); void setTid(boost::uint32_t tid) ; void setSccpContext(SccpContext sccp); boost::uint32_t getTid(void) const; SccpContext getSccpContext(void) const; std::size_t getHash(void) const; bool operator==( const PcapContext &rhs) const; void print() const; std::string getString() const ; }; typedef boost::shared_ptr<PcapContext> PcapContextPtrType; #endif
-- definitions that are used by the lemmas but not referenced by the a theorem import .definitions2 -- (∀x {call(x)} ⇒ P) ∈ CallQuantifiers structure callquantifier := (x: var) (P: prop) -- s ∈ DStacks := (R, σ, e) | s · (R, σ, let y = f(x) in e) inductive dstack | top : spec → env → exp → dstack | cons : dstack → spec → env → var → var → var → exp → dstack -- (R, σ, e) : dstack instance : has_coe (spec × env × exp) dstack := ⟨λe, dstack.top e.1 e.2.1 e.2.2⟩ -- stack precondition projection def dstack.pre: dstack → spec | (dstack.top R _ _) := R | (dstack.cons _ R _ _ _ _ _) := R lemma sizeof_substack {s: dstack} {R: spec} {σ: env} {f x y: var} {e: exp}: s.sizeof < (dstack.cons s R σ f x y e).sizeof := begin unfold dstack.sizeof, change sizeof s < 1 + sizeof s + sizeof R + sizeof σ + sizeof f + sizeof x + sizeof y + sizeof e, rw[add_assoc], rw[add_assoc], rw[add_assoc], rw[add_assoc], rw[add_assoc], rw[add_assoc], rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, rw[add_comm], rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end -- top-level calls and quantifiers in positive and negative positions mutual inductive prop.has_call_p, prop.has_call_n with prop.has_call_p: calltrigger → prop → Prop | calltrigger {x: term} : prop.has_call_p ⟨x⟩ (prop.call x) | not {P: prop} {c: calltrigger} : prop.has_call_n c P → prop.has_call_p c P.not | and₁ {P₁ P₂: prop} {c: calltrigger} : prop.has_call_p c P₁ → prop.has_call_p c (P₁ ⋀ P₂) | and₂ {P₁ P₂: prop} {c: calltrigger} : prop.has_call_p c P₂ → prop.has_call_p c (P₁ ⋀ P₂) | or₁ {P₁ P₂: prop} {c: calltrigger} : prop.has_call_p c P₁ → prop.has_call_p c (P₁ ⋁ P₂) | or₂ {P₁ P₂: prop} {c: calltrigger} : prop.has_call_p c P₂ → prop.has_call_p c (P₁ ⋁ P₂) with prop.has_call_n: calltrigger → prop → Prop | not {P: prop} {c: calltrigger} : prop.has_call_p c P → prop.has_call_n c P.not | and₁ {P₁ P₂: prop} {c: calltrigger} : prop.has_call_n c P₁ → prop.has_call_n c (P₁ ⋀ P₂) | and₂ {P₁ P₂: prop} {c: calltrigger} : prop.has_call_n c P₂ → prop.has_call_n c (P₁ ⋀ P₂) | or₁ {P₁ P₂: prop} {c: calltrigger} : prop.has_call_n c P₁ → prop.has_call_n c (P₁ ⋁ P₂) | or₂ {P₁ P₂: prop} {c: calltrigger} : prop.has_call_n c P₂ → prop.has_call_n c (P₁ ⋁ P₂) -- sets of calls def calls_p (P: prop): set calltrigger := λc, prop.has_call_p c P def calls_n (P: prop): set calltrigger := λc, prop.has_call_n c P mutual inductive prop.has_quantifier_p, prop.has_quantifier_n with prop.has_quantifier_p: callquantifier → prop → Prop | callquantifier {x: var} {P: prop} : prop.has_quantifier_p ⟨x, P⟩ (prop.forallc x P) | not {P: prop} {q: callquantifier} : prop.has_quantifier_n q P → prop.has_quantifier_p q P.not | and₁ {P₁ P₂: prop} {q: callquantifier} : prop.has_quantifier_p q P₁ → prop.has_quantifier_p q (P₁ ⋀ P₂) | and₂ {P₁ P₂: prop} {q: callquantifier} : prop.has_quantifier_p q P₂ → prop.has_quantifier_p q (P₁ ⋀ P₂) | or₁ {P₁ P₂: prop} {q: callquantifier} : prop.has_quantifier_p q P₁ → prop.has_quantifier_p q (P₁ ⋁ P₂) | or₂ {P₁ P₂: prop} {q: callquantifier} : prop.has_quantifier_p q P₂ → prop.has_quantifier_p q (P₁ ⋁ P₂) with prop.has_quantifier_n: callquantifier → prop → Prop | not {P: prop} {q: callquantifier} : prop.has_quantifier_p q P → prop.has_quantifier_n q P.not | and₁ {P₁ P₂: prop} {q: callquantifier} : prop.has_quantifier_n q P₁ → prop.has_quantifier_n q (P₁ ⋀ P₂) | and₂ {P₁ P₂: prop} {q: callquantifier} : prop.has_quantifier_n q P₂ → prop.has_quantifier_n q (P₁ ⋀ P₂) | or₁ {P₁ P₂: prop} {q: callquantifier} : prop.has_quantifier_n q P₁ → prop.has_quantifier_n q (P₁ ⋁ P₂) | or₂ {P₁ P₂: prop} {q: callquantifier} : prop.has_quantifier_n q P₂ → prop.has_quantifier_n q (P₁ ⋁ P₂) -- universal quantifiers below existential quantifiers only occur in positive positions, -- so can be skolemized instead of instantiated -- sets of quantifiers def quantifiers_p (P: prop): set callquantifier := λc, has_quantifier_p c P def quantifiers_n (P: prop): set callquantifier := λc, has_quantifier_n c P def quantifiers (P: prop): set callquantifier := quantifiers_p P ∪ quantifiers_n P -- propositions without call triggers or quantifiers do not participate in instantiations def no_instantiations(P: prop): Prop := (calls_p P = ∅) ∧ (calls_n P = ∅) ∧ (quantifiers_p P = ∅) ∧ (quantifiers_n P = ∅) -- set of calltriggers after substitution def calltrigger.subst (σ: env) (c: calltrigger): calltrigger := ⟨term.subst_env σ c.x⟩ def calls_p_subst (σ: env) (P: prop): set calltrigger := (calltrigger.subst σ) '' calls_p P def calls_n_subst (σ: env) (P: prop): set calltrigger := (calltrigger.subst σ) '' calls_n P -- uses variables (either free or quantified) inductive prop.uses_var (x: var) : prop → Prop | term {t: term} : free_in_term x t → prop.uses_var t | not {P: prop} : prop.uses_var P → prop.uses_var (prop.not P) | and₁ {P₁ P₂: prop} : prop.uses_var P₁ → prop.uses_var (prop.and P₁ P₂) | and₂ {P₁ P₂: prop} : prop.uses_var P₂ → prop.uses_var (prop.and P₁ P₂) | or₁ {P₁ P₂: prop} : prop.uses_var P₁ → prop.uses_var (prop.or P₁ P₂) | or₂ {P₁ P₂: prop} : prop.uses_var P₂ → prop.uses_var (prop.or P₁ P₂) | pre₁ {t₁ t₂: term} : free_in_term x t₁ → prop.uses_var (prop.pre t₁ t₂) | pre₂ {t₁ t₂: term} : free_in_term x t₂ → prop.uses_var (prop.pre t₁ t₂) | preop {t: term} {op: unop} : free_in_term x t → prop.uses_var (prop.pre₁ op t) | preop₁ {t₁ t₂: term} {op: binop} : free_in_term x t₁ → prop.uses_var (prop.pre₂ op t₁ t₂) | preop₂ {t₁ t₂: term} {op: binop} : free_in_term x t₂ → prop.uses_var (prop.pre₂ op t₁ t₂) | post₁ {t₁ t₂: term} : free_in_term x t₁ → prop.uses_var (prop.post t₁ t₂) | post₂ {t₁ t₂: term} : free_in_term x t₂ → prop.uses_var (prop.post t₁ t₂) | call {t: term} : free_in_term x t → prop.uses_var (prop.call t) | forallc {y: var} {P: prop} : prop.uses_var P → prop.uses_var (prop.forallc y P) | uquantified {P: prop} : prop.uses_var (prop.forallc x P) | exis {y: var} {P: prop} : prop.uses_var P → prop.uses_var (prop.exis y P) | equantified {P: prop} : prop.uses_var (prop.exis x P) inductive vc.uses_var (x: var) : vc → Prop | term {t: term} : free_in_term x t → vc.uses_var t | not {P: vc} : vc.uses_var P → vc.uses_var (vc.not P) | and₁ {P₁ P₂: vc} : vc.uses_var P₁ → vc.uses_var (vc.and P₁ P₂) | and₂ {P₁ P₂: vc} : vc.uses_var P₂ → vc.uses_var (vc.and P₁ P₂) | or₁ {P₁ P₂: vc} : vc.uses_var P₁ → vc.uses_var (vc.or P₁ P₂) | or₂ {P₁ P₂: vc} : vc.uses_var P₂ → vc.uses_var (vc.or P₁ P₂) | pre₁ {t₁ t₂: term} : free_in_term x t₁ → vc.uses_var (vc.pre t₁ t₂) | pre₂ {t₁ t₂: term} : free_in_term x t₂ → vc.uses_var (vc.pre t₁ t₂) | preop {t: term} {op: unop} : free_in_term x t → vc.uses_var (vc.pre₁ op t) | preop₁ {t₁ t₂: term} {op: binop} : free_in_term x t₁ → vc.uses_var (vc.pre₂ op t₁ t₂) | preop₂ {t₁ t₂: term} {op: binop} : free_in_term x t₂ → vc.uses_var (vc.pre₂ op t₁ t₂) | post₁ {t₁ t₂: term} : free_in_term x t₁ → vc.uses_var (vc.post t₁ t₂) | post₂ {t₁ t₂: term} : free_in_term x t₂ → vc.uses_var (vc.post t₁ t₂) | univ {y: var} {P: vc} : vc.uses_var P → vc.uses_var (vc.univ y P) | quantified {P: vc} : vc.uses_var (vc.univ x P) -- evaluation relation that includes the current function precondition for each stack frame inductive dstep : dstack → dstack → Prop notation s₁ `⟹` s₂:100 := dstep s₁ s₂ | ctx {s s': dstack} {R: spec} {σ: env} {y f x: var} {e: exp}: (s ⟹ s') → (dstack.cons s R σ y f x e ⟹ dstack.cons s' R σ y f x e) | tru {R: spec} {σ: env} {x: var} {e: exp}: (R, σ, lett x = true in e) ⟹ (R, σ[x↦value.true], e) | fals {R: spec} {σ: env} {x: var} {e: exp}: (R, σ, letf x = false in e) ⟹ (R, σ[x↦value.false], e) | num {R: spec} {σ: env} {x: var} {e: exp} {n: ℤ}: (R, σ, letn x = n in e) ⟹ (R, σ[x↦value.num n], e) | closure {σ: env} {R' R S: spec} {f x: var} {e₁ e₂: exp}: (R', σ, letf f[x] req R ens S {e₁} in e₂) ⟹ (R', σ[f↦value.func f x R S e₁ σ], e₂) | unop {R: spec} {op: unop} {σ: env} {x y: var} {e: exp} {v₁ v: value}: (σ x = v₁) → (unop.apply op v₁ = v) → ((R, σ, letop y = op [x] in e) ⟹ (R, σ[y↦v], e)) | binop {R: spec} {op: binop} {σ: env} {x y z: var} {e: exp} {v₁ v₂ v: value}: (σ x = v₁) → (σ y = v₂) → (binop.apply op v₁ v₂ = v) → ((R, σ, letop2 z = op [x, y] in e) ⟹ (R, σ[z↦v], e)) | app {σ σ': env} {R' R S: spec} {f g x y z: var} {e e': exp} {v: value}: (σ f = value.func g z R S e σ') → (σ x = v) → ((R', σ, letapp y = f[x] in e') ⟹ (dstack.cons (R, (σ'[g↦value.func g z R S e σ'][z↦v]), e) R' σ y f x e')) | return {σ₁ σ₂ σ₃: env} {f g gx x y z: var} {R₁ R₂ R S: spec} {e e': exp} {v vₓ: value}: (σ₁ z = v) → (σ₂ f = value.func g gx R S e σ₃) → (σ₂ x = vₓ) → (dstack.cons (R₁, σ₁, exp.return z) R₂ σ₂ y f x e' ⟹ (R₂, σ₂[y↦v], e')) | ite_true {R: spec} {σ: env} {e₁ e₂: exp} {x: var}: (σ x = value.true) → ((R, σ, exp.ite x e₁ e₂) ⟹ (R, σ, e₁)) | ite_false {R: spec} {σ: env} {e₁ e₂: exp} {x: var}: (σ x = value.false) → ((R, σ, exp.ite x e₁ e₂) ⟹ (R, σ, e₂)) notation s₁ `⟹` s₂:100 := dstep s₁ s₂ -- transitive closure inductive trans_dstep : dstack → dstack → Prop notation s `⟹*` s':100 := trans_dstep s s' | rfl {s: dstack} : s ⟹* s | trans {s s' s'': dstack} : (s ⟹* s') → (s' ⟹ s'') → (s ⟹* s'') notation s `⟹*` s':100 := trans_dstep s s' def is_dvalue (s: dstack) := ∃(R: spec) (σ: env) (x: var) (v: value), s = (R, σ, exp.return x) ∧ (σ x = v) -- runtime verification of stacks inductive stack.dvcgen : dstack → propctx → Prop notation `⊩ₛ` s `:` Q : 10 := stack.dvcgen s Q | top {R: spec} {P: prop} {σ: env} {e: exp} {Q: propctx}: (⊩ σ : P) → FV R.to_prop ⊆ FV P → (σ ⊨ R.to_prop.to_vc) → (R ⋀ P ⊩ e : Q) → (⊩ₛ (R, σ, e) : P ⋀ Q) | cons {P₁ P₂ P₃: prop} {s: dstack} {σ₁ σ₂: env} {f fx g x y: var} {R₁ R₂ S₂: spec} {e₁ e₂: exp} {v: value} {Q₁ Q₂ Q₂': propctx}: (⊩ₛ s : Q₂') → y ∉ σ₁ → (⊩ σ₁ : P₁) → (⊩ σ₂ : P₂ ) → (⊩ (σ₂[f↦value.func f fx R₂ S₂ e₂ σ₂][fx↦v]) : P₃) → FV R₁.to_prop ⊆ FV P₁ → (σ₁ ⊨ R₁.to_prop.to_vc) → (σ₁ g = value.func f fx R₂ S₂ e₂ σ₂) → (σ₁ x = v) → (R₁ ⋀ P₁ ⋀ prop.call x ⋀ prop.post g x ⋀ y ≡ term.app g x ⊩ e₁ : Q₁) → (P₂ ⋀ spec.func f fx R₂ S₂ ⋀ R₂ ⊩ e₂ : Q₂) → (∀σ' t, (σ' ⊨ (Q₂' t).to_vc) → σ' ⊨ (P₃ ⋀ (Q₂ t)).to_vc) → (∀v: value, FV (P₃ ⋀ (Q₂ v)) ⊆ FV (Q₂' v)) → ⦃ prop.implies (R₁ ⋀ P₁ ⋀ prop.call x) (term.unop unop.isFunc g ⋀ prop.pre g x) ⦄ → ((R₂, σ₂[f↦value.func f fx R₂ S₂ e₂ σ₂][fx↦v], e₂) ⟹* s) → (⊩ₛ dstack.cons s R₁ σ₁ y g x e₁ : P₁ ⋀ propctx.exis y (prop.call x ⋀ prop.post g x ⋀ y ≡ term.app g x ⋀ Q₁)) notation `⊩ₛ` s `:` Q : 10 := stack.dvcgen s Q inductive stack_equiv_dstack : stack → dstack → Prop | top {R: spec} {σ: env} {e: exp} : stack_equiv_dstack (stack.top σ e) (dstack.top R σ e) | cons {s': stack} {d': dstack} {R: spec} {σ: env} {f x y: var} {e: exp}: stack_equiv_dstack s' d' → stack_equiv_dstack (stack.cons s' σ f x y e) (dstack.cons d' R σ f x y e)
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import measure_theory.decomposition.signed_hahn import measure_theory.measure.mutually_singular /-! # Jordan decomposition This file proves the existence and uniqueness of the Jordan decomposition for signed measures. The Jordan decomposition theorem states that, given a signed measure `s`, there exists a unique pair of mutually singular measures `μ` and `ν`, such that `s = μ - ν`. The Jordan decomposition theorem for measures is a corollary of the Hahn decomposition theorem and is useful for the Lebesgue decomposition theorem. ## Main definitions * `measure_theory.jordan_decomposition`: a Jordan decomposition of a measurable space is a pair of mutually singular finite measures. We say `j` is a Jordan decomposition of a signed measure `s` if `s = j.pos_part - j.neg_part`. * `measure_theory.signed_measure.to_jordan_decomposition`: the Jordan decomposition of a signed measure. * `measure_theory.signed_measure.to_jordan_decomposition_equiv`: is the `equiv` between `measure_theory.signed_measure` and `measure_theory.jordan_decomposition` formed by `measure_theory.signed_measure.to_jordan_decomposition`. ## Main results * `measure_theory.signed_measure.to_signed_measure_to_jordan_decomposition` : the Jordan decomposition theorem. * `measure_theory.jordan_decomposition.to_signed_measure_injective` : the Jordan decomposition of a signed measure is unique. ## Tags Jordan decomposition theorem -/ noncomputable theory open_locale classical measure_theory ennreal nnreal variables {α β : Type*} [measurable_space α] namespace measure_theory /-- A Jordan decomposition of a measurable space is a pair of mutually singular, finite measures. -/ @[ext] structure jordan_decomposition (α : Type*) [measurable_space α] := (pos_part neg_part : measure α) [pos_part_finite : is_finite_measure pos_part] [neg_part_finite : is_finite_measure neg_part] (mutually_singular : pos_part ⟂ₘ neg_part) attribute [instance] jordan_decomposition.pos_part_finite attribute [instance] jordan_decomposition.neg_part_finite namespace jordan_decomposition open measure vector_measure variable (j : jordan_decomposition α) instance : has_zero (jordan_decomposition α) := { zero := ⟨0, 0, mutually_singular.zero_right⟩ } instance : inhabited (jordan_decomposition α) := { default := 0 } instance : has_involutive_neg (jordan_decomposition α) := { neg := λ j, ⟨j.neg_part, j.pos_part, j.mutually_singular.symm⟩, neg_neg := λ j, jordan_decomposition.ext _ _ rfl rfl } instance : has_smul ℝ≥0 (jordan_decomposition α) := { smul := λ r j, ⟨r • j.pos_part, r • j.neg_part, mutually_singular.smul _ (mutually_singular.smul _ j.mutually_singular.symm).symm⟩ } instance has_smul_real : has_smul ℝ (jordan_decomposition α) := { smul := λ r j, if hr : 0 ≤ r then r.to_nnreal • j else - ((-r).to_nnreal • j) } @[simp] lemma zero_pos_part : (0 : jordan_decomposition α).pos_part = 0 := rfl @[simp] lemma zero_neg_part : (0 : jordan_decomposition α).neg_part = 0 := rfl @[simp] lemma neg_pos_part : (-j).pos_part = j.neg_part := rfl @[simp] lemma neg_neg_part : (-j).neg_part = j.pos_part := rfl @[simp] lemma smul_pos_part (r : ℝ≥0) : (r • j).pos_part = r • j.pos_part := rfl @[simp] lemma smul_neg_part (r : ℝ≥0) : (r • j).neg_part = r • j.neg_part := rfl lemma real_smul_def (r : ℝ) (j : jordan_decomposition α) : r • j = if hr : 0 ≤ r then r.to_nnreal • j else - ((-r).to_nnreal • j) := rfl @[simp] lemma coe_smul (r : ℝ≥0) : (r : ℝ) • j = r • j := show dite _ _ _ = _, by rw [dif_pos (nnreal.coe_nonneg r), real.to_nnreal_coe] lemma real_smul_nonneg (r : ℝ) (hr : 0 ≤ r) : r • j = r.to_nnreal • j := dif_pos hr lemma real_smul_neg (r : ℝ) (hr : r < 0) : r • j = - ((-r).to_nnreal • j) := dif_neg (not_le.2 hr) lemma real_smul_neg_part_nonneg (r : ℝ) (hr : 0 ≤ r) : (r • j).neg_part = r.to_nnreal • j.neg_part := by { rw [real_smul_def, ← smul_neg_part, dif_pos hr] } lemma real_smul_pos_part_neg (r : ℝ) (hr : r < 0) : (r • j).pos_part = (-r).to_nnreal • j.neg_part := by { rw [real_smul_def, ← smul_neg_part, dif_neg (not_le.2 hr), neg_pos_part] } lemma real_smul_neg_part_neg (r : ℝ) (hr : r < 0) : (r • j).neg_part = (-r).to_nnreal • j.pos_part := by { rw [real_smul_def, ← smul_pos_part, dif_neg (not_le.2 hr), neg_neg_part] } /-- The signed measure associated with a Jordan decomposition. -/ def to_signed_measure : signed_measure α := j.pos_part.to_signed_measure - j.neg_part.to_signed_measure lemma to_signed_measure_zero : (0 : jordan_decomposition α).to_signed_measure = 0 := begin ext1 i hi, erw [to_signed_measure, to_signed_measure_sub_apply hi, sub_self, zero_apply], end lemma to_signed_measure_neg : (-j).to_signed_measure = -j.to_signed_measure := begin ext1 i hi, rw [neg_apply, to_signed_measure, to_signed_measure, to_signed_measure_sub_apply hi, to_signed_measure_sub_apply hi, neg_sub], refl, end lemma to_signed_measure_smul (r : ℝ≥0) : (r • j).to_signed_measure = r • j.to_signed_measure := begin ext1 i hi, rw [vector_measure.smul_apply, to_signed_measure, to_signed_measure, to_signed_measure_sub_apply hi, to_signed_measure_sub_apply hi, smul_sub, smul_pos_part, smul_neg_part, ← ennreal.to_real_smul, ← ennreal.to_real_smul], refl end /-- A Jordan decomposition provides a Hahn decomposition. -/ lemma exists_compl_positive_negative : ∃ S : set α, measurable_set S ∧ j.to_signed_measure ≤[S] 0 ∧ 0 ≤[Sᶜ] j.to_signed_measure ∧ j.pos_part S = 0 ∧ j.neg_part Sᶜ = 0 := begin obtain ⟨S, hS₁, hS₂, hS₃⟩ := j.mutually_singular, refine ⟨S, hS₁, _, _, hS₂, hS₃⟩, { refine restrict_le_restrict_of_subset_le _ _ (λ A hA hA₁, _), rw [to_signed_measure, to_signed_measure_sub_apply hA, show j.pos_part A = 0, by exact nonpos_iff_eq_zero.1 (hS₂ ▸ measure_mono hA₁), ennreal.zero_to_real, zero_sub, neg_le, zero_apply, neg_zero], exact ennreal.to_real_nonneg }, { refine restrict_le_restrict_of_subset_le _ _ (λ A hA hA₁, _), rw [to_signed_measure, to_signed_measure_sub_apply hA, show j.neg_part A = 0, by exact nonpos_iff_eq_zero.1 (hS₃ ▸ measure_mono hA₁), ennreal.zero_to_real, sub_zero], exact ennreal.to_real_nonneg }, end end jordan_decomposition namespace signed_measure open classical jordan_decomposition measure set vector_measure variables {s : signed_measure α} {μ ν : measure α} [is_finite_measure μ] [is_finite_measure ν] /-- Given a signed measure `s`, `s.to_jordan_decomposition` is the Jordan decomposition `j`, such that `s = j.to_signed_measure`. This property is known as the Jordan decomposition theorem, and is shown by `measure_theory.signed_measure.to_signed_measure_to_jordan_decomposition`. -/ def to_jordan_decomposition (s : signed_measure α) : jordan_decomposition α := let i := some s.exists_compl_positive_negative in let hi := some_spec s.exists_compl_positive_negative in { pos_part := s.to_measure_of_zero_le i hi.1 hi.2.1, neg_part := s.to_measure_of_le_zero iᶜ hi.1.compl hi.2.2, pos_part_finite := infer_instance, neg_part_finite := infer_instance, mutually_singular := begin refine ⟨iᶜ, hi.1.compl, _, _⟩, { rw [to_measure_of_zero_le_apply _ _ hi.1 hi.1.compl], simp }, { rw [to_measure_of_le_zero_apply _ _ hi.1.compl hi.1.compl.compl], simp } end } lemma to_jordan_decomposition_spec (s : signed_measure α) : ∃ (i : set α) (hi₁ : measurable_set i) (hi₂ : 0 ≤[i] s) (hi₃ : s ≤[iᶜ] 0), s.to_jordan_decomposition.pos_part = s.to_measure_of_zero_le i hi₁ hi₂ ∧ s.to_jordan_decomposition.neg_part = s.to_measure_of_le_zero iᶜ hi₁.compl hi₃ := begin set i := some s.exists_compl_positive_negative, obtain ⟨hi₁, hi₂, hi₃⟩ := some_spec s.exists_compl_positive_negative, exact ⟨i, hi₁, hi₂, hi₃, rfl, rfl⟩, end /-- **The Jordan decomposition theorem**: Given a signed measure `s`, there exists a pair of mutually singular measures `μ` and `ν` such that `s = μ - ν`. In this case, the measures `μ` and `ν` are given by `s.to_jordan_decomposition.pos_part` and `s.to_jordan_decomposition.neg_part` respectively. Note that we use `measure_theory.jordan_decomposition.to_signed_measure` to represent the signed measure corresponding to `s.to_jordan_decomposition.pos_part - s.to_jordan_decomposition.neg_part`. -/ @[simp] lemma to_signed_measure_to_jordan_decomposition (s : signed_measure α) : s.to_jordan_decomposition.to_signed_measure = s := begin obtain ⟨i, hi₁, hi₂, hi₃, hμ, hν⟩ := s.to_jordan_decomposition_spec, simp only [jordan_decomposition.to_signed_measure, hμ, hν], ext k hk, rw [to_signed_measure_sub_apply hk, to_measure_of_zero_le_apply _ hi₂ hi₁ hk, to_measure_of_le_zero_apply _ hi₃ hi₁.compl hk], simp only [ennreal.coe_to_real, subtype.coe_mk, ennreal.some_eq_coe, sub_neg_eq_add], rw [← of_union _ (measurable_set.inter hi₁ hk) (measurable_set.inter hi₁.compl hk), set.inter_comm i, set.inter_comm iᶜ, set.inter_union_compl _ _], { apply_instance }, { exact (disjoint_compl_right.inf_left _).inf_right _ } end section variables {u v w : set α} /-- A subset `v` of a null-set `w` has zero measure if `w` is a subset of a positive set `u`. -/ lemma subset_positive_null_set (hu : measurable_set u) (hv : measurable_set v) (hw : measurable_set w) (hsu : 0 ≤[u] s) (hw₁ : s w = 0) (hw₂ : w ⊆ u) (hwt : v ⊆ w) : s v = 0 := begin have : s v + s (w \ v) = 0, { rw [← hw₁, ← of_union set.disjoint_sdiff_right hv (hw.diff hv), set.union_diff_self, set.union_eq_self_of_subset_left hwt], apply_instance }, have h₁ := nonneg_of_zero_le_restrict _ (restrict_le_restrict_subset _ _ hu hsu (hwt.trans hw₂)), have h₂ := nonneg_of_zero_le_restrict _ (restrict_le_restrict_subset _ _ hu hsu ((w.diff_subset v).trans hw₂)), linarith, end /-- A subset `v` of a null-set `w` has zero measure if `w` is a subset of a negative set `u`. -/ lemma subset_negative_null_set (hu : measurable_set u) (hv : measurable_set v) (hw : measurable_set w) (hsu : s ≤[u] 0) (hw₁ : s w = 0) (hw₂ : w ⊆ u) (hwt : v ⊆ w) : s v = 0 := begin rw [← s.neg_le_neg_iff _ hu, neg_zero] at hsu, have := subset_positive_null_set hu hv hw hsu, simp only [pi.neg_apply, neg_eq_zero, coe_neg] at this, exact this hw₁ hw₂ hwt, end /-- If the symmetric difference of two positive sets is a null-set, then so are the differences between the two sets. -/ lemma of_diff_eq_zero_of_symm_diff_eq_zero_positive (hu : measurable_set u) (hv : measurable_set v) (hsu : 0 ≤[u] s) (hsv : 0 ≤[v] s) (hs : s (u ∆ v) = 0) : s (u \ v) = 0 ∧ s (v \ u) = 0 := begin rw restrict_le_restrict_iff at hsu hsv, have a := hsu (hu.diff hv) (u.diff_subset v), have b := hsv (hv.diff hu) (v.diff_subset u), erw [of_union (set.disjoint_of_subset_left (u.diff_subset v) disjoint_sdiff_self_right) (hu.diff hv) (hv.diff hu)] at hs, rw zero_apply at a b, split, all_goals { linarith <|> apply_instance <|> assumption }, end /-- If the symmetric difference of two negative sets is a null-set, then so are the differences between the two sets. -/ lemma of_diff_eq_zero_of_symm_diff_eq_zero_negative (hu : measurable_set u) (hv : measurable_set v) (hsu : s ≤[u] 0) (hsv : s ≤[v] 0) (hs : s (u ∆ v) = 0) : s (u \ v) = 0 ∧ s (v \ u) = 0 := begin rw [← s.neg_le_neg_iff _ hu, neg_zero] at hsu, rw [← s.neg_le_neg_iff _ hv, neg_zero] at hsv, have := of_diff_eq_zero_of_symm_diff_eq_zero_positive hu hv hsu hsv, simp only [pi.neg_apply, neg_eq_zero, coe_neg] at this, exact this hs, end lemma of_inter_eq_of_symm_diff_eq_zero_positive (hu : measurable_set u) (hv : measurable_set v) (hw : measurable_set w) (hsu : 0 ≤[u] s) (hsv : 0 ≤[v] s) (hs : s (u ∆ v) = 0) : s (w ∩ u) = s (w ∩ v) := begin have hwuv : s ((w ∩ u) ∆ (w ∩ v)) = 0, { refine subset_positive_null_set (hu.union hv) ((hw.inter hu).symm_diff (hw.inter hv)) (hu.symm_diff hv) (restrict_le_restrict_union _ _ hu hsu hv hsv) hs symm_diff_subset_union _, rw ←inter_symm_diff_distrib_left, exact inter_subset_right _ _ }, obtain ⟨huv, hvu⟩ := of_diff_eq_zero_of_symm_diff_eq_zero_positive (hw.inter hu) (hw.inter hv) (restrict_le_restrict_subset _ _ hu hsu (w.inter_subset_right u)) (restrict_le_restrict_subset _ _ hv hsv (w.inter_subset_right v)) hwuv, rw [← of_diff_of_diff_eq_zero (hw.inter hu) (hw.inter hv) hvu, huv, zero_add] end lemma of_inter_eq_of_symm_diff_eq_zero_negative (hu : measurable_set u) (hv : measurable_set v) (hw : measurable_set w) (hsu : s ≤[u] 0) (hsv : s ≤[v] 0) (hs : s (u ∆ v) = 0) : s (w ∩ u) = s (w ∩ v) := begin rw [← s.neg_le_neg_iff _ hu, neg_zero] at hsu, rw [← s.neg_le_neg_iff _ hv, neg_zero] at hsv, have := of_inter_eq_of_symm_diff_eq_zero_positive hu hv hw hsu hsv, simp only [pi.neg_apply, neg_inj, neg_eq_zero, coe_neg] at this, exact this hs, end end end signed_measure namespace jordan_decomposition open measure vector_measure signed_measure function private lemma eq_of_pos_part_eq_pos_part {j₁ j₂ : jordan_decomposition α} (hj : j₁.pos_part = j₂.pos_part) (hj' : j₁.to_signed_measure = j₂.to_signed_measure) : j₁ = j₂ := begin ext1, { exact hj }, { rw ← to_signed_measure_eq_to_signed_measure_iff, suffices : j₁.pos_part.to_signed_measure - j₁.neg_part.to_signed_measure = j₁.pos_part.to_signed_measure - j₂.neg_part.to_signed_measure, { exact sub_right_inj.mp this }, convert hj' } end /-- The Jordan decomposition of a signed measure is unique. -/ theorem to_signed_measure_injective : injective $ @jordan_decomposition.to_signed_measure α _ := begin /- The main idea is that two Jordan decompositions of a signed measure provide two Hahn decompositions for that measure. Then, from `of_symm_diff_compl_positive_negative`, the symmetric difference of the two Hahn decompositions has measure zero, thus, allowing us to show the equality of the underlying measures of the Jordan decompositions. -/ intros j₁ j₂ hj, -- obtain the two Hahn decompositions from the Jordan decompositions obtain ⟨S, hS₁, hS₂, hS₃, hS₄, hS₅⟩ := j₁.exists_compl_positive_negative, obtain ⟨T, hT₁, hT₂, hT₃, hT₄, hT₅⟩ := j₂.exists_compl_positive_negative, rw ← hj at hT₂ hT₃, -- the symmetric differences of the two Hahn decompositions have measure zero obtain ⟨hST₁, -⟩ := of_symm_diff_compl_positive_negative hS₁.compl hT₁.compl ⟨hS₃, (compl_compl S).symm ▸ hS₂⟩ ⟨hT₃, (compl_compl T).symm ▸ hT₂⟩, -- it suffices to show the Jordan decompositions have the same positive parts refine eq_of_pos_part_eq_pos_part _ hj, ext1 i hi, -- we see that the positive parts of the two Jordan decompositions are equal to their -- associated signed measures restricted on their associated Hahn decompositions have hμ₁ : (j₁.pos_part i).to_real = j₁.to_signed_measure (i ∩ Sᶜ), { rw [to_signed_measure, to_signed_measure_sub_apply (hi.inter hS₁.compl), show j₁.neg_part (i ∩ Sᶜ) = 0, by exact nonpos_iff_eq_zero.1 (hS₅ ▸ measure_mono (set.inter_subset_right _ _)), ennreal.zero_to_real, sub_zero], conv_lhs { rw ← set.inter_union_compl i S }, rw [measure_union, show j₁.pos_part (i ∩ S) = 0, by exact nonpos_iff_eq_zero.1 (hS₄ ▸ measure_mono (set.inter_subset_right _ _)), zero_add], { refine set.disjoint_of_subset_left (set.inter_subset_right _ _) (set.disjoint_of_subset_right (set.inter_subset_right _ _) disjoint_compl_right) }, { exact hi.inter hS₁.compl } }, have hμ₂ : (j₂.pos_part i).to_real = j₂.to_signed_measure (i ∩ Tᶜ), { rw [to_signed_measure, to_signed_measure_sub_apply (hi.inter hT₁.compl), show j₂.neg_part (i ∩ Tᶜ) = 0, by exact nonpos_iff_eq_zero.1 (hT₅ ▸ measure_mono (set.inter_subset_right _ _)), ennreal.zero_to_real, sub_zero], conv_lhs { rw ← set.inter_union_compl i T }, rw [measure_union, show j₂.pos_part (i ∩ T) = 0, by exact nonpos_iff_eq_zero.1 (hT₄ ▸ measure_mono (set.inter_subset_right _ _)), zero_add], { exact set.disjoint_of_subset_left (set.inter_subset_right _ _) (set.disjoint_of_subset_right (set.inter_subset_right _ _) disjoint_compl_right) }, { exact hi.inter hT₁.compl } }, -- since the two signed measures associated with the Jordan decompositions are the same, -- and the symmetric difference of the Hahn decompositions have measure zero, the result follows rw [← ennreal.to_real_eq_to_real (measure_ne_top _ _) (measure_ne_top _ _), hμ₁, hμ₂, ← hj], exact of_inter_eq_of_symm_diff_eq_zero_positive hS₁.compl hT₁.compl hi hS₃ hT₃ hST₁, all_goals { apply_instance }, end @[simp] lemma to_jordan_decomposition_to_signed_measure (j : jordan_decomposition α) : (j.to_signed_measure).to_jordan_decomposition = j := (@to_signed_measure_injective _ _ j (j.to_signed_measure).to_jordan_decomposition (by simp)).symm end jordan_decomposition namespace signed_measure open jordan_decomposition /-- `measure_theory.signed_measure.to_jordan_decomposition` and `measure_theory.jordan_decomposition.to_signed_measure` form a `equiv`. -/ @[simps apply symm_apply] def to_jordan_decomposition_equiv (α : Type*) [measurable_space α] : signed_measure α ≃ jordan_decomposition α := { to_fun := to_jordan_decomposition, inv_fun := to_signed_measure, left_inv := to_signed_measure_to_jordan_decomposition, right_inv := to_jordan_decomposition_to_signed_measure } lemma to_jordan_decomposition_zero : (0 : signed_measure α).to_jordan_decomposition = 0 := begin apply to_signed_measure_injective, simp [to_signed_measure_zero], end lemma to_jordan_decomposition_neg (s : signed_measure α) : (-s).to_jordan_decomposition = -s.to_jordan_decomposition := begin apply to_signed_measure_injective, simp [to_signed_measure_neg], end lemma to_jordan_decomposition_smul (s : signed_measure α) (r : ℝ≥0) : (r • s).to_jordan_decomposition = r • s.to_jordan_decomposition := begin apply to_signed_measure_injective, simp [to_signed_measure_smul], end private lemma to_jordan_decomposition_smul_real_nonneg (s : signed_measure α) (r : ℝ) (hr : 0 ≤ r): (r • s).to_jordan_decomposition = r • s.to_jordan_decomposition := begin lift r to ℝ≥0 using hr, rw [jordan_decomposition.coe_smul, ← to_jordan_decomposition_smul], refl end lemma to_jordan_decomposition_smul_real (s : signed_measure α) (r : ℝ) : (r • s).to_jordan_decomposition = r • s.to_jordan_decomposition := begin by_cases hr : 0 ≤ r, { exact to_jordan_decomposition_smul_real_nonneg s r hr }, { ext1, { rw [real_smul_pos_part_neg _ _ (not_le.1 hr), show r • s = -(-r • s), by rw [neg_smul, neg_neg], to_jordan_decomposition_neg, neg_pos_part, to_jordan_decomposition_smul_real_nonneg, ← smul_neg_part, real_smul_nonneg], all_goals { exact left.nonneg_neg_iff.2 (le_of_lt (not_le.1 hr)) } }, { rw [real_smul_neg_part_neg _ _ (not_le.1 hr), show r • s = -(-r • s), by rw [neg_smul, neg_neg], to_jordan_decomposition_neg, neg_neg_part, to_jordan_decomposition_smul_real_nonneg, ← smul_pos_part, real_smul_nonneg], all_goals { exact left.nonneg_neg_iff.2 (le_of_lt (not_le.1 hr)) } } } end lemma to_jordan_decomposition_eq {s : signed_measure α} {j : jordan_decomposition α} (h : s = j.to_signed_measure) : s.to_jordan_decomposition = j := by rw [h, to_jordan_decomposition_to_signed_measure] /-- The total variation of a signed measure. -/ def total_variation (s : signed_measure α) : measure α := s.to_jordan_decomposition.pos_part + s.to_jordan_decomposition.neg_part lemma total_variation_zero : (0 : signed_measure α).total_variation = 0 := by simp [total_variation, to_jordan_decomposition_zero] lemma total_variation_neg (s : signed_measure α) : (-s).total_variation = s.total_variation := by simp [total_variation, to_jordan_decomposition_neg, add_comm] lemma null_of_total_variation_zero (s : signed_measure α) {i : set α} (hs : s.total_variation i = 0) : s i = 0 := begin rw [total_variation, measure.coe_add, pi.add_apply, add_eq_zero_iff] at hs, rw [← to_signed_measure_to_jordan_decomposition s, to_signed_measure, vector_measure.coe_sub, pi.sub_apply, measure.to_signed_measure_apply, measure.to_signed_measure_apply], by_cases hi : measurable_set i, { rw [if_pos hi, if_pos hi], simp [hs.1, hs.2] }, { simp [if_neg hi] } end lemma absolutely_continuous_ennreal_iff (s : signed_measure α) (μ : vector_measure α ℝ≥0∞) : s ≪ᵥ μ ↔ s.total_variation ≪ μ.ennreal_to_measure := begin split; intro h, { refine measure.absolutely_continuous.mk (λ S hS₁ hS₂, _), obtain ⟨i, hi₁, hi₂, hi₃, hpos, hneg⟩ := s.to_jordan_decomposition_spec, rw [total_variation, measure.add_apply, hpos, hneg, to_measure_of_zero_le_apply _ _ _ hS₁, to_measure_of_le_zero_apply _ _ _ hS₁], rw ← vector_measure.absolutely_continuous.ennreal_to_measure at h, simp [h (measure_mono_null (i.inter_subset_right S) hS₂), h (measure_mono_null (iᶜ.inter_subset_right S) hS₂)] }, { refine vector_measure.absolutely_continuous.mk (λ S hS₁ hS₂, _), rw ← vector_measure.ennreal_to_measure_apply hS₁ at hS₂, exact null_of_total_variation_zero s (h hS₂) } end lemma total_variation_absolutely_continuous_iff (s : signed_measure α) (μ : measure α) : s.total_variation ≪ μ ↔ s.to_jordan_decomposition.pos_part ≪ μ ∧ s.to_jordan_decomposition.neg_part ≪ μ := begin split; intro h, { split, all_goals { refine measure.absolutely_continuous.mk (λ S hS₁ hS₂, _), have := h hS₂, rw [total_variation, measure.add_apply, add_eq_zero_iff] at this }, exacts [this.1, this.2] }, { refine measure.absolutely_continuous.mk (λ S hS₁ hS₂, _), rw [total_variation, measure.add_apply, h.1 hS₂, h.2 hS₂, add_zero] } end -- TODO: Generalize to vector measures once total variation on vector measures is defined lemma mutually_singular_iff (s t : signed_measure α) : s ⟂ᵥ t ↔ s.total_variation ⟂ₘ t.total_variation := begin split, { rintro ⟨u, hmeas, hu₁, hu₂⟩, obtain ⟨i, hi₁, hi₂, hi₃, hipos, hineg⟩ := s.to_jordan_decomposition_spec, obtain ⟨j, hj₁, hj₂, hj₃, hjpos, hjneg⟩ := t.to_jordan_decomposition_spec, refine ⟨u, hmeas, _, _⟩, { rw [total_variation, measure.add_apply, hipos, hineg, to_measure_of_zero_le_apply _ _ _ hmeas, to_measure_of_le_zero_apply _ _ _ hmeas], simp [hu₁ _ (set.inter_subset_right _ _)] }, { rw [total_variation, measure.add_apply, hjpos, hjneg, to_measure_of_zero_le_apply _ _ _ hmeas.compl, to_measure_of_le_zero_apply _ _ _ hmeas.compl], simp [hu₂ _ (set.inter_subset_right _ _)] } }, { rintro ⟨u, hmeas, hu₁, hu₂⟩, exact ⟨u, hmeas, (λ t htu, null_of_total_variation_zero _ (measure_mono_null htu hu₁)), (λ t htv, null_of_total_variation_zero _ (measure_mono_null htv hu₂))⟩ } end lemma mutually_singular_ennreal_iff (s : signed_measure α) (μ : vector_measure α ℝ≥0∞) : s ⟂ᵥ μ ↔ s.total_variation ⟂ₘ μ.ennreal_to_measure := begin split, { rintro ⟨u, hmeas, hu₁, hu₂⟩, obtain ⟨i, hi₁, hi₂, hi₃, hpos, hneg⟩ := s.to_jordan_decomposition_spec, refine ⟨u, hmeas, _, _⟩, { rw [total_variation, measure.add_apply, hpos, hneg, to_measure_of_zero_le_apply _ _ _ hmeas, to_measure_of_le_zero_apply _ _ _ hmeas], simp [hu₁ _ (set.inter_subset_right _ _)] }, { rw vector_measure.ennreal_to_measure_apply hmeas.compl, exact hu₂ _ (set.subset.refl _) } }, { rintro ⟨u, hmeas, hu₁, hu₂⟩, refine vector_measure.mutually_singular.mk u hmeas (λ t htu _, null_of_total_variation_zero _ (measure_mono_null htu hu₁)) (λ t htv hmt, _), rw ← vector_measure.ennreal_to_measure_apply hmt, exact measure_mono_null htv hu₂ } end lemma total_variation_mutually_singular_iff (s : signed_measure α) (μ : measure α) : s.total_variation ⟂ₘ μ ↔ s.to_jordan_decomposition.pos_part ⟂ₘ μ ∧ s.to_jordan_decomposition.neg_part ⟂ₘ μ := measure.mutually_singular.add_left_iff end signed_measure end measure_theory
------------------------------------------------------------------------ -- The Agda standard library -- -- Unary relations ------------------------------------------------------------------------ {-# OPTIONS --without-K --safe #-} module Relation.Unary where open import Data.Empty open import Data.Unit.Base using (⊤) open import Data.Product open import Data.Sum.Base using (_⊎_; [_,_]) open import Function.Base open import Level open import Relation.Nullary hiding (Irrelevant) open import Relation.Nullary.Decidable.Core using (True) open import Relation.Binary.PropositionalEquality.Core using (_≡_) private variable a b c ℓ ℓ₁ ℓ₂ : Level A : Set a B : Set b C : Set c ------------------------------------------------------------------------ -- Definition -- Unary relations are known as predicates and `Pred A ℓ` can be viewed -- as some property that elements of type A might satisfy. -- Consequently `P : Pred A ℓ` can also be seen as a subset of A -- containing all the elements of A that satisfy property P. This view -- informs much of the notation used below. Pred : ∀ {a} → Set a → (ℓ : Level) → Set (a ⊔ suc ℓ) Pred A ℓ = A → Set ℓ ------------------------------------------------------------------------ -- Special sets -- The empty set. ∅ : Pred A 0ℓ ∅ = λ _ → ⊥ -- The singleton set. {_} : A → Pred A _ { x } = x ≡_ -- The universal set. U : Pred A 0ℓ U = λ _ → ⊤ ------------------------------------------------------------------------ -- Membership infix 4 _∈_ _∉_ _∈_ : A → Pred A ℓ → Set _ x ∈ P = P x _∉_ : A → Pred A ℓ → Set _ x ∉ P = ¬ x ∈ P ------------------------------------------------------------------------ -- Subset relations infix 4 _⊆_ _⊇_ _⊈_ _⊉_ _⊂_ _⊃_ _⊄_ _⊅_ _⊆_ : Pred A ℓ₁ → Pred A ℓ₂ → Set _ P ⊆ Q = ∀ {x} → x ∈ P → x ∈ Q _⊇_ : Pred A ℓ₁ → Pred A ℓ₂ → Set _ P ⊇ Q = Q ⊆ P _⊈_ : Pred A ℓ₁ → Pred A ℓ₂ → Set _ P ⊈ Q = ¬ (P ⊆ Q) _⊉_ : Pred A ℓ₁ → Pred A ℓ₂ → Set _ P ⊉ Q = ¬ (P ⊇ Q) _⊂_ : Pred A ℓ₁ → Pred A ℓ₂ → Set _ P ⊂ Q = P ⊆ Q × Q ⊈ P _⊃_ : Pred A ℓ₁ → Pred A ℓ₂ → Set _ P ⊃ Q = Q ⊂ P _⊄_ : Pred A ℓ₁ → Pred A ℓ₂ → Set _ P ⊄ Q = ¬ (P ⊂ Q) _⊅_ : Pred A ℓ₁ → Pred A ℓ₂ → Set _ P ⊅ Q = ¬ (P ⊃ Q) -- The following primed variants of _⊆_ can be used when 'x' can't -- be inferred from 'x ∈ P'. infix 4 _⊆′_ _⊇′_ _⊈′_ _⊉′_ _⊂′_ _⊃′_ _⊄′_ _⊅′_ _⊆′_ : Pred A ℓ₁ → Pred A ℓ₂ → Set _ P ⊆′ Q = ∀ x → x ∈ P → x ∈ Q _⊇′_ : Pred A ℓ₁ → Pred A ℓ₂ → Set _ Q ⊇′ P = P ⊆′ Q _⊈′_ : Pred A ℓ₁ → Pred A ℓ₂ → Set _ P ⊈′ Q = ¬ (P ⊆′ Q) _⊉′_ : Pred A ℓ₁ → Pred A ℓ₂ → Set _ P ⊉′ Q = ¬ (P ⊇′ Q) _⊂′_ : Pred A ℓ₁ → Pred A ℓ₂ → Set _ P ⊂′ Q = P ⊆′ Q × Q ⊈′ P _⊃′_ : Pred A ℓ₁ → Pred A ℓ₂ → Set _ P ⊃′ Q = Q ⊂′ P _⊄′_ : Pred A ℓ₁ → Pred A ℓ₂ → Set _ P ⊄′ Q = ¬ (P ⊂′ Q) _⊅′_ : Pred A ℓ₁ → Pred A ℓ₂ → Set _ P ⊅′ Q = ¬ (P ⊃′ Q) ------------------------------------------------------------------------ -- Properties of sets infix 10 Satisfiable Universal IUniversal -- Emptiness - no element satisfies P. Empty : Pred A ℓ → Set _ Empty P = ∀ x → x ∉ P -- Satisfiable - at least one element satisfies P. Satisfiable : Pred A ℓ → Set _ Satisfiable P = ∃ λ x → x ∈ P syntax Satisfiable P = ∃⟨ P ⟩ -- Universality - all elements satisfy P. Universal : Pred A ℓ → Set _ Universal P = ∀ x → x ∈ P syntax Universal P = Π[ P ] -- Implicit universality - all elements satisfy P. IUniversal : Pred A ℓ → Set _ IUniversal P = ∀ {x} → x ∈ P syntax IUniversal P = ∀[ P ] -- Decidability - it is possible to determine if an arbitrary element -- satisfies P. Decidable : Pred A ℓ → Set _ Decidable P = ∀ x → Dec (P x) -- Erasure: A decidable predicate gives rise to another one, more -- amenable to η-expansion ⌊_⌋ : {P : Pred A ℓ} → Decidable P → Pred A ℓ ⌊ P? ⌋ a = Lift _ (True (P? a)) -- Irrelevance - any two proofs that an element satifies P are -- indistinguishable. Irrelevant : Pred A ℓ → Set _ Irrelevant P = ∀ {x} (a : P x) (b : P x) → a ≡ b -- Recomputability - we can rebuild a relevant proof given an -- irrelevant one. Recomputable : Pred A ℓ → Set _ Recomputable P = ∀ {x} → .(P x) → P x ------------------------------------------------------------------------ -- Operations on sets infix 10 ⋃ ⋂ infixr 9 _⊢_ infixr 8 _⇒_ infixr 7 _∩_ infixr 6 _∪_ infix 4 _≬_ -- Complement. ∁ : Pred A ℓ → Pred A ℓ ∁ P = λ x → x ∉ P -- Implication. _⇒_ : Pred A ℓ₁ → Pred A ℓ₂ → Pred A _ P ⇒ Q = λ x → x ∈ P → x ∈ Q -- Union. _∪_ : Pred A ℓ₁ → Pred A ℓ₂ → Pred A _ P ∪ Q = λ x → x ∈ P ⊎ x ∈ Q -- Intersection. _∩_ : Pred A ℓ₁ → Pred A ℓ₂ → Pred A _ P ∩ Q = λ x → x ∈ P × x ∈ Q -- Infinitary union. ⋃ : ∀ {i} (I : Set i) → (I → Pred A ℓ) → Pred A _ ⋃ I P = λ x → Σ[ i ∈ I ] P i x syntax ⋃ I (λ i → P) = ⋃[ i ∶ I ] P -- Infinitary intersection. ⋂ : ∀ {i} (I : Set i) → (I → Pred A ℓ) → Pred A _ ⋂ I P = λ x → (i : I) → P i x syntax ⋂ I (λ i → P) = ⋂[ i ∶ I ] P -- Positive version of non-disjointness, dual to inclusion. _≬_ : Pred A ℓ₁ → Pred A ℓ₂ → Set _ P ≬ Q = ∃ λ x → x ∈ P × x ∈ Q -- Update. _⊢_ : (A → B) → Pred B ℓ → Pred A ℓ f ⊢ P = λ x → P (f x) ------------------------------------------------------------------------ -- Predicate combinators -- These differ from the set operations above, as the carrier set of the -- resulting predicates are not the same as the carrier set of the -- component predicates. infixr 2 _⟨×⟩_ infixr 2 _⟨⊙⟩_ infixr 1 _⟨⊎⟩_ infixr 0 _⟨→⟩_ infixl 9 _⟨·⟩_ infix 10 _~ infixr 9 _⟨∘⟩_ infixr 2 _//_ _\\_ -- Product. _⟨×⟩_ : Pred A ℓ₁ → Pred B ℓ₂ → Pred (A × B) _ (P ⟨×⟩ Q) (x , y) = x ∈ P × y ∈ Q -- Sum over one element. _⟨⊎⟩_ : Pred A ℓ → Pred B ℓ → Pred (A ⊎ B) _ P ⟨⊎⟩ Q = [ P , Q ] -- Sum over two elements. _⟨⊙⟩_ : Pred A ℓ₁ → Pred B ℓ₂ → Pred (A × B) _ (P ⟨⊙⟩ Q) (x , y) = x ∈ P ⊎ y ∈ Q -- Implication. _⟨→⟩_ : Pred A ℓ₁ → Pred B ℓ₂ → Pred (A → B) _ (P ⟨→⟩ Q) f = P ⊆ Q ∘ f -- Product. _⟨·⟩_ : (P : Pred A ℓ₁) (Q : Pred B ℓ₂) → (P ⟨×⟩ (P ⟨→⟩ Q)) ⊆ Q ∘ uncurry (flip _$_) (P ⟨·⟩ Q) (p , f) = f p -- Converse. _~ : Pred (A × B) ℓ → Pred (B × A) ℓ P ~ = P ∘ swap -- Composition. _⟨∘⟩_ : Pred (A × B) ℓ₁ → Pred (B × C) ℓ₂ → Pred (A × C) _ (P ⟨∘⟩ Q) (x , z) = ∃ λ y → (x , y) ∈ P × (y , z) ∈ Q -- Post-division. _//_ : Pred (A × C) ℓ₁ → Pred (B × C) ℓ₂ → Pred (A × B) _ (P // Q) (x , y) = Q ∘ (y ,_) ⊆ P ∘ (x ,_) -- Pre-division. _\\_ : Pred (A × C) ℓ₁ → Pred (A × B) ℓ₂ → Pred (B × C) _ P \\ Q = (P ~ // Q ~) ~
(* Prefer to not include this file Require Export ECAlg. Require Export SM3. Open Scope N_scope. (* TODO RANDOMLY sample a number in [low, high] *) Definition SampleN (low : N)(high : N)(seed : N) : N := low + (seed mod (high + 1 - low)). (*Compute map (SampleN 10 20) (Nlist 15). *) (* Generally try each element in l until func returns false. Should all true returns true *) Fixpoint Scrutinize (DomType : Type)(test : DomType -> bool)(l : list DomType) : bool := match l with | [] => true | h :: tl => match test h with | false => false | true => Scrutinize DomType test tl end end. Definition ScrutN (test : N -> bool)(l : list N): bool := Scrutinize N test l. (* For B.1.10, false if composite *) Definition TryFunb (func : N -> bool)(l : list N) : bool := ScrutN func l. (* match l with | [] => true | j :: tl => match func j with | false => false (* b.5 *) | true => TryFunb tl func (* b.6 *) end end. *) (* Fixpoint TryFunb (l : list N)(func : N -> (bool * N)) : (bool * N * N) := match l with | [] => (true, 0, 0) | j :: tl => match func j with | (false, i) => (false, j, i) (* b.5 *) | (true, i) => TryFunb tl func (* b.6 *) end end. *) Fixpoint TryFunb4 (b u : N)(func : N -> N -> option bool)(l : list N) : bool := match l with | [] => false (* b.5 *) | i :: tl => let b2 := (N.square b) mod u in match func i b2 with | Some result => result | None => TryFunb4 b2 u func tl end end. Definition NInterval (low : N)(high : N) : list N := map (N.add low) (Nlist (high + 1 - low)). (* Returns (v, w) so that m = 2 ^ v * w and w is odd *) Fixpoint Decom_tail (v : N)(n : positive) : N * positive := match n with | xH => (v, xH) | xI _ => (v, n) | xO n' => Decom_tail (v + 1) n' end. Definition Decom (m : N) : N * N := match m with | N0 => (0, 0) | Npos n => match Decom_tail N0 n with | (v, w) => (v, Npos w) end end. (*B.1.10 u is odd and T is positive. If returns true then u is a ProbPrime. If Returns false then u is a composite. *) (* TODO NInterval is too long in memory *) Definition ProPrimTest (T : N)(u : N) : bool := let m := u - 1 in let (v, w) := Decom m in ( TryFunb (fun j => let a := SampleN 2 m j in let b := (a ^ w) mod u in if orb (N.eqb b 1) (N.eqb b m) then true (* b.3 *) else TryFunb4 b u (* b.4 *) (fun i b2 => if N.eqb b2 m then Some true else (* b.4.2 *) if N.eqb b2 1 then Some false else (* b.4.3 *) None (* b.4.4 *) ) (NInterval 1 (v - 1))) ) (NInterval 1 T). (* Definition ProPrimTest_debug (T : N)(u : N) : (bool * N * N * N * N * N * N) := let m := u - 1 in let (v, w) := Decom m in ( TryFunb (NInterval 1 T) (fun j => let a := SampleN 2 m j in let b := (a ^ w) mod u in if orb (N.eqb b 1) (N.eqb b m) then (true, j) (* b.3 *) else TryFunb4 (NInterval 1 (v - 1)) b u (* b.4 *) (fun i b2 => if N.eqb b2 m then Some true else (* b.4.2 *) if N.eqb b2 1 then Some false else (* b.4.3 *) None (* b.4.4 *) ) ), u, m, v, w). Definition ProPrimTest (T : N)(u : N) : bool := match ProPrimTest_debug T u with | (result, _, _, _, _, _, _) => result end. *) (* Compute map (ProPrimTest_debug 999) (NInterval 3 99). (* 100% Correct *) *) (* From C.2 Example 1 *) Definition constant_a := HexString.to_N "0xBB8E5E8FBC115E139FE6A814FE48AAA6F0ADA1AA5DF91985". Definition constant_p := HexString.to_N "0xBDB6F4FE3E8B1D9E0DA8C0D46F4C318CEFE4AFE3B6B8551F". (* true if passed the test, i.e. not singular *) Definition SingTest (a b p : N) : bool := negb (4 * (P_power a 3 p) + 27 * (square b) =? 0). (* D.1.1 method 2, true if this tuple is valid*) Definition CheckSEED (SEED : bL)(a p : N) : option (bL * N * N) := (*if Nat.leb (List.length SEED) 191%nat then None else*) let b := (SM3_HashN SEED) mod p in if negb (SingTest a b p) then None else Some (SEED, a, b). Fixpoint GenSab_tail (p a : N)(seedl : list bL) : option (bL * N * N) := match seedl with | [] => None | h :: tl => match CheckSEED h a p with | Some tuple => Some tuple | None => GenSab_tail p a tl end end. Definition constant_seedlist := map (fun x => NtobL_len 192 x) [0; 1; 2 ^ 90; 2 ^ 191]. Definition GenSab (a p : N) : option (bL * N * N) := GenSab_tail p a constant_seedlist. Definition DisplaySab (para : option (bL * N * N)) := match para with | None => ("", "", "") | Some (SEED, a, b) => (bStohS (bLtobS SEED), HexString.of_N a, HexString.of_N b) end. (* D.2.1 method 2 *) Definition VeriSab (p b : N)(SEED : bL) : bool := b =? (SM3_HashN SEED) mod p. Definition constant_T := 999. (* A.4.2.1, true means pass *) (* j = B - i + 1 *) Fixpoint MOV_Test_tail (q n : N)(j : nat)(acc : list (bool * N)) : list (bool * N) := match j with | O => acc (* i = B + 1, break *) | S j' => match acc with | [] => [] (*which will not happen*) | (b_old, t_old) :: tl => let t := (t_old * q) mod n in let b := andb b_old (negb (t =? 1)) in MOV_Test_tail q n j' ((b, t) :: acc) end end. (* n is a prime and q is a prime exponent *) Definition MOV_Test (B: nat)(q n : N) : bool := fst (List.hd (false, 0) (MOV_Test_tail q n B [(true, 1)])). Definition constant_B := 27%nat. (* A.4.2.2, true means pass *) Definition Anomalous_Curve_Test (p order: N) : bool := negb (p =? order). (* floor(2*sqrt(p)) *) Definition floor2sqrt(p : N) : N := let r2 := N.double (N.sqrt p) in if r2 =? N.sqrt (p * 4) then r2 else r2 + 1. Definition Computeh' (p n : N) : N := N.div (p + 1 + (floor2sqrt p)) n. (* 5.2.2 returns None if valid, otherwise Some error message*) (* Quick tests for large inputs *) Definition VeriSysPara_Quick (p a b n h xG yG order : N)(SEED : bL) : option string := if even p then Some "p is even." else if p <=? a then Some "a >= p" else if p <=? b then Some "b >= p" else if p <=? xG then Some "xG >= p" else if p <=? yG then Some "yG >= p" else let SEED_len := (N.of_nat (List.length SEED)) in if andb (0 <? SEED_len) (SEED_len <? 192) then Some "SEED is shorter than 192." else if andb (0 <? SEED_len ) (negb (VeriSab p b SEED)) then Some "Failed in VeriSab." else if negb (SingTest p a b) then Some "Failed in SingTest." else if negb (OnCurve_pf p a b xG yG) then Some "Failed in OnCurveTest." else if n <=? N.shiftl 1 191 then Some "n <= 2 ^ 192." else if square n <=? 16 * p then Some "n <= 4 p ^ 1/2." else if negb (h =? Computeh' p n) then Some "h != h'." else None. (* These tests are quite time consuming *) Definition VeriSysPara (p a b n h xG yG order: N)(SEED : bL) : option string := match VeriSysPara_Quick p a b n h xG yG order SEED with | Some msg => Some msg | None => if negb (GE_eqb (pf_mul p a (Cop (xG, yG)) n) InfO) then Some "[n]G != O." else if negb (ProPrimTest constant_T p) then Some "p is a composite." else if negb (ProPrimTest constant_T n) then Some "n is a composite." else if negb (MOV_Test constant_B p n ) then Some "Failed in MOV test" else if negb (Anomalous_Curve_Test p order) then Some "Failed in Anomalous Curve Test" else None end. Module tests. (* (* C.2 *) (* Example 1 *) Time Compute let p := hStoN "BDB6F4FE3E8B1D9E0DA8C0D46F4C318CEFE4AFE3B6B8551F" in let a := hStoN "BB8E5E8FBC115E139FE6A814FE48AAA6F0ADA1AA5DF91985" in let b := hStoN "1854BEBDC31B21B7AEFC80AB0ECD10D5B1B3308E6DBF11C1" in let xG := hStoN "4AD5F7048DE709AD51236DE65E4D4B482C836DC6E4106640" in let yG := hStoN "02BB3A02D4AAADACAE24817A4CA3A1B014B5270432DB27D2" in let n := hStoN "BDB6F4FE3E8B1D9E0DA8C0D40FC962195DFAE76F56564677" in let h := 1 in (*By Hasse Thm*) let order := 1 in (*There is no way for me to know it, just assign it to test*) VeriSysPara_Quick p a b n h xG yG order [] . (* None *) (* Example 2 *) Time Compute let p := hStoN "8542D69E4C044F18E8B92435BF6FF7DE457283915C45517D722EDB8B08F1DFC3" in let a := hStoN "787968B4FA32C3FD2417842E73BBFEFF2F3C848B6831D7E0EC65228B3937E498" in let b := hStoN "63E4C6D3B23B0C849CF84241484BFE48F61D59A5B16BA06E6E12D1DA27C5249A" in let xG := hStoN "421DEBD61B62EAB6746434EBC3CC315E32220B3BADD50BDC4C4E6C147FEDD43D" in let yG := hStoN "0680512BCBB42C07D47349D2153B70C4E5D7FDFCBFA36EA1A85841B9E46E09A2" in let n := hStoN "8542D69E4C044F18E8B92435BF6FF7DD297720630485628D5AE74EE7C32E79B7" in let h := 1 in (*By Hasse Thm*) let order := 1 in (*There is no way for me to know it, just assign it to test*) VeriSysPara_Quick p a b n h xG yG order [] . (* None *) End tests. *) (* B.2.4, Irredicible Polynomial Test*) (* j = d/2 - i *) Fixpoint IrdBody (sq : N -> N)(gcd : N -> N -> N)(f u' : N)(j : nat) : bool := match j with | O => true | S j' => let u := B_mod (sq u') f in let g := gcd (B_add u 2) f in if N.eqb g 1 then IrdBody sq gcd f u j' else false end. Definition IrdTest (f : N) : bool := let d := size_nat f in let u := 2%N in IrdBody (Bp_sq_raw) B_gcd f u (Nat.div d 2). (* (* TODO need test casess *) Compute IrdTest 37. (* Correct *) Compute List.length []. Print map. Compute map N.double [2; 3]. Definition TPB_list := map decode_TPB TPB_IRP. (*Compute map IrdTest (TPB_list). All true, correct *) Definition PPB_list := map decode_PPB PPB_IRP. (*Time Compute map IrdTest (PPB_list).*) (*Finished transaction in 393.439 secs (393.19u,0.153s) (successful)All true, correct *) *) End tests. *)
(* Title: HOL/Auth/n_german_lemma_inv__47_on_rules.thy Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences *) header{*The n_german Protocol Case Study*} theory n_german_lemma_inv__47_on_rules imports n_german_lemma_on_inv__47 begin section{*All lemmas on causal relation between inv__47*} lemma lemma_inv__47_on_rules: assumes b1: "r \<in> rules N" and b2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__47 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" proof - have c1: "(\<exists> j. j\<le>N\<and>r=n_SendReqS j)\<or> (\<exists> i. i\<le>N\<and>r=n_SendReqEI i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendReqES i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvReq N i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInvE i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInvS i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInvAck i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendGntS i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendGntE N i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvGntS i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvGntE i)\<or> (\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)" apply (cut_tac b1, auto) done moreover { assume d1: "(\<exists> j. j\<le>N\<and>r=n_SendReqS j)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendReqSVsinv__47) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqEI i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendReqEIVsinv__47) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqES i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendReqESVsinv__47) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReq N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvReqVsinv__47) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvE i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInvEVsinv__47) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInvSVsinv__47) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInvAckVsinv__47) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvInvAckVsinv__47) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendGntSVsinv__47) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendGntEVsinv__47) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvGntSVsinv__47) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvGntEVsinv__47) done } moreover { assume d1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_StoreVsinv__47) done } ultimately show "invHoldForRule s f r (invariants N)" by satx qed end
{-# OPTIONS --cubical --no-import-sorts --safe #-} module Cubical.Algebra.Ring where open import Cubical.Algebra.Ring.Base public open import Cubical.Algebra.Ring.Properties public
{-# OPTIONS --without-K #-} module container where import container.core import container.fixpoint import container.equality import container.m import container.w
module MJ.Types where open import Prelude hiding (_≟_) open import Data.Fin.Properties as FinP using () open import Data.Vec open import Data.List open import Relation.Binary.Core open import Relation.Nullary open import Relation.Binary data Cid (c : ℕ) : Set where cls : Fin c → Cid c Object : Cid c _cid≟_ : ∀ {c} → Decidable (_≡_ {A = Cid c}) cls x cid≟ cls y with x FinP.≟ y cls x cid≟ cls .x | yes refl = yes refl cls x cid≟ cls y | no ¬p = no (λ{ refl → ¬p refl}) cls x cid≟ Object = no (λ ()) Object cid≟ cls x = no (λ ()) Object cid≟ Object = yes refl data Ty (c : ℕ) : Set where void : Ty c int : Ty c ref : Cid c → Ty c data Ty⁺ (c : ℕ) : Set where vty : Ty c → Ty⁺ c obj : Cid c → Ty⁺ c World : ℕ → Set World c = List (Ty⁺ c) Sig : ℕ → Set Sig c = List (Ty c) × Ty c _≟_ : ∀ {c} → Decidable (_≡_ {A = Ty c}) void ≟ void = yes refl void ≟ int = no (λ ()) void ≟ ref x = no (λ ()) int ≟ void = no (λ ()) int ≟ int = yes refl int ≟ ref x = no (λ ()) ref x ≟ void = no (λ ()) ref x ≟ int = no (λ ()) ref x ≟ ref y with x cid≟ y ref x ≟ ref y | yes p = yes (cong ref p) ref x ≟ ref y | no ¬p = no λ{ refl → ¬p refl }
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import category_theory.concrete_category.bundled import category_theory.discrete_category import category_theory.types import category_theory.bicategory.strict /-! # Category of categories > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains the definition of the category `Cat` of all categories. In this category objects are categories and morphisms are functors between these categories. ## Implementation notes Though `Cat` is not a concrete category, we use `bundled` to define its carrier type. -/ universes v u namespace category_theory /-- Category of categories. -/ @[nolint check_univs] -- intended to be used with explicit universe parameters def Cat := bundled category.{v u} namespace Cat instance : inhabited Cat := ⟨⟨Type u, category_theory.types⟩⟩ instance : has_coe_to_sort Cat (Type u) := ⟨bundled.α⟩ instance str (C : Cat.{v u}) : category.{v u} C := C.str /-- Construct a bundled `Cat` from the underlying type and the typeclass. -/ def of (C : Type u) [category.{v} C] : Cat.{v u} := bundled.of C /-- Bicategory structure on `Cat` -/ instance bicategory : bicategory.{(max v u) (max v u)} Cat.{v u} := { hom := λ C D, C ⥤ D, id := λ C, 𝟭 C, comp := λ C D E F G, F ⋙ G, hom_category := λ C D, functor.category C D, whisker_left := λ C D E F G H η, whisker_left F η, whisker_right := λ C D E F G η H, whisker_right η H, associator := λ A B C D, functor.associator, left_unitor := λ A B, functor.left_unitor, right_unitor := λ A B, functor.right_unitor, pentagon' := λ A B C D E, functor.pentagon, triangle' := λ A B C, functor.triangle } /-- `Cat` is a strict bicategory. -/ instance bicategory.strict : bicategory.strict Cat.{v u} := { id_comp' := λ C D F, by cases F; refl, comp_id' := λ C D F, by cases F; refl, assoc' := by intros; refl } /-- Category structure on `Cat` -/ instance category : large_category.{max v u} Cat.{v u} := strict_bicategory.category Cat.{v u} @[simp] lemma id_map {C : Cat} {X Y : C} (f : X ⟶ Y) : (𝟙 C : C ⥤ C).map f = f := functor.id_map f @[simp] lemma comp_obj {C D E : Cat} (F : C ⟶ D) (G : D ⟶ E) (X : C) : (F ≫ G).obj X = G.obj (F.obj X) := functor.comp_obj F G X @[simp] lemma comp_map {C D E : Cat} (F : C ⟶ D) (G : D ⟶ E) {X Y : C} (f : X ⟶ Y) : (F ≫ G).map f = G.map (F.map f) := functor.comp_map F G f /-- Functor that gets the set of objects of a category. It is not called `forget`, because it is not a faithful functor. -/ def objects : Cat.{v u} ⥤ Type u := { obj := λ C, C, map := λ C D F, F.obj } section local attribute [simp] eq_to_hom_map /-- Any isomorphism in `Cat` induces an equivalence of the underlying categories. -/ def equiv_of_iso {C D : Cat} (γ : C ≅ D) : C ≌ D := { functor := γ.hom, inverse := γ.inv, unit_iso := eq_to_iso $ eq.symm γ.hom_inv_id, counit_iso := eq_to_iso γ.inv_hom_id } end end Cat /-- Embedding `Type` into `Cat` as discrete categories. This ought to be modelled as a 2-functor! -/ @[simps] def Type_to_Cat : Type u ⥤ Cat := { obj := λ X, Cat.of (discrete X), map := λ X Y f, discrete.functor (discrete.mk ∘ f), map_id' := λ X, begin apply functor.ext, tidy, end, map_comp' := λ X Y Z f g, begin apply functor.ext, tidy, end } instance : faithful Type_to_Cat.{u} := { map_injective' := λ X Y f g h, funext (λ x, congr_arg discrete.as (functor.congr_obj h ⟨x⟩)), } instance : full Type_to_Cat.{u} := { preimage := λ X Y F, discrete.as ∘ F.obj ∘ discrete.mk, witness' := begin intros X Y F, apply functor.ext, { intros x y f, dsimp, ext, }, { rintros ⟨x⟩, ext, refl, } end } end category_theory
(** Borrowed from Pierce's "Software Foundations" *) Require Import Arith Arith.EqNat. Require Import Omega. Inductive id : Type := Id : nat -> id. Reserved Notation "m <<= n" (at level 70, no associativity). Reserved Notation "m >> n" (at level 70, no associativity). Reserved Notation "m << n" (at level 70, no associativity). Inductive le_id : id -> id -> Prop := le_conv : forall n m, n <= m -> (Id n) <<= (Id m) where "n <<= m" := (le_id n m). Inductive lt_id : id -> id -> Prop := lt_conv : forall n m, n < m -> (Id n) << (Id m) where "n << m" := (lt_id n m). Inductive gt_id : id -> id -> Prop := gt_conv : forall n m, n > m -> (Id n) >> (Id m) where "n >> m" := (gt_id n m). Notation "n <<= m" := (le_id n m). Notation "n >> m" := (gt_id n m). Notation "n << m" := (lt_id n m). Lemma lt_eq_lt_id_dec: forall (id1 id2 : id), {id1 << id2} + {id1 = id2} + {id2 << id1}. Proof. intros. destruct id1, id2. (* or intros [n] [m] *) remember (lt_eq_lt_dec n n0). destruct s. destruct s. - left. left. constructor. assumption. - left. right. rewrite e. reflexivity. - right. constructor. assumption. Qed. (** SearchAbout nat. *) Lemma gt_eq_gt_id_dec: forall (id1 id2 : id), {id1 >> id2} + {id1 = id2} + {id2 >> id1}. Proof. intros. destruct id1, id2. remember (lt_eq_lt_dec n n0). destruct s. destruct s. - right. constructor. assumption. - left. right. rewrite e. reflexivity. - left. left. constructor. assumption. Qed. Lemma le_gt_id_dec : forall id1 id2 : id, {id1 <<= id2} + {id1 >> id2}. Proof. intros. destruct id1, id2. remember (le_gt_dec n n0). destruct s. - left. constructor. assumption. - right. constructor. assumption. Qed. Lemma eq_dec : forall n m : nat, {n = m} + {n <> m}. Proof. intros n. induction n. intros. - destruct m as [|m]. auto. auto. - destruct m as [|m]. auto. destruct (IHn m). auto. auto. Qed. Lemma eq_id_dec : forall id1 id2 : id, {id1 = id2} + {id1 <> id2}. Proof. intros. destruct id1, id2. remember (eq_dec n n0). destruct s. - auto. - right. unfold not in *. intro. inversion H. contradiction. Qed. Lemma eq_id : forall (T:Type) x (p q:T), (if eq_id_dec x x then p else q) = p. Proof. intros. destruct (eq_id_dec x x); tauto. Qed. Lemma neq_id : forall (T:Type) x y (p q:T), x <> y -> (if eq_id_dec x y then p else q) = q. Proof. intros. destruct (eq_id_dec x y); tauto. Qed. Lemma lt_gt_id_false : forall id1 id2 : id, id1 >> id2 -> id2 >> id1 -> False. Proof. intros. destruct id1, id2. inversion_clear H. inversion_clear H0. omega. Qed. Lemma le_gt_id_false : forall id1 id2 : id, id2 <<= id1 -> id2 >> id1 -> False. Proof. intros. destruct id1, id2. inversion_clear H. inversion_clear H0. omega. Qed. Lemma le_lt_eq_id_dec : forall id1 id2 : id, id1 <<= id2 -> {id1 = id2} + {id2 >> id1}. Proof. intros. destruct id1, id2. remember (le_lt_eq_dec n n0). destruct s. - inversion_clear H. auto. - right. constructor. auto. - left. rewrite e. auto. Qed. Lemma neq_lt_gt_id_dec : forall id1 id2 : id, id1 <> id2 -> {id1 >> id2} + {id2 >> id1}. Proof. intros. remember (gt_eq_gt_id_dec id1 id2). destruct s. destruct s. auto. tauto. auto. Qed. Lemma eq_gt_id_false : forall id1 id2 : id, id1 = id2 -> id1 >> id2 -> False. Proof. intros. destruct id1, id2. inversion_clear H0. inversion H. omega. Qed.
Sistema: dS/dt=-bS, dI/dt=bI, b es positivo (b=beta) ```python from sympy import * from sympy.abc import S,I,t,b ``` ```python #puntos criticos P=-b*S Q=b*I #establecer P(S,I)=0 y Q(S,I)=0 Peqn=Eq(P,0) Qeqn=Eq(Q,0) print(solve((Peqn,Qeqn),S,I)) #Eigenvalores y eigenvectores M=Matrix([[-b,0],[0,b]]) print(M.eigenvals()) pprint(M.eigenvects()) ``` {I: 0, S: 0} {-b: 1, b: 1} ⎡⎛ ⎡⎡1⎤⎤⎞ ⎛ ⎡⎡0⎤⎤⎞⎤ ⎢⎜-b, 1, ⎢⎢ ⎥⎥⎟, ⎜b, 1, ⎢⎢ ⎥⎥⎟⎥ ⎣⎝ ⎣⎣0⎦⎦⎠ ⎝ ⎣⎣1⎦⎦⎠⎦ El sistema tiene un punto critico en el origen el cual tiene eigenvalores -b y b, ya que b es postivo los eigenvalores son reales distintos uno positivo y otro negativo por lo que el punto critico es un punto silla, el cual es inestable. Ya que el sistema tiene un punto critico que es un punto silla, por la definicion 9 el indice del punto critico es -1 y por el teorema 1 entonces no hay ciclos limites en el sistema, es decir no existe una solucion periodica aislada del sistema. ```python import matplotlib.pyplot as plt import numpy as np from scipy.integrate import odeint import pylab as pl import matplotlib ``` ```python def dx_dt(x,t): return [ -0.5*x[0] , 0.5*x[1] ] #trayectorias en tiempo hacia adelante ts=np.linspace(0,10,500) ic=np.linspace(20000,100000,3) for r in ic: for s in ic: x0=[r,s] xs=odeint(dx_dt,x0,ts) plt.plot(xs[:,0],xs[:,1],"-", color="orangered", lw=1.5) #trayectorias en tiempo hacia atras ts=np.linspace(0,-10,500) ic=np.linspace(20000,100000,3) for r in ic: for s in ic: x0=[r,s] xs=odeint(dx_dt,x0,ts) plt.plot(xs[:,0],xs[:,1],"-", color="orangered", lw=1.5) #etiquetas de ejes y estilo de letra plt.xlabel('S',fontsize=20) plt.ylabel('I',fontsize=20) plt.tick_params(labelsize=12) plt.ticklabel_format(style="sci", scilimits=(0,0)) plt.xlim(0,100000) plt.ylim(0,100000) #campo vectorial X,Y=np.mgrid[0:100000:15j,0:100000:15j] u=-0.5*X v=0.5*Y pl.quiver(X,Y,u,v,color='dimgray') plt.savefig("SI.pdf",bbox_inches='tight') plt.show() ``` Analisis de existencia de Bifurcaciones El punto critico del sistema no varia con el cambio en el valor de b (beta) ya que es idependiente de este parametro. ```python ```
namespace TBA -- Let's work with some inductive types other than `Nat`! -- Here is our very own definition of `List`: inductive List (α : Type) where | nil : List α | cons (head : α) (tail : List α) : List α notation (priority := high) "[" "]" => List.nil -- `[]` infixr:67 (priority := high) " :: " => List.cons -- `a :: as` -- as a warm-up exercise, let's define concatenation of two lists def append (as bs : List α) : List α := match as with | [] => bs | a :: as => a :: append as bs infixl:65 (priority := high) " ++ " => append example : 1::2::[] ++ 3::4::[] = 1::2::3::4::[] := rfl -- as with associativity on `Nat`, think twice about what induction variable to use! theorem append_assoc : (as ++ bs) ++ cs = as ++ (bs ++ cs) := by induction as with | nil => rfl | cons a as ih => simp [append, ih] open Decidable /- One important special case of `Decidable` is decidability of equalities: ``` abbrev DecidableEq (α : Type) := (a b : α) → Decidable (a = b) def decEq [s : DecidableEq α] (a b : α) : Decidable (a = b) := s a b ``` Note: `DecidableEq` is defined using `abbrev` instead of `def` because typeclass resolution only unfolds the former for performance reasons. Let's try to prove that `List` equality is decidable! -/ -- hint: Something is still missing. Do we need to assume anything about `α`? -- hint: Apply `match` case distinctions until the the appropriate `Decidable` constructor is clear, -- then fill in its proof argument with `by`. -- We could also do everything in a `by` block, but it's nicer to reserve tactics for proofs so we have -- more control about the code of programs, i.e. the part that is actually executed def ldecEq [DecidableEq α] (as bs : List α) : Decidable (as = bs) := /-SOL_-/ match as, bs with | [], [] => isTrue rfl | [], b :: bs => isFalse (by intro h; contradiction) -- or simply: | a :: as, [] => isFalse (by simp) | a :: as, b :: bs => match decEq a b, ldecEq as bs with | isTrue _, isTrue _ => isTrue (by simp_all) | isFalse _, _ => isFalse (by intro h; injection h; simp_all) | _, isFalse _ => isFalse (by intro h; injection h; simp_all) -- Let's declare the instance: instance [DecidableEq α] : DecidableEq (List α) := /-SOL_-/ldecEq/-END-/ -- This should now work: #eval decEq (1::2::[]) (1::3::[]) /- `DecidabePred` is another convenient abbreviation of `Decidable` ``` abbrev DecidablePred (r : α → Prop) := (a : α) → Decidable (r a) ``` If we have `[DecidablePred p]`, we can e.g. use `if p a then ...` for some `a : α`. `filter p as` is a simple list function that should remove all elements `a` for which `p a` does not hold. -/ def filter (p : α → Prop) [DecidablePred p] (as : List α) : List α := match as with | [] => [] | a::as => if p a then a :: filter p as else filter p as example : filter (fun x => x % 2 = 0) (1::2::3::4::[]) = 2::4::[] := rfl variable {p : α → Prop} [DecidablePred p] {as bs : List α} -- These helper theorems can be useful, also for manual rewriting @[simp] theorem filter_cons_true (h : p a) : filter p (a :: as) = a :: filter p as := by simp [filter, h] @[simp] theorem filter_cons_false (h : ¬ p a) : filter p (a :: as) = filter p as := by simp [filter, h] -- It's worthwhile thinking about what's actually happening here: -- * first, `filter p (a :: as)` is unfolded to `if p a then a :: filter p as else filter p as` -- (note that the second `filter` cannot be unfolded) -- * then `if p a then ...` is rewritten to `if True then ...` using `h` -- * finally, `if True then a :: filter p as else ...` is rewritten to `a :: filter p as` using -- the built-in simp theorem `Lean.Simp.ite_true` -- useful tactic: `by_cases h : q` for a decidable proposition `q` theorem filter_idem : filter p (filter p as) = filter p as := by induction as with | nil => rfl | cons a as ih => by_cases h : p a <;> simp [ih, h] theorem filter_append : filter p (as ++ bs) = filter p as ++ filter p bs := by induction as with | nil => rfl | cons a as ih => by_cases h : p a <;> simp [append, ih, h] -- list membership as an inductive predicate: inductive Mem (a : α) : List α → Prop where -- either it's the first element... | head {as} : Mem a (a::as) -- or it's in the remainder list | tail {as} : Mem a as → Mem a (a'::as) infix:50 " ∈ " => Mem -- recall that `a ≠ b` is the same as `a = b → False` theorem mem_of_nonempty_filter (h : ∀ a, p a → a = x) : filter p as ≠ [] → x ∈ as := by intro hfil induction as with | nil => contradiction | cons a as ih => by_cases hpa : p a case inl => rw [h _ hpa] exact Mem.head case inr => rw [filter_cons_false hpa] at hfil exact Mem.tail (ih hfil) -- This proof is pretty long! Some hints: -- * If you have an assumption `h : a ∈ []`, you can solve the current goal by `cases h`: -- since there is no `Mem` constructor that could possibly match `[]`, there is nothing left to prove! -- This exclusion of cases, and case analysis on inductive predicates in general, -- is also called *rule inversion* since we (try to) apply the introduction rules (constructors) -- "in reverse". -- * On the other hand, if you try to do case analysis on a proof of e.g. `a ∈ filter p as`, -- Lean will complain with "dependent elimination failed" since it *doesn't* know yet if -- the argument `filter p as` is of the form `_ :: _` as demanded by the `Mem` constructors. -- You need to get the assumption into the shape `_ ∈ []` or `_ ∈ _ :: _` before applying -- `(no)match/cases` to it. theorem mem_filter : a ∈ filter p as ↔ a ∈ as ∧ p a := by apply Iff.intro case mp => intro h induction as with | nil => cases h | cons a' as ih => by_cases ha' : p a' case inl => rw [filter_cons_true ha'] at h cases h with | head => exact ⟨Mem.head, ha'⟩ | tail h => exact ⟨Mem.tail (ih h).1, (ih h).2⟩ case inr => rw [filter_cons_false ha'] at h exact ⟨Mem.tail (ih h).1, (ih h).2⟩ case mpr => intro ⟨h, hpa⟩ induction as with | nil => cases h | cons a' as ih => cases h with | head => rw [filter_cons_true hpa] constructor | tail ha => by_cases hpa' : p a' case inl => rw [filter_cons_true hpa'] exact Mem.tail (ih ha) case inr => rw [filter_cons_false hpa'] exact ih ha -- Here is an alternative definition of list membership via `append` inductive Mem' (a : α) : List α → Prop where | intro (as bs) : Mem' a (as ++ (a :: bs)) infix:50 " ∈' " => Mem' -- Let's prove that they are equivalent! theorem mem_mem' : a ∈ as ↔ a ∈' as := by constructor case mp => intro h induction h with | head => exact ⟨[], _⟩ | tail h ih => have ⟨as', bs'⟩ := ih exact ⟨_::as', _⟩ case mpr => intro ⟨as', bs'⟩ induction as' with | nil => exact Mem.head | cons a' as' ih => exact Mem.tail ih end TBA
theory T56 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) " nitpick[card nat=4,timeout=86400] oops end
The Navy Oceanographic Meteorological Automatic Device ( NOMAD ) buoy 's 6 @-@ metre ( 20 ft ) hull was originally designed in the 1940s for the United States Navy ’ s offshore data collection program . Between 1951 and 1970 , a total of 21 NOMAD buoys were built and deployed at sea . Since the 1970s , weather buoy use has superseded the role of weather ships by design , as they are cheaper to operate and maintain . The earliest reported use of drifting buoys was to study the behavior of ocean currents within the Sargasso Sea in 1972 and 1973 . Drifting buoys have been used increasingly since 1979 , and as of 2005 , 1250 drifting buoys roamed the Earth 's oceans .
{-# OPTIONS --cubical --no-import-sorts --guardedness --safe #-} module Cubical.Codata.M.AsLimit.Container where open import Cubical.Foundations.Prelude open import Cubical.Foundations.Equiv using (_≃_) open import Cubical.Foundations.Function using (_∘_) open import Cubical.Data.Unit open import Cubical.Data.Prod open import Cubical.Data.Nat as ℕ using (ℕ ; suc ; _+_ ) open import Cubical.Foundations.Transport open import Cubical.Foundations.Univalence open import Cubical.Foundations.Isomorphism open import Cubical.Foundations.Function open import Cubical.Data.Sum open import Cubical.Foundations.Structure open import Cubical.Codata.M.AsLimit.helper ------------------------------------- -- Container and Container Functor -- ------------------------------------- -- Σ[ A ∈ (Type ℓ) ] (A → Type ℓ) Container : ∀ ℓ -> Type (ℓ-suc ℓ) Container ℓ = TypeWithStr ℓ (λ x → x → Type ℓ) -- Polynomial functor (P₀ , P₁) defined over a container -- https://ncatlab.org/nlab/show/polynomial+functor -- P₀ object part of functor P₀ : ∀ {ℓ} (S : Container ℓ) -> Type ℓ -> Type ℓ P₀ (A , B) X = Σ[ a ∈ A ] (B a -> X) -- P₁ morphism part of functor P₁ : ∀ {ℓ} {S : Container ℓ} {X Y} (f : X -> Y) -> P₀ S X -> P₀ S Y P₁ {S = S} f = λ { (a , g) -> a , f ∘ g } ----------------------- -- Chains and Limits -- ----------------------- record Chain ℓ : Type (ℓ-suc ℓ) where constructor _,,_ field X : ℕ -> Type ℓ π : {n : ℕ} -> X (suc n) -> X n open Chain public limit-of-chain : ∀ {ℓ} -> Chain ℓ → Type ℓ limit-of-chain (x ,, pi) = Σ[ x ∈ ((n : ℕ) → x n) ] ((n : ℕ) → pi {n = n} (x (suc n)) ≡ x n) shift-chain : ∀ {ℓ} -> Chain ℓ -> Chain ℓ shift-chain = λ X,π -> ((λ x → X X,π (suc x)) ,, λ {n} → π X,π {suc n}) ------------------------------------------------------ -- Limit type of a Container , and Shift of a Limit -- ------------------------------------------------------ Wₙ : ∀ {ℓ} -> Container ℓ -> ℕ -> Type ℓ Wₙ S 0 = Lift Unit Wₙ S (suc n) = P₀ S (Wₙ S n) πₙ : ∀ {ℓ} -> (S : Container ℓ) -> {n : ℕ} -> Wₙ S (suc n) -> Wₙ S n πₙ {ℓ} S {0} _ = lift tt πₙ S {suc n} = P₁ (πₙ S {n}) sequence : ∀ {ℓ} -> Container ℓ -> Chain ℓ X (sequence S) n = Wₙ S n π (sequence S) {n} = πₙ S {n} PX,Pπ : ∀ {ℓ} (S : Container ℓ) -> Chain ℓ PX,Pπ {ℓ} S = (λ n → P₀ S (X (sequence S) n)) ,, (λ {n : ℕ} x → P₁ (λ z → z) (π (sequence S) {n = suc n} x )) ----------------------------------- -- M type is limit of a sequence -- ----------------------------------- M : ∀ {ℓ} -> Container ℓ → Type ℓ M = limit-of-chain ∘ sequence
@with_kw struct BlochBoundaryCondition <: AbstractBoundaryCondition k⃗::Vec end function BlochBoundaryCondition(planewave_source::PlaneWaveSource) # I think we need to include the refractive index of the surrounding medium BlochBoundaryCondition(k⃗₀(planewave_source)) end
function ff=lpcar2ff(ar,np) %LPCAR2FF LPC: Convert AR coefs to complex spectrum FF=(AR,NP) % Copyright (C) Mike Brookes 1998 % Version: $Id: lpcar2ff.m,v 1.4 2007/05/04 07:01:38 dmb Exp $ % % VOICEBOX is a MATLAB toolbox for speech processing. % Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You can obtain a copy of the GNU General Public License from % http://www.gnu.org/copyleft/gpl.html or by writing to % Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% [nf,p1]=size(ar); if nargin<2 np=p1-1; end ff=(rfft(ar.',2*np+2).').^(-1);
[STATEMENT] lemma istate_\<Delta>0: assumes B: "B vl vl1" shows "\<Delta>0 istate vl istate vl1" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<Delta>0 istate vl istate vl1 [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: B vl vl1 goal (1 subgoal): 1. \<Delta>0 istate vl istate vl1 [PROOF STEP] unfolding \<Delta>0_def B_def [PROOF STATE] proof (prove) using this: BC vl vl1 \<and> validValSeqFrom vl1 istate goal (1 subgoal): 1. BC vl vl1 \<and> eqButUID istate istate \<and> validValSeqFrom vl1 istate [PROOF STEP] by auto
Formal statement is: lemma lmeasurable_interior: "bounded S \<Longrightarrow> interior S \<in> lmeasurable" Informal statement is: If $S$ is a bounded set, then the interior of $S$ is Lebesgue measurable.
(* Title: HOL/Auth/n_germanSimp_lemma_on_inv__25.thy Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences *) header{*The n_germanSimp Protocol Case Study*} theory n_germanSimp_lemma_on_inv__25 imports n_germanSimp_base begin section{*All lemmas on causal relation between inv__25 and some rule r*} lemma n_SendInv__part__0Vsinv__25: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__25 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInv__part__0 i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__25 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendInv__part__1Vsinv__25: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__25 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInv__part__1 i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__25 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendInvAckVsinv__25: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__25 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInvAck i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__25 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvInvAckVsinv__25: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__25 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvInvAck i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__25 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendGntSVsinv__25: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__25 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendGntS i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__25 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendGntEVsinv__25: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__25 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendGntE N i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__25 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Ident ''Chan3'') p__Inv4) ''Cmd'')) (Const InvAck)) (eqn (IVar (Para (Ident ''ShrSet'') p__Inv4)) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvGntSVsinv__25: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__25 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvGntS i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__25 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvGntEVsinv__25: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__25 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvGntE i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__25 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_StoreVsinv__25: assumes a1: "\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__25 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_RecvReqE__part__0Vsinv__25: assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__0 N i" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__25 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_RecvReqE__part__1Vsinv__25: assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__1 N i" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__25 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_RecvReqSVsinv__25: assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvReqS N i" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__25 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done end
proposition open_surjective_linear_image: fixes f :: "'a::real_normed_vector \<Rightarrow> 'b::euclidean_space" assumes "open A" "linear f" "surj f" shows "open(f ` A)"
Formal statement is: lemma const_poly_dvd_iff: fixes c :: "'a::{comm_semiring_1,semiring_no_zero_divisors}" shows "[:c:] dvd p \<longleftrightarrow> (\<forall>n. c dvd coeff p n)" Informal statement is: A constant polynomial $c$ divides a polynomial $p$ if and only if $c$ divides every coefficient of $p$.
\chapter[SetCuts\mbox{ : } conversion from range to kinetic energy] {SetCuts\mbox{ : } conversion from range to kinetic energy } \section{Charged particles} Starting from a particle cut given in stopping range, the method constructs a vector holding the cut values in kinetic energy for every material. The main steps of the algorithm are the same for all the charged particles, the only difference is that different energy loss formulae are used for electrons, positrons and heavy charged particles ( muon,pion,proton,...). In the case of charged hadrons this procedure is applied for the proton and antiproton only , the cut values in kinetic energy for other hadrons are computed using the proton and antiproton energy loss and range tables . \subsection{General scheme} \begin{enumerate} \item An energy loss table is created and filled for all the elements in the element table. \item For every material in the material table the following steps are performed: \begin{enumerate} \item a range vector is constructed using the energy loss table and formulae for the low energy part of the calculations, \item the conversion from stopping range to kinetic energy is performed and the corresponding element of the {\tt KineticEnergyCuts} vector is set (It contains the particle cut value in kinetic energy for the actual material.), \item the range vector is deleted. \end{enumerate} \item The energy loss table is deleted at the end of the process. \end{enumerate} \subsection{Energy loss formula for heavy charged particles} The energy loss of the particle is calculated from a simplified Bethe-Bloch formula if the kinetic energy of the particle is above the value : \[ T_{lim}=2 \,MeV \times \left( \frac { \mbox{particle mass}}{\mbox{proton mass}} \right) \] The simplified here means that the low energy shell correction term and the high energy Sternheimer density correction term have been omitted. Below the energy value $T_{lim}$ a simple parametrized energy loss formula is used to compute the loss, which reproduces the energy loss values of the stopping power tables fairly well. The main reason of using a parametrized formula for low energy is that the Bethe-Bloch breaks down at low energy. The formula has the following form : \[ \frac{dE}{dx} = \left \{ \begin{array}{ll} a*\sqrt{\frac{T}{M}}+b*\frac{T}{M} & \mbox{for $T \in [0, \, T_0]$} \\ \\ c*\sqrt{\frac{T}{M}} & \mbox{for $T \in [T_0, \, T_{lim}]$} \end{array} \right. \] \begin{tabbing} whereb:bbb\= \kill where : \> M = particle mass, \\ \> T = kinetic energy, \\ \> $ T_0=0.1 \, MeV \times Z^{1/3} \times \mbox{ M/(proton mass)} $\\ \> Z = atomic number. \end{tabbing} the paramaters $a,b,c$ have been chosen in such a way that $dE/dx$ is a continuous function of T at $T=T_{lim}$ and $T=T_0$ , and $dE/dx$ reaches its maximum at the correct T value. \subsection{Energy loss of electrons and positrons} The Berger-Seltzer energy loss formula has been used for T $>$ 10 keV to compute the energy loss comes from the ionization . This formula plays the role of the Bethe-Bloch for electrons ( see e.g. the GEANT3 manual).Below 10 keV the simple c/(T/mass of electron) parametrization has been used, where c can be determined from the requirement of continuity at T = 10 keV. As in the case of electrons the radiation loss is important even at relative low (few MeV ) energy, a second term has been added to the energy loss formula which accounts for the radiation losses (losses due to bremsstrahlung). This second term is an empirical parametrized formula. For positrons a different formula is used to calculate the ionization loss, the term accounting for the radiation losses is the same than that for electrons. \subsection{Range calculation} The stopping range is defined as : \[ R(T)= \int_0^T \frac{1}{(dE/dx)} \, dE \] The integration has been done analytically for the low energy part and numerically above an energy limit. \section{Photons} Starting from a particle cut given in absorption length, the method constructs a vector holding the cut values in kinetic energy for every material. The main steps of the algorithm are the following : \subsection{General scheme} \begin{enumerate} \item A cross section table is created and filled for all the elements in the element table. \item For every material in the material table the following steps are performed: \begin{enumerate} \item an absorption length vector is constructed using the cross section table \item the conversion from absorption length to kinetic energy is performed and the corresponding element of the {\tt KineticEnergyCuts} vector is set (It contains the particle cut value in kinetic energy for the actual material.), \item the absorption length vector is deleted. \end{enumerate} \item The cross section table is deleted at the end of the process. \end{enumerate} \subsection{Cross section formula for elements} An approximate empirical formula is used to compute the {\em absorption cross section} of a photon in an element. The {\em absorption cross section} means here the sum of the cross sections of the gamma conversion, Compton scattering and photoelectric effect. These processes are the 'destructive' processes for photons , they destroy the photon or decrease its energy. (The coherent or Rayleigh scattering changes the direction of the gamma only , its cross section is not included in the {\em absorption cross section}.) \subsection{Absorption length vector} The {\tt AbsorptionLength} vector is calculated for every material as : \begin{center} {\tt AbsorptionLength} = 5/(macroscopic absorption cross section) \end{center} The factor 5 comes from the requirement that the probability of having no 'destructive' interaction should be small, hence \begin{eqnarray*} \exp(-\mbox{{\tt AbsorptionLength * MacroscopicCrossSection}}) &=&\exp(-5) \\ &=& 6.7 \times 10^{-3} \end{eqnarray*} \subsection{Meaningful cuts in absorption length} The photon cross section for a material has a minimum at a certain kinetic energy $T_{min}$. The {\tt AbsorptionLength} has a maximum at $T=T_{min}$, the value of the maximal {\tt AbsorptionLength} is the biggest "meaningful" cut in absorption length . If the cut given by the user is bigger than this maximum, a warning is printed and the cut in kinetic energy is set to the maximum gamma energy (i.e. all the photons will be killed in the material). \section{Status of this document} 9.10.98 created by L. Urb\'an.
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.multiset.basic /-! # Sections of a multiset -/ namespace multiset variables {α : Type*} section sections /-- The sections of a multiset of multisets `s` consists of all those multisets which can be put in bijection with `s`, so each element is an member of the corresponding multiset. -/ def sections (s : multiset (multiset α)) : multiset (multiset α) := multiset.rec_on s {0} (λs _ c, s.bind $ λa, c.map (multiset.cons a)) (assume a₀ a₁ s pi, by simp [map_bind, bind_bind a₀ a₁, cons_swap]) @[simp] lemma sections_zero : sections (0 : multiset (multiset α)) = {0} := rfl @[simp] lemma sections_cons (s : multiset (multiset α)) (m : multiset α) : sections (m ::ₘ s) = m.bind (λa, (sections s).map (multiset.cons a)) := rec_on_cons m s lemma coe_sections : ∀(l : list (list α)), sections ((l.map (λl:list α, (l : multiset α))) : multiset (multiset α)) = ((l.sections.map (λl:list α, (l : multiset α))) : multiset (multiset α)) | [] := rfl | (a :: l) := begin simp, rw [← cons_coe, sections_cons, bind_map_comm, coe_sections l], simp [list.sections, (∘), list.bind] end @[simp] lemma sections_add (s t : multiset (multiset α)) : sections (s + t) = (sections s).bind (λm, (sections t).map ((+) m)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, bind_assoc, map_bind, bind_map, -add_comm]) lemma mem_sections {s : multiset (multiset α)} : ∀{a}, a ∈ sections s ↔ s.rel (λs a, a ∈ s) a := multiset.induction_on s (by simp) (assume a s ih a', by simp [ih, rel_cons_left, -exists_and_distrib_left, exists_and_distrib_left.symm, eq_comm]) lemma card_sections {s : multiset (multiset α)} : card (sections s) = prod (s.map card) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma prod_map_sum [comm_semiring α] {s : multiset (multiset α)} : prod (s.map sum) = sum ((sections s).map prod) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, map_bind, sum_map_mul_left, sum_map_mul_right]) end sections end multiset
If $f$ is L-Lipschitz on $[a,b]$ and $g$ is M-Lipschitz on $[b,c]$, and $f(b) = g(b)$, then the function $h$ defined by $h(x) = f(x)$ if $x \leq b$ and $h(x) = g(x)$ if $x > b$ is $(\max\{L,M\})$-Lipschitz on $[a,c]$.
lemma dist_commute_lessI: "dist y x < e \<Longrightarrow> dist x y < e"
(* Property from Productive Use of Failure in Inductive Proof, Andrew Ireland and Alan Bundy, JAR 1996. This Isabelle theory is produced using the TIP tool offered at the following website: https://github.com/tip-org/tools This file was originally provided as part of TIP benchmark at the following website: https://github.com/tip-org/benchmarks Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly to make it compatible with Isabelle2017. Some proofs were added by Yutaka Nagashima.*) theory TIP_prop_20 imports "../../Test_Base" begin datatype 'a list = nil2 | cons2 "'a" "'a list" datatype Nat = Z | S "Nat" fun x :: "'a list => 'a list => 'a list" where "x (nil2) z = z" | "x (cons2 z2 xs) z = cons2 z2 (x xs z)" fun length :: "'a list => Nat" where "length (nil2) = Z" | "length (cons2 z xs) = S (length xs)" fun even :: "Nat => bool" where "even (Z) = True" | "even (S (Z)) = False" | "even (S (S z2)) = even z2" theorem property0 : "even (length (x y y))" oops end
Require Export XRdefinitions. Local Open Scope XR_scope. Fixpoint INR (n:nat) : R := match n with | O => R0 | S O => R1 | S n => INR n + R1 end. Arguments INR n%nat.
Set Implicit Arguments. Require Import List. Import ListNotations. Inductive zipper (A : Type) : Type := | Zip : list A -> list A -> zipper A. Section INTERFACE. Variables A B : Type. Definition past (z : zipper A) : list A := match z with | Zip ls _ => ls end. Definition future (z : zipper A) : list A := match z with | Zip _ rs => rs end. Definition empty : zipper A := Zip [] []. Definition from_list (xs : list A) : zipper A := Zip [] xs. Definition from_list_end (xs : list A) : zipper A := Zip (rev xs) []. Definition to_list (z : zipper A) : list A := match z with | Zip l r => l ++ r end. Definition beginp (z : zipper A) : bool := match z with | Zip [] _ => true | _ => false end. Definition endp (z : zipper A) : bool := match z with | Zip _ [] => true | _ => false end. Definition emptyp (z : zipper A) : bool := match z with | Zip [] [] => true | _ => false end. Definition startz (z : zipper A) : zipper A := match z with | Zip l r => Zip [] (rev l ++ r) end. Definition endz (z : zipper A) : zipper A := match z with | Zip l r => Zip (rev r ++ l) [] end. Definition cursor_type (z : zipper A) : Type := if negb (endp z) then A else unit. Definition cursor (z : zipper A) : cursor_type z. destruct (endp z) eqn : Ha ; unfold cursor_type ; rewrite Ha ; simpl. exact tt. destruct z. destruct l0 ; simpl in *. congruence. exact a. Defined. Definition safe_cursor (z : zipper A) : option A := match z with | Zip _ (r :: _) => Some r | _ => None end. Definition left (z : zipper A) : zipper A := match z with | Zip (a :: ls) rs => Zip ls (a :: rs) | _ => z end. Definition right (z : zipper A) : zipper A := match z with | Zip ls (a :: rs) => Zip (a :: ls) rs | _ => z end. Definition insert (x : A)(z : zipper A) : zipper A := match z with | Zip ls rs => Zip ls (x :: rs) end. Definition delete (z : zipper A) : zipper A := match z with | Zip ls (_ :: rs) => Zip ls rs | _ => z end. Definition push (x : A)(z : zipper A) : zipper A := match z with | Zip ls rs => Zip (x :: ls) rs end. Definition pop (z : zipper A) : zipper A := match z with | Zip (_ :: ls) rs => Zip ls rs | _ => z end. Definition replacez (x : A)(z : zipper A) : zipper A := match z with | Zip ls (_ :: rs) => Zip ls (x :: rs) | _ => z end. Definition reversez (z : zipper A) : zipper A := match z with | Zip ls rs => Zip rs ls end. Fixpoint foldrz_fuel (fuel : nat)(f : zipper A -> B -> B)(v : B)(z : zipper A) : B := match fuel with | O => v | S fuel' => f z (foldrz_fuel fuel' f v (right z)) end. Definition foldrz (f : zipper A -> B -> B)(v : B)(z : zipper A) : B := match z with | Zip _ rs => foldrz_fuel (length rs) f v z end. Fixpoint foldlz_fuel (fuel : nat)(f : B -> zipper A -> B)(v : B)(z : zipper A) : B := match fuel with | O => v | S fuel' => foldlz_fuel fuel' f (f v z) (right z) end. Definition foldlz (f : B -> zipper A -> B)(v : B)(z : zipper A) : B := match z with | Zip ls _ => foldlz_fuel (length ls) f v z end. End INTERFACE.
{-# OPTIONS --prop --rewriting #-} open import Examples.Sorting.Sequential.Comparable module Examples.Sorting.Sequential.Core (M : Comparable) where open import Calf.CostMonoid open CostMonoid costMonoid hiding (zero; _+_; _≤_; ≤-refl; ≤-trans) public open import Examples.Sorting.Core costMonoid fromℕ M public