Datasets:
AI4M
/

text
stringlengths
0
3.34M
(* * Copyright 2014, General Dynamics C4 Systems * * SPDX-License-Identifier: GPL-2.0-only *) (* X64-specific CSpace invariants *) theory ArchCSpacePre_AI imports "../CSpacePre_AI" begin context Arch begin global_naming X64 lemmas typ_at_eq_kheap_obj = typ_at_eq_kheap_obj atyp_at_eq_kheap_obj lemmas set_cap_atyp_ats[wp] = abs_atyp_at_lifts[OF set_cap_typ_at] definition "final_matters_arch ac \<equiv> (case ac of ASIDPoolCap r as \<Rightarrow> True | ASIDControlCap \<Rightarrow> False | IOPortCap first_port last_port \<Rightarrow> True \<comment> \<open>FIXME: stab in the dark.\<close> | IOPortControlCap \<Rightarrow> False | PageCap dev r rghts maptype sz mapdata \<Rightarrow> False | PageTableCap r mapdata \<Rightarrow> True | PageDirectoryCap r mapdata \<Rightarrow> True | PDPointerTableCap r mapdata \<Rightarrow> True | PML4Cap r mapdata \<Rightarrow> True)" lemma is_page_cap_PageCap[simp]: "is_page_cap (PageCap dev ref rghts maptype pgsiz mapdata)" by (simp add: is_page_cap_def) lemma pageBitsForSize_eq[simp]: "(pageBitsForSize sz = pageBitsForSize sz') = (sz = sz')" by (cases sz; cases sz'; simp add: pageBits_def ptTranslationBits_def) lemma aobj_ref_cases': "aobj_ref acap = (case acap of ASIDControlCap \<Rightarrow> aobj_ref acap | _ \<Rightarrow> aobj_ref acap)" by (simp split: arch_cap.split) lemma aobj_ref_cases: "aobj_ref acap = (case acap of ASIDPoolCap w1 w2 \<Rightarrow> Some w1 | ASIDControlCap \<Rightarrow> None | IOPortCap _ _ \<Rightarrow> None | PageCap dev w s mt sz opt \<Rightarrow> Some w | PageTableCap w opt \<Rightarrow> Some w | PageDirectoryCap w opt \<Rightarrow> Some w | PDPointerTableCap w opt \<Rightarrow> Some w | PML4Cap w opt \<Rightarrow> Some w | IOPortControlCap \<Rightarrow> None)" apply (subst aobj_ref_cases') apply (clarsimp cong: arch_cap.case_cong) done definition "ups_of_heap h \<equiv> \<lambda>p. case h p of Some (ArchObj (DataPage dev sz)) \<Rightarrow> Some sz | _ \<Rightarrow> None" lemma ups_of_heap_typ_at: "ups_of_heap (kheap s) p = Some sz \<longleftrightarrow> data_at sz p s" by (auto simp: typ_at_eq_kheap_obj ups_of_heap_def data_at_def split: option.splits Structures_A.kernel_object.splits arch_kernel_obj.splits) lemma ups_of_heap_typ_at_def: "ups_of_heap (kheap s) \<equiv> \<lambda>p. if \<exists>!sz. data_at sz p s then Some (THE sz. data_at sz p s) else None" apply (rule eq_reflection) apply (rule ext) apply (clarsimp simp: ups_of_heap_typ_at) apply (intro conjI impI) apply (frule (1) theI') apply safe apply (fastforce simp: ups_of_heap_typ_at) by (auto simp: obj_at_def data_at_def) lemma ups_of_heap_non_arch_upd: "h x = Some ko \<Longrightarrow> non_arch_obj ko \<Longrightarrow> non_arch_obj ko' \<Longrightarrow> ups_of_heap (h(x \<mapsto> ko')) = ups_of_heap h" by (rule ext) (auto simp add: ups_of_heap_def non_arch_obj_def split: kernel_object.splits) crunch inv[wp]: lookup_ipc_buffer "I" lemma vs_cap_ref_to_table_cap_ref: "\<not> is_pg_cap cap \<Longrightarrow> vs_cap_ref cap = table_cap_ref cap" by (simp add: is_pg_cap_def table_cap_ref_def vs_cap_ref_simps split: cap.splits arch_cap.splits) lemma cap_master_cap_pg_cap: "\<lbrakk>cap_master_cap cap = cap_master_cap cap'\<rbrakk> \<Longrightarrow> is_pg_cap cap = is_pg_cap cap'" by (clarsimp simp:cap_master_cap_def is_cap_simps split:cap.splits arch_cap.splits dest!:cap_master_cap_eqDs) lemma master_arch_cap_obj_refs: "cap_master_arch_cap c = cap_master_arch_cap c' \<Longrightarrow> aobj_ref c = aobj_ref c'" by (simp add: cap_master_arch_cap_def split: arch_cap.splits) lemma master_arch_cap_cap_class: "cap_master_arch_cap c = cap_master_arch_cap c' \<Longrightarrow> acap_class c = acap_class c'" by (simp add: cap_master_arch_cap_def split: arch_cap.splits) lemma is_cap_free_index_update[simp]: "is_pml4_cap (src_cap\<lparr>free_index := a\<rparr>) = is_pml4_cap src_cap" "is_pdpt_cap (src_cap\<lparr>free_index := a\<rparr>) = is_pdpt_cap src_cap" "is_pd_cap (src_cap\<lparr>free_index := a\<rparr>) = is_pd_cap src_cap" "is_pt_cap (src_cap\<lparr>free_index := a\<rparr>) = is_pt_cap src_cap" by (simp add:is_cap_simps free_index_update_def split:cap.splits)+ lemma masked_as_full_test_function_stuff[simp]: "is_pml4_cap (masked_as_full a cap) = is_pml4_cap a" "is_pdpt_cap (masked_as_full a cap) = is_pdpt_cap a" "is_pd_cap (masked_as_full a cap) = is_pd_cap a" "is_pt_cap (masked_as_full a cap) = is_pt_cap a" "vs_cap_ref (masked_as_full a cap) = vs_cap_ref a" by (auto simp:masked_as_full_def) lemma same_aobject_as_commute: "same_aobject_as x y \<Longrightarrow> same_aobject_as y x" by (cases x; cases y; clarsimp simp: same_aobject_as_def) lemmas wellformed_cap_simps = wellformed_cap_def [simplified wellformed_acap_def, split_simps cap.split arch_cap.split] lemma is_vspace_table_Null[simp]: "\<not> is_pt_cap NullCap \<and> \<not> is_pd_cap NullCap \<and> \<not> is_pdpt_cap NullCap \<and> \<not> is_pml4_cap NullCap" by (simp add: is_pt_cap_def is_pd_cap_def is_pdpt_cap_def is_pml4_cap_def) lemma unique_table_caps_upd_eqD: "\<lbrakk>ms a = Some b; cap_asid b = cap_asid b'; obj_refs b = obj_refs b'; is_pd_cap b = is_pd_cap b'; is_pt_cap b = is_pt_cap b'; is_pdpt_cap b = is_pdpt_cap b'; is_pml4_cap b = is_pml4_cap b'\<rbrakk> \<Longrightarrow> unique_table_caps (ms (a \<mapsto> b')) = unique_table_caps (ms)" unfolding unique_table_caps_def apply (rule iffI) apply (intro allI impI,elim allE) apply (erule impE) apply (rule_tac p = p in fun_upd_Some) apply assumption apply (erule impE) apply (rule_tac p = p' in fun_upd_Some) apply simp apply (simp add: if_distrib split:if_splits) apply (intro allI impI,elim allE) apply (erule impE) apply (rule_tac p = p in fun_upd_Some_rev) apply simp+ apply (erule impE) apply (rule_tac p = p' in fun_upd_Some_rev) apply simp+ apply (simp add: if_distrib split:if_splits) done (* FIXME: unused *) lemma set_untyped_cap_as_full_not_final_not_pg_cap: "\<lbrace>\<lambda>s. (\<exists>a b. (a, b) \<noteq> dest \<and> \<not> is_pg_cap cap' \<and> cte_wp_at (\<lambda>cap. gen_obj_refs cap = gen_obj_refs cap' \<and> \<not> is_pg_cap cap) (a, b) s) \<and> cte_wp_at ((=) src_cap) src s\<rbrace> set_untyped_cap_as_full src_cap cap src \<lbrace>\<lambda>_ s.(\<exists>a b. (a, b) \<noteq> dest \<and> \<not> is_pg_cap cap' \<and> cte_wp_at (\<lambda>cap. gen_obj_refs cap = gen_obj_refs cap' \<and> \<not> is_pg_cap cap) (a, b) s)\<rbrace>" apply (rule hoare_pre) apply (wp hoare_vcg_ex_lift) apply (rule_tac Q = "cte_wp_at Q slot" and Q'="cte_wp_at ((=) src_cap) src" for Q slot in P_bool_lift' ) apply (wp set_untyped_cap_as_full_cte_wp_at) subgoal by (auto simp: cte_wp_at_caps_of_state is_cap_simps masked_as_full_def cap_bits_untyped_def) apply (wp set_untyped_cap_as_full_cte_wp_at_neg) apply (auto simp: cte_wp_at_caps_of_state is_cap_simps masked_as_full_def cap_bits_untyped_def) done lemma arch_derived_is_device: "\<lbrakk>cap_master_arch_cap c = cap_master_arch_cap c'; is_derived_arch (ArchObjectCap c) (ArchObjectCap c')\<rbrakk> \<Longrightarrow> arch_cap_is_device c' = arch_cap_is_device c" apply (case_tac c) apply (clarsimp simp: is_derived_arch_def cap_range_def is_cap_simps cap_master_cap_def cap_master_arch_cap_def split: if_split_asm cap.splits arch_cap.splits)+ done lemma valid_arch_mdb_simple: "\<And>s capa. \<lbrakk>valid_arch_mdb (is_original_cap s) (caps_of_state s); is_simple_cap cap; caps_of_state s src = Some capa\<rbrakk> \<Longrightarrow> valid_arch_mdb ((is_original_cap s) (dest := is_cap_revocable cap capa)) (caps_of_state s(dest \<mapsto> cap))" by (auto simp: valid_arch_mdb_def ioport_revocable_def is_cap_revocable_def arch_is_cap_revocable_def is_simple_cap_def safe_parent_for_def is_cap_simps) lemma free_index_update_irq_revocable[simp]: "ms src = Some src_cap \<Longrightarrow> ioport_revocable P (ms(src \<mapsto> src_cap\<lparr>free_index:=a\<rparr>)) = ioport_revocable P ms" unfolding ioport_revocable_def apply (rule iffI) apply clarify apply (drule_tac x = p in spec) apply (case_tac "p = src") apply (clarsimp simp:free_index_update_def)+ apply (simp add: free_index_update_def split:cap.splits) done lemma valid_arch_mdb_free_index_update: "\<lbrakk>m src = Some capa;m' = m (src\<mapsto> capa\<lparr>free_index :=x\<rparr>) \<rbrakk> \<Longrightarrow> valid_arch_mdb c (m') = valid_arch_mdb c (m)" by (clarsimp simp:valid_arch_mdb_def) lemma set_cap_update_free_index_valid_arch_mdb: "\<lbrace>\<lambda>s. valid_arch_mdb (is_original_cap s) (caps_of_state s) \<and> is_untyped_cap src_cap\<rbrace> set_cap (free_index_update f src_cap) src \<lbrace>\<lambda>rv s. valid_arch_mdb (is_original_cap s) (caps_of_state s)\<rbrace>" apply (clarsimp simp: valid_arch_mdb_def) apply (rule hoare_pre) apply (wps set_cap_rvk_cdt_ct_ms) apply wpsimp by (clarsimp simp: ioport_revocable_def is_cap_simps free_index_update_def split: cap.splits) lemma set_untyped_cap_as_full_valid_arch_mdb: "\<lbrace>\<lambda>s. valid_arch_mdb (is_original_cap s) (caps_of_state s)\<rbrace> set_untyped_cap_as_full src_cap c src \<lbrace>\<lambda>rv s. valid_arch_mdb (is_original_cap s) (caps_of_state s)\<rbrace>" by (wpsimp wp: set_cap_update_free_index_valid_arch_mdb simp: set_untyped_cap_as_full_def) lemma valid_arch_mdb_not_arch_cap_update: "\<And>s cap capa. \<lbrakk>\<not>is_arch_cap cap; valid_arch_mdb (is_original_cap s) (caps_of_state s)\<rbrakk> \<Longrightarrow> valid_arch_mdb ((is_original_cap s)(dest := True)) (caps_of_state s(src \<mapsto> cap, dest\<mapsto>capa))" by (auto simp: valid_arch_mdb_def ioport_revocable_def is_cap_simps) lemma valid_arch_mdb_derived_cap_update: "\<And>s capa. \<lbrakk>valid_arch_mdb (is_original_cap s) (caps_of_state s); is_derived (cdt s) src cap capa\<rbrakk> \<Longrightarrow> valid_arch_mdb ((is_original_cap s)(dest := is_cap_revocable cap capa)) (caps_of_state s(dest \<mapsto> cap))" apply (clarsimp simp: valid_arch_mdb_def ioport_revocable_def is_cap_simps is_cap_revocable_def arch_is_cap_revocable_def) by (clarsimp simp: is_derived_def is_cap_simps is_derived_arch_def split: if_split_asm) lemma valid_arch_mdb_free_index_update': "\<And>s capa. \<lbrakk>valid_arch_mdb (is_original_cap s) (caps_of_state s); caps_of_state s src = Some capa; is_untyped_cap cap\<rbrakk> \<Longrightarrow> valid_arch_mdb ((is_original_cap s) (dest := is_cap_revocable cap capa)) (caps_of_state s(dest \<mapsto> cap, src \<mapsto> max_free_index_update capa))" by (auto simp: valid_arch_mdb_def ioport_revocable_def is_cap_simps is_cap_revocable_def arch_is_cap_revocable_def free_index_update_def split: cap.splits) lemma weak_derived_IOPortControl[simp]: "weak_derived (ArchObjectCap IOPortControlCap) cap \<Longrightarrow> cap = ArchObjectCap IOPortControlCap" by (clarsimp simp: weak_derived_def copy_of_def same_object_as_def is_cap_simps split: if_split_asm cap.splits arch_cap.splits) lemma valid_arch_mdb_weak_derived_update: "\<And>s capa. \<lbrakk>valid_arch_mdb (is_original_cap s) (caps_of_state s); caps_of_state s src = Some capa; weak_derived cap capa\<rbrakk> \<Longrightarrow> valid_arch_mdb ((is_original_cap s) (dest := is_original_cap s src, src := False)) (caps_of_state s(dest \<mapsto> cap, src \<mapsto> NullCap))" by (auto simp: valid_arch_mdb_def ioport_revocable_def split: if_split_asm simp del: split_paired_All) lemma valid_arch_mdb_tcb_cnode_update: "valid_arch_mdb (is_original_cap s) (caps_of_state s) \<Longrightarrow> valid_arch_mdb ((is_original_cap s) ((t, tcb_cnode_index 2) := True)) (caps_of_state s((t, tcb_cnode_index 2) \<mapsto> ReplyCap t True canReplyGrant))" by (clarsimp simp: valid_arch_mdb_def ioport_revocable_def) lemmas valid_arch_mdb_updates = valid_arch_mdb_free_index_update valid_arch_mdb_not_arch_cap_update valid_arch_mdb_derived_cap_update valid_arch_mdb_free_index_update' valid_arch_mdb_weak_derived_update valid_arch_mdb_tcb_cnode_update lemma safe_parent_for_arch_not_arch': "\<not>is_arch_cap cap \<Longrightarrow> \<not>safe_parent_for_arch c cap" by (clarsimp simp: safe_parent_for_arch_def is_cap_simps) lemma ioport_revocableD: "\<lbrakk> cs p = Some (ArchObjectCap IOPortControlCap); ioport_revocable (is_original_cap s) cs \<rbrakk> \<Longrightarrow> is_original_cap s p" by (fastforce simp add: ioport_revocable_def simp del: split_paired_All) lemma safe_parent_arch_is_parent: "\<lbrakk>safe_parent_for_arch cap pcap; caps_of_state s p = Some pcap; valid_arch_mdb (is_original_cap s) (caps_of_state s)\<rbrakk> \<Longrightarrow> should_be_parent_of pcap (is_original_cap s p) cap f" apply (clarsimp simp: should_be_parent_of_def safe_parent_for_arch_def valid_arch_mdb_def) by (erule (1) ioport_revocableD) lemma safe_parent_for_arch_no_obj_refs: "safe_parent_for_arch cap c \<Longrightarrow> obj_refs cap = {}" by (clarsimp simp: safe_parent_for_arch_def) lemma valid_arch_mdb_same_master_cap: "\<lbrakk>valid_arch_mdb ioc cs; cs sl = Some cap; cap_master_cap cap' = cap_master_cap cap\<rbrakk> \<Longrightarrow> valid_arch_mdb ioc (cs(sl\<mapsto>cap'))" by (clarsimp simp: valid_arch_mdb_def ioport_revocable_def cap_master_cap_def split: cap.split_asm arch_cap.split_asm) lemma valid_arch_mdb_null_filter: "valid_arch_mdb (is_original_cap s) (null_filter (caps_of_state s)) = valid_arch_mdb (is_original_cap s) (caps_of_state s)" apply (clarsimp simp: null_filter_def valid_arch_mdb_def ioport_revocable_def) by auto lemma valid_arch_mdb_untypeds: "\<And>s. valid_arch_mdb (is_original_cap s) (caps_of_state s) \<Longrightarrow> valid_arch_mdb (\<lambda>x. x \<noteq> cref \<longrightarrow> is_original_cap s x) (caps_of_state s(cref \<mapsto> default_cap tp oref sz dev))" "\<And>s. valid_arch_mdb (is_original_cap s) (caps_of_state s) \<Longrightarrow> valid_arch_mdb (is_original_cap s) (caps_of_state s(cref \<mapsto> UntypedCap dev ptr sz idx))" by (clarsimp simp: valid_arch_mdb_def ioport_revocable_def)+ lemma same_object_as_ioports: "same_object_as c c' \<Longrightarrow> cap_ioports c = cap_ioports c'" by (clarsimp simp: same_object_as_def is_cap_simps cap_ioports_def split: cap.splits arch_cap.splits) lemma copy_of_ioports: "copy_of c c' \<Longrightarrow> cap_ioports c = cap_ioports c'" by (clarsimp simp: copy_of_def same_object_as_ioports split: if_split_asm) lemma weak_derived_cap_ioports: "weak_derived c c' \<Longrightarrow> cap_ioports c = cap_ioports c'" by (auto simp : weak_derived_def copy_of_ioports) end end
#include <cblas.h> #include <stdio.h> /* compilar: gcc fonte.c -o exec -lblas */ int main( void ) { int lda = 3; float A[] = { 1, 0, -1, 2, 3, 1 }; int ldb = 2; float B[] = { 5, 1, 6, -1, 7, 2 }; int ldc = 2; float C[] = { 0.00, 0.00, 0.00, 0.00 }; /* Compute C = A B */ cblas_sgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans, 2, 2, 3, 1.0, A, lda, B, ldb, 0.0, C, ldc ); printf( "[ %g, %g\n", C[ 0 ], C[ 1 ] ); printf( " %g, %g ]\n", C[ 2 ], C[ 3 ] ); return( 0 ); }
function [kW] = hp2kW(hp) % Convert power from mechanical horsepower to kilowatts. % Chad A. Greene 2012 kW = hp*0.745699872;
```python try: import openmdao.api as om import dymos as dm except ImportError: !python -m pip install openmdao[notebooks] !python -m pip install dymos[docs] import openmdao.api as om import dymos as dm ``` # Organizing Phases into Trajectories The majority of real-world use cases of optimal control involve complex trajectories that cannot be modeled with a single phase. For instance, different phases of a trajectory may have different equations of motion, different control parameterizations, or different path constraints. Phases are also necessary if the user wishes to impose intermediate constraints upon some variable, by imposing them as boundary constraints at a phase junction. The *Trajectory* class in Dymos is intended to simplify the development of multi-phase problems. It serves as a Group which contains the various phases belonging to the trajectory, and it provides linkage constraints that dictate how phases are linked together. This enables trajectories that are not only a sequence of phases in time, but may include branching behavior, allowing us to do things like track/constrain the path of a jettisoned rocket stage. It supports a `get_values` method similar to that of Phases that allows the user to retrieve the value of a variable within the trajectory. When verifying an answer with explicit simulation, the `simulate` method of Trajectory can simulate all of its member phases in parallel, providing a significant performance improvement for some cases. ## Instantiating a Trajectory Instantiating a Trajectory is simple. Simply invoke `Trajectory()`. The trajectory object itself is an OpenMDAO `Group` which serves as a container for its constituent Phases. - phases An OpenMDAO `Group` or `ParallelGroup` holding the member phases - linkages A Dymos `PhaseLinkageComp` that manages all of the linkage constraints that dictate how the phases are connected. ## Adding Phases Phases are added to a Trajectory using the `add_phase` method. ```{eval-rst} .. automethod:: dymos.Trajectory.add_phase :noindex: ``` ## Defining Phase Linkages Having added phases to the Trajectory, they now exist as independent Groups within the OpenMDAO model. In order to enforce continuity among certain variables across phases, the user must declare which variables are to be continuous in value at each phase boundary. There are two methods in dymos which provide this functionality. The `add_linkage_constraint` method provides a very general way of coupling two phases together. It does so by generating a constraint of the following form: \begin{align} c = \mathrm{sign}_a \mathrm{var}_a + \mathrm{sign}_b \mathrm{var}_b \end{align} Method `add_linkage_constraint` lets the user specify the variables and phases to be compared for this constraint, as well as the location of the variable in each phase (either 'initial' or 'final') By default this method is setup to provide continuity in a variable between two phases: - the sign of variable `a` is +1 while the sign of variable `b` is -1. - the location of variable `a` is 'final' while the location of variable `b` is 'initial'. - the default value of the constrained quantity is 0.0. In this way, the default behavior constrains the final value of some variable in phase `a` to be the same as the initial value of some variable in phase `b`. Other values for these options can provide other functionality. For instance, to simulate a mass jettison, we could require that the initial value of `mass` in phase `b` be 1000 kg less than the value of mass at the end of phase `a`. Providing arguments `equals = 1000, units='kg` would achieve this. Similarly, specifying other values for the locations of the variables in each phase can be used to ensure that two phases start or end at the same condition - such as the case in a branching trajectory or a rendezvous. While `add_linkage_constraint` gives the user a powerful capability, providing simple state and time continuity across multiple phases would be a very verbose undertaking using this method. The `link_phases` method is intended to simplify this process. In the finite-burn orbit raising example, there are three phases: `burn1`, `coast`, `burn2`. This case is somewhat unusual in that the thrust acceleration is modeled as a state variable. The acceleration needs to be zero in the coast phase, but continuous between `burn1` and `burn2`, assuming no mass was jettisoned during the coast and that the thrust magnitude doesn't change. ### add_linkage_constraint ```{eval-rst} .. automethod:: dymos.Trajectory.add_linkage_constraint :noindex: ``` ### link_phases ```{eval-rst} .. automethod:: dymos.Trajectory.link_phases :noindex: ``` ## Examples of using the `link_phases` method **Typical Phase Linkage Sequence** A typical phase linkage sequence, where all phases use the same ODE (and therefore have the same states), are simply linked sequentially in time. ```python t.link_phases(['phase1', 'phase2', 'phase3']) ``` **Adding an Additional Linkage** If the user wants some control variable, `u`, to be continuous in value between `phase2` and `phase3` only, they could indicate that with the following code: ```python t.link_phases(['phase2', 'phase3'], vars=['u']) ``` **Branching Trajectories** For a more complex example, consider the case where there are two phases which branch off from the same point, such as the case of a jettisoned stage. The nominal trajectory consists of the phase sequence `['a', 'b', 'c']`. Let phase `['d']` be the phase that tracks the jettisoned component to its impact with the ground. The linkages in this case would be defined as: ```python t.link_phases(['a', 'b', 'c']) t.link_phases(['b', 'd']) ``` **Specifying Linkage Locations** Phase linkages assume that, for each pair, the state/control values at the end (`'final'`) of the first phase are linked to the state/control values at the start of the second phase (`'initial'`). The user can override this behavior, but they must specify a pair of location strings for each pair given in `phases`. For instance, in the following example phases `a` and `b` have the same initial time and state, but phase `c` follows phase `b`. Note since there are three phases provided, there are two linkages and thus two pairs of location specifiers given. ```python t.link_phases(['a', 'b', 'c'], locs=[('initial', 'initial'), ('final', 'initial')]) ``` ## Trajectory-Level Parameters Often times, there are parameters which apply to the entirety of a trajectory that potentially need to be optimized. If we implemented these as parameters within each phase individually, we would need some constraints to ensure that they held the same value within each phase. To avoid this complexity, Dymos Trajectory objects support their own Parameters. Like their Phase-based counterparts, Trajectory parameters produce may be design variables for the problem or used as inputs to the trajectory from external sources. When using Trajectory parameters, their values are connected to each phase as an Input Parameter within the Phase. Because ODEs in different phases may have different names for parameters (e.g. 'mass', 'm', 'm_total', etc) Dymos allows the user to specify the targeted ODE parameters on a phase-by-phase basis using the `targets` and `target_params` option. It can take on the following values. * If `targets` is `None` the trajectory parameter will be connected to the phase input parameter of the same name in each phase, if it exists (otherwise it is not connected to that phase). * Otherwise targets should be specified as a dictionary. And the behavior depends on the value associated with each phase name: * If the phase name is not in the given dictionary, attempt to connect to an existing parameter of the same name in that phase. * If the associated value is None, explicitly omit a connection to that phase. * If the associated value is a string, connect to an existing input parameter whose name is given by the string in that phase. * If the associated value is a Sequence, create an input parameter in that phase connected to the ODE targets given by the Sequence. ## Explicit Simulation of Trajectories The `simulate` method on Trajectory is similar to that of the `simulate` method of Phases. When invoked, it will perform a simulation of each Phase in the trajectory.
import tactic variable {α : Type*} variables (s t u : set α) open set example (h : s ⊆ t) : s ∩ u ⊆ t ∩ u := begin intros x xsu, exact ⟨h xsu.1, xsu.2⟩, end /- Alternatively -/ example (h : s ⊆ t) : s ∩ u ⊆ t ∩ u := by exact λ x ⟨xs, xu⟩, ⟨h xs, xu⟩
/* * Copyright 2013 Stanford University. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * - Neither the name of the copyright holders nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This is the code for parsing the log.txt files dumped by Nimbus * scheduler/worker. * * Author: Omid Mashayekhi <[email protected]> */ #include <boost/tokenizer.hpp> #include <iostream> // NOLINT #include <fstream> // NOLINT #include <sstream> // NOLINT #include <string> #include <map> using boost::tokenizer; using boost::char_separator; int main(int argc, char *argv[]) { std::ifstream input; std::string file_name; double useful_time = 0; double start_time, end_time; std::map<std::string, double> time_profile; if (argc <= 1) file_name = "log.txt"; else file_name = argv[1]; std::cout << "file name: " << file_name << std::endl; input.open(file_name.c_str()); if (input.fail()) { std::cout << "Could not open file: " << file_name << std::endl; return -1; } while (true) { std::string line; getline(input, line); if (input.fail()) break; // std::cout << line << std::endl; char_separator<char> separator(" \t"); tokenizer<char_separator<char> > tokens(line, separator); tokenizer<char_separator<char> >::iterator iter = tokens.begin(); std::string job_name; iter++; iter++; iter++; iter++; job_name = *iter; if (time_profile.find(job_name) == time_profile.end()) time_profile[job_name] = 0; double time; iter++; iter++; iter++; iter++; std::stringstream ss(*iter); ss >> time; time_profile[job_name] = time_profile[job_name] + time; // std::cout << job_name << time << std::endl; iter++; iter++; std::stringstream sss(*iter); sss >> end_time; if (job_name == "main") start_time = end_time; } input.close(); std::map<std::string, double>::iterator iter; for (iter = time_profile.begin(); iter != time_profile.end(); iter++) { printf("name: %25s time(s): %6.3lf\n", iter->first.c_str(), iter->second/1000); useful_time += iter->second/1000; } printf("\n%-20s %6.3lf\n", "total time(s):", end_time - start_time); printf("%-20s %6.3lf\n", "useful time(s):", useful_time); printf("%-20s %6.3lf\n", "nimbus overhead(s):", end_time - start_time - useful_time); printf("%-20s %6.3lf\n", "efficiency:", useful_time/(end_time - start_time)); }
lemma is_nth_power_mult_coprime_natD: fixes a b :: nat assumes "coprime a b" "is_nth_power n (a * b)" "a > 0" "b > 0" shows "is_nth_power n a" "is_nth_power n b"
[STATEMENT] lemma star_inductl_one: "1 + x \<cdot> y \<le> y \<Longrightarrow> x\<^sup>\<star> \<le> y" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (1::'a) + x \<cdot> y \<le> y \<Longrightarrow> x\<^sup>\<star> \<le> y [PROOF STEP] using star_inductl [PROOF STATE] proof (prove) using this: ?z + ?x \<cdot> ?y \<le> ?y \<Longrightarrow> ?x\<^sup>\<star> \<cdot> ?z \<le> ?y goal (1 subgoal): 1. (1::'a) + x \<cdot> y \<le> y \<Longrightarrow> x\<^sup>\<star> \<le> y [PROOF STEP] by force
r=359.73 https://sandbox.dams.library.ucdavis.edu/fcrepo/rest/collection/sherry-lehmann/catalogs/d7jp4g/media/images/d7jp4g-102/svc:tesseract/full/full/359.73/default.jpg Accept:application/hocr+xml
result = 0 b = 1 for i in range(0,n): temp = result result = b b = temp + b
(*<*) theory TheoryCombination imports Main begin nitpick_params[user_axioms=true, show_all, expect=genuine, format = 3] (*>*) section \<open>Semantic Embedding of Carmo and Jones' Dyadic Deontic Logic (DDL) augmented with Kaplanian contexts\<close> subsection \<open>Definition of Types\<close> typedecl w \<comment> \<open> Type for possible worlds (Kaplan's "circumstances of evaluation" or "counterfactual situations") \<close> typedecl e \<comment> \<open> Type for individuals (entities eligible to become agents) \<close> typedecl c \<comment> \<open> Type for Kaplanian "contexts of use" \<close> type_synonym wo = "w\<Rightarrow>bool" \<comment> \<open> contents/propositions are identified with their truth-sets \<close> type_synonym cwo = "c\<Rightarrow>wo" \<comment> \<open> sentence meaning (Kaplan's "character") is a function from contexts to contents \<close> type_synonym m = "cwo" \<comment> \<open> we use the letter 'm' for characters (reminiscent of "meaning") \<close> subsection \<open>Semantic Characterisation of DDL\<close> abbreviation subset::"wo\<Rightarrow>wo\<Rightarrow>bool" (infix "\<sqsubseteq>" 46) where "\<alpha> \<sqsubseteq> \<beta> \<equiv> \<forall>w. \<alpha> w \<longrightarrow> \<beta> w" abbreviation intersection::"wo\<Rightarrow>wo\<Rightarrow>wo" (infixr "\<sqinter>" 48) where "\<alpha> \<sqinter> \<beta> \<equiv> \<lambda>x. \<alpha> x \<and> \<beta> x" abbreviation union::"wo\<Rightarrow>wo\<Rightarrow>wo" (infixr "\<squnion>" 48) where "\<alpha> \<squnion> \<beta> \<equiv> \<lambda>x. \<alpha> x \<or> \<beta> x" abbreviation complement::"wo\<Rightarrow>wo" ("\<sim>_"[45]46) where "\<sim>\<alpha> \<equiv> \<lambda>x. \<not>\<alpha> x" abbreviation instantiated::"wo\<Rightarrow>bool" ("\<I>_"[45]46) where "\<I> \<phi> \<equiv> \<exists>x. \<phi> x" abbreviation setEq::"wo\<Rightarrow>wo\<Rightarrow>bool" (infix "=\<^sub>s" 46) where "\<alpha> =\<^sub>s \<beta> \<equiv> \<forall>x. \<alpha> x \<longleftrightarrow> \<beta> x" abbreviation univSet :: "wo" ("\<top>") where "\<top> \<equiv> \<lambda>w. True" abbreviation emptySet :: "wo" ("\<bottom>") where "\<bottom> \<equiv> \<lambda>w. False" consts av::"w\<Rightarrow>wo" \<comment> \<open> set of worlds that are open alternatives (aka. actual versions) of w \<close> pv::"w\<Rightarrow>wo" \<comment> \<open> set of worlds that are possible alternatives (aka. potential versions) of w \<close> ob::"wo\<Rightarrow>wo\<Rightarrow>bool" \<comment> \<open> set of propositions which are obligatory in a given context (of type wo) \<close> axiomatization where sem_3a: "\<forall>w. \<I>(av w)" and \<comment> \<open> av is serial: in every situation there is always an open alternative \<close> sem_4a: "\<forall>w. av w \<sqsubseteq> pv w" and \<comment> \<open> open alternatives are possible alternatives \<close> sem_4b: "\<forall>w. pv w w" and \<comment> \<open> pv is reflexive: every situation is a possible alternative to itself \<close> sem_5a: "\<forall>X. \<not>(ob X \<bottom>)" and \<comment> \<open> contradictions cannot be obligatory \<close> sem_5b: "\<forall>X Y Z. (X \<sqinter> Y) =\<^sub>s (X \<sqinter> Z) \<longrightarrow> (ob X Y \<longleftrightarrow> ob X Z)" and sem_5c: "\<forall>X Y Z. \<I>(X \<sqinter> Y \<sqinter> Z) \<and> ob X Y \<and> ob X Z \<longrightarrow> ob X (Y \<sqinter> Z)" and sem_5d: "\<forall>X Y Z. (Y \<sqsubseteq> X \<and> ob X Y \<and> X \<sqsubseteq> Z) \<longrightarrow> ob Z ((Z \<sqinter> (\<sim>X)) \<squnion> Y)" and sem_5e: "\<forall>X Y Z. Y \<sqsubseteq> X \<and> ob X Z \<and> \<I>(Y \<sqinter> Z) \<longrightarrow> ob Y Z" subsection \<open>Verifying Semantic Conditions\<close> lemma sem_5b1: "ob X Y \<longrightarrow> ob X (Y \<sqinter> X)" by (metis (no_types, lifting) sem_5b) lemma sem_5b2: "(ob X (Y \<sqinter> X) \<longrightarrow> ob X Y)" by (metis (no_types, lifting) sem_5b) lemma sem_5ab: "ob X Y \<longrightarrow> \<I>(X \<sqinter> Y)" by (metis (full_types) sem_5a sem_5b) lemma sem_5bd1: "Y \<sqsubseteq> X \<and> ob X Y \<and> X \<sqsubseteq> Z \<longrightarrow> ob Z ((\<sim>X) \<squnion> Y)" using sem_5b sem_5d by smt lemma sem_5bd2: "ob X Y \<and> X \<sqsubseteq> Z \<longrightarrow> ob Z ((Z \<sqinter> (\<sim>X)) \<squnion> Y)" using sem_5b sem_5d by (smt sem_5b1) lemma sem_5bd3: "ob X Y \<and> X \<sqsubseteq> Z \<longrightarrow> ob Z ((\<sim>X) \<squnion> Y)" by (smt sem_5bd2 sem_5b) lemma sem_5bd4: "ob X Y \<and> X \<sqsubseteq> Z \<longrightarrow> ob Z ((\<sim>X) \<squnion> (X \<sqinter> Y))" using sem_5bd3 by auto lemma sem_5bcd: "(ob X Z \<and> ob Y Z) \<longrightarrow> ob (X \<squnion> Y) Z" using sem_5b sem_5c sem_5d oops (* 5e and 5ab justify redefinition of @{cite "O\<langle>\<phi>|\<sigma>\<rangle>"} as (ob A B)*) lemma "ob A B \<longleftrightarrow> (\<I>(A \<sqinter> B) \<and> (\<forall>X. X \<sqsubseteq> A \<and> \<I>(X \<sqinter> B) \<longrightarrow> ob X B))" using sem_5e sem_5ab by blast abbreviation pand::"m\<Rightarrow>m\<Rightarrow>m" (infixr"\<^bold>\<and>" 51) where "\<phi>\<^bold>\<and>\<psi> \<equiv> \<lambda>c w. (\<phi> c w)\<and>(\<psi> c w)" abbreviation por::"m\<Rightarrow>m\<Rightarrow>m" (infixr"\<^bold>\<or>" 50) where "\<phi>\<^bold>\<or>\<psi> \<equiv> \<lambda>c w. (\<phi> c w)\<or>(\<psi> c w)" abbreviation pimp::"m\<Rightarrow>m\<Rightarrow>m" (infix"\<^bold>\<rightarrow>" 49) where "\<phi>\<^bold>\<rightarrow>\<psi> \<equiv> \<lambda>c w. (\<phi> c w)\<longrightarrow>(\<psi> c w)" abbreviation pequ::"m\<Rightarrow>m\<Rightarrow>m" (infix"\<^bold>\<leftrightarrow>" 48) where "\<phi>\<^bold>\<leftrightarrow>\<psi> \<equiv> \<lambda>c w. (\<phi> c w)\<longleftrightarrow>(\<psi> c w)" abbreviation pnot::"m\<Rightarrow>m" ("\<^bold>\<not>_" [52]53) where "\<^bold>\<not>\<phi> \<equiv> \<lambda>c w. \<not>(\<phi> c w)" abbreviation cjboxa :: "m\<Rightarrow>m" ("\<^bold>\<box>\<^sub>a_" [52]53) where "\<^bold>\<box>\<^sub>a\<phi> \<equiv> \<lambda>c w. \<forall>v. (av w) v \<longrightarrow> (\<phi> c v)" abbreviation cjdiaa :: "m\<Rightarrow>m" ("\<^bold>\<diamond>\<^sub>a_" [52]53) where "\<^bold>\<diamond>\<^sub>a\<phi> \<equiv> \<lambda>c w. \<exists>v. (av w) v \<and> (\<phi> c v)" abbreviation cjboxp :: "m\<Rightarrow>m" ("\<^bold>\<box>\<^sub>p_" [52]53) where "\<^bold>\<box>\<^sub>p\<phi> \<equiv> \<lambda>c w. \<forall>v. (pv w) v \<longrightarrow> (\<phi> c v)" abbreviation cjdiap :: "m\<Rightarrow>m" ("\<^bold>\<diamond>\<^sub>p_" [52]53) where "\<^bold>\<diamond>\<^sub>p\<phi> \<equiv> \<lambda>c w. \<exists>v. (pv w) v \<and> (\<phi> c v)" abbreviation cjtaut :: "m" ("\<^bold>\<top>") where "\<^bold>\<top> \<equiv> \<lambda>c w. True" abbreviation cjcontr :: "m" ("\<^bold>\<bottom>") where "\<^bold>\<bottom> \<equiv> \<lambda>c w. False" abbreviation cjod :: "m\<Rightarrow>m\<Rightarrow>m" ("\<^bold>O\<langle>_|_\<rangle>"54) where "\<^bold>O\<langle>\<phi>|\<sigma>\<rangle> \<equiv> \<lambda>c w. ob (\<sigma> c) (\<phi> c)" abbreviation cjos :: "m\<Rightarrow>m" ("\<^bold>O\<langle>_\<rangle>"[53]54) where "\<^bold>O\<langle>\<phi>\<rangle> \<equiv> \<^bold>O\<langle>\<phi>|\<^bold>\<top>\<rangle>" abbreviation cjoa :: "m\<Rightarrow>m" ("\<^bold>O\<^sub>a_" [53]54) where "\<^bold>O\<^sub>a\<phi> \<equiv> \<lambda>c w. (ob (av w)) (\<phi> c) \<and> (\<exists>x. (av w) x \<and> \<not>(\<phi> c x))" abbreviation cjop :: "m\<Rightarrow>m" ("\<^bold>O\<^sub>i_" [53]54) where "\<^bold>O\<^sub>i\<phi> \<equiv> \<lambda>c w. (ob (pv w)) (\<phi> c) \<and> (\<exists>x. (pv w) x \<and> \<not>(\<phi> c x))" abbreviation modvalidctx :: "m\<Rightarrow>c\<Rightarrow>bool" ("\<lfloor>_\<rfloor>\<^sup>M") where "\<lfloor>\<phi>\<rfloor>\<^sup>M \<equiv> \<lambda>c. \<forall>w. \<phi> c w" \<comment> \<open> context-dependent modal validity \<close> abbreviation modvalid :: "m\<Rightarrow>bool" ("\<lfloor>_\<rfloor>") where "\<lfloor>\<phi>\<rfloor> \<equiv> \<forall>c. \<lfloor>\<phi>\<rfloor>\<^sup>M c" \<comment> \<open> general modal validity (modally valid in each context) \<close> abbreviation mboxS5 :: "m\<Rightarrow>m" ("\<^bold>\<box>\<^sup>S\<^sup>5_" [52]53) where "\<^bold>\<box>\<^sup>S\<^sup>5\<phi> \<equiv> \<lambda>c w. \<forall>v. \<phi> c v" abbreviation mdiaS5 :: "m\<Rightarrow>m" ("\<^bold>\<diamond>\<^sup>S\<^sup>5_" [52]53) where "\<^bold>\<diamond>\<^sup>S\<^sup>5\<phi> \<equiv> \<lambda>c w. \<exists>v. \<phi> c v" subsection \<open>Verifying the Embedding\<close> lemma "\<lfloor>P \<^bold>\<rightarrow> \<^bold>O\<^sub>aP\<rfloor>" nitpick oops \<comment> \<open> (actual) deontic modal collapse is countersatisfiable \<close> lemma "\<lfloor>P \<^bold>\<rightarrow> \<^bold>O\<^sub>iP\<rfloor>" nitpick oops \<comment> \<open> (ideal) deontic modal collapse is countersatisfiable \<close> lemma "\<lfloor>P \<^bold>\<rightarrow> \<^bold>\<box>\<^sub>aP\<rfloor>" nitpick oops \<comment> \<open> alethic modal collapse is countersatisfiable (implies all other necessity operators) \<close> lemma NecDDLa: "\<lfloor>A\<rfloor> \<Longrightarrow> \<lfloor>\<^bold>\<box>\<^sub>aA\<rfloor>" by simp (* Valid only using classical (not Kaplan's indexical) validity*) lemma NecDDLp: "\<lfloor>A\<rfloor> \<Longrightarrow> \<lfloor>\<^bold>\<box>\<^sub>pA\<rfloor>" by simp (* Valid only using classical (not Kaplan's indexical) validity*) subsection \<open>Verifying Axiomatic Characterisation and C&J Theorems\<close> lemma C_2: "\<lfloor>\<^bold>O\<langle>A | B\<rangle> \<^bold>\<rightarrow> \<^bold>\<diamond>\<^sup>S\<^sup>5(B \<^bold>\<and> A)\<rfloor>" by (simp add: sem_5ab) lemma C_3: "\<lfloor>((\<^bold>\<diamond>\<^sup>S\<^sup>5(A \<^bold>\<and> B \<^bold>\<and> C)) \<^bold>\<and> \<^bold>O\<langle>B|A\<rangle> \<^bold>\<and> \<^bold>O\<langle>C|A\<rangle>) \<^bold>\<rightarrow> \<^bold>O\<langle>(B \<^bold>\<and> C)| A\<rangle>\<rfloor>" by (simp add: sem_5c) lemma C_4: "\<lfloor>(\<^bold>\<box>\<^sup>S\<^sup>5(A \<^bold>\<rightarrow> B) \<^bold>\<and> \<^bold>\<diamond>\<^sup>S\<^sup>5(A \<^bold>\<and> C) \<^bold>\<and> \<^bold>O\<langle>C|B\<rangle>) \<^bold>\<rightarrow> \<^bold>O\<langle>C|A\<rangle>\<rfloor>" using sem_5e by blast lemma C_5: "\<lfloor>\<^bold>\<box>\<^sup>S\<^sup>5(A \<^bold>\<leftrightarrow> B) \<^bold>\<rightarrow> (\<^bold>O\<langle>C|A\<rangle> \<^bold>\<rightarrow> \<^bold>O\<langle>C|B\<rangle>)\<rfloor>" using sem_5ab sem_5e by blast lemma C_6: "\<lfloor>\<^bold>\<box>\<^sup>S\<^sup>5(C \<^bold>\<rightarrow> (A \<^bold>\<leftrightarrow> B)) \<^bold>\<rightarrow> (\<^bold>O\<langle>A|C\<rangle> \<^bold>\<leftrightarrow> \<^bold>O\<langle>B|C\<rangle>)\<rfloor>" by (metis sem_5b) lemma C_7: "\<lfloor>\<^bold>O\<langle>B|A\<rangle> \<^bold>\<rightarrow> \<^bold>\<box>\<^sup>S\<^sup>5\<^bold>O\<langle>B|A\<rangle>\<rfloor>" by blast lemma C_8: "\<lfloor>\<^bold>O\<langle>B|A\<rangle> \<^bold>\<rightarrow> \<^bold>O\<langle>A \<^bold>\<rightarrow> B| \<^bold>\<top>\<rangle>\<rfloor>" using sem_5bd4 by presburger lemma CJ_3: "\<lfloor>\<^bold>\<box>\<^sub>pA \<^bold>\<rightarrow> \<^bold>\<box>\<^sub>aA\<rfloor>" by (simp add: sem_4a) lemma CJ_4: "\<lfloor>\<^bold>\<not>\<^bold>O\<langle>\<^bold>\<bottom>|A\<rangle>\<rfloor>" by (simp add: sem_5a) lemma CJ_5: "\<lfloor>(\<^bold>O\<langle>B|A\<rangle> \<^bold>\<and> \<^bold>O\<langle>C|A\<rangle>) \<^bold>\<rightarrow> \<^bold>O\<langle>B\<^bold>\<and>C|A\<rangle>\<rfloor>" nitpick oops \<comment> \<open> countermodel found \<close> lemma CJ_5_minus: "\<lfloor>\<^bold>\<diamond>\<^sup>S\<^sup>5(A \<^bold>\<and> B \<^bold>\<and> C) \<^bold>\<and> (\<^bold>O\<langle>B|A\<rangle> \<^bold>\<and> \<^bold>O\<langle>C|A\<rangle>) \<^bold>\<rightarrow> \<^bold>O\<langle>B\<^bold>\<and>C|A\<rangle>\<rfloor>" by (simp add: sem_5c) lemma CJ_6: "\<lfloor>\<^bold>O\<langle>B|A\<rangle> \<^bold>\<rightarrow> \<^bold>O\<langle>B|A\<^bold>\<and>B\<rangle>\<rfloor>" by (smt C_2 C_4) lemma CJ_7: "\<lfloor>A \<^bold>\<leftrightarrow> B\<rfloor> \<longrightarrow> \<lfloor>\<^bold>O\<langle>C|A\<rangle> \<^bold>\<leftrightarrow> \<^bold>O\<langle>C|B\<rangle>\<rfloor>" using sem_5ab sem_5e by blast (* Valid only using classical (not Kaplan's indexical) validity*) lemma CJ_8: "\<lfloor>C \<^bold>\<rightarrow> (A \<^bold>\<leftrightarrow> B)\<rfloor> \<longrightarrow> \<lfloor>\<^bold>O\<langle>A|C\<rangle> \<^bold>\<leftrightarrow> \<^bold>O\<langle>B|C\<rangle>\<rfloor>" using C_6 by simp (* Valid only using classical (not Kaplan's indexical) validity*) lemma CJ_9a: "\<lfloor>\<^bold>\<diamond>\<^sub>p\<^bold>O\<langle>B|A\<rangle> \<^bold>\<rightarrow> \<^bold>\<box>\<^sub>p\<^bold>O\<langle>B|A\<rangle>\<rfloor>" by simp lemma CJ_9p: "\<lfloor>\<^bold>\<diamond>\<^sub>a\<^bold>O\<langle>B|A\<rangle> \<^bold>\<rightarrow> \<^bold>\<box>\<^sub>a\<^bold>O\<langle>B|A\<rangle>\<rfloor>" by simp lemma CJ_9_var_a: "\<lfloor>\<^bold>O\<langle>B|A\<rangle> \<^bold>\<rightarrow> \<^bold>\<box>\<^sub>a\<^bold>O\<langle>B|A\<rangle>\<rfloor>" by simp lemma CJ_9_var_b: "\<lfloor>\<^bold>O\<langle>B|A\<rangle> \<^bold>\<rightarrow> \<^bold>\<box>\<^sub>p\<^bold>O\<langle>B|A\<rangle>\<rfloor>" by simp section \<open>Extending the Carmo and Jones DDL Logical Framework\<close> consts Agent::"c\<Rightarrow>e" \<comment> \<open> function retrieving the agent corresponding to context c \<close> consts World::"c\<Rightarrow>w" \<comment> \<open> function retrieving the world corresponding to context c \<close> abbreviation ldtruectx::"m\<Rightarrow>c\<Rightarrow>bool" ("\<lfloor>_\<rfloor>\<^sub>_") where "\<lfloor>\<phi>\<rfloor>\<^sub>c \<equiv> \<phi> c (World c)" \<comment> \<open> truth in the given context \<close> abbreviation ldvalid::"m\<Rightarrow>bool" ("\<lfloor>_\<rfloor>\<^sup>D") where "\<lfloor>\<phi>\<rfloor>\<^sup>D \<equiv> \<forall>c. \<lfloor>\<phi>\<rfloor>\<^sub>c" \<comment> \<open> LD validity (true in every context) \<close> lemma "\<lfloor>A\<rfloor> \<Longrightarrow> \<lfloor>A\<rfloor>\<^sup>D" by simp lemma "\<lfloor>A\<rfloor>\<^sup>D \<Longrightarrow> \<lfloor>A\<rfloor>" nitpick oops \<comment> \<open> countermodel found \<close> lemma "\<lfloor>P \<^bold>\<rightarrow> \<^bold>O\<^sub>aP\<rfloor>\<^sup>D" nitpick oops lemma "\<lfloor>P \<^bold>\<rightarrow> \<^bold>\<box>\<^sub>aP\<rfloor>\<^sup>D" nitpick oops lemma NecLDa: "\<lfloor>A\<rfloor>\<^sup>D \<Longrightarrow> \<lfloor>\<^bold>\<box>\<^sub>aA\<rfloor>\<^sup>D" nitpick oops lemma NecLDp: "\<lfloor>A\<rfloor>\<^sup>D \<Longrightarrow> \<lfloor>\<^bold>\<box>\<^sub>pA\<rfloor>\<^sup>D" nitpick oops abbreviation ldvalidbox :: "m\<Rightarrow>m" ("\<^bold>\<box>\<^sup>D_" [52]53) where "\<^bold>\<box>\<^sup>D\<phi> \<equiv> \<lambda>c w. \<lfloor>\<phi>\<rfloor>\<^sup>D" \<comment> \<open> notice the D superscript \<close> lemma "\<lfloor>\<^bold>\<box>\<^sup>D\<phi>\<rfloor>\<^sub>C \<equiv> \<forall>c.\<lfloor>\<phi>\<rfloor>\<^sub>c" by simp \<comment> \<open> this operator works analogously to the box operator in modal logic S5 \<close> lemma NecLD: "\<lfloor>A\<rfloor>\<^sup>D \<Longrightarrow> \<lfloor>\<^bold>\<box>\<^sup>DA\<rfloor>\<^sup>D" by simp abbreviation mforall::"('t\<Rightarrow>m)\<Rightarrow>m" ("\<^bold>\<forall>") where "\<^bold>\<forall>\<Phi> \<equiv> \<lambda>c w.\<forall>x. (\<Phi> x c w)" abbreviation mexists::"('t\<Rightarrow>m)\<Rightarrow>m" ("\<^bold>\<exists>") where "\<^bold>\<exists>\<Phi> \<equiv> \<lambda>c w.\<exists>x. (\<Phi> x c w)" abbreviation mforallBinder::"('t\<Rightarrow>m)\<Rightarrow>m" (binder"\<^bold>\<forall>"[8]9) where "\<^bold>\<forall>x. (\<phi> x) \<equiv> \<^bold>\<forall>\<phi>" abbreviation mexistsBinder::"('t\<Rightarrow>m)\<Rightarrow>m" (binder"\<^bold>\<exists>"[8]9) where "\<^bold>\<exists>x. (\<phi> x) \<equiv> \<^bold>\<exists>\<phi>" type_synonym cwe = "c\<Rightarrow>w\<Rightarrow>e" \<comment> \<open>type alias for indexical individual terms\<close> abbreviation cthe::"(c\<Rightarrow>w\<Rightarrow>e\<Rightarrow>bool)\<Rightarrow>cwe" ("the") where "the \<phi> \<equiv> \<lambda>c w. THE x. \<phi> c w x" abbreviation ctheBinder::"(c\<Rightarrow>w\<Rightarrow>e\<Rightarrow>bool)\<Rightarrow>cwe" (binder"the"[8]9) where "the x. (\<phi> x) \<equiv> the \<phi>" abbreviation dthat::"cwe\<Rightarrow>cwe" ("dthat[_]" [62]63) where "dthat[\<alpha>] \<equiv> \<lambda>c w. \<alpha> c (World c)" abbreviation Dthat::"(c\<Rightarrow>w\<Rightarrow>e\<Rightarrow>bool)\<Rightarrow>cwe" ("Dthat[_]" [62]63) where "Dthat[\<alpha>] \<equiv> dthat[the \<alpha>] " abbreviation ceq:: "cwe\<Rightarrow>cwe\<Rightarrow>m" (infix "\<^bold>\<approx>" 60) where "\<alpha> \<^bold>\<approx> \<beta> \<equiv> \<lambda>c w. \<alpha> c w = \<beta> c w" (**standard equality for characters*) lemma "\<lfloor>\<alpha> \<^bold>\<approx> dthat[\<alpha>]\<rfloor>\<^sup>D" by simp \<comment> \<open>using indexical validity\<close> lemma "\<lfloor>\<alpha> \<^bold>\<approx> dthat[\<alpha>]\<rfloor>" nitpick oops \<comment> \<open>counterexample if using classical validity\<close> lemma "\<lfloor>\<^bold>\<box>\<^sup>S\<^sup>5(\<alpha> \<^bold>\<approx> dthat[\<alpha>])\<rfloor>\<^sup>D" nitpick oops \<comment> \<open>counterexample\<close> lemma "\<lfloor>\<^bold>\<box>\<^sup>S\<^sup>5(dthat[\<beta>] \<^bold>\<approx> dthat[\<alpha>])\<rfloor>\<^sub>x\<Longrightarrow>\<lfloor>(dthat[\<beta>] \<^bold>\<approx> dthat[\<alpha>])\<rfloor>\<^sup>D" nitpick oops \<comment> \<open>counterexample\<close> lemma "\<lfloor>dthat[\<beta>] \<^bold>\<approx> dthat[\<alpha>]\<rfloor>\<^sup>D \<longleftrightarrow> \<lfloor>\<beta> \<^bold>\<approx> \<alpha>\<rfloor>\<^sup>D" by simp lemma "\<lfloor>dthat[\<beta>] \<^bold>\<approx> dthat[\<alpha>] \<^bold>\<leftrightarrow> (\<beta> \<^bold>\<approx> \<alpha>) \<rfloor>\<^sup>D" by simp abbreviation cactually :: "m\<Rightarrow>m" ("\<^bold>\<A>_" [52]53) where "\<^bold>\<A>\<phi> \<equiv> \<lambda>c w. \<phi> c (World c)" lemma "\<lfloor>\<phi> \<^bold>\<leftrightarrow> \<^bold>\<A>\<phi>\<rfloor>\<^sup>D" by simp lemma "\<lfloor>\<^bold>\<box>\<^sup>S\<^sup>5(\<phi> \<^bold>\<leftrightarrow> \<^bold>\<A>\<phi>)\<rfloor>\<^sup>D" nitpick oops lemma "\<lfloor>\<^bold>\<box>\<^sup>S\<^sup>5(\<phi> \<^bold>\<leftrightarrow> \<^bold>\<A>\<phi>)\<rfloor>" nitpick oops lemma "\<lfloor>\<phi>\<rfloor>\<^sup>D \<longleftrightarrow> \<lfloor>\<^bold>\<A>\<phi>\<rfloor> " by simp abbreviation stable::"m\<Rightarrow>c\<Rightarrow>bool" where "stable \<phi> c \<equiv> \<forall>w. \<phi> c w \<longrightarrow> \<lfloor>\<phi>\<rfloor>\<^sup>M c" abbreviation stableCharacter::"m\<Rightarrow>bool" where "stableCharacter \<phi> \<equiv> \<forall>c. stable \<phi> c" lemma "\<forall>c. stable (\<^bold>\<A>\<phi>) c" by simp \<comment> \<open> (i)\<close> lemma "stableCharacter \<phi> \<longrightarrow> (\<lfloor>\<phi>\<rfloor>\<^sup>D \<longrightarrow> \<lfloor>\<phi>\<rfloor>)" by blast \<comment> \<open> (ii)\<close> lemma "stableCharacter \<phi> \<longrightarrow> (\<lfloor>\<phi>\<rfloor>\<^sup>D \<longrightarrow> \<lfloor>\<^bold>\<box>\<^sub>a\<phi>\<rfloor>\<^sup>D)" by blast \<comment> \<open> (iii)\<close> lemma "\<lfloor>\<phi>\<rfloor>\<^sup>D \<longrightarrow> \<lfloor>\<^bold>\<box>\<^sub>a\<phi>\<rfloor>\<^sup>D" nitpick oops \<comment> \<open>counterexample in the general case\<close> (*<*) end (*>*)
If $f$ is continuous at $a$ and $g$ is continuous at $f(a)$, then $g \circ f$ is continuous at $a$.
If $f$ is continuous at $a$ and $g$ is continuous at $f(a)$, then $g \circ f$ is continuous at $a$.
# Part D: Comparison of toroidal meniscus models with different profile shapes ## Introduction So far all the capillary entry pressures for the percoaltion examples were calculated using the ``Standard`` physics model which is the ``Washburn`` model for straight walled capillary tubes. This has been shown to be a bad model for fibrous media where the walls of throats are converging and diverging. In the study [Capillary Hysteresis in Neutrally Wettable Fibrous Media: A Pore Network Study of a Fuel Cell Electrode](http://link.springer.com/10.1007/s11242-017-0973-2) percolation in fibrous media was simulated using a meniscus model that assumed the contrictions between fibers are similar to a toroid: This model was first proposed by Purcell and treats the inner solid profile as a circle. As the fluid invades through the center of the torus the meniscus is pinned to the surface and the "effective" contact angle becomes influenced by the converging diverging geometry and is a function of the filling angle $\alpha$. The shape of the meniscus as the invading phase moves upwards through the torus with key model parameters is shown below. Different intrinsic contact angles through invading phase are shown above: (a) 60$^\circ$, (b) 90$^\circ$ and (c) 120$^\circ$. All scenarios clearly show an inflection of the meniscus curvature signifying a switch in the sign of the capillary pressure from negative to positive. This inflection is predicted to occur for all contact angles by the model with varying filling angle. The capillary pressure can be shown to be: $P_C = -2\sigma cos(\theta-\alpha))/(r+R(1-cos(\alpha))$ A consequence of the circular solid profile is that all fluid behaves as non-wetting fluid because $\alpha$ can range from -90$^\circ$ to 90$^\circ$ degrees and so even if $\theta$ is 0 then the meniscus is still pinned at zero capillary pressure at the very furthest part of the throat where the $\alpha$ is 90$^\circ$ Considering other shapes of solid profile this situation can be avoided. It will be shown by reformulating the Purcell model in a more general way that allows for a flexible defintion of the solid profile that filling angle can be limited to values below 90 and allow for spontaneous imbibition (percolation threshold below zero) of highly wetting fluids. ## Set up We will set up a trivially small network with one throat to demonstrate the use of the meniscus model. Here we do the imports and define a few functions for plotting. ```python import matplotlib %matplotlib inline import matplotlib.pyplot as plt import numpy as np import sympy as syp from sympy import lambdify, symbols from sympy import atan as sym_atan from sympy import cos as sym_cos from sympy import sin as sym_sin from sympy import sqrt as sym_sqrt from sympy import pi as sym_pi from ipywidgets import interact, fixed from IPython.display import display import warnings np.random.seed(10) warnings.simplefilter(action='ignore') matplotlib.rcParams['figure.figsize'] = (5, 5) ``` ```python theta = 60 fiberRad = 5e-6 throatRad = 1e-5 max_bulge = 1e-5 ``` Now we define our two pore network and add the meniscus model in several modes: 'max' returns the maximum pressure experienced by the meniscus as it transitions through the throat, i.e. the burst entry pressure. 'touch' is the pressure at which the meniscus has protruded past the throat center a distance defined by the 'touch_length' dictionary key. In network simulations this could be set to the pore_diameter. Finally the 'men' mode accepts a target_Pc parameter and returns all the mensicus information required for assessing cooperative filling or plotting. ```python import openpnm as op %config InlineBackend.figure_formats = ['svg'] import openpnm.models.physics as pm net = op.network.Cubic(shape=[2, 1, 1], spacing=5e-5) geo = op.geometry.SpheresAndCylinders(network=net, pores=net.pores(), throats=net.throats()) phase = op.phases.Water(network=net) phase['pore.contact_angle'] = theta phys = op.physics.Standard(network=net, phase=phase, geometry=geo) geo['throat.diameter'] = throatRad*2 geo['throat.touch_length'] = max_bulge ``` We define a plotting function that uses the meniscus data: $\alpha$ is filling angle as defined above, $radius$ is the radius of curvature of the mensicus, $center$ is the position of the centre of curvature relative to the throat center along the axis of the throat, $\gamma$ is the angle between the throat axis and the line joining the meniscus center and meniscus contact point. ```python def plot_meniscus(target_Pc, meniscus_model=None, ax=None): throatRad = geo['throat.diameter'][0]/2 theta = np.deg2rad(phys['pore.contact_angle'][0]) throat_a = phys['throat.scale_a'] throat_b = phys['throat.scale_b'] x_points = np.arange(-0.99, 0.99, 0.01)*throat_a if ax is None: fig, ax = plt.subplots() if meniscus_model.__name__ == 'purcell': # Parameters for plotting fibers x, R, rt, s, t = syp.symbols('x, R, rt, s, t') y = R*syp.sqrt(1- (x/R)**2) r = rt + (R-y) rx = syp.lambdify((x, R, rt), r, 'numpy') ax.plot(x_points, rx(x_points, fiberRad, throatRad), 'k-'); ax.plot(x_points, -rx(x_points, fiberRad, throatRad), 'k-'); phys.add_model(propname='throat.meniscus', model=meniscus_model, mode='men', r_toroid=fiberRad, target_Pc=target_Pc) elif meniscus_model.__name__ == 'sinusoidal': x, a, b, rt, sigma, theta = syp.symbols('x, a, b, rt, sigma, theta') y = (sym_cos(sym_pi*x/(2*a)))*b r = rt + (b-y) rx = lambdify((x, a, b, rt), r, 'numpy') ax.plot(x_points, rx(x_points, throat_a, throat_b, throatRad), 'k-'); ax.plot(x_points, -rx(x_points, throat_a, throat_b, throatRad), 'k-'); phys.add_model(propname='throat.meniscus', model=meniscus_model, mode='men', r_toroid=fiberRad, target_Pc=target_Pc) else: # General Ellipse x, a, b, rt, sigma, theta = syp.symbols('x, a, b, rt, sigma, theta') profile_equation = phys.models['throat.entry_pressure']['profile_equation'] if profile_equation == 'elliptical': y = sym_sqrt(1 - (x/a)**2)*b elif profile_equation == 'sinusoidal': y = (sym_cos(sym_pi*x/(2*a)))*b r = rt + (b-y) rx = lambdify((x, a, b, rt), r, 'numpy') ax.plot(x_points, rx(x_points, throat_a, throat_b, throatRad), 'k-'); ax.plot(x_points, -rx(x_points, throat_a, throat_b, throatRad), 'k-'); phys.add_model(propname='throat.meniscus', model=meniscus_model, profile_equation=profile_equation, mode='men', target_Pc=target_Pc) men_data = {} men_data['alpha'] = phys['throat.meniscus.alpha'] men_data['gamma'] = phys['throat.meniscus.gamma'] men_data['radius'] = phys['throat.meniscus.radius'] men_data['center'] = phys['throat.meniscus.center'] arc_cen = men_data['center'] arc_rad = men_data['radius'] arc_angle = men_data['gamma'] angles = np.linspace(-arc_angle, arc_angle, 100) arcx = arc_cen + arc_rad*np.cos(angles) arcy = arc_rad*np.sin(angles) ax.plot(arcx, arcy, 'b-') ax.scatter(phys['throat.meniscus.pos'], phys['throat.meniscus.rx']); ax.axis('equal') ax.ticklabel_format(style='sci', axis='both', scilimits=(-6,-6)) return ax ``` # Circular (Purcell) ```python circular_model = pm.meniscus.purcell phys.add_model(propname='throat.max', model=circular_model, mode='max', r_toroid=fiberRad) phys.add_model(propname='throat.touch', model=circular_model, mode='touch', r_toroid=fiberRad) phys.add_model(propname='throat.meniscus', model=circular_model, mode='men', r_toroid=fiberRad, target_Pc=1000) touch_Pc = phys['throat.touch'][0] print('Pressure at maximum bulge', np.around(touch_Pc, 0)) max_Pc_circle = phys['throat.max'][0] print('Circular profile critical entry pressure', np.around(max_Pc_circle, 0)) ``` Pressure at maximum bulge 7213.0 Circular profile critical entry pressure 8165.0 We can see that the touch_Pc calculated earlier, corresponds with the tip of the meniscus exceeding the max_bulge parameter. Try changing this and re-running to see what happens. ```python ax = plot_meniscus(target_Pc=touch_Pc, meniscus_model=circular_model) ax.plot([max_bulge, max_bulge], [-throatRad, throatRad], 'r--'); ``` [<matplotlib.lines.Line2D at 0x7f1048c87d00>] ```python ax = plot_meniscus(target_Pc=max_Pc_circle, meniscus_model=circular_model) ``` We can interact with the mensicus model by changing the target_Pc parameter. ```python interact(plot_meniscus, target_Pc=(-2000, max_Pc_circle, 1), meniscus_model=fixed(circular_model), ax=fixed(None)); ``` interactive(children=(FloatSlider(value=3082.0, description='target_Pc', max=8165.324889242946, min=-2000.0, s… <function __main__.plot_meniscus(target_Pc, meniscus_model=None, ax=None)> Here we can see that the critical entry pressure for the circular profile is positive, even though the intrinsic contact angle is highly non-wetting # Sinusoidal Now we can start to compare the different meniscus models: ```python sinusoidal_model = pm.meniscus.sinusoidal ``` ```python display(sinusoidal_model) ``` <function openpnm.models.physics.meniscus.sinusoidal(target, mode='max', target_Pc=None, num_points=1000.0, r_toroid=5e-06, throat_diameter='throat.diameter', pore_diameter='pore.diameter', touch_length='throat.touch_length', surface_tension='pore.surface_tension', contact_angle='pore.contact_angle')> ```python phys.add_model(propname='throat.meniscus', model=sinusoidal_model, mode='men', r_toroid=fiberRad, target_Pc=1000) ``` The equation for the solid sinusoidal profile is: ```python x, a, b, rt, sigma, theta = syp.symbols('x, a, b, rt, sigma, theta') y = (sym_cos(sym_pi*x/(2*a)))*b r = rt + b-y r ``` $\displaystyle - b \cos{\left(\frac{\pi x}{2 a} \right)} + b + rt$ ```python # Derivative of profile rprime = r.diff(x) rprime ``` $\displaystyle \frac{\pi b \sin{\left(\frac{\pi x}{2 a} \right)}}{2 a}$ ```python # Filling angle alpha = sym_atan(rprime) alpha ``` $\displaystyle \operatorname{atan}{\left(\frac{\pi b \sin{\left(\frac{\pi x}{2 a} \right)}}{2 a} \right)}$ ```python # Angle between y axis, meniscus center and meniscus contact point eta = sym_pi - (theta + alpha) eta ``` $\displaystyle - \theta - \operatorname{atan}{\left(\frac{\pi b \sin{\left(\frac{\pi x}{2 a} \right)}}{2 a} \right)} + \pi$ ```python # Angle between x axis, meniscus center and meniscus contact point gamma = sym_pi/2 - eta gamma ``` $\displaystyle \theta + \operatorname{atan}{\left(\frac{\pi b \sin{\left(\frac{\pi x}{2 a} \right)}}{2 a} \right)} - \frac{\pi}{2}$ ```python # Radius of curvature of meniscus rm = r/sym_cos(eta) rm ``` $\displaystyle - \frac{- b \cos{\left(\frac{\pi x}{2 a} \right)} + b + rt}{\cos{\left(\theta + \operatorname{atan}{\left(\frac{\pi b \sin{\left(\frac{\pi x}{2 a} \right)}}{2 a} \right)} \right)}}$ ```python # Distance along x-axis from center of curvature to meniscus contact point d = rm*sym_sin(eta) d ``` $\displaystyle - \frac{\left(- b \cos{\left(\frac{\pi x}{2 a} \right)} + b + rt\right) \sin{\left(\theta + \operatorname{atan}{\left(\frac{\pi b \sin{\left(\frac{\pi x}{2 a} \right)}}{2 a} \right)} \right)}}{\cos{\left(\theta + \operatorname{atan}{\left(\frac{\pi b \sin{\left(\frac{\pi x}{2 a} \right)}}{2 a} \right)} \right)}}$ ```python # Capillary Pressure p = 2*sigma/rm p ``` $\displaystyle - \frac{2 \sigma \cos{\left(\theta + \operatorname{atan}{\left(\frac{\pi b \sin{\left(\frac{\pi x}{2 a} \right)}}{2 a} \right)} \right)}}{- b \cos{\left(\frac{\pi x}{2 a} \right)} + b + rt}$ ```python phys.add_model(propname='throat.max', model=sinusoidal_model, mode='max', r_toroid=fiberRad) phys.add_model(propname='throat.touch', model=sinusoidal_model, mode='touch', r_toroid=fiberRad) max_Pc_sin = phys['throat.max'][0] print(max_Pc_sin) ``` 4729.770413396985 ```python plot_meniscus(target_Pc=max_Pc_sin, meniscus_model=sinusoidal_model); ``` <AxesSubplot:> ```python interact(plot_meniscus, target_Pc=(-2000, max_Pc_sin, 1), meniscus_model=fixed(sinusoidal_model), ax=fixed(None)); ``` interactive(children=(FloatSlider(value=1364.0, description='target_Pc', max=4729.770413396985, min=-2000.0, s… <function __main__.plot_meniscus(target_Pc, meniscus_model=None, ax=None)> Now the crtical entry pressure is negative signifying that spontaneous imbibition will occur # General Elliptical Similarly we can define an elliptical profile and use the same method to determine the capillary pressure: ```python y = sym_sqrt(1 - (x/a)**2)*b y ``` $\displaystyle b \sqrt{1 - \frac{x^{2}}{a^{2}}}$ In-fact this is the model that OpenPNM uses for Purcell as well with a = b = fiber radius ```python # Scale ellipse in x direction phys['throat.scale_a'] = fiberRad # Scale ellipse in y direction phys['throat.scale_b'] = fiberRad general_model = pm.meniscus.general_toroidal phys.add_model(propname='throat.entry_pressure', model=general_model, profile_equation='elliptical', mode='max') max_Pc_ellipse = phys['throat.entry_pressure'][0] print(max_Pc_ellipse) ``` 8165.324889242946 ```python plot_meniscus(target_Pc=max_Pc_ellipse, meniscus_model=general_model); ``` <AxesSubplot:> ```python max_Pc_ellipse ``` 8165.324889242946 ```python interact(plot_meniscus, target_Pc=(-2000, max_Pc_ellipse, 1), meniscus_model=fixed(general_model), ax=fixed(None)); ``` interactive(children=(FloatSlider(value=3082.0, description='target_Pc', max=8165.324889242946, min=-2000.0, s… <function __main__.plot_meniscus(target_Pc, meniscus_model=None, ax=None)> The two scale factors can now be used to determine a wide range of capillary behaviours with one general model. Below we run the model for a range of scaling factors showing the effect on the sign and magnitude of the entry pressure. ```python bs = np.linspace(0.2, 1.0, 4)*throatRad phys['throat.scale_a'] = throatRad elliptical_pressures = [] sinusoidal_pressures = [] fig, (ax1, ax2) = plt.subplots(2, len(bs), figsize=(10, 10)) for i in range(len(bs)): phys['throat.scale_b'] = bs[i] phys.add_model(propname='throat.entry_pressure', model=general_model, profile_equation='elliptical', mode='max', num_points=1000) Pc = phys['throat.entry_pressure'] elliptical_pressures.append(Pc) plot_meniscus(target_Pc=Pc, meniscus_model=general_model, ax=ax1[i]) for i in range(len(bs)): phys['throat.scale_b'] = bs[i] phys.add_model(propname='throat.entry_pressure', model=general_model, profile_equation='sinusoidal', mode='max', num_points=1000) Pc = phys['throat.entry_pressure'] sinusoidal_pressures.append(Pc) plot_meniscus(target_Pc=Pc, meniscus_model=general_model, ax=ax2[i]) ``` ```python plt.figure() plt.plot(bs/throatRad, elliptical_pressures, 'g-'); plt.plot(bs/throatRad, sinusoidal_pressures, 'r-'); ``` [<matplotlib.lines.Line2D at 0x7f1048287e20>] Here we can see that the two different shaped profiles lead to quite different capiallary behaviour. The elliptical profile always resuls in positive pressure and the meniscus is basically pinned to the end of the throat where highest pressure occurs as alpha always reaches 90. Whereas the sinusiodal model allows for spontaneous imbibition where a breakthrough may occur at negative capillary pressure for wetting fluids if the wall angle is shallow.
module Verified.Applicative.Vect import Data.Vect import Verified.Applicative import Verified.Functor import Verified.Functor.Vect applicativeMap_Vect : (vs : Vect n a) -> (g : a -> b) -> map g vs = pure g <*> vs applicativeMap_Vect [] g = Refl applicativeMap_Vect (v :: vs) g = rewrite (applicativeMap_Vect vs g) in Refl applicativeIdentity_Vect : (vs : Vect n a) -> pure id <*> vs = vs applicativeIdentity_Vect [] = Refl applicativeIdentity_Vect (x :: xs) = rewrite (applicativeIdentity_Vect xs) in Refl applicativeInterchange_Vect : (x : a) -> (g : Vect n (a -> b)) -> g <*> pure x = pure (\g' => g' x) <*> g applicativeInterchange_Vect x [] = Refl applicativeInterchange_Vect x (f :: fs) = rewrite (applicativeInterchange_Vect x fs) in Refl applicativeComposition_Vect : (xs : Vect n a) -> (g1 : Vect n (a -> b)) -> (g2 : Vect n (b -> c)) -> pure (.) <*> g2 <*> g1 <*> xs = g2 <*> (g1 <*> xs) applicativeComposition_Vect [] [] [] = Refl applicativeComposition_Vect (v :: vs) (g1 :: g1s) (g2 :: g2s) = rewrite (applicativeComposition_Vect vs g1s g2s) in Refl applicativeHomomorphism_Vect : {n : Nat} -> (x : a) -> (g : a -> b) -- pure g <*> pure x = pure (g x) -> Vect.zipWith apply (Vect.replicate n g) (Vect.replicate n x) = Vect.replicate n (g x) applicativeHomomorphism_Vect {n = Z } x g = Refl applicativeHomomorphism_Vect {n = (S k)} x g = rewrite (applicativeHomomorphism_Vect x g {n=k}) in Refl instance VerifiedApplicative (Vect vlen) where applicativeMap = applicativeMap_Vect applicativeIdentity = applicativeIdentity_Vect applicativeInterchange = applicativeInterchange_Vect applicativeComposition = applicativeComposition_Vect applicativeHomomorphism = applicativeHomomorphism_Vect
\chapter{Chapter 13} \begin{shop}{162\,000} \begin{itemize} \item Eden Pharmaceuticals \begin{itemize} \item Sell \begin{itemize} \item Weapons: Everything \item Accessories: Everything but Warrior's Wristband \item Components: Everything \end{itemize} \item Buy \begin{itemize} \item Deceptisol x3 (2 if not enough gil) \item Fortisol x3 \item Aegisol x3 \end{itemize} \end{itemize} \end{itemize} \end{shop} \begin{menu} \begin{itemize} \paradigm \begin{itemize} \item Battle Team \begin{itemize} \item Switch Sazh with Vanille (1 $\leftrightarrow$ 3) \item \paradigmdeck{% \paradigmline{Vanille}{Snow}{Sazh}}% {\paradigmline{(\rav)}{(\rav)}{(\syn)}}% {\paradigmline{\com)}{\com}{\com}}% {\paradigmline{\rav)}{\sen}{\rav}}% {\paradigmline{\med}{\com}{\com}}% {\paradigmline[5]{\textit{(\sab)}}{\textit{(\rav)}}{\textit{\rav}}}% {\paradigmline{\rav}{\rav}{\rav}} \end{itemize} \end{itemize} \crystarium \begin{itemize} \item Vanille \begin{itemize} \item Medic \begin{itemize} \item 7 nodes Left 1, HP +100 to the side \end{itemize} \end{itemize} \item Snow \begin{itemize} \item Commando \begin{itemize} \item 16 nodes, Role level 4 \end{itemize} \end{itemize} \item Sazh \begin{itemize} \item Commando \begin{itemize} \item ($\uparrow$) 5 nodes up 2, Adrenaline to the top \item 3 nodes right 2, Accessory to the side \item 2 nodes, HP +100 \end{itemize} \end{itemize} \end{itemize} \equip \begin{itemize} \item Sazh \begin{itemize} \item Optimize: Balanced \end{itemize} \end{itemize} \end{itemize} \end{menu} Activate \textbf{Deceptisol} during the jump to the left, don't cancel. Activate \textbf{Fortisol, Aegisol} before the statue. \vfill \renewcommand{\first}{[1] Malevolence (\rav/\rav/\syn)} \renewcommand{\second}{[2] Cerberus (\com/\com/\com)} \renewcommand{\third}{[3] Mystic Tower (\rav/\sen/\rav)} \renewcommand{\fifth}{[5] Smart Bomb (\sab/\rav/\rav)} \renewcommand{\sixth}{[6] Tri-Disaster (\rav/\rav/\rav)} \begin{battle}[0:55]{Bandersnatch \& Jabberwocky} \begin{itemize} \item \fifth \begin{itemize} \item Imperil x5 Bandersnatch \item Repeat until Imperil is inflicted \end{itemize} \item \sixth \begin{itemize} \item Fira-Aerora Bandersnatch \item Summon when Bandersnatch is at 410\% \item Repeat \item X - Gestalt \item {\it If below 485\% chain:} B - Force Blasters \item Y - Gaian Salvo \item Retry if not dead \item Auto-chain \item Shift after Snow's fifth Attack \end{itemize} \item \fifth \begin{itemize} \item If Breath of the Beast, shift to [3] until the attack is done \item Deprotect-Poison-Deprotect-Poison-Poison \item Cancel and repeat if the second Deprotect doesn't land \item Shift when Snow finishes his second string \end{itemize} \item \sixth \begin{itemize} \item Fire-Water-Aerora \item Fire-Water-Fire for interruption \item Shift to cancel Snow's ready animation \end{itemize} \item \second \begin{itemize} \item Repeat \textit{if no Deprotect else }Poison x5 \item Repeat until victory \end{itemize} \end{itemize} \itemdrop{0.13}{Aegisol} \end{battle} \textbf{Deceptisol} when jumping, don't cancel. \begin{menu} \begin{itemize} \paradigm \begin{itemize} \item Battle Team \begin{itemize} \item \paradigmdeck{% \paradigmline{Vanille}{Snow}{Sazh}}% {\paradigmline{\rav}{\rav}{\syn}}% {\paradigmline{(\sab)}{\com}{\com}}% {\paradigmline{\textit{(\sab)}}{\textit{\sen}}{\textit{(\syn)}}}% {\paradigmline{\med}{\com}{\com}}% {\paradigmline{\sab}{\rav}{\rav}}% {\paradigmline{\rav}{\rav}{\rav}} \end{itemize} \end{itemize} \end{itemize} \end{menu} Activate \textbf{Ethersol, Fortisol, Aegisol}. \vfill \renewcommand{\second}{[2] Devastation (\sab/\com/\com)} \renewcommand{\fifth}{[5] Smart Bomb (\sab/\rav/\rav)} \renewcommand{\sixth}{[6] Tri-Disaster (\rav/\rav/\rav)} \renewcommand{\third}{[3] Premeditation (\sab/\sen/\syn)} \renewcommand{\fourth}{[4] Tireless Charge (\med/\com/\com)} \renewcommand{\first}{[1] Malevolence (\rav/\rav/\syn)} \begin{battle}[0:45]{Wladislaus} \begin{itemize} \item \third \begin{itemize} \item Libra \item Deprotect x5 \item Shift after Sazh's third Enfire \end{itemize} \item \second \begin{itemize} \item If no Deprotect, Repeat \item Renew \item If no Deprotect, Repeat \item Repeat when Mounting Contempt \end{itemize} \item \third \begin{itemize} \item If no Deprotect, Repeat \item Shift after Snow is hit by Mounting Contempt \end{itemize} \item \fourth \begin{itemize} \item Auto-heal \item Auto-heal after Wladislaus's attack \item Shift after Snow's fifth attack, cancel ready animation \end{itemize} \item \second \begin{itemize} \item Should die to Snow and Sazh. Otherwise repeat same process as above. \item Can Renew a second time if needed \end{itemize} \end{itemize} \end{battle} Take the left elevator, then \textbf{Ethersol} and \textbf{Deceptisol} while it rises. On the jumps, activate \textbf{Fortisol}, \textbf{Aegisol}, Menu. \begin{menu} \begin{itemize} \crystarium \begin{itemize} \item \textit{(Optional)} Vanille \begin{itemize} \item Medic \begin{itemize} \item 3 nodes, HP +200 \end{itemize} \end{itemize} \item Sazh \begin{itemize} \item Commando \begin{itemize} \item 4 nodes, HP +90 \end{itemize} \item Sentinel \begin{itemize} \item 6 nodes, Provoke \end{itemize} \end{itemize} \item Snow \begin{itemize} \item Commando \begin{itemize} \item 6 nodes, Str +30 \end{itemize} \end{itemize} \end{itemize} \equip \begin{itemize} \item Snow \begin{itemize} \item Remove \begin{itemize} \item All Power Gloves \end{itemize} \end{itemize} \item Sazh \begin{itemize} \item Optimize: Balanced \end{itemize} \item Snow \begin{itemize} \item Optimize: Balanced \end{itemize} \end{itemize} \paradigm \begin{itemize} \item \paradigmdeck{% \paradigmline{Vanille}{Snow}{Sazh}}% {\paradigmline{\rav}{\rav}{\syn}}% {\paradigmline[2]{\textit{(\rav)}}{\textit{\com}}{\textit{\com}}}% {\paradigmline{(\med)}{\sen}{(\sen)}}% {\paradigmline{\med}{\com}{\com}}% {\paradigmline{\sab}{\rav}{\rav}}% {\paradigmline{\rav}{\rav}{\rav}} \item Battle Team \begin{itemize} \item Switch Vanille with Sazh (1 $\leftrightarrow$ 3) \end{itemize} \end{itemize} \end{itemize} \end{menu} \vfill \renewcommand{\fourth}{[4] Tireless Charge (\com/\com/\med)} \renewcommand{\second}{[2] Aggression (\com/\com/\rav)} \renewcommand{\third}{[3] Consolidation (\sen/\sen/\med)} \renewcommand{\first}{[1] Malevolence (\syn/\rav/\rav)} \renewcommand{\fifth}{[5] Smart Bomb (\rav/\rav/\sab)} \renewcommand{\sixth}{[6] Tri-Disaster (\rav/\rav/\rav)} \begin{battle}[1:55]{Tiamat Eliminator} \begin{itemize} \item \second \begin{itemize} \item Shift Immediately \end{itemize} \item \sixth \begin{itemize} \item Cold Blood \item Libra \item Repeat, shift after \stagger \end{itemize} \item \second \begin{itemize} \item Blitz-Blitz \item Repeat \end{itemize} \item \fourth \begin{itemize} \item Repeat \item Shift as soon as he uses ``Descend'' \end{itemize} \item \fifth \begin{itemize} \item Repeat, shift when Snow and Vanille finish their strings \end{itemize} \item \sixth \begin{itemize} \item Shift Immediately \end{itemize} \item \fifth \begin{itemize} \item Repeat \item Renew if needed \item Repeat, shift when Deprotect, Imperil, and Poison have all landed \end{itemize} \item \sixth \begin{itemize} \item Repeat \end{itemize} \item \second \begin{itemize} \item Repeat, ATB Refresh with [1] until dead. \end{itemize} \end{itemize} \end{battle} \begin{shop}{44\,000} \begin{itemize} \item Eden Pharmaceuticals \begin{itemize} \item Sell \begin{itemize} \item Accessories \begin{itemize} \item Imperial Armlet \end{itemize} \end{itemize} \item Buy \begin{itemize} \item Librascope x2 \item Fortisol x1 \item Aegisol x1 \end{itemize} \end{itemize} \end{itemize} \end{shop} \pickup{Ethersol}{in the final hallway} Activate all shrouds. \vfill \begin{battle}[1:26]{Barthandelus 3} \begin{itemize} \item \second \begin{itemize} \item Librascope \item Blitz-Blitz, \rav-buffer the first Blitz \end{itemize} \item \fifth \begin{itemize} \item Fire-Thunder-Fire-Thunder \item Repeat \item Repeat two spells if no Imperil or was inflicted late \item Shift at 200\% chain (no Imperil) or 220\% chain (Imperil) \end{itemize} \item \third \begin{itemize} \item Potion twice, Renew if Vanille is likely to die to Ultima \item \textit{If no Imperil} \begin{itemize} \item Potion \item Shift after Ultima \item \fifth \begin{itemize} \item Throw Potions until Imperil inflicts \item If \stagger\ Retry \end{itemize} \item \fourth \begin{itemize} \item Repeat until close to Ultima \end{itemize} \item \third \begin{itemize} \item Throw Potions \item Shift after Ultima hits \end{itemize} \end{itemize} \item \textit{If Imperil and no Deprotect} \begin{itemize} \item \fifth \begin{itemize} \item Renew \item Shift after Deprotect \end{itemize} \end{itemize} \end{itemize} \item \sixth \begin{itemize} \item Renew if anyone is yellow health \item Cold Blood \item Shift towards the end for ATB refresh \end{itemize} \item \second \begin{itemize} \item Repeat twice, Shift after Snow's ready animation (don't animation cancel) \end{itemize} \item \fourth \begin{itemize} \item Repeat until Laughter \item If Snow would jump before Laughter hits, shift to [2] and back to [1] to have him stay on the ground \item Repeat after Laughter \end{itemize} \item \second \begin{itemize} \item Repeat until victory \end{itemize} \item \textit{If stagger ends}: \item \third \begin{itemize} \item Renew if you still have one \item Potion after Ultima \end{itemize} \item \textit{If Bart is close to death}: \begin{itemize} \item \fourth \begin{itemize} \item Repeat until victory \end{itemize} \end{itemize} \item \textit{Else}: \begin{itemize} \item \sixth \begin{itemize} \item Fire-Thunder-Fire-Thunder \item Repeat until \stagger \item Use [5] to inflict any missing debuffs \end{itemize} \item \first \begin{itemize} \item Repeat until victory \end{itemize} \end{itemize} \end{itemize} \end{battle} \ifthenelse{\equal{\platformtype}{pc}} { \input{./Chapters/chapter13-pc-orphan1.tex} } { \ifthenelse{\equal{\platformtype}{console}} {\input{./Chapters/chapter13-console-orphan1.tex} } } \end{multicols*} \renewcommand{\fourth}{[4] Tireless Charge (\com/\com/\med)} \renewcommand{\second}{[2] Aggression (\com/\com/\rav)} \renewcommand{\third}{[3] Consolidation (\sen/\sen/\med)} \renewcommand{\first}{[1] Malevolence (\syn/\rav/\rav)} \renewcommand{\fifth}{[5] Smart Bomb (\rav/\rav/\sab)} \renewcommand{\sixth}{[6] Tri-Disaster (\rav/\rav/\rav)} \begin{battle}[1:05]{Orphan 2} \begin{multicols}{2} \begin{itemize} \item \second \begin{itemize} \item Attack x1 \item Shift after the bullets hit Orphan \end{itemize} \item \first \begin{itemize} \item Auto-support Vanille ($\downarrow$, Haste) \item Auto-support Sazh (Haste) \item Haste-Enthunder Snow \item Shift after Snow's fifth spell \end{itemize} \item \sixth \begin{itemize} \item Auto-chain, shift after the third spell \end{itemize} \item \first \begin{itemize} \item Bravery-Enthunder Sazh, shift Immediately \end{itemize} \columnbreak \item \sixth \begin{itemize} \item \textit{If you hear Orphan starting to slap:} \begin{itemize} \item Potion immediately \item Auto-chain \end{itemize} \item \textit{Else:} \begin{itemize} \item Auto-chain 2 spells \end{itemize} \item Shift after Snow's fifth spell \end{itemize} \item \fifth \begin{itemize} \item Cold Blood, should \stagger during the animation \item Wait for Deprotect and Imperil \end{itemize} \item \fourth \begin{itemize} \item Blitz-Blitz, make sure to not miss Bullets \item Auto-battle 2-3 Attacks if just Launched \item Repeat this pattern until victory \end{itemize} \end{itemize} \end{multicols} \end{battle}
From mathcomp Require Import all_ssreflect. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Section Aux. Definition update (T : finType) S (m : {ffun T -> S}) (x : T) (f : S -> S) : {ffun T -> S} := [ffun i => if i == x then f (m i) else m i]. End Aux. Variable (n : nat). (* state per node *) Record node_st := { rcount : nat ; max : nat ; has_sent : {ffun 'I_n -> bool} }. Definition set_send_node (s : node_st) i : node_st := {| rcount := s.(rcount) ; max := s.(max) ; has_sent := update s.(has_sent) i (fun _ => true) |}. Definition node_recv (s : node_st) m := {| rcount := s.(rcount).+1 ; max := maxn s.(max) m ; has_sent := s.(has_sent) |}. (* Definition node_recv (s : node_st) *) Record cprotocol_st := { cqueues : {ffun 'I_n -> seq nat} ; cnode_sts : {ffun 'I_n -> node_st} }. Definition set_send (s : cprotocol_st) (i j : 'I_n) : cprotocol_st := {| cqueues := update s.(cqueues) j (fun pq => [:: val i & pq]) ; cnode_sts := update s.(cnode_sts) i (fun pst => set_send_node pst j) |}. Definition do_recv (s : cprotocol_st) m i := {| cnode_sts := update s.(cnode_sts) i (fun pst => node_recv pst m) ; cqueues := update s.(cqueues) i (fun pq => rem m pq) |}. Definition get_max (s : cprotocol_st) i := (s.(cnode_sts) i).(max). Inductive label := Eps | Decided of nat. Definition get_label s i := if (s.(cnode_sts) i).(rcount) < n then Eps else Decided (get_max s i). Reserved Notation "s1 --[ l ]-->_c s2" (at level 30). Inductive concrete_step : cprotocol_st -> label -> cprotocol_st -> Prop := | Send : forall s1 i j, (s1.(cnode_sts) i).(has_sent) j = false -> let s2 := set_send s1 i j in (* ---------------------------- *) s1 --[Eps]-->_c s2 | Recv : forall s1 i (m : 'I_n), (* (s1.(node_sts) i).(rcount).+1 < n -> *) val m \in s1.(cqueues) i -> let s2 := do_recv s1 i m in (* ---------------------------- *) s1 --[get_label s2 i]-->_c s2 (* | Decide : *) (* forall s1 i (m : 'I_n), *) (* (s1.(node_sts) i).(rcount).+1 = n -> *) (* val m \in s1.(queues) i -> *) (* let s2 := do_recv s1 i m in *) (* (* ---------------------------- *) *) (* s1 --[Decided (get_max s2 i) ]--> s2 *) where "s1 --[ l ]-->_c s2" := (concrete_step s1 l s2). Inductive Phase := SendP of nat | RecvP of nat. Record aprotocol_st := { phase : Phase (* ; step_i : nat *) (* ; step_j : nat *) ; aqueues : {ffun 'I_n -> seq nat} ; anode_sts : {ffun 'I_n -> node_st} }. Definition set_phase s p := {| phase := p ; aqueues := s.(aqueues) ; anode_sts := s.(anode_sts) |}. Definition phase_next p (hsent : {ffun 'I_n -> bool}):= match p with | SendP i => if [forall i, hsent i == true] then if i < n then SendP i.+1 else RecvP 0 else SendP i | RecvP i => RecvP i.+1 end. Definition set_asend (s : aprotocol_st) (i j : 'I_n) : aprotocol_st := {| phase := phase_next s.(phase) (s.(anode_sts) i).(has_sent) ; aqueues := update s.(aqueues) j (fun pq => [:: val i & pq]) ; anode_sts := update s.(anode_sts) i (fun pst => set_send_node pst j) |}. Reserved Notation "s1 --[ l ]-->_a s2" (at level 30). Inductive abs_step : aprotocol_st -> label -> aprotocol_st -> Prop := | A_Send : forall s1 (i : 'I_n) j, s1.(phase) = SendP i -> (s1.(anode_sts) i).(has_sent) j = false -> let s2 := set_asend s1 i j in (* ---------------------------- *) s1 --[Eps]-->_a s2 where "s1 --[ l ]-->_a s2" := (abs_step s1 l s2). (* Not sure how this should look *) Lemma Send_left : forall s1 s2 s3 s4 l1 l2 l3 : s1 --[ l1 ]-->_c s2 -> s2 --[ l2 ]-->_c (Send ...) -> (Send ...) --[ l3 ]-->_c s4 -> exists l1' l2' l3' s2', s1 --[ l1' ]-->_c (Send ...) -> (Send ...) --[ l2' ]-->_c s2' -> s2' --[ l3' ]-->_c s4.
Require Import prosa.classic.util.all. Require Import prosa.classic.model.arrival.basic.job prosa.classic.model.arrival.basic.task_arrival. Require Import prosa.classic.model.schedule.uni.service prosa.classic.model.schedule.uni.workload prosa.classic.model.schedule.uni.schedule prosa.classic.model.schedule.uni.response_time prosa.classic.model.schedule.uni.schedule_of_task. Require Import prosa.classic.model.schedule.uni.limited.rbf prosa.classic.model.schedule.uni.limited.schedule. Require Import prosa.classic.model.arrival.curves.bounds. Require Import prosa.classic.analysis.uni.arrival_curves.workload_bound. Require Import prosa.classic.model.schedule.uni.limited.abstract_RTA.definitions prosa.classic.model.schedule.uni.limited.abstract_RTA.sufficient_condition_for_lock_in_service prosa.classic.model.schedule.uni.limited.abstract_RTA.reduction_of_search_space prosa.classic.model.schedule.uni.limited.abstract_RTA.abstract_rta. From mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq path fintype bigop. (** * Abstract Response-Time Analysis with sequential jobs *) (** In this module we propose the general framework for response-time analysis (RTA) of uniprocessor scheduling of real-time tasks with arbitrary arrival models and sequential jobs. *) Module AbstractSeqRTA. Import Job ArrivalCurves TaskArrival ScheduleOfTask UniprocessorSchedule Workload Service ResponseTime MaxArrivalsWorkloadBound AbstractRTADefinitions AbstractRTALockInService AbstractRTAReduction AbstractRTA. (* In this section we prove that the maximum among the solutions of the response-time bound recurrence for some set of parameters is a response-time bound for tsk. Note that in this section we _do_ rely on the hypothesis about job sequentiality. This allows us to provide a more precise response-time bound function, since jobs of the same task will be executed strictly in the order they arrive. *) Section Sequential_Abstract_RTA. Context {Task: eqType}. Variable task_cost: Task -> time. Context {Job: eqType}. Variable job_arrival: Job -> time. Variable job_cost: Job -> time. Variable job_task: Job -> Task. (* Consider any arrival sequence with consistent, non-duplicate arrivals. *) Variable arr_seq: arrival_sequence Job. Hypothesis H_arrival_times_are_consistent: arrival_times_are_consistent job_arrival arr_seq. Hypothesis H_arr_seq_is_a_set: arrival_sequence_is_a_set arr_seq. (* Next, consider any uniprocessor schedule of this arrival sequence... *) Variable sched: schedule Job. Hypothesis H_jobs_come_from_arrival_sequence: jobs_come_from_arrival_sequence sched arr_seq. (* ... where jobs do not execute before their arrival nor after completion. *) Hypothesis H_jobs_must_arrive_to_execute: jobs_must_arrive_to_execute job_arrival sched. Hypothesis H_completed_jobs_dont_execute: completed_jobs_dont_execute job_cost sched. (* Assume that the job costs are no larger than the task costs. *) Hypothesis H_job_cost_le_task_cost: cost_of_jobs_from_arrival_sequence_le_task_cost task_cost job_cost job_task arr_seq. (* For simplicity, let's define some local names. *) Let job_pending_at := pending job_arrival job_cost sched. Let job_completed_by := completed_by job_cost sched. Let arrivals_between := jobs_arrived_between arr_seq. Let task_scheduled_at := task_scheduled_at job_task sched. Let response_time_bounded_by := is_response_time_bound_of_task job_arrival job_cost job_task arr_seq sched. (* Consider an arbitrary task set. *) Variable ts: list Task. (* In addition, assume that all jobs come from the task set. *) Hypothesis H_all_jobs_from_taskset: forall j, arrives_in arr_seq j -> job_task j \in ts. (* Let max_arrivals be a family of proper arrival curves, i.e., for any task tsk in ts [max_arrival tsk] is (1) an arrival bound of tsk, and (2) it is a monotonic function that equals 0 for the empty interval delta = 0. *) Variable max_arrivals: Task -> time -> nat. Hypothesis H_family_of_proper_arrival_curves: family_of_proper_arrival_curves job_task arr_seq max_arrivals ts. (* Let tsk be any task in ts that is to be analyzed. *) Variable tsk: Task. Hypothesis H_tsk_in_ts: tsk \in ts. (* Consider proper job lock-in service and task lock-in functions, i.e... *) Variable job_lock_in_service: Job -> time. Variable task_lock_in_service: Task -> time. (* ...we assume that for all jobs in the arrival sequence the lock-in service is (1) positive, (2) no bigger than costs of the corresponding jobs, and (3) a job becomes nonpreemptive after it reaches its lock-in service... *) Hypothesis H_proper_job_lock_in_service: proper_job_lock_in_service job_cost arr_seq sched job_lock_in_service. (* ...and that [task_lock_in_service tsk] is (1) no bigger than tsk's cost, (2) for any job of task tsk job_lock_in_service is bounded by task_lock_in_service. *) Hypothesis H_proper_task_lock_in_service: proper_task_lock_in_service task_cost job_task arr_seq job_lock_in_service task_lock_in_service tsk. (* Assume we are provided with abstract functions for interference and interfering workload. *) Variable interference: Job -> time -> bool. Variable interfering_workload: Job -> time -> time. (* Let's define some local names for clarity. *) Let task_rbf := task_request_bound_function task_cost max_arrivals tsk. Let work_conserving := work_conserving job_arrival job_cost job_task arr_seq sched tsk. Let busy_intervals_are_bounded_by := busy_intervals_are_bounded_by job_arrival job_cost job_task arr_seq sched tsk. Let job_interference_is_bounded_by := job_interference_is_bounded_by job_arrival job_cost job_task arr_seq sched tsk. Let busy_interval := busy_interval job_arrival job_cost sched interference interfering_workload. Let task_workload_between := task_workload_between job_cost job_task arr_seq tsk. Let arrivals_of_task_before := arrivals_of_task_before job_task arr_seq. Let task_service_between := task_service_between job_task arr_seq sched tsk. (* In this section, we introduce a few new definitions to make it easier to express the new bound of the worst-case execution time. *) Section Definitions. (* When assuming sequential jobs, we can introduce an additional hypothesis that ensures that the values of interference and workload remain consistent. It states that any of tsk's job, that arrived before the busy interval, should be completed by the beginning of the busy interval. *) Definition interference_and_workload_consistent_with_sequential_jobs := forall j t1 t2, arrives_in arr_seq j -> job_task j = tsk -> job_cost j > 0 -> busy_interval j t1 t2 -> task_workload_between 0 t1 = task_service_between 0 t1. (* Next we introduce the notion of task interference. Intuitively, task tsk incurs interference when some of the jobs of task tsk incur interference. As a result, tsk cannot make any progress. More formally, task tsk experiences interference at a time instant time t, if at time t task tsk is not scheduled and there exists a job of tsk that (1) experiences interference and (2) has arrived before some time instant [upper_bound]. It is important to note two subtle points: according to our semantics of the interference function, jobs from the same task can cause interference to each other. In the definition of interference of a task we want to avoid such situations. That is why we use the term [~~ task_scheduled_at tsk t]. Moreover, in order to make the definition constructive, we introduce an upper bound on the arrival time of jobs from task tsk. As a result, we need to consider only a finite number of jobs. For the function to produce the correct values it is enough to specify a sufficiently large upper_bound. Usually as upper_bound one can use the end of the corresponding busy interval. *) Definition task_interference_received_before (tsk: Task) (upper_bound: time) (t: time) := (~~ task_scheduled_at tsk t) && has (fun j => interference j t) (arrivals_of_task_before tsk upper_bound). (* Next we define the cumulative task interference. *) Definition cumul_task_interference tsk upper_bound t1 t2 := \sum_(t1 <= t < t2) task_interference_received_before tsk upper_bound t. (* We say that task interference is bounded by task_interference_bound_function (tIBF) iff for any job j of task tsk cumulative _task_ interference within the interval [t1, t1 + R) is bounded by function tIBF(tsk, A, R). Note that this definition is almost the same as the definition of job_interference_is_bounded_by from the non-nesessary-sequential case. However, in this case we ignore the interference that comes from jobs from the same task. *) Definition task_interference_is_bounded_by (task_interference_bound_function: Task -> time -> time -> time) := forall j R t1 t2, arrives_in arr_seq j -> job_task j = tsk -> t1 + R < t2 -> ~~ job_completed_by j (t1 + R) -> busy_interval j t1 t2 -> let offset := job_arrival j - t1 in cumul_task_interference tsk t2 t1 (t1 + R) <= task_interference_bound_function tsk offset R. End Definitions. (* In this section, we prove that the maximum among the solutions of the response-time bound recurrence is a response-time bound for tsk. *) Section ResponseTimeBound. (* For simplicity, let's define some local names. *) Let cumul_interference := cumul_interference interference. Let cumul_workload := cumul_interfering_workload interfering_workload. Let cumul_task_interference := cumul_task_interference tsk. (* We assume that the schedule is work-conserving. *) Hypothesis H_work_conserving: work_conserving interference interfering_workload. (* Unlike the previous theorem [uniprocessor_response_time_bound], we assume that (1) jobs are sequential, moreover (2) functions interference and interfering_workload are consistent with the hypothesis of sequential jobs. *) Hypothesis H_sequential_jobs: sequential_jobs job_arrival job_cost sched job_task. Hypothesis H_interference_and_workload_consistent_with_sequential_jobs: interference_and_workload_consistent_with_sequential_jobs. (* Assume we have a constant L which bounds the busy interval of any of tsk's jobs. *) Variable L: time. Hypothesis H_busy_interval_exists: busy_intervals_are_bounded_by interference interfering_workload L. (* Next, we assume that task_interference_bound_function is a bound on interference incurred by the task. *) Variable task_interference_bound_function: Task -> time -> time -> time. Hypothesis H_task_interference_is_bounded: task_interference_is_bounded_by task_interference_bound_function. (* Given any job j of task tsk that arrives exactly A units after the beginning of the busy interval, the bound on the total interference incurred by j within an interval of length Δ is no greater than [task_rbf (A + ε) - task_cost tsk + task's IBF Δ]. Note that in case of sequential jobs the bound consists of two parts: (1) the part that bounds the interference received from other jobs of task tsk -- [task_rbf (A + ε) - task_cost tsk] and (2) any other interferece that is bounded by task_IBF(tsk, A, Δ). *) Let total_interference_bound tsk A Δ := task_rbf (A + ε) - task_cost tsk + task_interference_bound_function tsk A Δ. (* Note that since we consider the modified interference bound function, the search space has also changed. One can see that the new search space is guaranteed to include any A for which [task_rbf (A) ≠ task_rbf (A + ε)], since this implies the fact that [total_interference_bound (tsk, A, Δ) ≠ total_interference_bound (tsk, A + ε, Δ)]. *) Let is_in_search_space_seq := is_in_search_space tsk L total_interference_bound. (* Consider any value R, and assume that for any relative arrival time A from the search space there is a solution F of the response-time recurrence that is bounded by R. In contrast to the formula in "non-sequential" Abstract RTA, assuming that jobs are sequential leads to a more precise response-time bound. Now we can explicitly express the interference caused by other jobs of the task under consideration. To understand the right part of the fixpoint in the equation it is helpful to note that the bound on the total interference (bound_of_total_interference) is equal to [task_rbf (A + ε) - task_cost tsk + tIBF tsk A Δ]. Besides, a job must receive enough service to become non-preemptive [task_lock_in_service tsk]. The sum of these two quantities is exactly the right-hand side of the equation. *) Variable R: nat. Hypothesis H_R_is_maximum_seq: forall A, is_in_search_space_seq A -> exists F, A + F = (task_rbf (A + ε) - (task_cost tsk - task_lock_in_service tsk)) + task_interference_bound_function tsk A (A + F) /\ F + (task_cost tsk - task_lock_in_service tsk) <= R. (* In this section we prove a few simple lemmas about the completion of jobs from the task considering the busy interval of the job under consideration. *) Section CompletionOfJobsFromSameTask. (* Consider any two jobs j1 j2 of tsk. *) Variable j1 j2: Job. Hypothesis H_j1_arrives: arrives_in arr_seq j1. Hypothesis H_j2_arrives: arrives_in arr_seq j2. Hypothesis H_j1_from_tsk: job_task j1 = tsk. Hypothesis H_j2_from_tsk: job_task j2 = tsk. Hypothesis H_j1_cost_positive: job_cost_positive job_cost j1. (* Consider the busy interval [t1, t2) of job j1. *) Variable t1 t2: time. Hypothesis H_busy_interval: busy_interval j1 t1 t2. (* We prove that if a job from task tsk arrived before the beginning of the busy interval, then it must be completed before the beginning of the busy interval *) Lemma completed_before_beginning_of_busy_interval: job_arrival j2 < t1 -> completed_by job_cost sched j2 t1. Proof. move => JA; move: (H_j2_from_tsk) => /eqP TSK2eq. move: (posnP (job_cost j2)) => [ZERO|POS]. { by rewrite /is_response_time_bound_of_job /completed_by ZERO. } move: (H_interference_and_workload_consistent_with_sequential_jobs j1 t1 t2 H_j1_arrives H_j1_from_tsk H_j1_cost_positive H_busy_interval) => SWEQ. eapply all_jobs_have_completed_equiv_workload_eq_service with (j := j2) in SWEQ; eauto 2; try done. by apply arrived_between_implies_in_arrivals with job_arrival. Qed. (* Next we prove that if a job is pending after the beginning of the busy interval [t1, t2) then it arrives after t1 . *) Lemma arrives_after_beginning_of_busy_interval: forall t, t1 <= t -> job_pending_at j2 t -> arrived_between job_arrival j2 t1 t.+1. Proof. intros t GE PEND. rewrite /arrived_between; apply/andP; split; last first. { by move: PEND => /andP [ARR _]; rewrite ltnS. } rewrite leqNgt; apply/negP; intros LT. move: (H_busy_interval) => [[/andP [AFR1 AFR2] [QT _]] _]. have L12 := completed_before_beginning_of_busy_interval. feed L12; try done. apply completion_monotonic with (t' := t) in L12; try done. by move: PEND => /andP [_ /negP H2]. Qed. End CompletionOfJobsFromSameTask. (* Since we are going to use the [uniprocessor_response_time_bound] theorem to prove the theorem of this section, we have to show that all the hypotheses are satisfied. Namely, we need to show that hypotheses [H_sequential_jobs, H_i_w_are_task_consistent and H_task_interference_is_bounded_by] imply [H_job_interference_is_bounded], and the fact that [H_R_is_maximum_seq] implies [H_R_is_maximum]. *) (* In this section we show that there exists a bound for cumulative interference for any job of task tsk, i.e., the hypothesis H_job_interference_is_bounded holds. *) Section BoundOfCumulativeJobInterference. (* Consider any job j of tsk. *) Variable j: Job. Hypothesis H_j_arrives: arrives_in arr_seq j. Hypothesis H_job_of_tsk: job_task j = tsk. Hypothesis H_job_cost_positive: job_cost_positive job_cost j. (* Consider the busy interval [t1, t2) of job j. *) Variable t1 t2: time. Hypothesis H_busy_interval: busy_interval j t1 t2. (* Let's define A as a relative arrival time of job j (with respect to time t1). *) Let A := job_arrival j - t1. (* Consider an arbitrary time x... *) Variable x: time. (* ...such that (t1 + x) is inside the busy interval... *) Hypothesis H_inside_busy_interval: t1 + x < t2. (* ... and job j is not completed by time (t1 + x). *) Hypothesis H_job_j_is_not_completed: ~~ job_completed_by j (t1 + x). (* We start by proving that the cumulative interference incurred by job j is bounded by the sum of the task workload on the interval [t1, t1 + A] and the cumulative interference of j's task. *) Lemma bound_for_cumulative_job_interference_actual: cumul_interference j t1 (t1 + x) <= (task_workload_between t1 (t1 + A + ε) - job_cost j) + cumul_task_interference t2 t1 (t1 + x). Proof. set (y := t1 + x) in *. have IN: j \in arrivals_between t1 (t1 + A + ε). { eapply arrived_between_implies_in_arrivals; eauto 2. move: (H_busy_interval) => [[/andP [GE _] [_ _]] _]. by apply/andP; split; last rewrite /A subnKC // addn1. } have Fact1: task_service_of_jobs_received_in job_task arr_seq sched tsk t1 (t1 + A + ε) t1 y - service_during sched j t1 y <= task_workload_between t1 (t1 + A + ε) - job_cost j. { rewrite /task_workload /task_service_of_jobs_received_in /service_of_jobs /workload_of_jobs. rewrite (big_rem j) ?[X in _ <= X - _](big_rem j) //=. rewrite H_job_of_tsk eq_refl. rewrite addnC -addnBA; last by done. rewrite [X in _ <= X - _]addnC -addnBA; last by done. rewrite !subnn !addn0. by apply service_of_jobs_le_workload. } apply leq_trans with ( task_service_of_jobs_received_in job_task arr_seq sched tsk t1 (t1+A+ε) t1 y - service_during sched j t1 y + cumul_task_interference t2 t1 y); [clear Fact1 | by rewrite leq_add2r]. rewrite /cumul_interference /cumul_interference /task_service_of_jobs_received_in /service_of_jobs /service_during exchange_big //= /cumul_task_interference /Sequential_Abstract_RTA.cumul_task_interference. rewrite -(leq_add2r (\sum_(t1 <= t < y) service_at sched j t)). rewrite [X in _ <= X]addnC addnA subnKC; last first. { by rewrite exchange_big //= (big_rem j) //= H_job_of_tsk eq_refl leq_addr. } rewrite -big_split -big_split //=. rewrite big_nat_cond [X in _ <= X]big_nat_cond leq_sum //; move => t /andP [NEQ _]. have Fact1: service_at sched j t <= \sum_(i0 <- arrivals_between t1 (t1 + A + ε) | job_task i0 == tsk) service_at sched i0 t. { by rewrite (big_rem j) // H_job_of_tsk eq_refl leq_addr. } unfold task_scheduled_at, ScheduleOfTask.task_scheduled_at. case SCHEDt: (sched t) => [s | ]; last first. { rewrite {1}/service_at {1}/scheduled_at SCHEDt; simpl; rewrite addn0. case INT: (interference j t); last by done. apply leq_trans with (task_interference_received_before tsk t2 t); last by rewrite leq_addl. rewrite lt0b. rewrite /task_interference_received_before /task_scheduled_at /ScheduleOfTask.task_scheduled_at SCHEDt; simpl. apply/hasP; exists j; last by done. rewrite /arrivals_of_task_before mem_filter; apply/andP; split. - by rewrite /is_job_of_task H_job_of_tsk. - move: (H_busy_interval) => [[/andP [_ LT] [_ _]] _]. by eapply arrived_between_implies_in_arrivals; eauto. } have ARRs: arrives_in arr_seq s. { by apply H_jobs_come_from_arrival_sequence with t; apply/eqP. } case TSK: (job_task s == tsk); last first. { have ZERO: service_at sched j t = 0. { rewrite /service_at /scheduled_at SCHEDt. apply/eqP; rewrite eqb0; apply/negP. intros FALSE; move: FALSE => /eqP FALSE; inversion FALSE; subst s. by move: TSK => /eqP TSK; apply TSK. } rewrite ZERO; clear ZERO. have ZERO: \sum_(i <- arrivals_between t1 (t1 + A + ε) | job_task i == tsk) service_at sched i t = 0. { rewrite /service_at /scheduled_at SCHEDt. apply big1; move => k /eqP TSK2. apply/eqP; rewrite eqb0; apply/negP. intros FALSE; move: FALSE => /eqP FALSE; inversion FALSE; subst s. by move: TSK => /eqP TSK; apply TSK. } rewrite ZERO; clear ZERO. rewrite addn0 add0n. rewrite /task_interference_received_before /task_scheduled_at /ScheduleOfTask.task_scheduled_at. rewrite SCHEDt TSK; simpl. case INT: (interference j t); last by done. rewrite lt0b. apply/hasP; exists j; last by done. rewrite /arrivals_of_task_before mem_filter; apply/andP; split. - by rewrite /is_job_of_task H_job_of_tsk. - move: (H_busy_interval) => [[/andP [_ LT] [_ _]] _]. by eapply arrived_between_implies_in_arrivals; eauto. } { rewrite /task_interference_received_before /task_scheduled_at /ScheduleOfTask.task_scheduled_at SCHEDt TSK. simpl; rewrite addn0. case EQ: (j == s). { move: EQ => /eqP EQ; subst s. move: (H_work_conserving j t1 t2 t H_j_arrives H_job_of_tsk H_job_cost_positive H_busy_interval) => WORK. feed WORK. { by move: NEQ => /andP [NEQ1 NEQ2]; apply/andP; split; last apply ltn_trans with y. } move: WORK => [_ ZIJT]. feed ZIJT; first by rewrite /scheduled_at SCHEDt. move: ZIJT => /negP /eqP; rewrite eqb_negLR; simpl; move => /eqP ZIJT. rewrite ZIJT; simpl; rewrite add0n. by done. } { have NSCHED: scheduled_at sched j t = false. { apply/negP; intros SCHED. move: SCHEDt => /eqP SCHEDt. move: (only_one_job_scheduled sched j s t SCHED SCHEDt) => EQjs. by rewrite EQjs eq_refl in EQ. } rewrite /service_at NSCHED. have IJT: interference j t = true. { have NEQT: t1 <= t < t2. { move: NEQ => /andP [NEQ1 NEQ2]. apply/andP; split; first by done. by apply ltn_trans with y. } move: (H_work_conserving j t1 t2 t H_j_arrives H_job_of_tsk H_job_cost_positive H_busy_interval NEQT) => [Hn _]. apply/negPn/negP; intros CONTR; move: CONTR => /negP CONTR. by apply Hn in CONTR; rewrite NSCHED in CONTR. } rewrite IJT; clear IJT. simpl. rewrite addn0. rewrite big_mkcond; apply/sum_seq_gt0P. exists s; split. { intros. have ARR:= arrives_after_beginning_of_busy_interval j s _ _ _ _ _ t1 t2 _ t. feed_n 8 ARR; try done. { by move: TSK => /eqP TSK; rewrite TSK. } { by move: NEQ => /andP [T1 T2]. } { by move: SCHEDt => /eqP SCHEDt; apply scheduled_implies_pending. } case ARRNEQ: (job_arrival s <= job_arrival j). { move: ARR => /andP [РР _]. unfold arrivals_between in *. eapply arrived_between_implies_in_arrivals; eauto 2. apply/andP; split; first by done. rewrite /A subnKC. rewrite addn1 ltnS. by done. by move: (H_busy_interval) => [[/andP [BUS _] _] _]. } { exfalso. apply negbT in ARRNEQ; rewrite -ltnNge in ARRNEQ. move: (H_sequential_jobs j s t) => CONTR. feed_n 3 CONTR; try done. { by rewrite -H_job_of_tsk in TSK; rewrite eq_sym. } { by move: SCHEDt => /eqP SCHEDt. } move: H_job_j_is_not_completed => /negP H; apply: H. apply completion_monotonic with t; try done. apply ltnW. by move: NEQ => /andP [_ NEQ]. } } { move: TSK => /eqP TSK. by rewrite TSK eq_refl /service_at /scheduled_at SCHEDt eq_refl. } } } Qed. (* However, in order to obtain a more convenient bound of the cumulative interference, we need to abandon the actual workload in favor of a bound which depends on task parameters only. So, we show that actual workload of the task excluding workload of any job j is no greater than bound of workload excluding the cost of job j's task. *) Lemma task_rbf_excl_tsk_bounds_task_workload_excl_j: task_workload_between t1 (t1 + A + ε) - job_cost j <= task_rbf (A + ε) - task_cost tsk. Proof. unfold cost_of_jobs_from_arrival_sequence_le_task_cost, job_cost_le_task_cost in *. move: H_j_arrives H_job_of_tsk => ARR TSK. move: (H_busy_interval) => [[/andP [JAGET1 JALTT2] _] _]. apply leq_trans with ( task_cost tsk * num_arrivals_of_task job_task arr_seq tsk t1 (t1 + A + ε) - task_cost tsk); last first. { rewrite leq_sub2r //. rewrite leq_mul2l; apply/orP; right. rewrite -addnA -{2}[(A+1)](addKn t1). move: (H_family_of_proper_arrival_curves tsk H_tsk_in_ts) => [ARRB T]. by apply ARRB; last rewrite leq_addr. } { have Fact6: j \in arrivals_between (t1 + A) (t1 + A + ε). { apply (arrived_between_implies_in_arrivals job_arrival); try(done). apply/andP; split; rewrite /A subnKC //. by rewrite addn1 ltnSn //. } have Fact1: num_arrivals_of_task job_task arr_seq tsk (t1 + A) (t1 + A + ε) >= 1. { rewrite /num_arrivals_of_task /arrivals_of_task_between. rewrite -count_filter_fun -has_count; apply/hasP. by exists j; last rewrite /is_job_of_task TSK. } have Fact2: job_cost j <= task_workload_between (t1 + A) (t1 + A + ε). { rewrite /task_workload_between /Workload.task_workload_between /task_workload /workload_of_jobs /arrivals_between (big_rem j) //=. by rewrite TSK eq_refl leq_addr. } have Fact3: 0 < task_cost tsk. { apply leq_trans with (job_cost j); [ |rewrite -H_job_of_tsk]; auto. } have Fact4: j \in jobs_arriving_at arr_seq (t1 + A). { move: ARR => [t ARR]; rewrite subnKC //. by feed (H_arrival_times_are_consistent j t); try (subst t). } rewrite (@num_arrivals_of_task_cat _ _ _ _ _ (t1 + A)); last by apply/andP; split; rewrite leq_addr //. rewrite mulnDr. have Step1: task_workload_between t1 (t1 + A + ε) = task_workload_between t1 (t1 + A) + task_workload_between (t1 + A) (t1 + A + ε). { by apply workload_of_jobs_cat; apply/andP; split; rewrite leq_addr. } rewrite Step1; clear Step1. rewrite -!addnBA; first last. { by apply leq_trans with (job_cost j). } { apply leq_trans with (task_cost tsk); first by done. by rewrite -{1}[task_cost tsk]muln1 leq_mul2l; apply/orP; right. } rewrite leq_add; first by done. { rewrite // /num_arrivals_of_task -sum1_size big_distrr /= big_filter. rewrite /task_workload_between /Workload.task_workload_between /task_workload /workload_of_jobs. rewrite /is_job_of_task -TSK muln1. apply leq_sum_seq; move => j0 IN0 /eqP EQ. by rewrite -EQ; apply in_arrivals_implies_arrived in IN0; auto. } { unfold task_workload_between, Workload.task_workload_between, task_workload, workload_of_jobs, arrivals_between, jobs_arrived_between. rewrite {1}addn1 big_nat1. rewrite /num_arrivals_of_task /arrivals_of_task_between /jobs_arrived_between addn1 big_nat1. rewrite (big_rem j) //= TSK !eq_refl; simpl. rewrite addnC -addnBA; last by done. rewrite subnn addn0. rewrite (filter_size_rem _ j); [ | by done | by rewrite /is_job_of_task TSK]. rewrite mulnDr mulnC muln1 -addnBA; last by done. rewrite subnn addn0. rewrite mulnC. apply sum_majorant_constant. move => j' ARR' /eqP TSK2. unfold job_cost_le_task_cost in *. have ARR2: arrives_in arr_seq j'. { by exists (t1 + A); apply rem_in in ARR'. } by rewrite -TSK2; auto. } } Qed. (* Now we can use two lemmas above to get the following bound: *) Lemma bound_for_cumulative_job_interference: cumul_interference j t1 (t1 + x) <= (task_rbf (A + ε) - task_cost tsk) + cumul_task_interference t2 t1 (t1 + x). Proof. set (y := t1 + x) in *. have IN: j \in arrivals_between t1 (t1 + A + ε). { eapply arrived_between_implies_in_arrivals; eauto 2. move: (H_busy_interval) => [[/andP [GE _] _] _]. by apply/andP; split; last rewrite /A subnKC // addn1. } apply leq_trans with (task_workload_between t1 (t1+A+ε) - job_cost j + cumul_task_interference t2 t1 y). - by apply bound_for_cumulative_job_interference_actual. - rewrite leq_add2r. eapply task_rbf_excl_tsk_bounds_task_workload_excl_j; eauto 2. Qed. End BoundOfCumulativeJobInterference. (* In this section, we prove that [H_R_is_maximum_seq] implies [H_R_is_maximum]. *) Section MaxInSeqHypothesisImpMaxInNonseqHypothesis. (* Consider any job j of tsk. *) Variable j: Job. Hypothesis H_j_arrives: arrives_in arr_seq j. Hypothesis H_job_of_tsk: job_task j = tsk. (* For simplicity, let's define a local name for the search space. *) Let is_in_search_space A := is_in_search_space tsk L total_interference_bound A. (* We prove that [H_R_is_maximum] holds. *) Lemma max_in_seq_hypothesis_implies_max_in_nonseq_hypothesis: forall A, is_in_search_space A -> exists F, A + F = task_lock_in_service tsk + (task_rbf (A + ε) - task_cost tsk + task_interference_bound_function tsk A (A + F)) /\ F + (task_cost tsk - task_lock_in_service tsk) <= R. Proof. move: H_proper_job_lock_in_service => [PRJ1 [PRJ2 PRJ3]]. move: H_proper_task_lock_in_service => [PRT1 PRT2]. intros A INSP. clear H_sequential_jobs H_interference_and_workload_consistent_with_sequential_jobs. move: (H_R_is_maximum_seq _ INSP) => [F [FIX LE]]. exists F; split; last by done. rewrite {1}FIX. apply/eqP. rewrite addnA eqn_add2r. rewrite addnBA; last first. { apply leq_trans with (task_rbf 1). eapply rbf.RBF.task_rbf_1_ge_task_cost; eauto 2. eapply rbf.RBF.task_rbf_monotone; eauto 2. by rewrite addn1. } by rewrite subnBA; auto; rewrite addnC. Qed. End MaxInSeqHypothesisImpMaxInNonseqHypothesis. (* Finally, we apply the [uniprocessor_response_time_bound] theorem, and using the lemmas above, we prove that all the requirements are satisfied. So, R is a response time bound. *) Theorem uniprocessor_response_time_bound_seq: response_time_bounded_by tsk R. Proof. intros j ARR TSK. eapply uniprocessor_response_time_bound with (interference_bound_function := fun tsk A R => task_rbf (A + ε) - task_cost tsk + task_interference_bound_function tsk A R) (interfering_workload0 := interfering_workload); eauto 2. { clear ARR TSK H_R_is_maximum_seq R j. intros t1 t2 R j BUSY NEQ ARR TSK COMPL. move: (posnP (job_cost j)) => [ZERO|POS]. { exfalso. move: COMPL => /negP COMPL; apply: COMPL. by rewrite /is_response_time_bound_of_job /completed_by ZERO. } set (A := job_arrival j - t1) in *. apply leq_trans with (task_rbf (A + ε) - task_cost tsk + cumul_task_interference t2 t1 (t1 + R)). - by eapply bound_for_cumulative_job_interference; eauto 2. - by rewrite leq_add2l; apply H_task_interference_is_bounded. } { by eapply max_in_seq_hypothesis_implies_max_in_nonseq_hypothesis; eauto. } Qed. End ResponseTimeBound. End Sequential_Abstract_RTA. End AbstractSeqRTA.
%DNA damage process test case % % Author: Jonathan Karr, [email protected] % Affilitation: Covert Lab, Department of Bioengineering, Stanford University % Last updated: 7/13/2010 classdef DNADamage_Test < edu.stanford.covert.cell.sim.ReactionProcessTestCase %constants properties (Constant=true) expected_essentialGenes = {}; end %constructor methods function this = DNADamage_Test(name) this = [email protected](name); end end %simple test fixture methods function loadSimpleTestFixture(this) import edu.stanford.covert.cell.sim.constant.ChromosomeSequence; import edu.stanford.covert.cell.sim.state.Chromosome; %process m = this.process; %% chromosome state c = Chromosome([], []); c.monomerDNAFootprints = zeros(0, 1); c.complexDNAFootprints = zeros(0, 1); c.monomerDNAFootprintBindingStrandedness = repmat(c.dnaStrandedness_dsDNA, 0, 1); c.complexDNAFootprintBindingStrandedness = repmat(c.dnaStrandedness_dsDNA, 0, 1); c.monomerDNAFootprintRegionStrandedness = repmat(c.dnaStrandedness_dsDNA, 0, 1); c.complexDNAFootprintRegionStrandedness = repmat(c.dnaStrandedness_dsDNA, 0, 1); c.reactionBoundMonomer = zeros(0, 1); c.reactionBoundComplex = zeros(0, 1); c.reactionMonomerCatalysisMatrix = zeros(0, 0); c.reactionComplexCatalysisMatrix = zeros(0, 0); c.reactionThresholds = ... sum(c.reactionMonomerCatalysisMatrix, 2) + ... sum(c.reactionComplexCatalysisMatrix, 2); m.states = {c}; m.chromosome = c; %parameters c.relaxedBasesPerTurn = 10.5; c.equilibriumSuperhelicalDensity = -0.06; c.supercoiledSuperhelicalDensityTolerance = 0.10; %genome seq = reshape([ 'AGCATTTTCAGGCACGGGGATACGGTTCATGGCGCTCCCGGAGACGACAA' 'TCCAACCCGCTTGCGCCTTATAATCATTTCTCGAGCGAAAAACAAAAGCC' 'ATAGTGTCTCTGCGCATCACTCGCACCAATGAATTCCGCGTCTGATAGCC' 'TGCTTTGAGTCCCGGCTAATGTACAGTCCGATCACCCAACACCGGCAAGC' 'GTTGCGGCACTAAGCTGGCACGATATACCGGTCGGGCGCCTGGCAGCACC' 'AACTGTCGATAGGATCAGCGCTGTATCTAGAATGTGAGCTTGGCGGTCAG' 'CTATTCTTGAATGAATATTCTTAGGTCGAAGCCTGCATTCAGCACCGCGG' 'CGCTGCTAATTCTTTCGTTGGTTGGGCCAGCGAATGTGCGCCCTTCCGTA' 'CTGGTCATGGTGCGGAGAAGCAACGTAATGACCGGAACATCCATTACGAC' 'CCTAATCGAAGCTGACAGTTACTAGCGCTAGACGAGACGTACCAGGGAAG'],... 1,[]); c.sequence = ChromosomeSequence(seq); c.sequenceLen = length(seq); c.sequenceGCContent = getGCContent(c.sequence); %% enzymes m.enzymeWholeCellModelIDs = cell(0,1); m.enzymeNames = cell(0,1); m.enzymeMolecularWeights = zeros(0,1); m.enzymes = zeros(0, 1); m.boundEnzymes = zeros(0, 1); %% substrates %whole cell model IDs, molecular weights m.substrateWholeCellModelIDs = { 'AD'; 'CSN'; 'DA'; 'DAMP'; 'DC'; 'DCMP'; 'DG'; 'DGMP'; 'DHTHY'; 'DR5P'; 'DT'; 'DTMP'; 'ENU'; 'GLC'; 'GN'; 'H'; 'H2O'; 'MNU'; 'NH3'; 'NU'; 'O4eTHY'; 'O4mTHY'; 'PTRC'; 'THY'; 'THY64THY'; 'URA'; 'UVB_radiation'; 'butylene_glycol'; 'cyclodG'; 'dRibose5P_dRibose5P'; 'dhpURA'; 'gamma_radiation'; 'glchm5URA'; 'hm5URA'; 'ho5URA'; 'hydrogen_radical'; 'hydroxyl_radical'; 'm5CSN'; 'putTHY'}; m.substrateMolecularWeights = [ 135.1265; 111.1018; 251.2414; 329.2055; 227.2167; 305.1808; 267.2408; 345.2049; 128.1289; 212.0942; 242.2280; 320.1921; 117.1063; 180.1554; 151.1259; 1.0079; 18.0152; 103.0798; 17.0304; 89.0533; 154.1661; 140.1396; 90.1668; 126.1131; 252.2262; 112.0866; 0; 90.1206; 265.2250; 407.1811; 214.2179; 0; 304.2527; 142.1125; 128.0860; 1.0079; 17.0073; 125.1283; 212.2483]; %names m.substrateNames = m.substrateWholeCellModelIDs; %indices m.substrateIndexs_radiation = m.substrateIndexs({'UVB_radiation';'gamma_radiation'}); m.substrateIndexs_hydrogen = m.substrateIndexs({'H'}); m.substrateIndexs_hydroxylRadical = m.substrateIndexs({'hydroxyl_radical'}); m.substrateIndexs_water = m.substrateIndexs({'H2O'}); m.substrateIndexs_DR5P = m.substrateIndexs({'DR5P'}); m.substrateIndexs_dRibose5P_dRibose5P = m.substrateIndexs({'dRibose5P_dRibose5P'}); m.substrateIndexs_unmodifiedNucleobases = m.substrateIndexs({'AD';'CSN';'GN';'THY'}); m.substrateIndexs_unmodifiedNucleosides = m.substrateIndexs({'DA';'DC';'DG';'DT'}); m.substrateIndexs_unmodifiedDNMPs = m.substrateIndexs({'DAMP';'DCMP';'DGMP';'DTMP'}); m.substrateIndexs_modifiedNucleobases = m.substrateIndexs({ 'DHTHY'; 'O4eTHY'; 'O4mTHY'; 'THY64THY'; 'URA'; 'dhpURA'; 'glchm5URA'; 'hm5URA'; 'ho5URA'; 'm5CSN'; 'putTHY'}); m.substrateIndexs_modifiedNucleosides = m.substrateIndexs({'cyclodG'}); m.substrateIndexs_modifiedDNMPs = m.substrateIndexs({}); m.substrateMetaboliteLocalIndexs = (1:numel(m.substrateWholeCellModelIDs))'; m.substrateMetaboliteGlobalIndexs = m.substrateMetaboliteLocalIndexs; c.metabolite.dr5pIndexs = m.substrateIndexs({'DR5P'}) ; c.metabolite.waterIndexs = m.substrateIndexs({'H2O'}); c.metabolite.dnmpIndexs = m.substrateIndexs({'AD'; 'CSN'; 'GN'; 'THY'}); c.metabolite.m6ADIndexs = numel(m.substrateWholeCellModelIDs)+1; c.metabolite.molecularWeights = [m.substrateMolecularWeights; 0]; %% reactions -- 1 reaction of each type %whole cell model IDs m.reactionWholeCellModelIDs = { 'DNADamage_THYTHY_THY64THY_UVB_radiation'; 'DNADamage_hm5U_dhpURA_butylene_glycol'; 'DNADamage_hm5U_putTHY_PTRC'; 'DNADamage_THY_O4eTHY_ENU'; 'DNADamage_hm5U_glchm5URA_GLC'; 'DNADamage_THY_O4mTHY_MNU'; 'DNADamage_THY_DHTHY_hydrogen_radical'; 'DNADamage_DG_cyclodG_UVB_radiation'; 'DNADamage_URA_ho5URA_hydroxyl_radical'; 'DNADamage_SpontaneousBaseDeamination_m5C'; 'DNADamage_SpontaneousBaseLoss_thymine'; 'DNADamage_SpontaneousAbasicSiteStrandBreak'}; %names m.reactionNames = m.reactionWholeCellModelIDs; %types m.reactionTypes = { 'UV-B photodimerization'; 'base alkylation'; 'base amination'; 'base ethylation'; 'base glucosyl transfer'; 'base methylation'; 'base reduction'; 'photooxidation'; 'radiation (gamma-ray) induced base oxidation'; 'spontaneous base deamination'; 'spontaneous base loss'; 'strand break'}; %indices m.reactionIndexs_spontaneousBaseLoss = find(strcmp(m.reactionTypes,'spontaneous base loss')); m.reactionIndexs_spontaneousBaseDeamination = find(strcmp(m.reactionTypes,'spontaneous base deamination')); m.reactionIndexs_gammaRayBaseOxidation = find(strcmp(m.reactionTypes,'radiation (gamma-ray) induced base oxidation')); m.reactionIndexs_uvbDimerization = find(strcmp(m.reactionTypes,'UV-B photodimerization')); m.reactionIndexs_strandBreak = find(strcmp(m.reactionTypes,'strand break')); m.reactionIndexs_baseReduction = find(strcmp(m.reactionTypes,'base reduction')); m.reactionIndexs_baseAmination = find(strcmp(m.reactionTypes,'base amination')); m.reactionIndexs_baseGlucosylTransfer = find(strcmp(m.reactionTypes,'base glucosyl transfer')); m.reactionIndexs_baseAlkylation = find(strcmp(m.reactionTypes,'base alkylation')); m.reactionIndexs_baseEthylation = find(strcmp(m.reactionTypes,'base ethylation')); m.reactionIndexs_baseMethylation = find(strcmp(m.reactionTypes,'base methylation')); m.reactionIndexs_photooxidation = find(strcmp(m.reactionTypes,'photooxidation')); %ReactionProcess inherited reaction properties m.reactionCatalysisMatrix = zeros(length(m.reactionWholeCellModelIDs), 0); m.enzymeBounds = repmat([-Inf Inf], length(m.reactionWholeCellModelIDs), 1); %% reaction stoichiometry matrices, reaction sequences %allocate memory m.reactionStoichiometryMatrix = zeros(length(m.substrateWholeCellModelIDs), length(m.reactionWholeCellModelIDs)); m.reactionRadiationStoichiometryMatrix = zeros(length(m.substrateWholeCellModelIDs), length(m.reactionWholeCellModelIDs)); m.reactionSmallMoleculeStoichiometryMatrix = zeros(length(m.substrateWholeCellModelIDs), length(m.reactionWholeCellModelIDs)); m.reactionDNAStoichiometryMatrix = zeros(length(m.substrateWholeCellModelIDs), length(m.reactionWholeCellModelIDs)); m.reactionVulnerableMotifs = cell(length(m.reactionWholeCellModelIDs), 1); m.reactionVulnerableMotifTypes = cell(length(m.reactionWholeCellModelIDs), 1); m.reactionDamageTypes = cell(length(m.reactionWholeCellModelIDs), 1); m.reactionBounds = zeros(length(m.reactionWholeCellModelIDs), 2); %DNADamage_THYTHY_THY64THY_UVB_radiation m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'THY'}), m.reactionIndexs_uvbDimerization) = -2; m.reactionRadiationStoichiometryMatrix(m.substrateIndexs({'UVB_radiation'}), m.reactionIndexs_uvbDimerization) = -1; m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'THY64THY'}), m.reactionIndexs_uvbDimerization) = 1; m.reactionVulnerableMotifs{m.reactionIndexs_uvbDimerization} = 'TT'; m.reactionVulnerableMotifTypes{m.reactionIndexs_uvbDimerization} = 'sequence'; m.reactionDamageTypes{m.reactionIndexs_uvbDimerization} = 'intrastrandCrossLinks'; m.reactionBounds(m.reactionIndexs_uvbDimerization, 2) = 1.8300e-008; %DNADamage_hm5U_dhpURA_butylene_glycol m.reactionSmallMoleculeStoichiometryMatrix(m.substrateIndexs({'butylene_glycol'}), m.reactionIndexs_baseAlkylation) = -1; m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'hm5URA'}), m.reactionIndexs_baseAlkylation) = -1; m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'dhpURA'}), m.reactionIndexs_baseAlkylation) = 1; m.reactionSmallMoleculeStoichiometryMatrix(m.substrateIndexs({'H2O'}), m.reactionIndexs_baseAlkylation) = 1; m.reactionVulnerableMotifs{m.reactionIndexs_baseAlkylation} = m.substrateIndexs({'hm5URA'}); m.reactionVulnerableMotifTypes{m.reactionIndexs_baseAlkylation} = 'damagedBases'; m.reactionDamageTypes{m.reactionIndexs_baseAlkylation} = 'damagedBases'; m.reactionBounds(m.reactionIndexs_baseAlkylation, 2) = 0; %DNADamage_hm5U_putTHY_PTRC m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'hm5URA'}), m.reactionIndexs_baseAmination) = -1; m.reactionSmallMoleculeStoichiometryMatrix(m.substrateIndexs({'PTRC'}), m.reactionIndexs_baseAmination) = -1; m.reactionSmallMoleculeStoichiometryMatrix(m.substrateIndexs({'H'}), m.reactionIndexs_baseAmination) = 2; m.reactionSmallMoleculeStoichiometryMatrix(m.substrateIndexs({'H2O'}), m.reactionIndexs_baseAmination) = 1; m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'putTHY'}), m.reactionIndexs_baseAmination) = 1; m.reactionVulnerableMotifs{m.reactionIndexs_baseAmination} = m.substrateIndexs({'hm5URA'}); m.reactionVulnerableMotifTypes{m.reactionIndexs_baseAmination} = 'damagedBases'; m.reactionDamageTypes{m.reactionIndexs_baseAmination} = 'damagedBases'; m.reactionBounds(m.reactionIndexs_baseAmination, 2) = 0; %DNADamage_THY_O4eTHY_ENU m.reactionSmallMoleculeStoichiometryMatrix(m.substrateIndexs({'ENU'}), m.reactionIndexs_baseEthylation) = -1; m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'THY'}), m.reactionIndexs_baseEthylation) = -1; m.reactionSmallMoleculeStoichiometryMatrix(m.substrateIndexs({'NU'}), m.reactionIndexs_baseEthylation) = 1; m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'O4eTHY'}), m.reactionIndexs_baseEthylation) = 1; m.reactionVulnerableMotifs{m.reactionIndexs_baseEthylation} = 'T'; m.reactionVulnerableMotifTypes{m.reactionIndexs_baseEthylation} = 'sequence'; m.reactionDamageTypes{m.reactionIndexs_baseEthylation} = 'damagedBases'; m.reactionBounds(m.reactionIndexs_baseEthylation, 2) = 0; %DNADamage_hm5U_glchm5URA_GLC m.reactionSmallMoleculeStoichiometryMatrix(m.substrateIndexs({'GLC'}), m.reactionIndexs_baseGlucosylTransfer) = -1; m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'hm5URA'}), m.reactionIndexs_baseGlucosylTransfer) = -1; m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'glchm5URA'}), m.reactionIndexs_baseGlucosylTransfer) = 1; m.reactionSmallMoleculeStoichiometryMatrix(m.substrateIndexs({'H2O'}), m.reactionIndexs_baseGlucosylTransfer) = 1; m.reactionVulnerableMotifs{m.reactionIndexs_baseGlucosylTransfer} = m.substrateIndexs({'hm5URA'}); m.reactionVulnerableMotifTypes{m.reactionIndexs_baseGlucosylTransfer} = 'damagedBases'; m.reactionDamageTypes{m.reactionIndexs_baseGlucosylTransfer} = 'damagedBases'; m.reactionBounds(m.reactionIndexs_baseGlucosylTransfer, 2) = 0; %DNADamage_THY_O4mTHY_MNU m.reactionSmallMoleculeStoichiometryMatrix(m.substrateIndexs({'MNU'}), m.reactionIndexs_baseMethylation) = -1; m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'THY'}), m.reactionIndexs_baseMethylation) = -1; m.reactionSmallMoleculeStoichiometryMatrix(m.substrateIndexs({'NU'}), m.reactionIndexs_baseMethylation) = 1; m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'O4mTHY'}), m.reactionIndexs_baseMethylation) = 1; m.reactionVulnerableMotifs{m.reactionIndexs_baseMethylation} = 'T'; m.reactionVulnerableMotifTypes{m.reactionIndexs_baseMethylation} = 'sequence'; m.reactionDamageTypes{m.reactionIndexs_baseMethylation} = 'damagedBases'; m.reactionBounds(m.reactionIndexs_baseMethylation, 2) = 0; %DNADamage_THY_DHTHY_hydrogen_radical m.reactionSmallMoleculeStoichiometryMatrix(m.substrateIndexs({'hydrogen_radical'}), m.reactionIndexs_baseReduction) = -2; m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'THY'}), m.reactionIndexs_baseReduction) = -1; m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'DHTHY'}), m.reactionIndexs_baseReduction) = 1; m.reactionVulnerableMotifs{m.reactionIndexs_baseReduction} = 'T'; m.reactionVulnerableMotifTypes{m.reactionIndexs_baseReduction} = 'sequence'; m.reactionDamageTypes{m.reactionIndexs_baseReduction} = 'damagedBases'; m.reactionBounds(m.reactionIndexs_baseReduction, 2) = 0; %DNADamage_DG_cyclodG_UVB_radiation m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'DG'}), m.reactionIndexs_photooxidation) = -1; m.reactionRadiationStoichiometryMatrix(m.substrateIndexs({'UVB_radiation'}), m.reactionIndexs_photooxidation) = -1; m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'cyclodG'}), m.reactionIndexs_photooxidation) = 1; m.reactionSmallMoleculeStoichiometryMatrix(m.substrateIndexs({'H'}), m.reactionIndexs_photooxidation) = 2; m.reactionVulnerableMotifs{m.reactionIndexs_photooxidation} = 'G'; m.reactionVulnerableMotifTypes{m.reactionIndexs_photooxidation} = 'sequence'; m.reactionDamageTypes{m.reactionIndexs_photooxidation} = 'damagedBases'; m.reactionBounds(m.reactionIndexs_photooxidation, 2) = 0; %DNADamage_URA_ho5URA_hydroxyl_radical m.reactionRadiationStoichiometryMatrix(m.substrateIndexs({'gamma_radiation'}), m.reactionIndexs_gammaRayBaseOxidation) = -1; m.reactionSmallMoleculeStoichiometryMatrix(m.substrateIndexs({'H2O'}), m.reactionIndexs_gammaRayBaseOxidation) = -1; m.reactionSmallMoleculeStoichiometryMatrix(m.substrateIndexs({'H'}), m.reactionIndexs_gammaRayBaseOxidation) = 2; m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'URA'}), m.reactionIndexs_gammaRayBaseOxidation) = -1; m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'ho5URA'}), m.reactionIndexs_gammaRayBaseOxidation) = 1; m.reactionVulnerableMotifs{m.reactionIndexs_gammaRayBaseOxidation} = m.substrateIndexs({'URA'}); m.reactionVulnerableMotifTypes{m.reactionIndexs_gammaRayBaseOxidation} = 'damagedBases'; m.reactionDamageTypes{m.reactionIndexs_gammaRayBaseOxidation} = 'damagedBases'; m.reactionBounds(m.reactionIndexs_gammaRayBaseOxidation, 2) = 5.8999e-008; %DNADamage_SpontaneousBaseDeamination_m5C m.reactionSmallMoleculeStoichiometryMatrix(m.substrateIndexs({'H2O'}), m.reactionIndexs_spontaneousBaseDeamination) = -1; m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'m5CSN'}), m.reactionIndexs_spontaneousBaseDeamination) = -1; m.reactionSmallMoleculeStoichiometryMatrix(m.substrateIndexs({'NH3'}), m.reactionIndexs_spontaneousBaseDeamination) = 1; m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'THY'}), m.reactionIndexs_spontaneousBaseDeamination) = 1; m.reactionVulnerableMotifs{m.reactionIndexs_spontaneousBaseDeamination} = m.substrateIndexs({'m5CSN'}); m.reactionVulnerableMotifTypes{m.reactionIndexs_spontaneousBaseDeamination} = 'damagedBases'; m.reactionDamageTypes{m.reactionIndexs_spontaneousBaseDeamination} = 'damagedBases'; m.reactionBounds(m.reactionIndexs_spontaneousBaseDeamination, 2) = 2.2000e-014; %DNADamage_SpontaneousBaseLoss_thymine m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'DTMP'}), m.reactionIndexs_spontaneousBaseLoss) = -1; m.reactionSmallMoleculeStoichiometryMatrix(m.substrateIndexs({'H2O'}), m.reactionIndexs_spontaneousBaseLoss) = -1; m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'DR5P'}), m.reactionIndexs_spontaneousBaseLoss) = 1; m.reactionSmallMoleculeStoichiometryMatrix(m.substrateIndexs({'THY'}), m.reactionIndexs_spontaneousBaseLoss) = 1; m.reactionVulnerableMotifs{m.reactionIndexs_spontaneousBaseLoss} = 'T'; m.reactionVulnerableMotifTypes{m.reactionIndexs_spontaneousBaseLoss} = 'sequence'; m.reactionDamageTypes{m.reactionIndexs_spontaneousBaseLoss} = 'abasicSites'; m.reactionBounds(m.reactionIndexs_spontaneousBaseLoss, 2) = 6.0000e-012; %DNADamage_SpontaneousAbasicSiteStrandBreak m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'dRibose5P_dRibose5P'}), m.reactionIndexs_strandBreak) = -1; m.reactionSmallMoleculeStoichiometryMatrix(m.substrateIndexs({'H2O'}), m.reactionIndexs_strandBreak) = -1; m.reactionDNAStoichiometryMatrix(m.substrateIndexs({'DR5P'}), m.reactionIndexs_strandBreak) = 2; m.reactionSmallMoleculeStoichiometryMatrix(m.substrateIndexs({'H'}), m.reactionIndexs_strandBreak) = 1; m.reactionVulnerableMotifs{m.reactionIndexs_strandBreak} = true; m.reactionVulnerableMotifTypes{m.reactionIndexs_strandBreak} = 'abasicSites'; m.reactionDamageTypes{m.reactionIndexs_strandBreak} = 'strandBreaks'; m.reactionBounds(m.reactionIndexs_strandBreak, 2) = 1.9254e-006; %reaction DNA product [i, j] = find(m.reactionDNAStoichiometryMatrix > 0); m.reactionDNAProduct = zeros(numel(m.reactionWholeCellModelIDs), 1); m.reactionDNAProduct(j) = m.substrateMetaboliteGlobalIndexs(ismembc2(i, m.substrateMetaboliteLocalIndexs)); %reaction radiation [i, j] = find(m.reactionRadiationStoichiometryMatrix); m.reactionRadiation = zeros(numel(m.reactionWholeCellModelIDs), 1); m.reactionRadiation(j) = i; %reactionStoichiometryMatrix m.reactionStoichiometryMatrix = ... m.reactionRadiationStoichiometryMatrix + ... m.reactionSmallMoleculeStoichiometryMatrix + ... m.reactionDNAStoichiometryMatrix; %% initial state m.substrates = zeros(length(m.substrateWholeCellModelIDs), 1); m.chromosome.initialize(); end end %tests methods function testConstants(this) m = this.process; c = m.chromosome; %assert that are sorted assertTrue(issorted(m.substrateMetaboliteLocalIndexs)); %assert that this process doesn't create or modify m6AD assertFalse(any(m.substrateMetaboliteGlobalIndexs == c.metabolite.m6ADIndexs)); for i = 1:numel(m.reactionVulnerableMotifs) assertFalse(isequal(m.reactionVulnerableMotifs{i}, c.metabolite.m6ADIndexs)); end %check that reaction properties were loaded correctly from KB substrateWholeCellModelIDs = m.substrateWholeCellModelIDs; substrateMetaboliteGlobalIndexs = m.substrateMetaboliteGlobalIndexs; substrateMetaboliteLocalIndexs = m.substrateMetaboliteLocalIndexs; reactionWholeCellModelIDs = m.reactionWholeCellModelIDs; reactionTypes = m.reactionTypes; reactionDamageTypes = m.reactionDamageTypes; reactionVulnerableMotifs = m.reactionVulnerableMotifs; reactionVulnerableMotifTypes = m.reactionVulnerableMotifTypes; reactionSmallMoleculeStoichiometryMatrix = m.reactionSmallMoleculeStoichiometryMatrix; reactionDNAStoichiometryMatrix = m.reactionDNAStoichiometryMatrix; reactionRadiationStoichiometryMatrix = m.reactionRadiationStoichiometryMatrix; reactionBounds = m.reactionBounds; this.loadSimpleTestFixture(); [~, sbIdxs1, sbIdxs2] = intersect(substrateWholeCellModelIDs, m.substrateWholeCellModelIDs); [~, rxIdxs1, rxIdxs2] = intersect(reactionWholeCellModelIDs, m.reactionWholeCellModelIDs); for i=1:length(rxIdxs1) motif = reactionVulnerableMotifs{rxIdxs1(i)}; mMotif = m.reactionVulnerableMotifs{rxIdxs2(i)}; if isnumeric(motif) || isnumeric(mMotif) motif = substrateWholeCellModelIDs{substrateMetaboliteLocalIndexs(motif == substrateMetaboliteGlobalIndexs)}; mMotif = m.substrateWholeCellModelIDs{m.substrateMetaboliteLocalIndexs(mMotif == m.substrateMetaboliteGlobalIndexs)}; end assertEqual(reactionTypes{rxIdxs1(i)}, m.reactionTypes{rxIdxs2(i)}, sprintf('Error in definition of reaction %s', m.reactionWholeCellModelIDs{rxIdxs2(i)})); assertEqual(reactionDamageTypes{rxIdxs1(i)}, m.reactionDamageTypes{rxIdxs2(i)}, sprintf('Error in definition of reaction %s', m.reactionWholeCellModelIDs{rxIdxs2(i)})); assertEqual(motif, mMotif, sprintf('Error in definition of reaction %s', m.reactionWholeCellModelIDs{rxIdxs2(i)})); assertEqual(reactionVulnerableMotifTypes{rxIdxs1(i)}, m.reactionVulnerableMotifTypes{rxIdxs2(i)}, sprintf('Error in definition of reaction %s', m.reactionWholeCellModelIDs{rxIdxs2(i)})); assertEqual(reactionSmallMoleculeStoichiometryMatrix(sbIdxs1,rxIdxs1(i)), m.reactionSmallMoleculeStoichiometryMatrix(sbIdxs2,rxIdxs2(i)), sprintf('Error in definition of reaction %s', m.reactionWholeCellModelIDs{rxIdxs2(i)})); assertEqual(reactionDNAStoichiometryMatrix(sbIdxs1,rxIdxs1(i)), m.reactionDNAStoichiometryMatrix(sbIdxs2,rxIdxs2(i)), sprintf('Error in definition of reaction %s', m.reactionWholeCellModelIDs{rxIdxs2(i)})); assertEqual(reactionRadiationStoichiometryMatrix(sbIdxs1,rxIdxs1(i)), m.reactionRadiationStoichiometryMatrix(sbIdxs2,rxIdxs2(i)), sprintf('Error in definition of reaction %s', m.reactionWholeCellModelIDs{rxIdxs2(i)})); assertEqual(reactionBounds(rxIdxs1(i),1), m.reactionBounds(rxIdxs2(i),1), sprintf('Error in definition of reaction %s', m.reactionWholeCellModelIDs{rxIdxs2(i)})); assertElementsAlmostEqual(reactionBounds(rxIdxs1(i),2), m.reactionBounds(rxIdxs2(i),2), 'relative','1e-4', sprintf('Error in definition of reaction %s',m.reactionWholeCellModelIDs{rxIdxs2(i)})); end end function testReactionStoichiometryMatrixFactorization(this) m = this.process; dMW1 = m.reactionStoichiometryMatrix'*m.substrateMolecularWeights; dMW2 = (... m.reactionSmallMoleculeStoichiometryMatrix+... m.reactionDNAStoichiometryMatrix+... m.reactionRadiationStoichiometryMatrix)'*m.substrateMolecularWeights; assertElementsAlmostEqual(dMW1, dMW2); end function testBaseAlkylation(this) this.loadSimpleTestFixture(); m = this.process; rxIdx = m.reactionIndexs({'DNADamage_hm5U_dhpURA_butylene_glycol'}); %set amount of substrates m.substrates = ... max(0,-m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx)); %increase rate of damage m.reactionBounds(:,2) = 0; m.reactionBounds(rxIdx, 2) = 1; %set DNA to undamaged this.clearDNADamages(); m.chromosome.damagedBases(1,1) = m.substrateMetaboliteGlobalIndexs(m.substrateMetaboliteLocalIndexs == find(m.reactionDNAStoichiometryMatrix(:,rxIdx)<0)); %evolve state m.evolveState(); %find locations of damages [subs, vals] = find(m.chromosome.damagedBases); [~, idxs] = ismember(vals, m.substrateMetaboliteGlobalIndexs); vals = m.substrateMetaboliteLocalIndexs(idxs, :); %correct sequence damaged assertEqual([1 1], subs); %correct damage recorded assertEqual(find(m.reactionDNAStoichiometryMatrix(:,rxIdx)>0), unique(vals)); %no other damages occured assertEqual(m.chromosome.damagedBases, m.chromosome.getDamagedSites(true, true, true, true, false, false, true)); %substrates updated correctly nReactions = size(subs,1); assertEqual(m.substrates, ... nReactions * max(0,m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx))); end function testBaseAmination(this) this.loadSimpleTestFixture(); m = this.process; rxIdx = m.reactionIndexs({'DNADamage_hm5U_putTHY_PTRC'}); %set amount of substrates m.substrates = ... max(0,-m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx)); %increase rate of damage m.reactionBounds(:,2) = 0; m.reactionBounds(rxIdx, 2) = 1; %set DNA to undamaged this.clearDNADamages(); m.chromosome.damagedBases(1,1) = m.substrateMetaboliteGlobalIndexs(m.substrateMetaboliteLocalIndexs == find(m.reactionDNAStoichiometryMatrix(:,rxIdx)<0)); %evolve state m.evolveState(); %find locations of damages [subs, vals] = find(m.chromosome.damagedBases); [~, idxs] = ismember(vals, m.substrateMetaboliteGlobalIndexs); vals = m.substrateMetaboliteLocalIndexs(idxs, :); %correct sequence damaged assertEqual([1 1], subs); %correct damage recorded assertEqual(find(m.reactionDNAStoichiometryMatrix(:,rxIdx)>0), unique(vals)); %no other damages occured assertEqual(m.chromosome.damagedBases, m.chromosome.getDamagedSites(true, true, true, true, false, false, true)); %substrates updated correctly nReactions = size(subs,1); assertEqual(m.substrates, ... nReactions * max(0,m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx))); end function testBaseEthylation(this) this.loadSimpleTestFixture(); m = this.process; rxIdx = m.reactionIndexs({'DNADamage_THY_O4eTHY_ENU'}); %set amount of substrates m.substrates = ... max(0, -m.reactionSmallMoleculeStoichiometryMatrix(:, rxIdx)); %increase rate of damage m.reactionBounds(:,2) = 0; m.reactionBounds(rxIdx, 2) = 10 / size(m.chromosome.sequence,1); %set DNA to undamaged this.clearDNADamages(); %evolve state m.evolveState(); %find locations of damages [subs, vals] = find(m.chromosome.damagedBases); [~, idxs] = ismember(vals, m.substrateMetaboliteGlobalIndexs); vals = m.substrateMetaboliteLocalIndexs(idxs, :); %correct sequence damaged assertTrue(~isempty(subs)); assertEqual(m.reactionVulnerableMotifs{rxIdx}, this.reactedSequences(subs, rxIdx)); %correct damage recorded assertEqual(find(m.reactionDNAStoichiometryMatrix(:,rxIdx)>0), unique(vals)); %no other damages occured assertEqual(m.chromosome.damagedBases, m.chromosome.getDamagedSites(true, true, true, true, false, false, true)); %substrates updated correctly nReactions = size(subs,1); assertEqual(m.substrates, ... nReactions * max(0,m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx))); end function testBaseGlucosylTransfer(this) this.loadSimpleTestFixture(); m = this.process; rxIdx = m.reactionIndexs({'DNADamage_hm5U_glchm5URA_GLC'}); %set amount of substrates m.substrates = ... max(0,-m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx)); %increase rate of damage m.reactionBounds(:,2) = 0; m.reactionBounds(rxIdx, 2) = 1; %set DNA to undamaged this.clearDNADamages(); m.chromosome.damagedBases(1,1) = m.substrateMetaboliteGlobalIndexs(m.substrateMetaboliteLocalIndexs == find(m.reactionDNAStoichiometryMatrix(:,rxIdx)<0)); %evolve state m.evolveState(); %find locations of damages [subs, vals] = find(m.chromosome.damagedBases); [~, idxs] = ismember(vals, m.substrateMetaboliteGlobalIndexs); vals = m.substrateMetaboliteLocalIndexs(idxs, :); %correct sequence damaged assertEqual([1 1], subs); %correct damage recorded assertEqual(find(m.reactionDNAStoichiometryMatrix(:,rxIdx)>0), unique(vals)); %no other damages occured assertEqual(m.chromosome.damagedBases, m.chromosome.getDamagedSites(true, true, true, true, false, false, true)); %substrates updated correctly nReactions = size(subs,1); assertEqual(m.substrates, ... nReactions * max(0,m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx))); end function testBaseMethylation(this) this.loadSimpleTestFixture(); m = this.process; rxIdx = m.reactionIndexs({'DNADamage_THY_O4mTHY_MNU'}); %set amount of substrates m.substrates = ... max(0,-m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx)); %increase rate of damage m.reactionBounds(:,2) = 0; m.reactionBounds(rxIdx, 2) = 10 / size(m.chromosome.sequence,1); %set DNA to undamaged this.clearDNADamages(); %evolve state m.evolveState(); %find locations of damages [subs, vals] = find(m.chromosome.damagedBases); [~, idxs] = ismember(vals, m.substrateMetaboliteGlobalIndexs); vals = m.substrateMetaboliteLocalIndexs(idxs, :); %correct sequence damaged assertEqual(m.reactionVulnerableMotifs{rxIdx}, this.reactedSequences(subs, rxIdx)); %correct damage recorded assertEqual(find(m.reactionDNAStoichiometryMatrix(:,rxIdx)>0), unique(vals)); %no other damages occured assertEqual(m.chromosome.damagedBases, m.chromosome.getDamagedSites(true, true, true, true, false, false, true)); %substrates updated correctly nReactions = size(subs,1); assertEqual(m.substrates, ... nReactions * max(0,m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx))); end function testBaseReduction(this) this.loadSimpleTestFixture(); m = this.process; rxIdx = m.reactionIndexs({'DNADamage_THY_DHTHY_hydrogen_radical'}); %set amount of substrates m.substrates = ... max(0,-m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx)); %increase rate of damage m.reactionBounds(:,2) = 0; m.reactionBounds(rxIdx, 2) = 10 / size(m.chromosome.sequence,1); %set DNA to undamaged this.clearDNADamages(); %evolve state m.evolveState(); %find locations of damages [subs, vals] = find(m.chromosome.damagedBases); [~, idxs] = ismember(vals, m.substrateMetaboliteGlobalIndexs); vals = m.substrateMetaboliteLocalIndexs(idxs, :); %correct sequence damaged assertEqual(m.reactionVulnerableMotifs{rxIdx}, this.reactedSequences(subs, rxIdx)); %correct damage recorded assertEqual(find(m.reactionDNAStoichiometryMatrix(:,rxIdx)>0), unique(vals)); %no other damages occured assertEqual(m.chromosome.damagedBases, m.chromosome.getDamagedSites(true, true, true, true, false, false, true)); %substrates updated correctly nReactions = size(subs,1); assertEqual(m.substrates, ... nReactions * max(0,m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx))); end function testPhotooxidation(this) this.loadSimpleTestFixture(); m = this.process; rxIdx = m.reactionIndexs({'DNADamage_DG_cyclodG_UVB_radiation'}); %set amount of substrates m.substrates = ... max(0,-m.reactionRadiationStoichiometryMatrix(:,rxIdx)) + ... max(0,-m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx)); %increase rate of damage m.reactionBounds(:,2) = 0; m.reactionBounds(rxIdx, 2) = 10 / size(m.chromosome.sequence,1); %set DNA to undamaged this.clearDNADamages(); %evolve state m.evolveState(); %find locations of damages [subs, vals] = find(m.chromosome.damagedBases); [~, idxs] = ismember(vals, m.substrateMetaboliteGlobalIndexs); vals = m.substrateMetaboliteLocalIndexs(idxs, :); %correct sequence damaged assertEqual(m.reactionVulnerableMotifs{rxIdx}, this.reactedSequences(subs, rxIdx)); %correct damage recorded assertEqual(find(m.reactionDNAStoichiometryMatrix(:,rxIdx)>0), unique(vals)); %no other damages occured assertEqual(m.chromosome.damagedBases, m.chromosome.getDamagedSites(true, true, true, true, false, false, true)); %substrates updated correctly nReactions = size(subs,1); assertEqual(m.substrates, ... max(0,-m.reactionRadiationStoichiometryMatrix(:,rxIdx)) + ... nReactions * max(0,m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx))); end function testGammaRayBaseOxidation(this) m = this.process; rxIdx = m.reactionIndexs({'DNADamage_URA_ho5URA_hydroxyl_radical'}); %set amount of substrates m.substrates = ... max(0,-m.reactionRadiationStoichiometryMatrix(:,rxIdx)) + ... max(0,-m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx)); %increase rate of damage m.reactionBounds(:,2) = 0; m.reactionBounds(rxIdx, 2) = 1; %set DNA to undamaged this.clearDNADamages(); m.chromosome.damagedBases(1,1) = m.substrateMetaboliteGlobalIndexs(m.substrateMetaboliteLocalIndexs == find(m.reactionDNAStoichiometryMatrix(:,rxIdx)<0)); %evolve state m.evolveState(); %find locations of damages [subs, vals] = find(m.chromosome.damagedBases); [~, idxs] = ismember(vals, m.substrateMetaboliteGlobalIndexs); vals = m.substrateMetaboliteLocalIndexs(idxs, :); %correct sequence damagedthis.reactedSequences(subs, rxIdx) assertEqual([1 1], subs); %correct damage recorded assertEqual(find(m.reactionDNAStoichiometryMatrix(:,rxIdx)>0), unique(vals)); %no other damages occured assertEqual(m.chromosome.damagedBases, m.chromosome.getDamagedSites(true, true, true, true, false, false, true)); %substrates updated correctly nReactions = size(subs,1); assertEqual(m.substrates, ... max(0,-m.reactionRadiationStoichiometryMatrix(:,rxIdx)) + ... nReactions * max(0,m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx))); end function testSpontaneousBaseDeamination(this) m = this.process; rxIdx = m.reactionIndexs({'DNADamage_SpontaneousBaseDeamination_m5C'}); %set amount of substrates m.substrates = ... max(0,-m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx)); %increase rate of damage m.reactionBounds(:,2) = 0; m.reactionBounds(rxIdx, 2) = 1; %set DNA to undamaged this.clearDNADamages(); m.chromosome.damagedBases(1,1) = m.substrateMetaboliteGlobalIndexs(m.substrateMetaboliteLocalIndexs == find(m.reactionDNAStoichiometryMatrix(:,rxIdx)<0)); %evolve state m.evolveState(); %find locations of damages [subs, vals] = find(m.chromosome.damagedBases); [~, idxs] = ismember(vals, m.substrateMetaboliteGlobalIndexs); vals = m.substrateMetaboliteLocalIndexs(idxs, :); %correct sequence damaged assertEqual([1 1], subs); %correct damage recorded assertEqual(find(m.reactionDNAStoichiometryMatrix(:,rxIdx)>0), unique(vals)); %no other damages occured assertEqual(m.chromosome.damagedBases, m.chromosome.getDamagedSites(true, true, true, true, false, false, true)); %substrates updated correctly nReactions = size(subs,1); assertEqual(m.substrates, ... nReactions * max(0,m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx))); end function testSpontaneousBaseLoss(this) m = this.process; rxIdx = m.reactionIndexs({'DNADamage_SpontaneousBaseLoss_thymine'}); %set amount of substrates m.substrates = ... max(0,-m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx)); %increase rate of damage m.reactionBounds(:,2) = 0; m.reactionBounds(rxIdx, 2) = 10 / size(m.chromosome.sequence,1); %set DNA to undamaged this.clearDNADamages(); %evolve state m.evolveState(); %find locations of damages [subs, vals] = find(m.chromosome.abasicSites); %correct sequence damaged assertEqual(m.reactionVulnerableMotifs{rxIdx}, this.reactedSequences(subs, rxIdx)); %correct damage recorded assertEqual(true, unique(vals)); %no other damages occured assertEqual(m.chromosome.abasicSites, m.chromosome.getDamagedSites(true, true, true, true, false, false, true)); %substrates updated correctly nReactions = size(subs,1); assertEqual(m.substrates, ... nReactions * max(0,m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx))); end function testStrandBreak(this) m = this.process; rxIdx = m.reactionIndexs({'DNADamage_SpontaneousAbasicSiteStrandBreak'}); %set amount of substrates m.substrates = ... max(0,-m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx)); %increase rate of damage m.reactionBounds(:,2) = 0; m.reactionBounds(rxIdx, 2) = 1; %set DNA to undamaged this.clearDNADamages(); m.chromosome.abasicSites(1, 1) = true; %evolve state m.evolveState(); %find locations of damages [subs, vals] = find(m.chromosome.strandBreaks); %correct sequence damaged assertEqual([1 1], subs); %correct damage recorded assertEqual(true, unique(vals)); %no other damages occured assertEqual(m.chromosome.strandBreaks | m.chromosome.strandBreaks5, m.chromosome.getDamagedSites(true, true, true, true, false, false, true) ~= 0); %substrates updated correctly nReactions = size(subs,1); assertEqual(m.substrates, ... nReactions * max(0,m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx))); end function testUVBDimerization(this) import edu.stanford.covert.util.CircularSparseMat; m = this.process; rxIdx = m.reactionIndexs({'DNADamage_THYTHY_THY64THY_UVB_radiation'}); %set amount of substrates m.substrates = ... max(0,-m.reactionRadiationStoichiometryMatrix(:,rxIdx)) + ... max(0,-m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx)); %increase rate of damage m.reactionBounds(:,2) = 0; m.reactionBounds(rxIdx, 2) = 10 / size(m.chromosome.sequence,1); %set DNA to undamaged this.clearDNADamages(); %evolve state m.evolveState(); %find locations of damages [subs, vals] = find(m.chromosome.intrastrandCrossLinks); [~, idxs] = ismember(vals, m.substrateMetaboliteGlobalIndexs); vals = m.substrateMetaboliteLocalIndexs(idxs, :); %correct sequence damaged assertEqual(m.reactionVulnerableMotifs{rxIdx}, this.reactedSequences(subs, rxIdx)); %correct damage recorded assertEqual(find(m.reactionDNAStoichiometryMatrix(:,rxIdx)>0), unique(vals)); %no other damages occured assertEqual(m.chromosome.intrastrandCrossLinks + m.chromosome.intrastrandCrossLinks5, m.chromosome.getDamagedSites(true, true, true, true, false, false, true)); %substrates updated correctly nReactions = size(subs,1); assertEqual(m.substrates, ... max(0,-m.reactionRadiationStoichiometryMatrix(:,rxIdx)) + ... nReactions * max(0,m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx))); end function testMultipleReactions(this) this.loadSimpleTestFixture(); m = this.process; rxIdx = m.reactionIndexs({'DNADamage_hm5U_dhpURA_butylene_glycol'; 'DNADamage_THY_O4eTHY_ENU'}); %set amount of substrates m.substrates = sum(... max(0,-m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx)),... 2); %increase rate of damage m.reactionBounds(:,2) = 0; m.reactionBounds(rxIdx, 2) = [1; 10 / size(m.chromosome.sequence,1)]; %set DNA to undamaged this.clearDNADamages(); m.chromosome.damagedBases(1,1) = m.substrateMetaboliteGlobalIndexs(m.substrateMetaboliteLocalIndexs == find(m.reactionDNAStoichiometryMatrix(:,rxIdx(1))<0)); %evolve state m.evolveState(); %find locations of damages [subs, vals] = find(m.chromosome.damagedBases); [~, idxs] = ismember(vals, m.substrateMetaboliteGlobalIndexs); vals = m.substrateMetaboliteLocalIndexs(idxs, :); %correct sequence damaged assertEqual([1 1], subs(vals == find(m.reactionDNAStoichiometryMatrix(:,rxIdx(1))>0),:)); assertEqual(m.reactionVulnerableMotifs{rxIdx(2)}, this.reactedSequences(subs(vals == find(m.reactionDNAStoichiometryMatrix(:,rxIdx(2))>0),:), rxIdx(2))); %correct damage recorded [~, vals] = find(m.chromosome.damagedBases); [~, idxs] = ismember(vals, m.substrateMetaboliteGlobalIndexs); vals = m.substrateMetaboliteLocalIndexs(idxs, :); assertEqual(find(any(m.reactionDNAStoichiometryMatrix(:,rxIdx)>0,2)), unique(vals)); %no other damages occured assertEqual(m.chromosome.damagedBases, m.chromosome.getDamagedSites(true, true, true, true, false, false, true)); %substrates updated correctly nReactions = sum(m.reactionDNAStoichiometryMatrix(vals,rxIdx)>0,1)'; assertEqual(m.substrates, ... max(0,m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx)) * nReactions); end function testFairness(this) this.loadSimpleTestFixture(); m = this.process; rxIdx = m.reactionIndexs({'DNADamage_hm5U_dhpURA_butylene_glycol'}); dnaSubstrate = find(m.reactionDNAStoichiometryMatrix(:,rxIdx)<0); dnaProduct = find(m.reactionDNAStoichiometryMatrix(:,rxIdx)>0); dnaSubstrate = m.substrateMetaboliteGlobalIndexs(m.substrateMetaboliteLocalIndexs == dnaSubstrate); dnaProduct = m.substrateMetaboliteGlobalIndexs(m.substrateMetaboliteLocalIndexs == dnaProduct); %set amount of substrates m.substrates = ... max(0,-m.reactionSmallMoleculeStoichiometryMatrix(:,rxIdx)); initial_substrates = m.substrates; %increase rate of damage m.reactionBounds(:,2) = 0; m.reactionBounds(rxIdx, 2) = 1; %set DNA to undamaged this.clearDNADamages(); m.chromosome.damagedBases(1:2,1) = dnaSubstrate; damagedBases = m.chromosome.damagedBases; counts = zeros(2,1); for i=1:200 %reset state m.substrates = initial_substrates; m.chromosome.damagedBases = damagedBases; %evolve state m.evolveState(); %find locations of damages [subs, vals] = find(m.chromosome.damagedBases); subs = subs(vals == dnaProduct,1); %update counts counts(subs) = counts(subs) + 1; end %check positions modified fairly assertTrue(max(counts)-min(counts) < 0.2 * max(counts)); end function testGeneEssentiality(this) m = this.process; c = m.chromosome; c.polymerizedRegions(1, 1:2) = size(c.sequence, 1); m.substrates(:) = 1e3; m.substrates(m.substrateIndexs_radiation) = 1; %increase rates of damage m.reactionBounds(:,2) = 10 / size(m.chromosome.sequence,1); damagedSites = m.chromosome.getDamagedSites(true, true, true, true, false, false, true); this.helpTestGeneEssentiality(... {},... @(m,i) nnz(m.chromosome.getDamagedSites(true, true, true, true, false, false, true)) > nnz(damagedSites)); end end %helper methods methods function clearDNADamages(this) m = this.process; m.chromosome.initialize(); end function sequence = reactedSequences(this, subs, rxIdx) m = this.process; positions = mod(... repmat(subs(:,1), 1, length(m.reactionVulnerableMotifs{rxIdx})) + ... repmat(2*mod(subs(:,2),2)-1, 1, length(m.reactionVulnerableMotifs{rxIdx})) .* ... repmat(0:length(m.reactionVulnerableMotifs{rxIdx})-1, size(subs,1), 1) ... -1, size(m.chromosome.sequence,1))+1; strands = repmat(subs(:,2), 1, length(m.reactionVulnerableMotifs{rxIdx})); sequence = reshape(unique(m.chromosome.sequence.subsequence(positions, strands),'rows'), size(m.reactionVulnerableMotifs{rxIdx})); end end end
theory Memory_Model imports Word_Lib.Word_Lemmas_32 RT_Log begin consts kernel_window_lower_bound :: "32 word" consts kernel_window_upper_bound :: "32 word" consts global_offset :: "32 word" consts ker_phy_lower_bound :: "paddr" consts ker_phy_upper_bound :: "paddr" definition high_ptable :: "paddr \<Rightarrow> paddr set" where "high_ptable rt = {rt r+ kernel_window_lower_bound .. rt r+ kernel_window_upper_bound}" definition "kernel_phy_mem = {ker_phy_lower_bound .. ker_phy_upper_bound}" definition pd_idx_offset :: "32 word \<Rightarrow> machine_word" where "pd_idx_offset vp = ((vaddr_pd_index vp) << 2)" definition va_to_pid_offset :: "vaddr set \<Rightarrow> 32 word set" where "va_to_pid_offset V = pd_idx_offset ` addr_val ` V" definition "pointer_to_high_ptable rt va \<equiv> rt r+ pd_idx_offset va \<in> high_ptable rt" (*making nG bit zero *) definition "global hp rt va \<equiv> (\<forall> bpa perms. get_pde' hp rt va = Some (SectionPDE bpa perms) \<longrightarrow> arm_p_nG perms = 0) \<and> (\<forall>p bpa perms. (get_pde' hp rt va = Some (PageTablePDE p) \<and> get_pte' hp p va = Some (SmallPagePTE bpa perms)) \<longrightarrow> arm_p_nG perms = 0)" definition vas_mapped_by_global_mappings :: "paddr \<Rightarrow> vaddr set" where "vas_mapped_by_global_mappings r \<equiv> Addr ` {va. r r+ pd_idx_offset va \<in> high_ptable r }" definition "non_global hp rt va \<equiv> (\<forall> bpa perms. get_pde' hp rt va = Some (SectionPDE bpa perms) \<longrightarrow> arm_p_nG perms = 1) \<and> (\<forall>p bpa perms. (get_pde' hp rt va = Some (PageTablePDE p) \<and> get_pte' hp p va = Some (SmallPagePTE bpa perms)) \<longrightarrow> arm_p_nG perms = 1)" definition global_mappings' :: "heap \<Rightarrow> paddr \<Rightarrow> bool" where "global_mappings' h r \<equiv> (\<forall>va. r r+ pd_idx_offset va \<in> high_ptable r \<longrightarrow> (\<exists>p perms. get_pde' h r (Addr va) = Some (SectionPDE p perms) \<and> arm_p_nG perms = 0 \<and> \<not>user_perms perms ) \<and> ptable_lift_m h r Kernel (Addr va) = Some (Addr va r- global_offset) \<and> (Addr va r- global_offset) \<in> kernel_phy_mem) \<and> ( \<forall>va. r r+ pd_idx_offset va \<notin> high_ptable r \<longrightarrow> non_global h r (Addr va))" definition global_mappings :: _ where "global_mappings s \<equiv> (\<forall>rt\<in>roots s. global_mappings' (heap s) rt)" definition hptable_eq :: "p_state \<Rightarrow> bool" where "hptable_eq s \<equiv> \<forall>rt rt'. rt\<in>roots s \<and>rt'\<in>roots s \<longrightarrow> (\<forall>va. rt r+ pd_idx_offset va \<in> high_ptable rt \<longrightarrow> get_pde' (heap s) rt (Addr va) = get_pde' (heap s) rt' (Addr va))" definition "pd_bits = (14 :: nat)" definition "kwindow_bound \<equiv> kernel_window_lower_bound < 2 ^ pd_bits \<and> kernel_window_upper_bound < 2 ^ pd_bits" definition kernel_mappings :: "p_state \<Rightarrow> bool" where "kernel_mappings s \<equiv> kwindow_bound \<and> hptable_eq s \<and> global_mappings s" definition vas_of_current_state_mapped_to_global_mappings_of_all_processes :: "p_state \<Rightarrow> vaddr set" where "vas_of_current_state_mapped_to_global_mappings_of_all_processes s = {va\<in>vas_mapped_by_global_mappings (root s). ptable_trace' (heap s) (root s) va \<subseteq> \<Union>(high_ptable ` roots s)}" definition kernel_safe :: "p_state \<Rightarrow> vaddr set" where "kernel_safe s = vas_mapped_by_global_mappings (root s) - vas_of_current_state_mapped_to_global_mappings_of_all_processes s" lemma global_mappings_ptable_lift' [simp]: "\<exists>rt. root s = rt \<and> mode s = Kernel \<and> rt \<in> roots s \<and> kernel_mappings s \<Longrightarrow> \<forall>va\<in>kernel_safe s. ptable_lift' (heap s) (root s) va = Some (Addr (addr_val va) r- global_offset)" by (clarsimp simp: kernel_mappings_def kernel_safe_def vas_mapped_by_global_mappings_def kernel_mappings_def global_mappings_def global_mappings'_def vas_of_current_state_mapped_to_global_mappings_of_all_processes_def ) lemma global_mappings_ptable_lift_m: "\<lbrakk>\<exists>rt. root s = rt \<and> rt \<in> roots s; kernel_mappings s; va \<in> kernel_safe s\<rbrakk> \<Longrightarrow> ptable_lift_m (heap s) (root s) Kernel va = Some (Addr (addr_val va) r- global_offset) " by (clarsimp simp: kernel_mappings_def kernel_safe_def vas_mapped_by_global_mappings_def kernel_mappings_def global_mappings_def global_mappings'_def) lemma global_mappings_ptable_decode_heap_pde: "\<lbrakk>root s \<in> roots s; kernel_mappings s ; va \<in> kernel_safe s\<rbrakk> \<Longrightarrow> \<exists>p perm. decode_heap_pde' (heap s) (root s r+ (vaddr_pd_index (addr_val va) << 2)) = Some (SectionPDE p perm)" apply (clarsimp simp: kernel_safe_def vas_mapped_by_global_mappings_def kernel_mappings_def global_mappings_def global_mappings'_def pd_idx_offset_def get_pde'_def global_mappings_def) apply force done (* Page Tables *) definition "ptable_footprint s rt \<equiv> \<Union>(ptable_trace' (heap s) rt ` UNIV)" definition "page_tables_in_high_memory s \<equiv> ptable_footprint s (root s) \<subseteq> kernel_phy_mem" abbreviation "non_overlapping_tables \<equiv> non_overlapping_defined_page_tables" lemma non_overlapping_tables_def: "non_overlapping_tables s \<equiv> \<forall>rt rt'. rt \<in> roots s \<and> rt' \<in> roots s \<and> rt \<noteq> rt' \<longrightarrow> ptable_footprint s rt \<inter> ptable_footprint s rt' = {}" by (auto simp: non_overlapping_defined_page_tables_def ptable_footprint_def) (* definition "root_log_area = set root_log_fp" *) definition "kernel_data s \<equiv> map (ptable_footprint s) (root_log s) @ [root_map_area]" definition "kernel_data_area s \<equiv> \<Union>set (kernel_data s)" definition "user_mappings s \<equiv> \<forall>rt \<in> roots s. \<forall>va pa. ptable_lift_m (heap s) rt User va = Some pa \<longrightarrow> (pa \<notin> kernel_phy_mem \<and> non_global (heap s) rt va)" definition "global_set_eq' s \<equiv> (\<Union>x\<in>global_entries (the ` {e \<in> range (pt_walk (asid s) (heap s) (root s)). \<not> is_fault e}). range_of x) = global_set s" lemma " \<lbrakk>user_mappings s ; rt \<in> roots s\<rbrakk> \<Longrightarrow> \<forall>va. ptable_lift_m (heap s) rt User va = Some pa \<longrightarrow> non_global (heap s) rt va" by (clarsimp simp: user_mappings_def ) fun non_overlapping where "non_overlapping [] = True" | "non_overlapping (x#xs) = ((x \<inter> \<Union>set xs = {}) \<and> non_overlapping xs)" definition "page_tables s \<equiv> non_overlapping (kernel_data s) \<and> user_mappings s \<and> kernel_data_area s \<subseteq> kernel_phy_mem" lemma non_overlapping_append[simp]: "non_overlapping (xs @ ys) = (non_overlapping xs \<and> non_overlapping ys \<and> \<Union>set xs \<inter> \<Union>set ys = {})" by (induct xs) auto lemma non_overlapping_map: "\<lbrakk> non_overlapping (map f xs); x \<in> set xs; y \<in> set xs; x \<noteq> y\<rbrakk> \<Longrightarrow> f x \<inter> f y = {}" by (induct xs) auto lemma non_overlapping_tables_from_kernel_data: "non_overlapping (kernel_data s) \<Longrightarrow> non_overlapping_tables s" by (clarsimp simp: non_overlapping_tables_def kernel_data_def non_overlapping_map roots_def) (* find_consts "('a \<Rightarrow> 'b option) \<Rightarrow> ('b \<Rightarrow> 'c option)" thm map_comp_def *) definition "global_set_eq s \<equiv> {va. root s r+ pd_idx_offset (addr_val va) \<in> high_ptable (root s)} = global_set s " (* MMU *) definition "aligned (rts :: paddr set) \<equiv> \<forall>rt\<in>rts. is_aligned (addr_val rt) pd_bits" definition mmu_layout :: "p_state \<Rightarrow> bool" where "mmu_layout s \<equiv> kernel_data_area s \<subseteq> kernel_phy_mem \<and> non_overlapping (kernel_data s) \<and> aligned (roots s) \<and> root_map s (root s) = Some (asid s) \<and> kernel_mappings s \<and> user_mappings s \<and> partial_inj (root_map s) \<and> global_set_eq s" (* kernel_safe_region preservation *) definition "k_phy_ad vp = Addr vp r- global_offset" lemma mmu_layout_pt_walk': "\<lbrakk> mmu_layout s; p \<notin> kernel_data_area s; rt \<in> roots s \<rbrakk> \<Longrightarrow> pt_walk a (heap s(p \<mapsto> v)) rt = pt_walk a (heap s) rt" apply (rule ext) apply (subst pt_walk_pt_trace_upd') apply (clarsimp simp: mmu_layout_def kernel_data_def kernel_data_area_def ptable_footprint_def roots_def) apply simp done lemma mmu_layout_pt_walk: "\<lbrakk> mmu_layout s; p \<notin> kernel_phy_mem; rt \<in> roots s \<rbrakk> \<Longrightarrow> pt_walk a (heap s(p \<mapsto> v)) rt = pt_walk a (heap s) rt" apply (rule mmu_layout_pt_walk'; assumption?) apply (auto simp: mmu_layout_def) done lemma mmu_layout_pt_walk_pair': "\<lbrakk> mmu_layout s; p \<notin> kernel_data_area s; rt \<in> roots s \<rbrakk> \<Longrightarrow> pt_walk_pair a (heap s(p \<mapsto> v)) rt = pt_walk_pair a (heap s) rt" apply (rule ext) apply (subst pt_walk_pair_pt_trace_upd') apply (clarsimp simp: mmu_layout_def kernel_data_def kernel_data_area_def ptable_footprint_def roots_def) apply simp done lemma mmu_layout_pt_walk_pair: "\<lbrakk> mmu_layout s; p \<notin> kernel_phy_mem; rt \<in> roots s \<rbrakk> \<Longrightarrow> pt_walk_pair a (heap s(p \<mapsto> v)) rt = pt_walk_pair a (heap s) rt" apply (rule mmu_layout_pt_walk_pair'; assumption?) apply (auto simp: mmu_layout_def) done lemma rootsI: "root_map s r \<noteq> None \<Longrightarrow> r \<in> roots s" by (simp add: roots_def') lemma mmu_layout_ptable_comp: "\<lbrakk> mmu_layout s; p \<notin> kernel_phy_mem \<rbrakk> \<Longrightarrow> incon_comp (asid s) (asid s)(heap s) (heap s(p \<mapsto> v)) (root s) (root s) = {}" apply (simp add: incon_comp_def) apply (subgoal_tac "root s \<in> roots s") apply (simp add: mmu_layout_pt_walk_pair ptable_comp_def) apply (clarsimp simp: mmu_layout_def intro!: rootsI) done lemma ptable_footprint_upd: "p \<notin> ptable_footprint s rt \<Longrightarrow> ptable_footprint (s\<lparr>p_state.heap := p_state.heap s(p \<mapsto> v)\<rparr>) rt = ptable_footprint s rt" by (simp add: ptable_footprint_def pt_trace_upd) lemma root_set_upd[simp]: "p \<notin> kernel_data_area s \<Longrightarrow> root_set (s\<lparr>p_state.heap := heap s(p \<mapsto> v)\<rparr>) = root_set s" by (clarsimp simp: kernel_data_area_def kernel_data_def root_set_not_elem[symmetric]) lemma root_set_upd'[simp]: "p \<notin> root_map_area \<Longrightarrow> root_set (s\<lparr>p_state.heap := heap s(p \<mapsto> v)\<rparr>) = root_set s" using root_set_not_elem by auto lemma root_map_upd[simp]: "p \<notin> kernel_data_area s \<Longrightarrow> root_map (s\<lparr>p_state.heap := heap s(p \<mapsto> v)\<rparr>) = root_map s" by (clarsimp simp: kernel_data_area_def root_map_def) lemma root_map_upd'[simp]: "p \<notin> root_map_area \<Longrightarrow> root_map (s\<lparr>p_state.heap := heap s(p \<mapsto> v)\<rparr>) = root_map s" by (clarsimp simp: kernel_data_area_def root_map_def) lemma roots_upd[simp]: "p \<notin> kernel_data_area s \<Longrightarrow> roots (s\<lparr>p_state.heap := heap s(p \<mapsto> v)\<rparr>) = roots s" by (clarsimp simp: kernel_data_area_def roots_def') lemma roots_upd'[simp]: "p \<notin> root_map_area \<Longrightarrow> roots (s\<lparr>p_state.heap := heap s(p \<mapsto> v)\<rparr>) = roots s" by (clarsimp simp: kernel_data_area_def roots_def') lemma ptable_footprint_upd_roots[simp]: "p \<notin> kernel_data_area s \<Longrightarrow> ptable_footprint (s\<lparr>p_state.heap := p_state.heap s(p \<mapsto> v)\<rparr>) ` (roots s) = ptable_footprint s ` (roots s)" by (rule set_eqI) (clarsimp simp: kernel_data_def kernel_data_area_def image_iff ptable_footprint_upd roots_def) lemma root_log_upd[simp]: "p \<notin> kernel_data_area s \<Longrightarrow> root_log (s\<lparr>p_state.heap := heap s(p \<mapsto> v)\<rparr>) = root_log s" by (clarsimp simp: kernel_data_area_def root_log_def) lemma kernel_data_upd: "p \<notin> kernel_data_area s \<Longrightarrow> kernel_data (s\<lparr>p_state.heap := heap s(p \<mapsto> v)\<rparr>) = kernel_data s" by (clarsimp simp: kernel_data_def kernel_data_area_def ptable_footprint_upd) lemma kernel_data_area_upd: "p \<notin> kernel_data_area s \<Longrightarrow> kernel_data_area (s\<lparr>p_state.heap := heap s(p \<mapsto> v)\<rparr>) = kernel_data_area s" by (clarsimp simp: kernel_data_area_def kernel_data_upd) lemma kernel_data_area_ptrace: "\<lbrakk>p \<notin> kernel_data_area s; rt \<in> roots s\<rbrakk> \<Longrightarrow> p \<notin> ptable_trace' (heap s) rt va " by (clarsimp simp: kernel_data_area_def kernel_data_def ptable_footprint_def roots_def) lemma kernel_data_area_ptrace': "\<lbrakk>p \<notin> kernel_data_area s; rt \<in> roots s\<rbrakk> \<Longrightarrow> p \<notin> ptable_trace' (heap s (p \<mapsto> v)) rt va " apply (clarsimp simp: kernel_data_area_def kernel_data_def ptable_footprint_def roots_def) using pt_trace_upd by blast lemma kernel_data_global_map_update [simp]: "p \<notin> kernel_data_area s \<Longrightarrow> global_mappings s = global_mappings (s\<lparr>heap := heap s(p \<mapsto> v)\<rparr>)" apply safe apply (clarsimp simp: global_mappings_def global_mappings'_def) apply (drule_tac x = rt in bspec, simp) apply (clarsimp) apply (rule conjI) apply clarsimp apply (subgoal_tac "p \<notin> ptable_trace' (heap s) rt (Addr va)") using pt_table_lift_trace_upd'' ptable_trace_get_pde apply auto[1] apply (rule kernel_data_area_ptrace; simp) apply clarsimp apply (subgoal_tac "p \<notin> ptable_trace' (heap s) rt (Addr va)") apply (clarsimp simp: non_global_def) apply (rule conjI) using ptable_trace_get_pde' apply blast apply (clarsimp) apply (thin_tac " \<forall>va. rt r+ pd_idx_offset va \<in> high_ptable rt \<longrightarrow> (\<exists>p perms. get_pde' (heap s) rt (Addr va) = Some (SectionPDE p perms) \<and> arm_p_nG perms = 0 \<and> \<not> user_perms perms) \<and> ptable_lift' (heap s) rt (Addr va) = Some (Addr (va - global_offset)) \<and> Addr (va - global_offset) \<in> kernel_phy_mem") apply (drule_tac x = "va" in spec, clarsimp) apply (subgoal_tac " get_pde' (heap s(p \<mapsto> v)) rt (Addr va) = get_pde' (heap s) rt (Addr va)") apply clarsimp apply (subgoal_tac "get_pte' (heap s) pa (Addr va) = get_pte' (heap s(p \<mapsto> v)) pa (Addr va)") apply clarsimp apply (subgoal_tac " p \<notin> ptable_trace' (heap s) rt (Addr va)") apply (clarsimp simp: get_pte'_def get_pde'_def decode_heap_pde'_def ptable_trace'_def Let_def decode_heap_pte'_def) apply (rule kernel_data_area_ptrace, simp, simp) apply (metis ptable_trace_get_pde') apply (rule kernel_data_area_ptrace, simp, simp) apply (clarsimp simp: global_mappings_def global_mappings'_def) apply (drule_tac x = rt in bspec, simp) apply (clarsimp) apply (rule conjI) apply clarsimp apply (subgoal_tac "p \<notin> ptable_trace' (heap s(p \<mapsto> v)) rt (Addr va)") apply (metis kernel_data_area_ptrace pt_table_lift_trace_upd' ptable_trace_get_pde') apply (rule kernel_data_area_ptrace'; simp) apply clarsimp apply (subgoal_tac "p \<notin> ptable_trace' (heap s(p \<mapsto> v)) rt (Addr va)") apply (clarsimp simp: non_global_def) apply (rule conjI) apply (simp add: kernel_data_area_ptrace ptable_trace_get_pde) apply (clarsimp) apply (thin_tac " \<forall>va. rt r+ pd_idx_offset va \<in> high_ptable rt \<longrightarrow> (\<exists>pa perms. get_pde' (heap s(p \<mapsto> v)) rt (Addr va) = Some (SectionPDE pa perms) \<and> arm_p_nG perms = 0 \<and> \<not> user_perms perms) \<and> ptable_lift' (heap s(p \<mapsto> v)) rt (Addr va) = Some (Addr (va - global_offset)) \<and> Addr (va - global_offset) \<in> kernel_phy_mem") apply (drule_tac x = "va" in spec, clarsimp) apply (subgoal_tac " get_pde' (heap s(p \<mapsto> v)) rt (Addr va) = get_pde' (heap s) rt (Addr va)") apply clarsimp apply (subgoal_tac "get_pte' (heap s) pa (Addr va) = get_pte' (heap s(p \<mapsto> v)) pa (Addr va)") apply clarsimp apply (subgoal_tac " p \<notin> ptable_trace' (heap s(p \<mapsto> v)) rt (Addr va)") apply (clarsimp simp: get_pte'_def get_pde'_def decode_heap_pde'_def ptable_trace'_def Let_def decode_heap_pte'_def) apply (rule kernel_data_area_ptrace', simp, simp) apply (simp add: kernel_data_area_ptrace ptable_trace_get_pde) by (rule kernel_data_area_ptrace', simp, simp) lemma kerenl_data_global_mappings [simp]: "p \<notin> kernel_data_area s \<Longrightarrow> hptable_eq s = hptable_eq (s\<lparr>heap := heap s(p \<mapsto> v)\<rparr>)" apply (safe) apply (clarsimp simp: hptable_eq_def) apply (subgoal_tac "get_pde' (heap s(p \<mapsto> v)) rt (Addr va) = get_pde' (heap s) rt (Addr va)") apply (subgoal_tac "get_pde' (heap s(p \<mapsto> v)) rt' (Addr va) = get_pde' (heap s) rt' (Addr va)") apply presburger apply (thin_tac "\<forall>rt rt'. rt \<in> roots s \<and> rt' \<in> roots s \<longrightarrow> (\<forall>va. rt r+ pd_idx_offset va \<in> high_ptable rt \<longrightarrow> get_pde' (heap s) rt (Addr va) = get_pde' (heap s) rt' (Addr va))") apply (subgoal_tac " p \<notin> ptable_trace' (heap s) rt' (Addr va)") apply (clarsimp simp: ptable_trace'_def get_pde'_def Let_def decode_heap_pde'_def split: pde.splits) apply (rule kernel_data_area_ptrace, simp, simp) apply (thin_tac "\<forall>rt rt'. rt \<in> roots s \<and> rt' \<in> roots s \<longrightarrow> (\<forall>va. rt r+ pd_idx_offset va \<in> high_ptable rt \<longrightarrow> get_pde' (heap s) rt (Addr va) = get_pde' (heap s) rt' (Addr va))") apply (subgoal_tac " p \<notin> ptable_trace' (heap s) rt (Addr va)") apply (clarsimp simp: ptable_trace'_def get_pde'_def Let_def decode_heap_pde'_def split: pde.splits) apply (rule kernel_data_area_ptrace, simp, simp) apply (clarsimp simp: hptable_eq_def) apply (subgoal_tac "get_pde' (heap s(p \<mapsto> v)) rt (Addr va) = get_pde' (heap s) rt (Addr va)") apply (subgoal_tac "get_pde' (heap s(p \<mapsto> v)) rt' (Addr va) = get_pde' (heap s) rt' (Addr va)") apply presburger apply (thin_tac "\<forall>rt rt'. rt \<in> roots s \<and> rt' \<in> roots s \<longrightarrow> (\<forall>va. rt r+ pd_idx_offset va \<in> high_ptable rt \<longrightarrow> get_pde' (heap s(p \<mapsto> v)) rt (Addr va) = get_pde' (heap s(p \<mapsto> v)) rt' (Addr va))") apply (subgoal_tac " p \<notin> ptable_trace' (heap s) rt' (Addr va)") apply (clarsimp simp: ptable_trace'_def get_pde'_def Let_def decode_heap_pde'_def split: pde.splits) apply (rule kernel_data_area_ptrace, simp, simp) apply (thin_tac "\<forall>rt rt'. rt \<in> roots s \<and> rt' \<in> roots s \<longrightarrow> (\<forall>va. rt r+ pd_idx_offset va \<in> high_ptable rt \<longrightarrow> get_pde' (heap s(p \<mapsto> v)) rt (Addr va) = get_pde' (heap s(p \<mapsto> v)) rt' (Addr va))") apply (subgoal_tac " p \<notin> ptable_trace' (heap s) rt (Addr va)") apply (clarsimp simp: ptable_trace'_def get_pde'_def Let_def decode_heap_pde'_def split: pde.splits) by (rule kernel_data_area_ptrace, simp, simp) lemma kernel_data_area_non_global[simp]: "\<lbrakk>p \<notin> kernel_data_area s ; rt \<in> roots s\<rbrakk> \<Longrightarrow> non_global (heap (s\<lparr>p_state.heap := heap s(p \<mapsto> v)\<rparr>)) rt va = non_global (heap s) rt va" apply (subgoal_tac "get_pde' (heap s) rt va = get_pde' (heap s(p \<mapsto> v)) rt va") apply safe apply (clarsimp simp: non_global_def) apply (subgoal_tac "get_pte' (heap s) pa va = get_pte' (heap s(p \<mapsto> v)) pa va") apply clarsimp apply (subgoal_tac " p \<notin> ptable_trace' (heap s(p \<mapsto> v)) rt va") apply (clarsimp simp: get_pte'_def get_pde'_def decode_heap_pde'_def ptable_trace'_def Let_def decode_heap_pte'_def) apply (rule kernel_data_area_ptrace', simp, simp) apply (clarsimp simp: non_global_def) apply (subgoal_tac "get_pte' (heap s) pa va = get_pte' (heap s(p \<mapsto> v)) pa va") apply clarsimp apply (subgoal_tac " p \<notin> ptable_trace' (heap s(p \<mapsto> v)) rt va") apply (clarsimp simp: get_pte'_def get_pde'_def decode_heap_pde'_def ptable_trace'_def Let_def decode_heap_pte'_def) apply (rule kernel_data_area_ptrace', simp, simp) apply (subgoal_tac " p \<notin> ptable_trace' (heap s(p \<mapsto> v)) rt va") apply (clarsimp simp: ptable_trace'_def get_pde'_def Let_def decode_heap_pde'_def split: pde.splits) by (simp add: kernel_data_area_ptrace') lemma kernel_mapping_upd: "p \<notin> kernel_data_area s \<Longrightarrow> kernel_mappings (s\<lparr>p_state.heap := heap s(p \<mapsto> v)\<rparr>) = kernel_mappings s" apply (clarsimp simp: kernel_mappings_def) apply (subgoal_tac "hptable_eq (s\<lparr>heap := heap s(p \<mapsto> v)\<rparr>) = hptable_eq s ") apply (subgoal_tac "global_mappings (s\<lparr>heap := heap s(p \<mapsto> v)\<rparr>) = global_mappings s ") apply simp apply (frule kernel_data_global_map_update) apply blast apply (frule_tac v = v in kerenl_data_global_mappings) by blast lemma mmu_layout_upd': "\<lbrakk> mmu_layout s; p \<notin> kernel_data_area s \<rbrakk> \<Longrightarrow> mmu_layout (s\<lparr>p_state.heap := heap s(p \<mapsto> v)\<rparr>)" apply (clarsimp simp: mmu_layout_def) apply (subgoal_tac "p \<notin> kernel_data_area s") prefer 2 apply blast apply (simp add: kernel_data_upd kernel_data_area_upd kernel_mapping_upd) apply rule apply (clarsimp simp: user_mappings_def) apply (subst (asm) pt_table_lift_trace_upd ) apply (simp add: kernel_data_def kernel_data_area_def ptable_footprint_def roots_def) apply simp apply (frule_tac v = v and rt =rt and va = va in kernel_data_area_non_global, simp) apply (clarsimp simp: non_global_def) by (clarsimp simp: global_set_eq_def) lemma mmu_layout_upd: "\<lbrakk> mmu_layout s; p \<notin> kernel_phy_mem \<rbrakk> \<Longrightarrow> mmu_layout (s\<lparr>p_state.heap := heap s(p \<mapsto> v)\<rparr>)" apply (rule mmu_layout_upd', assumption) apply (auto simp: mmu_layout_def) done end
lpbp := (1,2,3); rpbp := (1,3,4); gpbp := Group([lpbp, rpbp]); lfbp := (1,2,3)(4,5,6); rfbp := (1,6,7)(4,3,8); gfbp := Group([lfbp,rfbp]); bs := Blocks(gfbp, [1..8]); hom := ActionHomomorphism(gfbp, bs, OnSets); im := Image(hom); iso := IsomorphismGroups(im, gfbp); k := Kernel(im);
\chapter{CompilerFacade} \label{a:compilerfacade} \OverviewLineNoTitle \begin{footnotesize}\begin{verbatim} import java.io.*; public class CompilerFacade { CompilerFacade(String input, String output) { try { // lex the code Lexer lexer = new Lexer(input); SymbolTable symboltable = new SymbolTable(); // build a parsertree and SymbolTable Parser parser = new Parser(lexer, symboltable); Tree parsetree = parser.parse(); // generate code CodeGenerator codegenerator = new CodeGenerator(symboltable); String asmSource = codegenerator.generate(parsetree); // write assembler code FileWriter fp = new FileWriter(output); PrintWriter oup = new PrintWriter(fp); oup.println(asmSource); oup.close(); } catch(FileNotFoundException e) { System.out.print("Inputfile not found!\n" + e); } catch(IOException e) { System.out.print("IO error!\n" + e);} catch(Exception e) { System.out.print("Internal error!\n" + e);} } } \end{verbatim}\end{footnotesize}
\xname{scope} \chapter{Analysis Scope Construction} \label{chap:scope} A pre-requisite to analyzing a Java program using any program analysis framework, including Petablox, is to compute the {\it analysis scope}: which parts of the program to analyze. Several scope construction algorithms (so-called call-graph algorithms) exist in the literature that differ in scalability (i.e., how large a program they can handle with the available resources) and precision (i.e., how much of the program they deem is reachable). Petablox implements several standard scope construction algorithms. Besides scalability and precision, an additional metric of these algorithms in Petablox that can be controlled by users is usability, which concerns aspects such as excluding certain code from being analyzed even if it is reachable, and modeling Java features such as reflection, dynamic class loading, and native methods. These features affect which code are reachable but, in general, they cannot be modeled soundly by any program analysis framework. The best a framework can do is provide stubs for commonly-used native methods in the standard JDK library (e.g., the \code{arraycopy} method of class \code{java.lang.System}), offer users a range of options on how to resolve reflection (e.g., an option might be running the program and observing how reflection is resolved), etc. Petablox computes the analysis scope of the given program either if property \code{petablox.build.scope} is set to {\tt true} or if some other task (e.g., a program analysis specified via property \code{petablox.run.analyses}) demands it. The following sections describe Petablox's analysis scope computation in detail. Section \ref{sec:scope-reuse} describes how to reuse the analysis scope computed in a previous run of Petablox for a given program. Section \ref{sec:scope-algos} describes Petablox's analysis scope construction algorithms. Finally, Section \ref{sec:scope-exclude} describes how users can exclude certain classes from the analysis scope. %Users can set the following properties to control scope computation: % %\begin{itemize} %\item \code{petablox.main.class} %\item \code{petablox.class.path} %\item \code{petablox.reuse.scope} %\item \code{petablox.methods.file} %\item \code{petablox.reflect.file} %\item \code{petablox.scope.kind} %\item \code{petablox.ch.kind} %\item \code{petablox.reflect.kind} %\item \code{petablox.std.scope.exclude} %\item \code{petablox.ext.scope.exclude} %\item \code{petablox.scope.exclude} %\end{itemize} % %The meaning of these properties is explained on demand in \section{Scope Reuse} \label{sec:scope-reuse} If property \code{petablox.reuse.scope} has value {\tt true} and both files specified by properties \code{petablox.methods.file} and \code{petablox.reflect.file} exist, then Petablox regards those files as specifying which methods to consider reachable and how to resolve reflection, respectively. The format of the file specified by property \code{petablox.methods.file} is a list of zero or more lines, where each line is of the form \code{mname:mdesc@cname} specifying the method's name {\tt mname}, the method's descriptor {\tt mdesc}, and the method's declaring class {\tt cname} (e.g., \code{main:([Ljava/lang/String;)[email protected]}). The format of the file specified by property \code{petablox.reflect.file} is of the form: \begin{framed} \begin{verbatim} # resolvedClsForNameSites ... # resolvedObjNewInstSites ... # resolvedConNewInstSites ... # resolvedAryNewInstSites ... \end{verbatim} \end{framed} where each of the above ``{\tt ...}'' is a list of zero or more lines, where each line is of the form \code{bci!mname:mdesc@cname->type1,type2,...typeN} meaning the call site at bytecode offset {\tt bci} in the method denoted by {\tt mname:mdesc@cname} may resolve to any of reference types {\tt type1}, {\tt type2}, ..., {\tt typeN}. The meaning of the above four sections is as follows. \begin{itemize} \item {\tt resolvedClsForNameSites} lists each call to static method {\tt forName(String)} defined in class \code{java.lang.Class}, along with a list of the types of the named classes. \item {\tt resolvedObjNewInstSites} lists each call to instance method {\tt newInstance()} defined in class \code{java.lang.Class}, along with a list of the types of the instantiated classes. \item {\tt resolvedConNewInstSites} lists each call to instance method {\tt newInstance(Object[])} defined in class \code{java.lang.reflect.Constructor}, along with a list of the types of the instantiated classes. \item {\tt resolvedAryNewInstSites} lists each call to instance method {\tt newInstance(Class,int)} defined in class \code{java.lang.reflect.Array}, along with a list of the types of the instantiated classes. \end{itemize} The default value of property \code{petablox.reuse.scope} is {\tt false}. The default value of properties \code{petablox.methods.file} and \code{petablox.reflect.file} is \code{[petablox.out.dir]/methods.txt} and \code{[petablox.out.dir]/reflect.txt}, respectively. Property \code{petablox.out.dir} denotes the output directory of Petablox; its default value is \code{[petablox.work.dir]/petablox_output/}. Property \code{petablox.work.dir} denotes the working directory during Petablox's execution; its default value is the current directory. \section{Scope Construction Algorithms} \label{sec:scope-algos} If property \code{petablox.reuse.scope} has value {\tt false} or the files specified by properties \code{petablox.methods.file} or \code{petablox.reflect.file} do not exist, then Petablox computes analysis scope using the algorithm specified by property \code{petablox.scope.kind} and then writes the list of methods deemed reachable and the reflection resolved by that algorithm to the files specified by properties \code{petablox.methods.file} and \code{petablox.reflect.file}, respectively. The possible values of property \code{petablox.scope.kind} are [\code{rta}$|$\code{cha}$|$\code{dynamic}] (the default value is {\tt rta}). The following subsections describe the scope construction algorithm that Petablox runs in each of these three cases. In each case, Petablox at least expects properties \code{petablox.main.class} and \code{petablox.class.path} to be set to the fully-qualified name of the program's main class (e.g., \code{com.example.Main}) and the program's application classpath, respectively. \subsection{Rapid Type Analysis} If property \code{petablox.scope.kind} has value {\tt rta}, then Petablox computes analysis scope statically using Rapid Type Analysis (RTA). RTA is an iterative fixed-point algorithm. It maintains a set of reachable methods $M$. The initial iteration starts by assuming that only the main method in the main class is reachable (Petablox also handles class initializer methods but we ignore them here for brevity; we also ignore the set of reachable classes maintained besides the set of reachable methods). All object allocation sites $H$ contained in methods in $M$ are deemed reachable (i.e., control-flow within method bodies is ignored). Whenever a dynamically-dispatching method call site (i.e., an invokevirtual or invokeinterface site) with receiver of static type $t$ is encountered in a method in $M$, only subtypes of $t$ whose objects are allocated at some site in $H$ are considered to determine the possible target methods, and each such target method is added to $M$. The process terminates when no more methods can be added. %RTA is a relatively inexpensive and precise algorithm in practice. %Its key shortcoming is that it makes no attempt to resolve %reflection, which is rampant in real-world Java programs, and can %therefore be unsound (i.e., underestimate the set of reachable %classes and methods). The next option attempts to overcome this %problem. \item The \code{rta_reflect} value instructs Petablox to %compute analysis scope statically using Rapid Type Analysis and, %moreover, to resolve a common reflection %pattern: \begin{quote} \begin{verbatim} String s = ...; Class c = %Class.forName(s); Object o = c.newInstance(); T t = (T) %o; \end{verbatim} \end{quote} This analysis is identical to RTA %except that it additionally inspects every cast statement in the %program, such as the last statement in the above snippet, and queries %the class hierarchy to find all concrete classes that subclass %\code{T} (if \code{T} is a class) or that implement \code{T} (if %\code{T} is an interface). Petablox allows users to control which %classes are included in the class hierarchy (see Section %\ref{sec:cha}). \subsection{Class Hierarchy Analysis} If property \code{petablox.scope.kind} has value {\tt cha}, then Petablox computes analysis scope statically using Class Hierarchy Analysis (CHA). The key difference between CHA and RTA is that for invokevirtual and invokeinterface sites with receiver of static type $t$, CHA considers {\it all} subtypes of $t$ in the class hierarchy to determine the possible target methods, whereas RTA restricts them to types of objects allocated in methods deemed reachable so far. As a result, CHA is highly imprecise in practice, and also expensive since it grossly overestimates the set of reachable classes and methods. Nevertheless, Petablox allows users to control which classes are included in the class hierarchy, and thereby control the precision and cost of CHA, by setting property \code{petablox.ch.kind}, whose possible values are [\code{static}$|$\code{dynamic}] (the default value is {\tt static}). Petablox first constructs the entire classpath of the given program by concatenating in order the following classpaths: \begin{enumerate} \item The boot classpath, specified by property \code{sun.boot.class.path}. \item The library extensions classpath, comprising all jar files in directory \code{[java.home]/lib/dir/}. \item The application classpath of the given program, specified by property \code{petablox.class.path}, which is empty by default. \end{enumerate} All classes in the entire classpath (resulting from items 1--3 above) are included in the class hierarchy with the following exceptions: \begin{itemize} \item Duplicate classes, i.e., classes with the same name occurring in more than one classpath element; in this case, all occurrences except the first are excluded. \item Any class whose name's prefix is specified in the value of property \code{petablox.scope.exclude} (see Section \ref{sec:scope-exclude}). \item If property \code{petablox.ch.kind} has value {\tt dynamic}, then Petablox runs the given program and observes the set of all classes the JVM loads; any class not in this set is excluded. \item If the superclass of a class C is missing or if an interface implemented/extended by a class/interface C is missing, where ``missing" means that it is either not in the classpath resulting from items 1--3 above or it is excluded by one of these rules, then C itself is excluded. Note that this rule is recursive, e.g., if C has superclass B which in turn has superclass A, and A is missing, then both B and C are excluded. \end{itemize} \subsection{Dynamic Analysis} If property \code{petablox.scope.kind} has value {\tt dynamic}, then Petablox computes analysis scope dynamically, by running the program and observing the classes that are loaded at run-time. The number of times the program is run and the command-line arguments to be supplied to the program in each run is specified by properties \code{petablox.run.ids} and \code{petablox.args.<id>} for each run ID {\tt <id>}. By default, the program is run only once, using run ID {\tt 0}, and without any command-line arguments. Only classes loaded in some run are regarded as reachable but {\it all} methods of each loaded class are regarded as reachable regardless of whether they were invoked in the run. The rationale behind this decision is to both reduce the run-time instrumentation overhead and increase the predictive power of program analyses performed using the computed analysis scope. \section{Scope Exclusion} \label{sec:scope-exclude} Petablox can be instructed to exclude certain classes in a given program from being analyzed. This functionality might be desirable, for instance, if the given program contains a larger framework (e.g., Hadoop or Android) which must not be analyzed. Petablox provides three properties for this purpose. The value of each of these properties is a comma-separated list of prefixes of names of classes. Petablox treats the body of each method defined in each such class as a no-op. \begin{itemize} \item Property \code{petablox.std.scope.exclude} is intended to specify classes to be excluded from the scope of {\it all} programs to be analyzed, e.g., classes in the JDK standard library. Its default value is the empty list. \item Property \code{petablox.ext.scope.exclude} is intended to specify classes to be excluded from the scope of specific programs to be analyzed. Its default value is the empty list. \item Property \code{petablox.scope.exclude} specifies the final list of classes to be excluded from scope. Its default value is \code{[petablox.std.scope.exclude],[petablox.ext.scope.exclude]}. \end{itemize} {\bf Note:} The value of each of the above properties is a list of {\it prefixes}, not {\it regular expressions}. A valid value is ``\code{java.,com.sun.}", but not ``\code{java.*,com.sun.*}". %\begin{tabular} %petablox.scope.kind,petablox.ch.dynamic & runs program? & \# reachable classes & \# reachable methods & running time \\ %dynamic,- & yes & 314 & 4,491 & 25s \\ %cha,true & yes & 427 & 1,532 & 28s \\ %rta,- & no & 849 & 4,836 & 9s \\ %rta_reflect,true & yes & 849 & 4,836 & 34s \\ %rta_reflect,false & no & 9,871 & 58,726 & 7m6s \\ %cha,false & no & 14,121 & 74,613 & 4m11s %\end{tabular}
using 2022_01_comext using Test @testset "2022_01_comext.jl" begin # Write your tests here. end
## ----knitr-setup, echo = FALSE------------------------------------------- knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE) ## ----load-packages, message = FALSE, warning = FALSE--------------------- library(plyr) library(dplyr) library(magrittr) library(lubridate) library(ggplot2) library(devtools) load_all() ## ----update-load-raw-data------------------------------------------------ get_current_sos() import_country_codes() data(sos_raw) sosid <- paste0("SOS", 1:nrow(sos_raw)) ## ----clean-data---------------------------------------------------------- name <- clean_name(sos_raw) status <- clean_status(sos_raw) date_created <- clean_date_created(sos_raw) date_terminated <- clean_date_terminated(sos_raw) countries <- clean_countries(sos_raw) ## ----survclass-calculations---------------------------------------------- humans <- clean_humans(sos_raw) animals <- clean_animals(sos_raw) plants <- clean_plants(sos_raw) syndromic <- clean_syndromic(sos_raw) sos_surveillance_class <- data.frame(sosid, humans, animals, plants, syndromic) sos_surveillance_class %<>% # select(-sosid) %>% mutate(humans = factor(humans, levels = c("yes", "no", "nf"), labels = c("Yes", "No", "Not found"), ordered = TRUE), animals = factor(animals, levels = c("yes", "no", "nf"), labels = c("Yes", "No", "Not found"), ordered = TRUE), plants = factor(plants, levels = c("yes", "no", "nf"), labels = c("Yes", "No", "Not found"), ordered = TRUE), # I'm removing "blank" values from the Syndromic column, because # I don't think the difference is useful for this table. syndromic = revalue(syndromic, c("blank" = "nf")), syndromic = factor(syndromic, levels = c("yes", "no", "nf"), labels = c("Yes", "No", "Not found"), ordered = TRUE)) ## ----entity-calculations------------------------------------------------- entity_df <- clean_entity_type(sos_raw, return_type = "data.frame") entity_factor <- clean_entity_type(sos_raw, return_type = "factor") sos_entity <- data.frame(sosid, entity_df, entity_factor) ## ----survclass-table----------------------------------------------------- knitr::kable(summary(sos_surveillance_class[2:5]), col.names = c("Humans", "Animals", "Plants", "Syndromic"), caption = "Table 1. Classes of biosurveillance conducted. Note: for \"Syndromic\" variable, \"Blank\" and \"Not Found\" entries were combined.") ## ----table-summary------------------------------------------------------- library(reshape2) ggsurvclass <- sos_surveillance_class %>% melt(id.vars = "sosid") %>% mutate(variable = factor(variable, labels = c("Humans", "Animals", "Plants", "Syndromic Surveillance")), value = factor(value, levels = c("Yes", "No", "Not found"), ordered = TRUE)) %>% ggplot() ggsurvclass + geom_bar(aes(x = value, stat = "bin"), position = "dodge") + facet_grid(. ~ variable) + theme_bw() + labs(x = NULL, y = "Number of Systems", title = "Types of Biosurveillance Conducted") ## ----entity-plot--------------------------------------------------------- ggentity <- sos_entity %>% select(sosid, entity_factor) %>% ggplot() ggentity + geom_bar(aes(x = entity_factor, stat = "bin"), position = "dodge") + theme_bw() + labs(x = "Classes of entity", y = "Number of Systems", title = "Types of entities conducting biosurviellance") ## ----time-series--------------------------------------------------------- sos_dates <- data.frame(date_created, date_terminated) sos_dates$active_interval <- new_interval(sos_dates$date_created, sos_dates$date_terminated) sum_active_systems_for_year <- function(year, intervals) { sum(year %within% intervals, na.rm = TRUE) } # Create a data frame for a time-series plot time_series <- data.frame(year = parse_date_time(1900:2015, orders = "y")) time_series$number_active <- sapply(time_series$year, sum_active_systems_for_year, intervals = sos_dates$active_interval) # Create a data frame for the creation-termination histogram. date_hist <- data.frame(sosid, select(sos_dates, date_created, date_terminated)) %>% melt(id.vars = "sosid") %>% mutate(year = year(value)) %>% filter(year != 2015, year >= 1950) %>% group_by(year, variable) %>% summarize(count = n()) %>% dcast(year ~ variable) # We have to append rows for years not in the data frame, otherwise our over-under line will do weird things. years_not_in_df <- seq(1950, 2014)[!seq(1950, 2014) %in% date_hist$year] date_hist <- rbind(date_hist, data.frame(year = years_not_in_df, date_created = NA, date_terminated = NA)) date_hist[is.na(date_hist)] <- 0 max_creation <- date_hist %>% filter(date_created == max(date_created)) %>% select(year) max_termination <- date_hist %>% filter(date_terminated == max(date_terminated)) %>% select(year) most_systems_year <- time_series %>% filter(number_active == max(number_active)) %>% select(year) %>% mutate(year = year(year)) # Convert the "year" variable to a "year" from a full "date." ## ----date_hist-plot------------------------------------------------------ ggplot(data = date_hist, aes(x = year)) + geom_bar(aes(y = date_created), stat = "identity", fill = "#F8766D") + geom_bar(aes(y = -date_terminated), stat = "identity", fill = "#00BFC4") + geom_line(aes(y = date_created - date_terminated), size = 0.5) + theme_bw() + labs(x = "Year", y = "Number of Surveillance Systems", title = "Number of Surveillance Systems Created and Terminated") ## ----time-series-plots--------------------------------------------------- ggplot(time_series, aes(x = year, y = number_active)) + geom_line() + theme_bw() + labs(x = "Year", y = "Count of Active Systems", title = "Number of Active Surveillance Systems over Time") ## ----lifespan-plot------------------------------------------------------- active_period <- as.period(sos_dates$active_interval, unit = "years") active_duration <- as.duration(sos_dates$active_interval) active_years <- year(active_period) sos_dates %<>% mutate(years_active = year(as.period(active_interval, unit = "years"))) xlabs <- c(seq(0, 40, by = 10), ">50") ggplot(sos_dates, aes(x = pmin(sos_dates$years_active, 50), fill = current)) + layer(geom = "bar", stat = "bin", breaks = seq(0, 50)) + scale_x_continuous(labels = c(seq(0, 40, by = 10), ">50")) + labs(x = "Years Active", y = "Count", title = "Lifespan of Biosurveillance Systems") + theme_bw() ## ----time-series-by-entity-type------------------------------------------ sos_dates$entity_type <- clean_entity_type(sos_raw, return_type = "factor") time_series_entity <- expand.grid(year = time_series$year, entity_type = levels(sos_dates$entity_type)) time_series_entity %<>% group_by(entity_type, year) %>% mutate(number_active = sum_active_systems_for_year(year, sos_dates[sos_dates$entity_type == entity_type, "active_interval"])) %>% ungroup() %>% filter(year(year) >= 1990) ggplot(time_series_entity, aes(x = year, y = number_active, fill = entity_type, color = entity_type, order = desc(entity_type))) + geom_line() + theme_bw() + labs(x = "Year", y = "Count of Active Systems", title = "Active Surveillance Systems by Entity Class") ## ----countries----------------------------------------------------------- max_systems_in_country <- countries %>% summarise_each(funs = funs(sum)) %>% max() ## ----country-population-------------------------------------------------- library(curl) by_country <- countries %>% summarise_each(funs(n = sum(as.numeric(.)))) %>% t() %>% # Transpose it so that countries are rows. as.data.frame() %>% mutate(iso3 = rownames(.)) %>% arrange(desc(V1)) names(by_country)[1] <- "n_systems" pop_csv <- curl_download(url = "https://raw.githubusercontent.com/datasets/population/master/data/population.csv", destfile = tempfile()) population <- read.csv(pop_csv, stringsAsFactors = FALSE) population %<>% filter(Year == 2014) %>% select(iso3 = Country.Code, population = Value) by_country %<>% left_join(population) %>% mutate(systems_per_capita = n_systems / population) ## ----maps---------------------------------------------------------------- library(rworldmap) sos_map <- joinCountryData2Map(dF = by_country, joinCode = "ISO3", nameJoinColumn = "iso3", verbose = FALSE) sos_map$log_n_systems <- log(sos_map$n_systems) spplot(sos_map, zcol = "log_n_systems", main = "Count of Surveillance Systems") sos_map$log_systems_per_capita <- log(sos_map$systems_per_capita) spplot(sos_map, zcol = "log_systems_per_capita", main = "Surveillance Systems Per Capita")
#SOl Courtney Columbia U Department of Astronomy and Astrophysics NYC 2016 #[email protected] #--[DESCRIPTION]---------------------------------------------------------# ''' Date: May 2016 Handeler for twitter text parsing ''' #--[IMPORTS]--------------------------------------------------------------# from nltk.tokenize import word_tokenize import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt plt.ioff() from time import gmtime, strftime, sleep from astropy.table import Table from collections import Counter import numpy as np import nltk, time, os,sys,json,socket from datetime import datetime import csv #--[PROGRAM-OPTIONS]------------------------------------------------------# nltk.data.path.append('/root/SHARED/nltk_data/') hostname = socket.gethostname() if hostname == 'sol-Linux': OUT_PUT_PATH = '/home/sol/CLUSTER_RAID/Tweet_Output/Clean_Words/' All_Words_PATH = '/home/sol/CLUSTER_RAID/Tweet_Code/dictionary.txt' Table_PATH = '/home/sol/CLUSTER_RAID/Tweet_Output/' else: OUT_PUT_PATH = '/root/SHARED/Tweet_Output/Clean_Words/' All_Words_PATH = '/root/SHARED/Tweet_Code/dictionary.txt' Table_PATH = '/root/SHARED/Tweet_Output/' BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) def ct(text, colour=WHITE): seq = "\x1b[1;%dm" % (30+colour) + text + "\x1b[0m" return seq def list_files(path): # returns a list of names (with extension, without full path) of all files # in folder path files = [] for name in os.listdir(path): if os.path.isfile(os.path.join(path, name)): files.append(name) return files Names = {'PRP$':'pronoun, possessive','VBG':'verb, present participle or gerund', 'VBD':'verb, past tense','VBN':'verb, past participle','VBP':'verb, present tense not 3rd person singular', 'WDT':'determiner, WH','JJ':'adjective or numeral, ordinal','WP': 'pronoun, WH', 'VBZ':'verb, present tense 3rd person singular','DT':'determiner','RP':'particle', 'NN':'noun, common, singular or mass','TO':'"to" as preposition or infinitive marker', 'PRP':'pronoun, personal','RB':'adverb','NNS':'noun, common plural','NNP':'noun, proper singular', 'VB':'verb, base form','WRB':'adverb, WH', 'CC':'conjunction, coordinating', 'RBR':'adverb, comparative', 'CD':'cardinal numeral','-NONE-':'No matching tags found','EX':'existential, there there', 'IN':'conjunction or subordinating preposition','WP$':'pronoun, possessive WH', 'MD':'modal auxiliary', 'JJS':'adjective, superlative', 'JJR':'adjective, comparative', 'PDT': 'pre-determiner','RBS':'adverb, superlative', 'FW': 'foreign word', 'NNPS': 'noun, proper plural', 'UH': 'interjection'} Color_Keys = {'NN':GREEN, 'NNS':GREEN, 'NNP':GREEN, 'NNPS':GREEN, 'MD':YELLOW, 'JJR': YELLOW, 'JJS': YELLOW, 'JJ': YELLOW, 'DT': YELLOW, 'VBG':BLUE,'VBD':BLUE,'VBN':BLUE,'VBP':BLUE,'VBZ':BLUE,'VB':BLUE, 'RBS': MAGENTA,'RBR': MAGENTA,'RB': MAGENTA,'WRB': MAGENTA, 'PRP$':CYAN, 'PRP':CYAN, 'WP':CYAN, 'WP$':CYAN, "IN": RED, } names = [ 'time', 'weekday','PRP$', 'VBG', 'VBD', 'VBN', 'VBP', 'WDT', 'JJ', 'WP', 'VBZ', 'DT', 'RP', 'NN', 'TO', 'PRP', 'RB', 'NNS', 'NNP', 'VB', 'WRB', 'CC', 'RBR', 'CD', '-NONE-', 'EX', 'IN', 'WP$', 'MD', 'JJS', 'JJR', 'PDT', 'RBS' , 'FW', 'UH'] dtypes = [ 'float','S10','int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int', 'int'] Record_book_keys = ['PRP$', 'VBG', 'VBD', 'VBN', 'VBP', 'WDT', 'JJ', 'WP', 'VBZ', 'DT', 'RP', 'NN', 'TO', 'PRP', 'RB', 'NNS', 'NNP', 'VB', 'WRB', 'CC', 'RBR', 'CD', '-NONE-', 'EX', 'IN', 'WP$', 'MD', 'JJS', 'JJR', 'PDT', 'RBS' , 'FW', 'UH'] plt_clrs = ['indigo','gold','hotpink','firebrick','indianred','sage','yellow','mistyrose', 'darkolivegreen','olive','darkseagreen','pink','tomato','lightcoral','orangered','navajowhite','lime','palegreen', 'darkslategrey','greenyellow','burlywood','seashell','fuchsia','papayawhip','chartreuse','dimgray', 'black','peachpuff','springgreen','aquamarine','orange','lightsalmon','darkslategray','brown', 'indigo','gold','hotpink','firebrick','indianred','sage','yellow','mistyrose'] try: os.system('clear') fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) last_total_words = 0 total_words = 0 while True: Date = datetime.now().strftime("%a_%b_%d_%Y_%H_%M") date = Date count_all = Counter() words = [] print ct("-" * 70, WHITE) print ct(datetime.now().strftime("%a %b %d, %Y %H:%M"), BLUE) + "\t -- \tlast n_words: " + ct(str(last_total_words), RED) while date == Date: for word_set in list_files(OUT_PUT_PATH): with open(OUT_PUT_PATH+word_set,'r') as f: page = f.read() with open(OUT_PUT_PATH+word_set,'w') as f: pass #os.system('cat ~/SHARED/wordsloded.txt') #os.system('cat ~/SHARED/cleaning.txt') new_words = [tweet.replace('\n','').replace('[','').replace(']','').replace('"','').replace(' ','') for tweet in page.split(',') ] words += [i for i in new_words if i != ''] #print word_set, 'has ', len(words) #sleep(3) #print words #os.system('cat ~/SHARED/counting.txt') sys.stdout.write("\r" + ct(datetime.now().strftime("%H:%M:%S"), BLUE) + " :\t" + ct(str(len(words)), GREEN)) date = datetime.now().strftime("%a_%b_%d_%Y_%H_%M") last_total_words = total_words total_words = len(words) sys.stdout.write("\n") sys.stdout.flush() print ct("Tagging...", BLUE) tagged = nltk.pos_tag(words) print ct("Counting...", BLUE) count_all.update(tagged) os.system('clear') print "\t", ct("Number", CYAN), "\t", ct("Word", WHITE), " " * 11, ct("Type", WHITE) print ct("-" * 70, WHITE) for i in Counter(tagged).most_common(50): _space = 15 - len(i[0][0]) if i[0][1] in Color_Keys.keys(): color = Color_Keys[i[0][1]] print "\t", ct(str(i[1]), CYAN),'\t',ct(i[0][0], WHITE),' ' * _space,ct(Names[i[0][1]], color) else: print "\t", ct(str(i[1]), RED),'\t',ct(i[0][0], RED),' ' * _space,ct(Names[i[0][1]], RED) sleep(0.01 + (np.random.ranf()/1e1)) wrd_type_keys = [] plot_data = [] for (w, k), n in count_all.most_common(): if k in wrd_type_keys: continue else: wrd_type_keys.append(k) for wrd_typ in wrd_type_keys: num = 0 for (w, k), n in count_all.most_common(): if k == wrd_typ: num += n plot_data.append((wrd_typ, num)) # print plot_data for wrd_typ, num in plot_data: _num = round(np.log10(num), 1) # print wrd_typ, _num ax.bar(wrd_typ, _num, align='center') ax.set_title("Word Type Frequency\ntotal words:" + str(total_words) + "\n" + datetime.now().strftime("%a %b %d, %Y %H:%M")) ax.axes.tick_params(labelrotation=90) fig.savefig(Table_PATH + "plot") ax.clear() # plt.show() except KeyboardInterrupt: os.system('clear') sys.exit(0)
(********************************************************************* Cores in a bicategory The core of a category is the subgroupoid consisting of only the isomorphisms. This construction can be specified in arbitrary bicategories. The definition we use here, is inspired by https://ncatlab.org/nlab/show/core+in+a+2-category Contents 1. Groupoidal objects 2. Pseudofunctor from groupoids 3. Having cores *********************************************************************) Require Import UniMath.Foundations.All. Require Import UniMath.MoreFoundations.All. Require Import UniMath.CategoryTheory.Core.Categories. Require Import UniMath.CategoryTheory.Core.Functors. Require Import UniMath.Bicategories.Core.Bicat. Import Bicat.Notations. Require Import UniMath.Bicategories.Core.Invertible_2cells. Require Import UniMath.Bicategories.Core.Univalence. Require Import UniMath.Bicategories.Core.BicategoryLaws. Require Import UniMath.Bicategories.Core.Unitors. Require Import UniMath.Bicategories.Morphisms.Eso. Require Import UniMath.Bicategories.Morphisms.FullyFaithful. Require Import UniMath.Bicategories.DisplayedBicats.Examples.FullSub. Require Import UniMath.Bicategories.DisplayedBicats.Examples.BicatOfInvertibles. Require Import UniMath.Bicategories.PseudoFunctors.Display.PseudoFunctorBicat. Require Import UniMath.Bicategories.PseudoFunctors.PseudoFunctor. Import PseudoFunctor.Notations. Require Import UniMath.Bicategories.PseudoFunctors.UniversalArrow. Local Open Scope cat. (** 1. Groupoidal objects *) Definition groupoidal {B : bicat} (x : B) : UU := ∏ (w : B) (f g : w --> x) (α : f ==> g), is_invertible_2cell α. Definition isaprop_groupoidal {B : bicat} (x : B) : isaprop (groupoidal x). Proof. do 4 (use impred ; intro). apply isaprop_is_invertible_2cell. Qed. Definition bicat_of_groupoidal (B : bicat) : bicat := fullsubbicat B groupoidal. Definition is_univalent_2_1_bicat_of_groupoidal {B : bicat} (HB_2_1 : is_univalent_2_1 B) : is_univalent_2_1 (bicat_of_groupoidal B). Proof. apply is_univalent_2_1_fullsubbicat. exact HB_2_1. Defined. Definition is_univalent_2_0_bicat_of_groupoidal {B : bicat} (HB_2 : is_univalent_2 B) : is_univalent_2_0 (bicat_of_groupoidal B). Proof. apply is_univalent_2_0_fullsubbicat. - exact HB_2. - exact isaprop_groupoidal. Defined. Definition is_univalent_2_bicat_of_groupoidal {B : bicat} (HB_2 : is_univalent_2 B) : is_univalent_2 (bicat_of_groupoidal B). Proof. apply is_univalent_2_fullsubbicat. - exact HB_2. - exact isaprop_groupoidal. Defined. (** 2. Pseudofunctor from groupoids *) Definition groupoidal_to_inv2cells_data (B : bicat) : psfunctor_data (bicat_of_groupoidal B) (bicat_of_inv2cells B). Proof. use make_psfunctor_data. - exact (λ x, pr1 x ,, tt). - exact (λ _ _ f, f). - simple refine (λ x y f g α, pr1 α ,, _). exact (pr2 y (pr1 x) (pr1 f) (pr1 g) (pr1 α)). - refine (λ x, id2 _ ,, _) ; cbn. is_iso. - refine (λ _ _ _ f g, id2 _ ,, _) ; cbn. is_iso. Defined. Definition groupoidal_to_inv2cells_laws (B : bicat) : psfunctor_laws (groupoidal_to_inv2cells_data B). Proof. repeat split ; intro ; intros ; (use subtypePath ; [ intro ; apply isaprop_is_invertible_2cell | ]) ; cbn in *. - apply idpath. - apply idpath. - rewrite id2_rwhisker. rewrite !id2_left. apply idpath. - rewrite lwhisker_id2. rewrite !id2_left. apply idpath. - rewrite id2_rwhisker, lwhisker_id2. rewrite !id2_left, !id2_right. apply idpath. - rewrite id2_left, id2_right. apply idpath. - rewrite id2_left, id2_right. apply idpath. Qed. Definition groupoidal_to_inv2cells (B : bicat) : psfunctor (bicat_of_groupoidal B) (bicat_of_inv2cells B). Proof. use make_psfunctor. - exact (groupoidal_to_inv2cells_data B). - exact (groupoidal_to_inv2cells_laws B). - split ; intros ; apply is_invertible_2cell_bicat_of_inv2cells. Defined. (** 3. Having cores *) Definition has_cores (B : bicat) : UU := ∑ (R : right_universal_arrow (groupoidal_to_inv2cells B)), ∏ (x : B), let ε := pr1 (pr12 R (x ,, tt)) in is_eso ε × pseudomonic_1cell ε.
### Plotting workbook Plotting workbook to accompany the paper _Carbon Capture and Storage Energy Systems vs. Dispatchable Renewables for Climate Mitigation: A Bio-physical Comparison_ by Sgouridis, Dale, Csala, Chiesa & Bardi ```python import matplotlib.pyplot as plt import matplotlib as mpl import matplotlib.font_manager as font_manager plt.style.use('seaborn-darkgrid') %matplotlib inline prop = font_manager.FontProperties('Segoe UI') from sympy import * init_printing() ``` ### Eq. 6 Define EROI-CCS function (Eq. 6 in the paper) ```python var('EROI_CCS EROI f_op'); ``` ```python eq6=Eq(EROI_CCS,EROI/(1+f_op*EROI)) eq6 ``` ### Eq. 2 Define dispatchable EROI for renewables with storage (Eq. 2 in the paper) ```python phi = Symbol('phi') eta = Symbol('eta') var('EROI_disp EROI ESOI phi eta'); ``` ```python eq2=Eq(EROI_disp,((1-phi)+(eta*phi))/((1/EROI)+(eta*phi/ESOI))) eq2 ``` ### Figure 3 & Table 3 Now we generate the contour lines for _Figure 3_, using the examples from _Table 3_. We have two tyes of renewable energy plants, _PV_ and _Wind_, each with two cases of EROI, taken from the lower and upper boundaries encountered in studies. We have assumed a storage technology mixes taken from _Table 1_ of [Barnhart et al 2013](http://pubs.rsc.org/en/content/articlehtml/2013/ee/c3ee41973h). Here we have the ESOI values reported for 7 energy storage storage technologies, 5 types of electrochemical storage (Batteries), Compressed air (CAES) and pumped hydro (PHS). We have considered diffrent energy storage technology mixes for our PV and Wind examples. For PV, we have taken an equal mix of all 5 electrochemical storage technologies, without CAES or PHS (resulting in the pv share vector of `[0.2,0.2,0.2,0.2,0.2,0,0]`). For Wind, we have considered 50% battery storage (as an equal 10% from each technology), and 25-25% of CAES and PHS, resulting in the wind share vector of `[0.1,0.1,0.1,0.1,0.1,0.25,0.25]`). ```python etas=[0.90,0.75,0.90,0.75,0.60,0.70,0.85] #from (Barnhart et al 2013) S=[32,20,5,10,9,797,704] #from (Barnhart et al 2013) shr0=[0.2,0.2,0.2,0.2,0.2,0,0] #assumed shares for considered PV exmaples in this paper shr1=[0.1,0.1,0.1,0.1,0.1,0.25,0.25] #assumed shares for considered Wind exmaples in this paper eta_pv=sum([etas[i]*shr0[i] for i in range(len(etas))]) #resulting composite eta for pv eta_wind=sum([etas[i]*shr1[i] for i in range(len(etas))]) #resulting composite eta for wind S_pv=sum([S[i]*shr0[i] for i in range(len(etas))]) #resulting composite S for pv S_wind=sum([S[i]*shr1[i] for i in range(len(etas))]) #resulting composite S for wind print 'Composite eta for pv',eta_pv print 'Composite eta for wind',eta_wind print 'Composite ESOI for pv',S_pv print 'Composite ESOI for wind',S_wind ``` Composite eta for pv 0.78 Composite eta for wind 0.7775 Composite ESOI for pv 15.2 Composite ESOI for wind 382.85 ### Construct test cases: _Renewables_ ```python #define pretty output formatter for sympy equation def format_eq(eq): return [solve(eq[i])[0] for i in range(len(eq))] #return [float((repr(eq[i])[2:]).split(',')[1].strip()[:-1]) for i in range(len(eq))] ``` ```python eroi_pv=[10,40] #EROEIe for case [F, G] in Table 3 of the paper, PV plant eroi_disp_pv=format_eq([eq2.subs([[EROI,i],[phi,0.4],[eta,eta_pv],[ESOI,S_pv]]) for i in eroi_pv]) eroi_wind=[10,33] #EROEIe for case [H, I] in Table 3 of the paper, Wind plant eroi_disp_wind=format_eq([eq2.subs([[EROI,i],[phi,0.4],[eta,eta_wind],[ESOI,S_wind]]) for i in eroi_wind]) ``` ```python print 'PV [F,G]' eroi_disp_pv ``` ```python print 'Wind [H,I]' eroi_disp_wind ``` ### Construct test cases: _Fossils_ ```python eroi_gas=[9.6, 38.5] #EROEIe for case [A, B] in Table 3 of the paper, gas plant eroi_ccs_gas=format_eq([eq6.subs([[EROI,i],[f_op,0.147]]) for i in eroi_gas]) eroi_coal=[8.9, 22.6] #EROEIe for case [D, E] in Table 3 of the paper, coal plant eroi_ccs_coal=format_eq([eq6.subs([[EROI,i],[f_op,0.219]]) for i in eroi_coal]) ``` ```python print 'gas [A,B]' eroi_ccs_gas ``` ```python print 'coal [D,E]' eroi_ccs_coal ``` ### Figure 3 Produce contour lines for multiple $f_{op}$ and $\phi$ levels and place the example plants on the contours. Calculate the $EROI_{CCS}$ and $EROI_{disp}$, respectively, for multiple base $EROI$ values. Likewise we obtain a plot for comparison between dispatchable (i.e. with storage) EROI for renewables and CCS EROI for fossil fuel based power plants. ```python plt.figure(figsize=(5,4)) n=51 erois=range(1,n) ### Renewables contours colors=['#addd8e', '#78c679', '#31a354', '#006837'] plt.plot(0,0,lw=0,label='${\phi}$ (%)') #plot EROI_disp contour lines for various EROI values and phi levels #for eta and S assume a fully battery-based storage (worst case), i.e. the eta_pv and S_pv pv=1.0 #(pv share in hypothetical renewable technologies) phis=[0.1,0.2,0.3,0.4] #assumed levels for phi for r in range(len(phis)): phir=phis[r] eroi_disps=format_eq([eq2.subs([[EROI,i],[phi,phir],[eta,pv*eta_pv+(1-pv)*eta_wind],[ESOI,pv*S_pv+(1-pv)*S_wind]]) for i in erois]) plt.plot(erois,eroi_disps,c=colors[r],label=int(phir*100)) plt.xlabel('EROI') a=plt.gca() plt.text(-0.07, 0.65, 'EROI$_{disp}$', horizontalalignment='right', verticalalignment='bottom',rotation=90,#fontproperties=prop, size=11,color='#006837',transform=plt.gca().transAxes) plt.text(-0.07, 0.27, 'EROI$_{CCS}$', horizontalalignment='right', verticalalignment='bottom',rotation=90,#fontproperties=prop, size=11,color='#bd0036',transform=plt.gca().transAxes) ### Fossils contours colors=['#fed976', '#feb24c', '#f03b20', '#bd0036'] plt.plot(0,0,lw=0,label='$f_{op}$ (%)') fops=[0.05,0.1,0.15,0.2] #assumed levels for fop for r in range(len(fops)): fopr=fops[r] eroi_ccss=format_eq([eq6.subs([[EROI,i],[f_op,fopr]]) for i in erois]) plt.plot(erois,eroi_ccss,c=colors[r],label=int(fopr*100)) ### Table 3 cases cf="#f03b20" cr="#31a354" cg="#aaaaaa" s=30 #marker size plt.scatter(eroi_gas,eroi_ccs_gas,s,color=cf,marker='o') plt.scatter(eroi_coal,eroi_ccs_coal,s,color=cf,marker='^') plt.scatter(eroi_pv,eroi_disp_pv,s,color=cr,marker='d') plt.scatter(eroi_wind,eroi_disp_wind,s,color=cr,marker='s') plt.xlim(0,50) plt.ylim(0,40) #[F, G] plt.text(eroi_pv[1], eroi_disp_pv[1]-1.5, 'PV +\nBattery', horizontalalignment='center', verticalalignment='top', size=9,color=cr) #[H, I] plt.text(eroi_wind[1], eroi_disp_wind[1]+1.5, 'Wind + Battery +\n PHS + CAES', horizontalalignment='center', verticalalignment='bottom', size=9,color=cr) #[A, B] plt.text(eroi_gas[1], eroi_ccs_gas[1]-2.2, 'Gas + CCS', horizontalalignment='center', verticalalignment='top', size=9,color=cf) #[D, E] plt.text(eroi_coal[1], eroi_ccs_coal[1]-1, 'Coal + CCS', horizontalalignment='center', verticalalignment='top', size=9,color=cf) #Annotate cases ap=0.7 plt.text(eroi_coal[0]+2, eroi_ccs_coal[0]-0.5, 'D', horizontalalignment='center', verticalalignment='top', size=10,color=cf, bbox=dict(facecolor='white', edgecolor=cf, alpha=ap, boxstyle='round')) plt.text(eroi_gas[0]+2, eroi_ccs_gas[0]+2, 'B', horizontalalignment='center', verticalalignment='top', size=10,color=cf, bbox=dict(facecolor='white', edgecolor=cf, alpha=ap, boxstyle='round')) plt.text(eroi_coal[1], eroi_ccs_coal[1]+3.3, 'E', horizontalalignment='center', verticalalignment='top', size=10,color=cf, bbox=dict(facecolor='white', edgecolor=cf, alpha=ap, boxstyle='round')) plt.text(eroi_gas[1], eroi_ccs_gas[1]+3.3, 'A', horizontalalignment='center', verticalalignment='top', size=10,color=cf, bbox=dict(facecolor='white', edgecolor=cf, alpha=ap, boxstyle='round')) plt.text(eroi_pv[1], eroi_disp_pv[1]+3.3, 'G', horizontalalignment='center', verticalalignment='top', size=10,color=cr, bbox=dict(facecolor='white', edgecolor=cr, alpha=ap, boxstyle='round')) plt.text(eroi_wind[0]+2.6, eroi_disp_wind[0], 'F', horizontalalignment='center', verticalalignment='top', size=10,color=cr, bbox=dict(facecolor='white', edgecolor=cr, alpha=ap, boxstyle='round')) plt.text(eroi_pv[0], eroi_disp_pv[0]+5.3, 'H', horizontalalignment='center', verticalalignment='top', size=10,color=cr, bbox=dict(facecolor='white', edgecolor=cr, alpha=ap, boxstyle='round')) plt.text(eroi_wind[1], eroi_disp_wind[1]-2, 'I', horizontalalignment='center', verticalalignment='top', size=10,color=cr, bbox=dict(facecolor='white', edgecolor=cr, alpha=ap, boxstyle='round')) plt.legend(framealpha=0,loc=2,fontsize=9) plt.savefig('fig3.png',bbox_inches = 'tight', facecolor='w', pad_inches = 0.1, dpi=200) plt.show() ``` ### Figure 4 For this figure we are considering various levels of powerplant efficiency, and its effect on the EROI , under various capture ratio assumptions. This is described in Eq. 1 and Eq. 4 in the paper. Define parameters Electricity penalty (b) curve from Sanpasternich (2009) Figure 8 [kWh/kg CO2] ```python #CCS_op #operating CCS penalty #CR #capture ratio var('CCS_op CR'); CCS_op_eq=Eq(CCS_op,25.957**6 - 85.031*CR**5 + \ 114.5*CR**4 - 80.385*CR**3 + \ 31.47*CR**2 - 6.7725*CR + 1.1137) CCS_op_eq ``` Operational cost of coal fuel cycle over plant lifetime output [kWh] ```python #PP_op_L #operational cost of coal fuel cycle over plant lifetime #PP_op #operational cost of coal fuel cycle #PP_CF #powerplant capacity factor #PP_L #powerplant lifetime #eta #powerplant efficiency var('PP_op_L PP_op PP_CF eta PP_L'); PP_op_L_eq=Eq(PP_op_L,8760*PP_L*PP_CF*PP_op/eta) PP_op_L_eq ``` Carbon intensity of electricity [kg CO2/kWh] ```python #C_CO2 #carbon dioxide content of coal [kg/MJ] #Elec_CO2 #carbon intensity of electricity [kg CO2/kWh] var('Elec_CO2 C_CO2'); Elec_CO2_eq=Eq(Elec_CO2,C_CO2*3.6/eta) Elec_CO2_eq ``` Energy penalty of CCS [dmnl] ```python #b #energy penalty of CCS var('b'); b_eq=Eq(b,CCS_op*Elec_CO2*CR) b_eq ``` Emissions ```python #E #emissions var('E'); E_eq=Eq(E,CCS_op*(1-CR)) E_eq ``` Energy cost of constructing CCS plant ```python #CCS_cons_energy #energy cost of constructing CCS plant #f_cap #energy cost share of constructing CCS plant #PP_cons_energy #energy cost of power plant construction [MJ/MW], does not include energy embodied in materials var('CCS_cons_energy PP_cons_energy f_cap'); CCS_cons_energy_eq=Eq(CCS_cons_energy,f_cap*PP_cons_energy) CCS_cons_energy_eq ``` EROIs Energy cost of constructing CCS plant ```python #EROI_1 #EROI where CCS construction energy is a ratio of power plant construction energy [MJ_e/MW/(MJ_p/MW) = dmnl] #CCS_L #CCS plant lifetime var('EROI_1 CCS_L'); EROI_1_eq=Eq(EROI_1,8760*PP_L*PP_CF*(1-b)*3.6/\ (PP_cons_energy + PP_op_L + CCS_cons_energy*PP_L/CCS_L)) EROI_1_eq ``` ```python #EROI_1_adj #makes adjustment for electrical output [MJ_p/MJ_p = dmnl] var('EROI_1_adj'); EROI_1_adj_eq=Eq(EROI_1_adj,EROI_1/0.3) EROI_1_adj_eq ``` Energy cost of operating CCS plant ```python #EROI_2 #where CCS construction energy is a ratio of CCS operation energy [MJ_e/MJ_p = dmnl] var('EROI_2'); EROI_2_eq=Eq(EROI_2,8760*PP_L*PP_CF*(1-b)/\ (PP_cons_energy + PP_op_L + f_op*CCS_op + CCS_cons_energy*PP_L/CCS_L)) EROI_2_eq ``` ```python #EROI_2_adj #makes adjustment for electrical output [MJ_p/MJ_p = dmnl] var('EROI_2_adj'); EROI_2_adj_eq=Eq(EROI_2_adj,EROI_1/0.3) EROI_2_adj_eq ``` Translation to quantities as per defined in the paper ### Eq. 5 ```python #R #E_op/E_cap var('R'); eq5=Eq(EROI_CCS,(R+1)*EROI/(R+1+f_cap+f_op*(R+1)*EROI)) eq5 ``` ```python var('E_op E_cap'); R_eq=Eq(R,E_op/E_cap) R_eq ``` ### Eq. 4 ```python var('E_CCS E_out E_red'); eq4=Eq(EROI_CCS,E_out/((1+f_cap)*E_cap+E_op+f_op*E_out)) eq4 ``` ```python f_op_eq=Eq(f_op,E_red/E_out) f_op_eq ``` ```python f_cap_eq=Eq(f_cap,E_CCS/E_cap) f_cap_eq ``` ### Eq. 3 ```python eq3=Eq(EROI_CCS,E_out/(E_cap+E_op+E_red+E_CCS)) eq3 ``` ### Eq. 1 ```python var('E_in'); eq1=Eq(EROI,E_out/E_in) eq1 ``` ```python E_in_eq=Eq(E_in,E_cap+E_op) E_in_eq ``` ```python solve(E_in_eq,E_in)[0] ``` ```python eq1.subs([[E_in,solve(E_in_eq,E_in)[0]]]) ``` ### Verification Bactkrack to Eq. 3 from Eq. 5 ```python eq5 ``` Get back Eq. 4 from Eq. 5 ```python eq5.subs([[R,solve(R_eq,R)[0]],\ [EROI,solve(eq1.subs([[E_in,solve(E_in_eq,E_in)[0]]]),EROI)[0]]]).simplify() ``` ```python eq4 ``` Get back Eq. 3 from Eq. 4 ```python eq4.subs([[f_op,solve(f_op_eq,f_op)[0]],\ [f_cap,solve(f_cap_eq,f_cap)[0]]]).simplify() ``` ```python eq3 ``` ### Translate Translate example notation into paper equation notations ```python eq3 ``` ```python E_out_eq=Eq(E_out,8760*PP_L*PP_CF*(1-b)) E_out_eq ``` ```python E_out_eq.subs([[b,solve(b_eq,b)[0]]])\ .subs([[CCS_op,solve(CCS_op_eq,CCS_op)[0]]])\ .subs([[Elec_CO2,solve(Elec_CO2_eq,Elec_CO2)[0]]]) ``` ... ? Construct from bottom up ```python eq3 ```
function w = WeightTransform_Merched(W,E,Dint,N,M) % WeightTransform_Merched Mapping of Subband Adaptive Filters Coefficients % to Full-band Filter % % Weight trnasformation by Merched, Diniz, and Petraglia (see Section 4.4.3.2) % % by Lee, Gan, and Kuo, 2008 % Subband Adaptive Filtering: Theory and Implementation % Publisher: John Wiley and Sons, Ltd W = [W, conj(fliplr(W(:,2:end-1)))]; W = W.'; Wp = real(ifft(W,N)); G = zeros(N,M/N); G(1,:) = Wp(1,1:M/N); % Discard the last sample for m = 2:N aux = conv(E(m-1,:),Wp(m,:)); % Filtering by subfilters with polyphase % components of the analysis filter G(m,:) = aux(Dint+2:Dint+1+M/N); end w = reshape(G,M,1); % Equivalent full-band filter
% colony_count.m demo script % Runs colony_count on example image and displays segmentation results. % Load image. I = imread('plate_example.jpg'); % Call function. % Count is number of colonies, markers is the colony markers and mask is % the colony segmentation. Count == # of components in markers. % Optional parameter, this is the default. % Should encompass internal radius of Petri dish. radii = 115:1:130; [count,markers,mask] = colony_count(I,radii); disp([num2str(count) ' colonies detected.']); % Overlay image with markers and mask. J = rgb2gray(I); R = J; G = J; B = J; R(mask) = 255; R(markers) = 0; G(mask) = 0; G(markers) = 255; B(mask) = 0; B(markers) = 0; RGB = cat(3,R,G,B); figure();imshow(RGB); % Overlay image with just markers. R = J; G = J; B = J; R(markers) = 0; G(markers) = 255; B(markers) = 0; RGB = cat(3,R,G,B); figure();imshow(RGB);
/* * LogManager.cpp * !CHAOS * Created by Bisegni Claudio. * * Copyright 2012 INFN, National Institute of Nuclear Physics * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <chaos/common/global.h> #include <chaos/common/configuration/GlobalConfiguration.h> #include <boost/log/core.hpp> #include <boost/log/trivial.hpp> #include <boost/log/sources/severity_logger.hpp> #if BOOST_VERSION > 105300 //allocate the logger #include <boost/log/sources/severity_logger.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/utility/setup/console.hpp> #include <boost/log/utility/setup/file.hpp> #include <boost/log/sources/severity_logger.hpp> #include <boost/log/attributes/attribute_name.hpp> #include <boost/log/sinks/sync_frontend.hpp> #include <boost/log/sinks/syslog_backend.hpp> #include <boost/log/attributes.hpp> #include <boost/log/expressions.hpp> #include <boost/log/utility/setup/formatter_parser.hpp> namespace logging = boost::log; namespace keywords = boost::log::keywords; namespace attrs = boost::log::attributes; namespace sinks = boost::log::sinks; namespace expr = boost::log::expressions; #else #include <boost/log/filters.hpp> #include <boost/log/utility/init/to_file.hpp> #include <boost/log/utility/init/to_console.hpp> #include <boost/log/utility/init/common_attributes.hpp> #include <boost/log/formatters.hpp> namespace logging = boost::BOOST_LOG_NAMESPACE; namespace fmt = boost::log::formatters; #endif #include "LogManager.h" // #define BASE_LOG_FORMAT "[%TimeStamp%][%Severity%]: %_%" #define EXTENDEND_LOG_FORMAT "[%TimeStamp%][%Severity%][%ProcessID%][%ThreadID%]: %_%" using namespace chaos; using namespace chaos::log; std::ostream& operator<<(std::ostream& out, const level::LogSeverityLevel& level ) { switch (level) { case level::LSLDebug: out << "DEBUG"; break; case level::LSLInfo: out << "INFO"; break; case level::LSLNotice: out << "NOTICE"; break; case level::LSLWarning: out << "WARNING"; break; case level::LSLFatal: out << "FATAL"; break; } return out; } void LogManager::init() throw(CException) { //get the log configuration level::LogSeverityLevel logLevel = static_cast<level::LogSeverityLevel>(GlobalConfiguration::getInstance()->getConfiguration()->getInt32Value(InitOption::OPT_LOG_LEVEL)); bool logOnConsole = GlobalConfiguration::getInstance()->getConfiguration()->hasKey(InitOption::OPT_LOG_ON_CONSOLE)? GlobalConfiguration::getInstance()->getConfiguration()->getBoolValue(InitOption::OPT_LOG_ON_CONSOLE):false; bool logOnFile = GlobalConfiguration::getInstance()->getConfiguration()->hasKey(InitOption::OPT_LOG_ON_CONSOLE)? GlobalConfiguration::getInstance()->getConfiguration()->getBoolValue(InitOption::OPT_LOG_ON_FILE):false; string logFileName = GlobalConfiguration::getInstance()->getConfiguration()->getStringValue(InitOption::OPT_LOG_FILE); logging::add_common_attributes(); boost::shared_ptr< logging::core > pCore = boost::log::core::get(); // Create a backend #if (BOOST_VERSION / 100000) >= 1 && ((BOOST_VERSION / 100) % 1000) >= 54 logging::register_simple_formatter_factory< level::LogSeverityLevel, char >("Severity"); logging::core::get()->set_filter(expr::attr< level::LogSeverityLevel >("Severity") >= logLevel); #else logging::register_simple_formatter_factory< level::LogSeverityLevel >("Severity"); logging::core::get()->set_filter(logging::filters::attr< level::LogSeverityLevel >("Severity") >= logLevel); #endif if(logOnConsole){ #if (BOOST_VERSION / 100000) >= 1 && ((BOOST_VERSION / 100) % 1000) >= 54 logging::add_console_log(std::clog, logging::keywords::format = EXTENDEND_LOG_FORMAT); #else logging::init_log_to_console(std::clog, logging::keywords::format = EXTENDEND_LOG_FORMAT); #endif } if(logOnFile){ #if (BOOST_VERSION / 100000) >= 1 && ((BOOST_VERSION / 100) % 1000) >= 54 logging::add_file_log(keywords::file_name = logFileName, // file name pattern keywords::rotation_size = 10 * 1024 * 1024, // rotate files every 10 MiB... keywords::time_based_rotation = logging::sinks::file::rotation_at_time_point(0, 0, 0),// ...or at midnight keywords::format = EXTENDEND_LOG_FORMAT, keywords::auto_flush=true); #else logging::init_log_to_file(logging::keywords::file_name = logFileName, // file name pattern logging::keywords::rotation_size = 10 * 1024 * 1024, // rotate files every 10 MiB... logging::keywords::time_based_rotation = logging::sinks::file::rotation_at_time_point(0, 0, 0),// ...or at midnight logging::keywords::format = EXTENDEND_LOG_FORMAT, logging::keywords::auto_flush=true); #endif } //enable the log in case of needs pCore->set_logging_enabled(logOnConsole || logOnFile); }
[STATEMENT] lemma one_mult_mat_vec[simp]: "(v :: 'a :: semiring_1 vec) \<in> carrier_vec n \<Longrightarrow> 1\<^sub>m n *\<^sub>v v = v" [PROOF STATE] proof (prove) goal (1 subgoal): 1. v \<in> carrier_vec n \<Longrightarrow> 1\<^sub>m n *\<^sub>v v = v [PROOF STEP] by (intro eq_vecI, auto)
/* Title: Web API Client Library for Watch Inputs Author: Matthew Stapleton (Capsicum Corporation) <[email protected]> Description: This module connects to the ioMy Web API to pass various info back and forth Copyright: Capsicum Corporation 2016-2017 This file is part of Watch Inputs which is part of the iOmy project. iOmy is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. iOmy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with iOmy. If not, see <http://www.gnu.org/licenses/>. */ //Use Boost Chrono instead of C++11 chrono #define BOOST_ASIO_DISABLE_STD_CHRONO #include <stdio.h> #include <cctype> #include <cstring> #include <iomanip> #include <iostream> #include <istream> #include <ostream> #include <list> #include <map> #include <string> #include <sstream> #include <typeinfo> #include <boost/chrono.hpp> #include <boost/thread/thread.hpp> #include <boost/thread/recursive_mutex.hpp> #include <boost/atomic/atomic.hpp> #include <boost/asio.hpp> #include <boost/asio/steady_timer.hpp> #include <boost/asio/system_timer.hpp> #include <boost/bind.hpp> #include <boost/archive/iterators/base64_from_binary.hpp> #include <boost/archive/iterators/binary_from_base64.hpp> #include <boost/archive/iterators/transform_width.hpp> #include <boost/archive/iterators/remove_whitespace.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #ifdef __ANDROID__ #include <jni.h> #endif #include "moduleinterface.h" #include "webapiclientlib.hpp" #include "modules/commonlib/commonlib.h" #include "modules/debuglib/debuglib.h" #include "modules/dblib/dblib.h" #include "modules/configlib/configlib.hpp" using boost::asio::ip::tcp; static std::list<webapiclient_link_t *> webapi_links_queue; //List is a pointer so can hold derived objects instead of just the base class static std::list<webapiclient_comm_t *> webapi_comms_queue; static std::list<webapiclient_thing_t *> webapi_things_queue; static boost::recursive_mutex webapiclientlibmutex; static boost::thread webapiclientlib_mainthread; //Function Declarations static bool webapiclientlib_add_zigbee_link_to_webapi_queue(const webapiclient_zigbeelink_t& zigbeelink); static bool webapiclientlib_add_csrmesh_link_to_webapi_queue(const webapiclient_csrmeshlink_t& csrmeshlink); static bool webapiclientlib_add_zigbee_comm_to_webapi_queue(const webapiclient_zigbeecomm_t& zigbeecomm); static bool webapiclientlib_add_bluetooth_comm_to_webapi_queue(const webapiclient_bluetoothcomm_t& bluetoothcomm); static bool webapiclientlib_add_csrmesh_thing_to_webapi_queue(const webapiclient_csrmeshthing_t& csrmeshthing); static void webapiclientlib_setneedtoquit(bool val); static int webapiclientlib_getneedtoquit(); static int webapiclientlib_start(void); static void webapiclientlib_stop(void); static int webapiclientlib_init(void); static void webapiclientlib_shutdown(void); //C Exports extern "C" { BOOST_SYMBOL_EXPORT moduleinfo_ver_generic_t *webapiclientlib_getmoduleinfo(); //JNI Exports #ifdef __ANDROID__ JNIEXPORT jlong JNICALL Java_com_capsicumcorp_iomy_libraries_watchinputs_WebApiClientLib_jnigetmodulesinfo( JNIEnv* UNUSED(env), jobject UNUSED(obj)); #endif } //Module Interface Definitions static webapiclientlib_ifaceptrs_ver_1_t webapiclientlib_ifaceptrs_ver_1={ webapiclientlib_init, webapiclientlib_shutdown, webapiclientlib_add_zigbee_link_to_webapi_queue, webapiclientlib_add_csrmesh_link_to_webapi_queue, webapiclientlib_add_zigbee_comm_to_webapi_queue, webapiclientlib_add_bluetooth_comm_to_webapi_queue, webapiclientlib_add_csrmesh_thing_to_webapi_queue }; static moduleiface_ver_1_t webapiclientlib_ifaces[]={ { &webapiclientlib_ifaceptrs_ver_1, WEBAPICLIENTLIBINTERFACE_VER_1 }, { nullptr, 0 } }; static moduledep_ver_1_t webapiclientlib_deps[]={ { "debuglib", nullptr, DEBUGLIBINTERFACE_VER_1, 1 }, { "dblib", nullptr, DBLIBINTERFACE_VER_1, 1 }, { "configlib", nullptr, CONFIGLIBINTERFACECPP_VER_1, 1 }, { nullptr, nullptr, 0, 0 } }; //NOTE: Need to cast the deps as in this library it is defined as a fixed size static const moduleinfo_ver_1_t webapiclientlib_moduleinfo_ver_1={ MODULEINFO_VER_1, "webapiclientlib", webapiclientlib_init, webapiclientlib_shutdown, webapiclientlib_start, webapiclientlib_stop, nullptr, nullptr, (moduleiface_ver_1_t (* const)[]) &webapiclientlib_ifaces, (moduledep_ver_1_t (*)[]) &webapiclientlib_deps, }; //Find a pointer to module interface pointer //Returns the pointer to the interface or nullptr if not found //NOTE: A little slower than referencing the array element directly, but less likely to cause a programming fault // due to rearranging depencencies static const void *webapiclientlib_getmoduledepifaceptr(const char *modulename, unsigned ifacever) { int i=0; while (webapiclientlib_deps[i].modulename) { if (std::strcmp(webapiclientlib_deps[i].modulename, modulename)==0) { if (webapiclientlib_deps[i].ifacever==ifacever) { return webapiclientlib_deps[i].ifaceptr; } } ++i; } return nullptr; } //Returns an encoded string from a unencoded string //Based on http://stackoverflow.com/questions/10521581/base64-encode-using-boost-throw-exception/10973348#10973348 //The line break inserting at character 76 has been removed static std::string base64_encode(const std::string& s) { typedef boost::archive::iterators::base64_from_binary<boost::archive::iterators::transform_width<std::string::const_iterator,6,8> > it_base64_t; unsigned int writePaddChars = (3-s.length()%3)%3; std::string base64(it_base64_t(s.begin()),it_base64_t(s.end())); base64.append(writePaddChars,'='); return base64; } //Returns a decoded string from a base64 encoded string //Based on http://stackoverflow.com/questions/10521581/base64-encode-using-boost-throw-exception/10973348#10973348 static std::string base64_decode(const std::string& base64) { typedef boost::archive::iterators::transform_width< boost::archive::iterators::binary_from_base64<boost::archive::iterators::remove_whitespace<std::string::const_iterator> >, 8, 6 > it_binary_t; std::string tmps=base64; unsigned int paddChars = count(tmps.begin(), tmps.end(), '='); std::replace(tmps.begin(),tmps.end(),'=','A'); // replace '=' by base64 encoding of '\0' std::string result(it_binary_t(tmps.begin()), it_binary_t(tmps.end())); // decode result.erase(result.end()-paddChars,result.end()); // erase padding '\0' characters return result; } //From http://stackoverflow.com/questions/154536/encode-decode-urls-in-c static std::string url_encode(const std::string &value) { std::ostringstream escaped; escaped.fill('0'); escaped << std::hex; for (auto const& it : value) { std::string::value_type c = it; // Keep alphanumeric and other accepted characters intact if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') { escaped << c; continue; } // Any other characters are percent-encoded escaped << std::uppercase; escaped << '%' << std::setw(2) << int((unsigned char) c); escaped << std::nouppercase; } return escaped.str(); } std::string link_to_json(const webapiclient_link_t& link) { using boost::property_tree::ptree; ptree pt; std::ostringstream tmphexstr; pt.put("CommId", link.localpk); if (typeid(link)==typeid(webapiclient_zigbeelink_t)) { pt.put("Type", 2); //2=Zigbee device } else if (typeid(link)==typeid(webapiclient_csrmeshlink_t)) { pt.put("Type", 15); //15=Qualcomm CSRmesh Link } else { debuglib_ifaceptrs_ver_1_t *debuglibifaceptr=(debuglib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("debuglib", DEBUGLIBINTERFACE_VER_1); debuglibifaceptr->debuglib_printf(1, "%s: Unknown Typeid=%s\n", __func__, typeid(link).name()); } pt.put("InfoName", link.modelname); //Zigbee Addresses are 64-bit hexidecimal without the 0x part tmphexstr.width(16); tmphexstr.fill('0'); tmphexstr << std::uppercase << std::hex << link.addr; pt.put("SerialCode", tmphexstr.str()); pt.put("Displayname", link.userstr); if (typeid(link)==typeid(webapiclient_csrmeshlink_t)) { pt.put("State", 1); pt.put("InfoManufacturer", "Qualcomm"); pt.put("InfoManufacturerUrl", "www.qualcomm.com"); pt.put("ConnCryptTypeId", 1); pt.put("ConnUsername", ""); pt.put("ConnPassword", dynamic_cast<const webapiclient_csrmeshlink&>(link).networkKey); } if (typeid(link)==typeid(webapiclient_zigbeelink_t)) { ptree thingspt; for (const auto &thingit : dynamic_cast<const webapiclient_zigbeelink_t&>(link).things) { ptree thingpt; thingpt.put("Type", thingit.second.type); thingpt.put("State", thingit.second.state); thingpt.put("HWId", thingit.first); ptree iospt; for (const auto &ioit : thingit.second.io) { ptree iopt; iopt.put("RSType", ioit.rstype); iopt.put("UoM", ioit.uom); iopt.put("Type", ioit.iotype); iopt.put("Name", ioit.name); iopt.put("BaseConvert", ioit.baseconvert); iopt.put("SampleRate", ioit.samplerate); iospt.push_back(std::make_pair("", iopt)); } thingpt.put_child("IOs", iospt); thingspt.push_back(std::make_pair("", thingpt)); } pt.put_child("Things", thingspt); } std::ostringstream streamstr; write_json(streamstr, pt); return streamstr.str(); } std::string comm_to_json(const webapiclient_comm_t& comm) { using boost::property_tree::ptree; ptree pt; pt.put("HubId", comm.hubpk); pt.put("Type", comm.type); pt.put("Name", comm.name); //Zigbee Addresses are 64-bit hexidecimal without the 0x part std::ostringstream tmphexstr; tmphexstr.width(16); tmphexstr.fill('0'); tmphexstr << std::uppercase << std::hex << comm.addr; pt.put("Address", tmphexstr.str()); std::ostringstream streamstr; write_json(streamstr, pt); return streamstr.str(); } std::string thing_to_json(const webapiclient_thing_t& thing) { using boost::property_tree::ptree; ptree pt; ptree thingpt; std::ostringstream tmphexstr; thingpt.put("LinkId", thing.linkpk); thingpt.put("Type", thing.type); thingpt.put("State", thing.state); thingpt.put("HWId", thing.hwid); thingpt.put("Name", thing.name); if (typeid(thing)==typeid(webapiclient_csrmeshthing_t)) { const webapiclient_csrmeshthing_t& csrmeshthing=dynamic_cast<const webapiclient_csrmeshthing_t&>(thing); thingpt.put("SerialCode", csrmeshthing.serialcode); ptree iospt; for (const auto &ioit : csrmeshthing.io) { ptree iopt; iopt.put("RSType", ioit.rstype); iopt.put("UoM", ioit.uom); iopt.put("Type", ioit.iotype); iopt.put("Name", ioit.name); iopt.put("BaseConvert", ioit.baseconvert); iopt.put("SampleRate", ioit.samplerate); iospt.push_back(std::make_pair("", iopt)); } thingpt.put_child("IOs", iospt); } std::ostringstream streamstr; write_json(streamstr, thingpt); return streamstr.str(); } //Add a link to a queue for adding via the web api static bool webapiclientlib_add_link_to_webapi_queue(webapiclient_link_t* link) { debuglib_ifaceptrs_ver_1_t *debuglibifaceptr=(debuglib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("debuglib", DEBUGLIBINTERFACE_VER_1); debuglibifaceptr->debuglib_printf(1, "Entering %s\n", __func__); debuglibifaceptr->debuglib_printf(1, "%s: Adding device with address: %016" PRIX64 " to webapi queue\n", __func__, link->addr); { boost::lock_guard<boost::recursive_mutex> guard(webapiclientlibmutex); //Just add to the queue and quickly exit as the list can be pruned later in the webapi thread webapi_links_queue.push_back(link); } //Testing Code debuglibifaceptr->debuglib_printf(1, "%s: SUPER DEBUG: JSON output: \"%s\"\n", __func__, link_to_json(*link).c_str()); debuglibifaceptr->debuglib_printf(1, "Exiting %s\n", __func__); return true; } //Add a zigbee link to a queue for adding via the web api static bool webapiclientlib_add_zigbee_link_to_webapi_queue(const webapiclient_zigbeelink_t& zigbeelink) { webapiclient_zigbeelink_t *link=new webapiclient_zigbeelink_t; *link=zigbeelink; return webapiclientlib_add_link_to_webapi_queue(link); } //Add a CSRMesh link to a queue for adding via the web api static bool webapiclientlib_add_csrmesh_link_to_webapi_queue(const webapiclient_csrmeshlink_t& csrmeshlink) { webapiclient_csrmeshlink_t *link=new webapiclient_csrmeshlink_t; *link=csrmeshlink; return webapiclientlib_add_link_to_webapi_queue(link); } //Add a comm to a queue for adding via the web api static bool webapiclientlib_add_comm_to_webapi_queue(webapiclient_comm_t* comm) { debuglib_ifaceptrs_ver_1_t *debuglibifaceptr=(debuglib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("debuglib", DEBUGLIBINTERFACE_VER_1); debuglibifaceptr->debuglib_printf(1, "Entering %s\n", __func__); debuglibifaceptr->debuglib_printf(1, "%s: Adding Comm with address: %016" PRIX64 " to webapi queue\n", __func__, comm->addr); { boost::lock_guard<boost::recursive_mutex> guard(webapiclientlibmutex); //Just add to the queue and quickly exit as the list can be pruned later in the webapi thread webapi_comms_queue.push_back(comm); } //Testing Code debuglibifaceptr->debuglib_printf(1, "%s: SUPER DEBUG: JSON output: \"%s\"\n", __func__, comm_to_json(*comm).c_str()); debuglibifaceptr->debuglib_printf(1, "Exiting %s\n", __func__); return true; } //Add a zigbee comm to a queue for adding via the web api static bool webapiclientlib_add_zigbee_comm_to_webapi_queue(const webapiclient_zigbeecomm_t& zigbeecomm) { webapiclient_zigbeecomm_t *comm=new webapiclient_zigbeecomm_t; *comm=zigbeecomm; return webapiclientlib_add_comm_to_webapi_queue(comm); } //Add a bluetooth comm to a queue for adding via the web api static bool webapiclientlib_add_bluetooth_comm_to_webapi_queue(const webapiclient_bluetoothcomm_t& bluetoothcomm) { webapiclient_bluetoothcomm_t *comm=new webapiclient_bluetoothcomm_t; *comm=bluetoothcomm; return webapiclientlib_add_comm_to_webapi_queue(comm); } //Add a thing to a queue for adding via the web api static bool webapiclientlib_add_thing_to_webapi_queue(webapiclient_thing_t* thing) { debuglib_ifaceptrs_ver_1_t *debuglibifaceptr=(debuglib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("debuglib", DEBUGLIBINTERFACE_VER_1); debuglibifaceptr->debuglib_printf(1, "Entering %s\n", __func__); debuglibifaceptr->debuglib_printf(1, "%s: Adding device with name: %s to webapi queue\n", __func__, thing->name.c_str()); { boost::lock_guard<boost::recursive_mutex> guard(webapiclientlibmutex); //Just add to the queue and quickly exit as the list can be pruned later in the webapi thread webapi_things_queue.push_back(thing); } //Testing Code debuglibifaceptr->debuglib_printf(1, "%s: SUPER DEBUG: JSON output: \"%s\"\n", __func__, thing_to_json(*thing).c_str()); debuglibifaceptr->debuglib_printf(1, "Exiting %s\n", __func__); return true; } //Add a CSRMesh thing to a queue for adding via the web api static bool webapiclientlib_add_csrmesh_thing_to_webapi_queue(const webapiclient_csrmeshthing_t& csrmeshthing) { webapiclient_csrmeshthing_t *thing=new webapiclient_csrmeshthing_t; *thing=csrmeshthing; return webapiclientlib_add_thing_to_webapi_queue(thing); } //Setup a http request //Only POST is supported at the moment class httpclient { private: //Name, Value pair std::map<std::string, std::string> headers; //Name, Value pair std::map<std::string, std::string> formfields; std::string httppath; bool haveHttpAuth=false; std::string httpusername; std::string httppassword; public: httpclient() { addHeader("Accept", "*/*"); addHeader("User-Agent", "HTTP-Client 1.0"); addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } void addHeader(const std::string& name, const std::string& value) { headers[name]=value; } //Added an entire string as a header //Example: Host: www.example.com void addHeader(const std::string& str) { std::istringstream ss(str); std::string name, value; ss >> name; ss >> value; name.erase(name.end()-1); //Remove : at the end of the name addHeader(name, value); } void addFormField(const std::string& name, const std::string& value) { formfields[name]=value; } void addFormField(const std::string& name, const long int value) { std::ostringstream ss; ss << value; formfields[name]=ss.str(); } void setPath(std::string path) { this->httppath=path; } void addHttpAuth(const std::string& username, const std::string& password) { this->httpusername=username; this->httppassword=password; haveHttpAuth=true; } std::string toString() { std::ostringstream stream; std::ostringstream body; //Generate the body from the form data bool firstfield=true; for (auto const& formfieldit : formfields) { if (!firstfield) { body << "&"; } body << url_encode(formfieldit.first) << '=' << url_encode(formfieldit.second); firstfield=false; } stream << "POST " << httppath << " HTTP/1.0\r\n"; if (haveHttpAuth) { std::ostringstream authstring; authstring << httpusername << ':' << httppassword; stream << "Authorization: Basic " << base64_encode(authstring.str()) << "\r\n"; } for (auto const& headerit : headers) { stream << headerit.first << ": " << headerit.second << "\r\n"; } stream << "Content-Length: " << body.str().size() << "\r\n"; stream << "\r\n"; stream << body.str(); return stream.str(); } }; //Based on http://www.boost.org/doc/libs/1_61_0/doc/html/boost_asio/example/cpp03/http/client/async_client.cpp // and http://www.boost.org/doc/libs/1_61_0/doc/html/boost_asio/example/cpp03/timeouts/async_tcp_client.cpp //NOTE: Android doesn't know about service: "http" so have to use 80 for the port class asioclient { private: boost::atomic<bool> stopped_; tcp::resolver resolver_; tcp::socket socket_; boost::asio::streambuf response_; boost::asio::system_timer deadline_; std::string httpserver; std::string httppath; std::string webapiport; std::string apiusername, apipassword; std::string httpusername; std::string httppassword; debuglib_ifaceptrs_ver_1_t *debuglibifaceptr; std::string http_version; unsigned httpstatuscode; long httpbodylen; std::list<webapiclient_link_t *>::iterator linksit; std::list<webapiclient_comm_t *>::iterator commsit; std::list<webapiclient_thing_t *>::iterator thingsit; int requestmode; //1=Adding Link, 2=Adding Comm, 3=Adding Thing //See http://stackoverflow.com/questions/21120361/boostasioasync-write-and-buffers-over-65536-bytes //These variables need to stay allocated while the asio request is active so can't be local to a single function httpclient hc; boost::asio::streambuf commrequest_; boost::asio::streambuf linkrequest_; boost::asio::streambuf thingrequest_; public: asioclient(boost::asio::io_service& io_service) : stopped_(true), resolver_(io_service), socket_(io_service), deadline_(io_service) { //NOTE: When initialised globally, debuglibifaceptr won't be initialised yet } // Called by the user of the client class to initiate the connection process. // The endpoint iterator will have been obtained using a tcp::resolver. void start(const std::string& server, const std::string& webapiport, const std::string& path, const std::string& username, const std::string& password, const std::string &httpusername, const std::string &httppassword) { debuglibifaceptr=(debuglib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("debuglib", DEBUGLIBINTERFACE_VER_1); // Form the request. We specify the "Connection: close" header so that the // server will close the socket after transmitting the response. This will // allow us to treat all data up until the EOF as the content. if (!stopped_) { return; } stopped_=false; httpserver=server; httppath=path; this->webapiport=webapiport; apiusername=username; apipassword=password; this->httpusername=httpusername; this->httppassword=httppassword; //NOTE: We set the Mode and Data later on when submitting the request hc.setPath(httppath); if (httpusername != "") { //Send the http password straight away to reduce the number of packets hc.addHttpAuth(httpusername, httppassword); } hc.addHeader("Host", httpserver); hc.addFormField("Version", "0.4.11"); if (apiusername != "") { std::ostringstream tmpstr; tmpstr << "[\"" << apiusername << "\",\"" << apipassword << "\"]"; hc.addFormField("Access", tmpstr.str()); } //Loop through the zigbee comms and links queues adding each one at a time { boost::lock_guard<boost::recursive_mutex> guard(webapiclientlibmutex); if (webapi_links_queue.empty() && webapi_comms_queue.empty() && webapi_things_queue.empty()) { //No need to connect if the queue is empty return; } commsit=webapi_comms_queue.begin(); linksit=webapi_links_queue.begin(); thingsit=webapi_things_queue.begin(); } // Start an asynchronous resolve to translate the server and service names // into a list of endpoints. tcp::resolver::query query(httpserver, this->webapiport); resolver_.async_resolve(query, boost::bind(&asioclient::handle_resolve, this, boost::asio::placeholders::error, boost::asio::placeholders::iterator)); //Set a starting deadline timer deadline_.expires_from_now(boost::chrono::seconds(60)); // Start the deadline actor deadline_.async_wait(boost::bind(&asioclient::check_deadline, this)); } // This function terminates all the actors to shut down the connection. It // may be called by the user of the client class, or by the class itself in // response to graceful termination or an unrecoverable error. void stop() { debuglibifaceptr=(debuglib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("debuglib", DEBUGLIBINTERFACE_VER_1); if (stopped_) { return; } stopped_ = true; boost::system::error_code ignored_ec; try { socket_.shutdown(tcp::socket::shutdown_both, ignored_ec); } catch (std::exception& e) { //Ignore errors from this function for now } socket_.close(ignored_ec); deadline_.cancel(); response_.consume(response_.size()); } private: void handle_resolve(const boost::system::error_code& err, tcp::resolver::iterator endpoint_iterator) { if (stopped_) { return; } if (!err) { std::stringstream tmps; tmps << endpoint_iterator->endpoint(); debuglibifaceptr->debuglib_printf(1, "%s: Trying %s...\n", __func__, tmps.str().c_str()); // Set a deadline for the connect operation. deadline_.expires_from_now(boost::chrono::seconds(60)); // Attempt a connection to each endpoint in the list until we // successfully establish a connection. boost::asio::async_connect(socket_, endpoint_iterator, boost::bind(&asioclient::handle_connect, this, boost::asio::placeholders::error)); } else { debuglibifaceptr->debuglib_printf(1, "%s: Error: %s, Hostname: %s, Port: %s\n", __func__, err.message().c_str(), this->httpserver.c_str(), this->webapiport.c_str()); stop(); } } void reset_http_body() { http_version=""; httpstatuscode=0; httpbodylen=0; } void handle_connect(const boost::system::error_code& err) { if (stopped_) { return; } if (!err) { // The connection was successful. Send the comm requests send_comm_request(); } else { debuglibifaceptr->debuglib_printf(1, "%s: Error: %s\n", __func__, err.message().c_str()); stop(); } } void send_comm_request(void) { bool commokay; std::list<webapiclient_comm_t *>::iterator commsendit; //Send the next request or close connection if nothing else to send { boost::lock_guard<boost::recursive_mutex> guard(webapiclientlibmutex); commsendit=webapi_comms_queue.end(); } //Don't send the zigbee comm until all checks pass commokay=false; while (!commokay && commsit!=commsendit) { if (!(*commsit)->hubpk || !(*commsit)->okaytoadd) { //Step to next comm ++commsit; continue; } commokay=true; } if (commokay && !webapiclientlib_getneedtoquit()) { reset_http_body(); hc.addFormField("Mode", "AddComm"); hc.addFormField("Data", comm_to_json(**commsit).c_str()); std::ostream request_stream(&commrequest_); debuglibifaceptr->debuglib_printf(1, "%s: SUPER DEBUG: Sending comm request: %s\n", __func__, hc.toString().c_str()); request_stream << hc.toString(); requestmode=2; boost::asio::async_write(socket_, commrequest_, boost::bind(&asioclient::handle_write_request, this, boost::asio::placeholders::error)); } else if (!webapiclientlib_getneedtoquit()) { send_link_request(); } else { stop(); } } void send_link_request(void) { bool linkokay; std::list<webapiclient_link_t *>::iterator linksendit; //Send the next request or close connection if nothing else to send { boost::lock_guard<boost::recursive_mutex> guard(webapiclientlibmutex); linksendit=webapi_links_queue.end(); } //Don't send the link until all checks pass linkokay=false; while (!linkokay && linksit!=linksendit) { if (!(*linksit)->localpk || !(*linksit)->okaytoadd) { //Step to next link ++linksit; continue; } linkokay=true; } if (linkokay && !webapiclientlib_getneedtoquit()) { reset_http_body(); hc.addFormField("Mode", "AddLink"); hc.addFormField("Data", link_to_json(**linksit)); std::ostream request_stream(&linkrequest_); debuglibifaceptr->debuglib_printf(1, "%s: SUPER DEBUG: Sending link request: %s\n", __func__, hc.toString().c_str()); request_stream << hc.toString(); requestmode=1; boost::asio::async_write(socket_, linkrequest_, boost::bind(&asioclient::handle_write_request, this, boost::asio::placeholders::error)); } else if (!webapiclientlib_getneedtoquit()) { send_thing_request(); } else { stop(); } } void send_thing_request(void) { bool thingokay; std::list<webapiclient_thing_t *>::iterator thingsendit; //Send the next request or close connection if nothing else to send { boost::lock_guard<boost::recursive_mutex> guard(webapiclientlibmutex); thingsendit=webapi_things_queue.end(); } //Don't send the thing until all checks pass thingokay=false; while (!thingokay && thingsit!=thingsendit) { if (!(*thingsit)->linkpk || !(*thingsit)->okaytoadd) { //Step to next thing ++thingsit; continue; } thingokay=true; } if (thingokay && !webapiclientlib_getneedtoquit()) { reset_http_body(); hc.addFormField("Mode", "AddThing"); hc.addFormField("Data", thing_to_json(**thingsit)); std::ostream request_stream(&thingrequest_); debuglibifaceptr->debuglib_printf(1, "%s: SUPER DEBUG: Sending thing request: %s\n", __func__, hc.toString().c_str()); request_stream << hc.toString(); requestmode=3; boost::asio::async_write(socket_, thingrequest_, boost::bind(&asioclient::handle_write_request, this, boost::asio::placeholders::error)); } else { stop(); } } void handle_write_request(const boost::system::error_code& err) { if (stopped_) { return; } if (!err) { // Set a deadline for the read operation. deadline_.expires_from_now(boost::chrono::seconds(60)); // Read the response status line. The response_ streambuf will // automatically grow to accommodate the entire line. The growth may be // limited by passing a maximum size to the streambuf constructor. boost::asio::async_read_until(socket_, response_, "\r\n", boost::bind(&asioclient::handle_read_status_line, this, boost::asio::placeholders::error)); } else { debuglibifaceptr->debuglib_printf(1, "%s: Error: %s\n", __func__, err.message().c_str()); stop(); } } void handle_read_status_line(const boost::system::error_code& err) { if (stopped_) { return; } if (!err) { // Check that response is OK. std::istream response_stream(&response_); response_stream >> http_version; response_stream >> httpstatuscode; std::string status_message; std::getline(response_stream, status_message); if (!response_stream || http_version.substr(0, 5) != "HTTP/") { debuglibifaceptr->debuglib_printf(1, "%s: Invalid response: %s\n", __func__, http_version.c_str()); stop(); return; } else if (httpstatuscode == 401) { //Abort as the password was incorrect debuglibifaceptr->debuglib_printf(1, "%s: Authentication Failure\n", __func__); stop(); return; } else if (httpstatuscode != 200) { debuglibifaceptr->debuglib_printf(1, "%s: Response returned with status code: %u\n", __func__, httpstatuscode); stop(); return; } // Set a deadline for the read operation. deadline_.expires_from_now(boost::chrono::seconds(60)); // Read the response headers, which are terminated by a blank line. boost::asio::async_read_until(socket_, response_, "\r\n\r\n", boost::bind(&asioclient::handle_read_headers, this, boost::asio::placeholders::error)); } else { debuglibifaceptr->debuglib_printf(1, "%s: Error: %s\n", __func__, err.message().c_str()); stop(); } } void handle_read_headers(const boost::system::error_code& err) { if (stopped_) { return; } if (!err) { // Process the response headers. std::istream response_stream(&response_); std::string header; bool havebodylen=false; while (std::getline(response_stream, header) && header != "\r") { if (header.substr(0, 15) == "Content-Length:") { std::stringstream contentlengthstr(header.substr(15)); contentlengthstr >> httpbodylen; havebodylen=true; debuglibifaceptr->debuglib_printf(1, "%s: Content-Length=%ld\n", __func__, httpbodylen); } debuglibifaceptr->debuglib_printf(1, "%s: Header: %s\n", __func__, header.c_str()); } if (!havebodylen) { //Can't continue without proper body length so abort debuglibifaceptr->debuglib_printf(1, "%s: Error: Failed to retrieve Content-Length\n", __func__); stop(); return; } // Set a deadline for the read operation. deadline_.expires_from_now(boost::chrono::seconds(60)); if (httpstatuscode == 401) { //Abort as the password was incorrect debuglibifaceptr->debuglib_printf(1, "%s: Authentication Failure\n", __func__); stop(); return; } else if (httpstatuscode != 200) { debuglibifaceptr->debuglib_printf(1, "%s: Response returned with status code: %u\n", __func__, httpstatuscode); // Dummy read the body boost::asio::async_read(socket_, response_, boost::asio::transfer_exactly(httpbodylen-response_.size()), boost::bind(&asioclient::dummy_read_content, this, boost::asio::placeholders::error)); stop(); return; } else { // Read the body boost::asio::async_read(socket_, response_, boost::asio::transfer_exactly(httpbodylen-response_.size()), boost::bind(&asioclient::handle_read_content, this, boost::asio::placeholders::error)); } } else { debuglibifaceptr->debuglib_printf(1, "%s: Error: %s\n", __func__, err.message().c_str()); stop(); } } int process_response(std::string body) { int errcode=0; try { boost::property_tree::ptree pt; std::istringstream streamstr(body); read_json(streamstr, pt); bool iserror=pt.get<bool>("Error"); if (iserror) { errcode=pt.get<int>("ErrCode"); std::string errorstr=pt.get<std::string>("ErrMesg"); debuglibifaceptr->debuglib_printf(1, "%s: Webapi server returned error code: %d, error message: %s\n", __func__, errcode, errorstr.c_str()); if (errcode==0) { //Error code 0 normally means success so if there was an error adjust to -1 for the return errcode=-1; } } } catch (boost::property_tree::ptree_error &e) { debuglibifaceptr->debuglib_printf(1, "%s: Webapi server returned an unknown result\n", __func__); return -1; } return errcode; } void dummy_read_content(const boost::system::error_code& err) { response_.consume(httpbodylen); } void handle_read_content(const boost::system::error_code& err) { if (!err || err == boost::asio::error::eof) { // Write all of the data that has been read so far. std::string httpbody; int c; while ( (c=response_.sbumpc())!=EOF ) { httpbody+=(char) c; } debuglibifaceptr->debuglib_printf(1, "%s: SUPER DEBUG: Body: \"%s\"\n", __func__, httpbody.c_str()); int result=process_response(httpbody); if (result==0) { successful_send(); } else { failed_send(); } } else if (err != boost::asio::error::eof) { debuglibifaceptr->debuglib_printf(1, "%s: Error: %s\n", __func__, err.message().c_str()); stop(); } } //Do processing after the request has been sent and then send the next request void successful_send() { if (requestmode==1) { std::list<webapiclient_link_t *>::iterator linksprevit=linksit; debuglibifaceptr->debuglib_printf(1, "%s: SUPER DEBUG Removing Link from add queue due to success\n", __func__); //Step to next link before erasing the one that just got added ++linksit; //Erase the link that just got added delete (*linksprevit); webapi_links_queue.erase(linksprevit); //Only send one request at a time for now until HTTP/1.1 with Chunked Transfer Encoding is implemented stop(); //Send next request //send_link_request(); } else if (requestmode==3) { std::list<webapiclient_thing_t *>::iterator thingsprevit=thingsit; debuglibifaceptr->debuglib_printf(1, "%s: SUPER DEBUG Removing Thing from add queue due to success\n", __func__); //Step to next thing before erasing the one that just got added ++thingsit; //Erase the thing that just got added delete (*thingsprevit); webapi_things_queue.erase(thingsprevit); //Only send one request at a time for now until HTTP/1.1 with Chunked Transfer Encoding is implemented stop(); //Send next request //send_link_request(); } else if (requestmode==2) { std::list<webapiclient_comm_t *>::iterator commsprevit=commsit; debuglibifaceptr->debuglib_printf(1, "%s: SUPER DEBUG Removing Comm from add queue due to success\n", __func__); //Step to next comm before erasing the one that just got added ++commsit; //Erase the comm that just got added delete (*commsprevit); webapi_comms_queue.erase(commsprevit); //Only send one request at a time for now until HTTP/1.1 with Chunked Transfer Encoding is implemented stop(); //Send next request //send_comm_request(); } } //Do processing after the request has been sent and then send the next request void failed_send() { if (requestmode==1) { debuglibifaceptr->debuglib_printf(1, "%s: SUPER DEBUG Skipping adding Link for now due to error\n", __func__); //Skip the current link for now and step to next link ++linksit; //Send next request send_link_request(); } else if (requestmode==3) { debuglibifaceptr->debuglib_printf(1, "%s: SUPER DEBUG Skipping adding Thing for now due to error\n", __func__); //Skip the current thing for now and step to next link ++thingsit; //Send next request send_thing_request(); } else if (requestmode==2) { debuglibifaceptr->debuglib_printf(1, "%s: SUPER DEBUG Skipping adding Comm for now due to error\n", __func__); //Skip the current comm link for now and step to next comm link ++commsit; //Send next request send_comm_request(); } } void check_deadline() { if (stopped_) return; // Check whether the deadline has passed. We compare the deadline against // the current time since a new asynchronous operation may have moved the // deadline before this actor had a chance to run. if (deadline_.expires_at() <= boost::chrono::system_clock::now()) { debuglibifaceptr->debuglib_printf(1, "%s: Server took too long to respond\n", __func__); //Shutdown first as per Boost header file portability recommendation try { socket_.shutdown(tcp::socket::shutdown_both); } catch (std::exception& e) { //Ignore errors from this function for now } // The deadline has passed. The socket is closed so that any outstanding // asynchronous operations are cancelled. socket_.close(); } else { // Put the actor back to sleep. deadline_.async_wait(boost::bind(&asioclient::check_deadline, this)); } } }; class webapiclientloop_asyncloop { private: boost::mutex mtx_; boost::asio::io_service io_service; boost::asio::system_timer timer; asioclient client; public: webapiclientloop_asyncloop() : timer(io_service), client(io_service) { } void start() { debuglib_ifaceptrs_ver_1_t *debuglibifaceptr=(debuglib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("debuglib", DEBUGLIBINTERFACE_VER_1); update_timer_loop(); try { io_service.run(); io_service.reset(); } catch (std::exception& e) { debuglibifaceptr->debuglib_printf(1, "%s: Error while running service: %s\n", __func__, e.what()); } } void stop() { boost::lock_guard<boost::mutex> guard(mtx_); client.stop(); timer.expires_from_now(boost::chrono::seconds(0)); } private: //Get the hub pk for the comm devices from the configuration void set_hubpk_for_comm_devices(void) { debuglib_ifaceptrs_ver_1_t *debuglibifaceptr=(debuglib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("debuglib", DEBUGLIBINTERFACE_VER_1); configlib_ifaceptrs_ver_1_cpp_t *configlibifaceptr=(configlib_ifaceptrs_ver_1_cpp_t *) webapiclientlib_getmoduledepifaceptr("configlib", CONFIGLIBINTERFACECPP_VER_1); std::string hubpkstr; bool result=configlibifaceptr->getnamevalue_cpp("general", "hubpk", hubpkstr); if (!result) { return; } std::int64_t hubpk=std::atol(hubpkstr.c_str()); //Once we have begin and end iterators we shouldn't need a lock to traverse the list unless we modify the contents webapiclientlibmutex.lock(); auto webapi_comms_queueitbegin=webapi_comms_queue.begin(); auto webapi_comms_queueitend=webapi_comms_queue.end(); webapiclientlibmutex.unlock(); for (auto &it=webapi_comms_queueitbegin; it!=webapi_comms_queueitend; it++) { webapiclientlibmutex.lock(); (*it)->hubpk=hubpk; webapiclientlibmutex.unlock(); debuglibifaceptr->debuglib_printf(1, "%s: Found Hub PK: %" PRId64 " for Queued device: %016" PRIX64 "\n", __func__, hubpk, (*it)->addr); } } //Get the local pk for links based on the local address void set_locakpk_for_links(void) { debuglib_ifaceptrs_ver_1_t *debuglibifaceptr=(debuglib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("debuglib", DEBUGLIBINTERFACE_VER_1); dblib_ifaceptrs_ver_1_t *dblibifaceptr=(dblib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("dblib", DBLIBINTERFACE_VER_1);; int result; //Once we have begin and end iterators we shouldn't need a lock to traverse the list unless we modify the contents webapiclientlibmutex.lock(); auto webapi_links_queueitbegin=webapi_links_queue.begin(); auto webapi_links_queueitend=webapi_links_queue.end(); webapiclientlibmutex.unlock(); result=dblibifaceptr->begin(); if (result<0) { debuglibifaceptr->debuglib_printf(1, "%s: Failed to start database transaction\n", __func__); return; } for (auto &it=webapi_links_queueitbegin; it!=webapi_links_queueitend; it++) { int result; int64_t commpk; //Check the database to see if the link is linked to a comm debuglibifaceptr->debuglib_printf(1, "%s: Searching for Comm PK from address: %016" PRIX64 " for Queued Link: %016" PRIX64 "\n", __func__, (*it)->localaddr, (*it)->addr); result=dblibifaceptr->getcommpk((*it)->localaddr, &commpk); if (result==0) { webapiclientlibmutex.lock(); (*it)->localpk=commpk; webapiclientlibmutex.unlock(); debuglibifaceptr->debuglib_printf(1, "%s: Found Comm PK: %" PRId64 " from address: %016" PRIX64 " for Queued Link: %016" PRIX64 "\n", __func__, commpk, (*it)->localaddr, (*it)->addr); } } result=dblibifaceptr->end(); if (result<0) { dblibifaceptr->rollback(); } } //Get the link pk for things based on the local address void set_linkpk_for_things(void) { debuglib_ifaceptrs_ver_1_t *debuglibifaceptr=(debuglib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("debuglib", DEBUGLIBINTERFACE_VER_1); dblib_ifaceptrs_ver_1_t *dblibifaceptr=(dblib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("dblib", DBLIBINTERFACE_VER_1);; int result; //Once we have begin and end iterators we shouldn't need a lock to traverse the list unless we modify the contents webapiclientlibmutex.lock(); auto webapi_things_queueitbegin=webapi_things_queue.begin(); auto webapi_things_queueitend=webapi_things_queue.end(); webapiclientlibmutex.unlock(); result=dblibifaceptr->begin(); if (result<0) { debuglibifaceptr->debuglib_printf(1, "%s: Failed to start database transaction\n", __func__); return; } for (auto &it=webapi_things_queueitbegin; it!=webapi_things_queueitend; it++) { int result; int64_t linkpk; //Check the database to see if the link is linked to a comm debuglibifaceptr->debuglib_printf(1, "%s: Searching for Link PK from address: %016" PRIX64 " for Queued Thing: %08" PRIX32 "\n", __func__, (*it)->localaddr, (*it)->hwid); result=dblibifaceptr->getlinkpk((*it)->localaddr, &linkpk); if (result==0) { webapiclientlibmutex.lock(); (*it)->linkpk=linkpk; webapiclientlibmutex.unlock(); debuglibifaceptr->debuglib_printf(1, "%s: Found Link PK: %" PRId64 " from address: %016" PRIX64 " for Queued Thing: %08" PRIX32 "\n", __func__, linkpk, (*it)->localaddr, (*it)->hwid); } } result=dblibifaceptr->end(); if (result<0) { dblibifaceptr->rollback(); } } //Remove comm devices from the webapi queue that don't need to be re-added void remove_already_added_comm_devices(void) { debuglib_ifaceptrs_ver_1_t *debuglibifaceptr=(debuglib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("debuglib", DEBUGLIBINTERFACE_VER_1); dblib_ifaceptrs_ver_1_t *dblibifaceptr=(dblib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("dblib", DBLIBINTERFACE_VER_1);; int result; //debuglibifaceptr->debuglib_printf(1, "Entering %s\n", __func__); //Once we have begin and end iterators we shouldn't need a lock to traverse the list unless we modify the contents webapiclientlibmutex.lock(); auto webapi_comms_queueitbegin=webapi_comms_queue.begin(); auto webapi_comms_queueitend=webapi_comms_queue.end(); webapiclientlibmutex.unlock(); std::list< std::list<webapiclient_comm_t *>::iterator > comms_to_remove; result=dblibifaceptr->begin(); if (result<0) { debuglibifaceptr->debuglib_printf(1, "%s: Failed to start database transaction\n", __func__); return; } for (auto &it=webapi_comms_queueitbegin; it!=webapi_comms_queueitend; it++) { int result; int64_t commpk; //Check the database to see if the link has already been added result=dblibifaceptr->getcommpk((*it)->addr, &commpk); if (result==0) { debuglibifaceptr->debuglib_printf(1, "%s: Going to remove Comm device from queue: %016" PRIX64 " as it is already in the database\n", __func__, (*it)->addr); comms_to_remove.push_back(it); } else if (result<-1) { debuglibifaceptr->debuglib_printf(1, "%s: Failed to check with database for Comm device: %016" PRIX64 ", postponing sending to webapi\n", __func__, (*it)->addr); } else { (*it)->okaytoadd=true; } } result=dblibifaceptr->end(); if (result<0) { dblibifaceptr->rollback(); } webapiclientlibmutex.lock(); for (auto const &it : comms_to_remove) { debuglibifaceptr->debuglib_printf(1, "%s: Removing Comm device from queue: %016" PRIX64 "\n", __func__, (*it)->addr); delete (*it); webapi_comms_queue.erase(it); } webapiclientlibmutex.unlock(); //debuglibifaceptr->debuglib_printf(1, "Exiting %s\n", __func__); } //Remove links from the webapi queue that don't need to be re-added void remove_already_added_links(void) { debuglib_ifaceptrs_ver_1_t *debuglibifaceptr=(debuglib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("debuglib", DEBUGLIBINTERFACE_VER_1); dblib_ifaceptrs_ver_1_t *dblibifaceptr=(dblib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("dblib", DBLIBINTERFACE_VER_1);; int result; //debuglibifaceptr->debuglib_printf(1, "Entering %s\n", __func__); //Once we have begin and end iterators we shouldn't need a lock to traverse the list unless we modify the contents webapiclientlibmutex.lock(); auto webapi_links_queueitbegin=webapi_links_queue.begin(); auto webapi_links_queueitend=webapi_links_queue.end(); webapiclientlibmutex.unlock(); std::list< std::list<webapiclient_link_t *>::iterator > links_to_remove; result=dblibifaceptr->begin(); if (result<0) { debuglibifaceptr->debuglib_printf(1, "%s: Failed to start database transaction\n", __func__); return; } for (auto &it=webapi_links_queueitbegin; it!=webapi_links_queueitend; it++) { int result; int64_t linkpk; //Check the database to see if the link has already been added result=dblibifaceptr->getlinkpk((*it)->addr, &linkpk); if (result==0) { debuglibifaceptr->debuglib_printf(1, "%s: Going to remove Link from queue: %016" PRIX64 " as it is already in the database\n", __func__, (*it)->addr); links_to_remove.push_back(it); } else if (result<-1) { debuglibifaceptr->debuglib_printf(1, "%s: Failed to check with database for Link: %016" PRIX64 ", postponding sending to webapi\n", __func__, (*it)->addr); } else { (*it)->okaytoadd=true; } } result=dblibifaceptr->end(); if (result<0) { dblibifaceptr->rollback(); } webapiclientlibmutex.lock(); for (auto const &it : links_to_remove) { debuglibifaceptr->debuglib_printf(1, "%s: Removing Link from queue: %016" PRIX64 "\n", __func__, (*it)->addr); delete (*it); webapi_links_queue.erase(it); } webapiclientlibmutex.unlock(); //debuglibifaceptr->debuglib_printf(1, "Exiting %s\n", __func__); } //Remove things from the webapi queue that don't need to be re-added void remove_already_added_things(void) { debuglib_ifaceptrs_ver_1_t *debuglibifaceptr=(debuglib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("debuglib", DEBUGLIBINTERFACE_VER_1); dblib_ifaceptrs_ver_1_t *dblibifaceptr=(dblib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("dblib", DBLIBINTERFACE_VER_1);; int result; //debuglibifaceptr->debuglib_printf(1, "Entering %s\n", __func__); //Once we have begin and end iterators we shouldn't need a lock to traverse the list unless we modify the contents webapiclientlibmutex.lock(); auto webapi_things_queueitbegin=webapi_things_queue.begin(); auto webapi_things_queueitend=webapi_things_queue.end(); webapiclientlibmutex.unlock(); std::list< std::list<webapiclient_thing_t *>::iterator > things_to_remove; result=dblibifaceptr->begin(); if (result<0) { debuglibifaceptr->debuglib_printf(1, "%s: Failed to start database transaction\n", __func__); return; } for (auto &it=webapi_things_queueitbegin; it!=webapi_things_queueitend; it++) { int result; int64_t thingpk; //Check the database to see if the thing has already been added result=dblibifaceptr->getthingpk((*it)->serialcode, (*it)->hwid, &thingpk); if (result==0) { debuglibifaceptr->debuglib_printf(1, "%s: Going to remove Thing from queue: %08" PRIX32 " as it is already in the database\n", __func__, (*it)->hwid); things_to_remove.push_back(it); } else if (result<-1) { debuglibifaceptr->debuglib_printf(1, "%s: Failed to check with database for Thing: %08" PRIX32 ", postponding sending to webapi\n", __func__, (*it)->hwid); } else { (*it)->okaytoadd=true; } } result=dblibifaceptr->end(); if (result<0) { dblibifaceptr->rollback(); } webapiclientlibmutex.lock(); for (auto const &it : things_to_remove) { debuglibifaceptr->debuglib_printf(1, "%s: Removing Thing from queue: %08" PRIX32 "\n", __func__, (*it)->hwid); delete (*it); webapi_things_queue.erase(it); } webapiclientlibmutex.unlock(); //debuglibifaceptr->debuglib_printf(1, "Exiting %s\n", __func__); } void update_timer_loop() { dblib_ifaceptrs_ver_1_t *dblibifaceptr=(dblib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("dblib", DBLIBINTERFACE_VER_1);; configlib_ifaceptrs_ver_1_cpp_t *configlibifaceptr=(configlib_ifaceptrs_ver_1_cpp_t *) webapiclientlib_getmoduledepifaceptr("configlib", CONFIGLIBINTERFACECPP_VER_1); debuglib_ifaceptrs_ver_1_t *debuglibifaceptr=(debuglib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("debuglib", DEBUGLIBINTERFACE_VER_1); boost::lock_guard<boost::mutex> guard(mtx_); timer.expires_from_now(boost::chrono::seconds(5)); timer.async_wait(boost::bind(&webapiclientloop_asyncloop::timer_handler, this, boost::asio::placeholders::error)); if (dblibifaceptr->is_initialised()) { set_hubpk_for_comm_devices(); remove_already_added_comm_devices(); set_locakpk_for_links(); remove_already_added_links(); set_linkpk_for_things(); remove_already_added_things(); std::string webapihostname="", webapiport="80", webapiurl="", webapihttpuser="", webapihttppass="", webapiuser="", webapipass=""; bool result, missingval=false; result=configlibifaceptr->getnamevalue_cpp("webapiconfig", "hostname", webapihostname); if (!result) { missingval=true; } result=configlibifaceptr->getnamevalue_cpp("webapiconfig", "port", webapiport); result=configlibifaceptr->getnamevalue_cpp("webapiconfig", "url", webapiurl); if (!result) { missingval=true; } configlibifaceptr->getnamevalue_cpp("webapiconfig", "httpusername", webapihttpuser); configlibifaceptr->getnamevalue_cpp("webapiconfig", "httppassword", webapihttppass); configlibifaceptr->getnamevalue_cpp("webapiconfig", "apiusername", webapiuser); configlibifaceptr->getnamevalue_cpp("webapiconfig", "apipassword", webapipass); if (!missingval && (!webapi_links_queue.empty() || !webapi_comms_queue.empty() || !webapi_things_queue.empty())) { debuglibifaceptr->debuglib_printf(1, "%s: Starting client connection\n", __func__); client.start(webapihostname, webapiport, webapiurl, webapiuser, webapipass, webapihttpuser, webapihttppass); } } } //Called every time the main timer triggers void timer_handler(const boost::system::error_code& error) { if (!webapiclientlib_getneedtoquit()) { update_timer_loop(); } } }; webapiclientloop_asyncloop gasyncloop; static void webapiclientlib_mainloop(void) { debuglib_ifaceptrs_ver_1_t *debuglibifaceptr=(debuglib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("debuglib", DEBUGLIBINTERFACE_VER_1); debuglibifaceptr->debuglib_printf(1, "Entering %s\n", __func__); while (!webapiclientlib_getneedtoquit()) { //Auto restart the loop if it crashes before we are ready to quit gasyncloop.start(); } debuglibifaceptr->debuglib_printf(1, "Exiting %s\n", __func__); } static boost::atomic<bool> webapiclientlib_needtoquit(false); static void webapiclientlib_setneedtoquit(bool val) { webapiclientlib_needtoquit.store(val); } static int webapiclientlib_getneedtoquit() { return webapiclientlib_needtoquit.load(); } static bool webapiclientlib_havemainthread=false; static int webapiclientlib_start(void) { debuglib_ifaceptrs_ver_1_t *debuglibifaceptr=(debuglib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("debuglib", DEBUGLIBINTERFACE_VER_1); int result=0; debuglibifaceptr->debuglib_printf(1, "Entering %s\n", __func__); if (!webapiclientlib_havemainthread) { try { debuglibifaceptr->debuglib_printf(1, "%s: Starting the main thread\n", __func__); webapiclientlib_mainthread=boost::thread(webapiclientlib_mainloop); webapiclientlib_havemainthread=true; } catch (boost::thread_resource_error& e) { debuglibifaceptr->debuglib_printf(1, "%s: Failed to spawn main thread\n", __func__); } } debuglibifaceptr->debuglib_printf(1, "Exiting %s\n", __func__); return result; } static void webapiclientlib_stop(void) { debuglib_ifaceptrs_ver_1_t *debuglibifaceptr=(debuglib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("debuglib", DEBUGLIBINTERFACE_VER_1); debuglibifaceptr->debuglib_printf(1, "Entering %s\n", __func__); if (webapiclientlib_havemainthread) { debuglibifaceptr->debuglib_printf(1, "%s: Cancelling the main thread\n", __func__); webapiclientlib_setneedtoquit(true); gasyncloop.stop(); webapiclientlib_mainthread.interrupt(); debuglibifaceptr->debuglib_printf(1, "%s: Waiting for main thread to exit\n", __func__); webapiclientlib_mainthread.join(); webapiclientlib_havemainthread=false; } debuglibifaceptr->debuglib_printf(1, "Exiting %s\n", __func__); } static int webapiclientlib_inuse=0; //Only do full shutdown when inuse = 0 static bool webapiclientlib_shuttingdown=false; static int webapiclientlib_init(void) { debuglib_ifaceptrs_ver_1_t *debuglibifaceptr=(debuglib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("debuglib", DEBUGLIBINTERFACE_VER_1); dblib_ifaceptrs_ver_1_t *dblibifaceptr=(dblib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("dblib", DBLIBINTERFACE_VER_1);; debuglibifaceptr->debuglib_printf(1, "Entering %s\n", __func__); if (webapiclientlib_shuttingdown) { debuglibifaceptr->debuglib_printf(1, "Exiting %s, already shutting down\n", __func__); return -1; } ++webapiclientlib_inuse; if (webapiclientlib_inuse>1) { //Already initialised debuglibifaceptr->debuglib_printf(1, "Exiting %s, already initialised, use count=%d\n", __func__, webapiclientlib_inuse); return -1; } //Let the database library know that we want to use it dblibifaceptr->init(); webapiclientlib_needtoquit=false; debuglibifaceptr->debuglib_printf(1, "Exiting %s\n", __func__); return 0; } static void webapiclientlib_shutdown(void) { debuglib_ifaceptrs_ver_1_t *debuglibifaceptr=(debuglib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("debuglib", DEBUGLIBINTERFACE_VER_1); dblib_ifaceptrs_ver_1_t *dblibifaceptr=(dblib_ifaceptrs_ver_1_t *) webapiclientlib_getmoduledepifaceptr("dblib", DBLIBINTERFACE_VER_1);; debuglibifaceptr->debuglib_printf(1, "Entering %s\n", __func__); if (webapiclientlib_inuse==0) { //Already uninitialised debuglibifaceptr->debuglib_printf(1, "WARNING: Exiting %s, Already shutdown\n", __func__); return; } --webapiclientlib_inuse; if (webapiclientlib_inuse>0) { //Module still in use debuglibifaceptr->debuglib_printf(1, "Exiting %s, Still in use, use count=%d\n", __func__, webapiclientlib_inuse); return; } //Start shutting down library webapiclientlib_shuttingdown=true; //Finished using the database library dblibifaceptr->shutdown(); for (auto const &it : webapi_links_queue) { delete it; } webapi_links_queue.clear(); for (auto const &it : webapi_comms_queue) { delete it; } webapi_comms_queue.clear(); debuglibifaceptr->debuglib_printf(1, "Exiting %s\n", __func__); //Finished shutting down webapiclientlib_shuttingdown=false; } moduleinfo_ver_generic_t *webapiclientlib_getmoduleinfo() { return (moduleinfo_ver_generic_t *) &webapiclientlib_moduleinfo_ver_1; } #ifdef __ANDROID__ JNIEXPORT jlong JNICALL Java_com_capsicumcorp_iomy_libraries_watchinputs_WebApiClientLib_jnigetmodulesinfo( JNIEnv* UNUSED(env), jobject UNUSED(obj)) { return (jlong) webapiclientlib_getmoduleinfo(); } #endif
# LAR input: is a collection of five random cubes in the same 3D space # REMARK: is not a cellular complex; cells intersect out of boundaries # julia> @show V,FV,EV; (V, FV, EV) = ([1.01181 0.215639 0.91979 0.123616 1.02252 0.226347 0.930498 0.134324 0.0458309 -0.301827 0.348275 0.0006172 0.579367 0.23171 0.881811 0.534154 -0.0521776 0.627953 -0.190635 0.489496 -0.0233884 0.656742 -0.161846 0.518285 0.27652 -0.0875132 0.52527 0.161237 0.509324 0.145291 0.758074 0.394041 0.27631 0.564484 0.0058279 0.294002 1.01221 1.30039 0.741732 1.02991; 0.160033 0.0680099 0.956278 0.864255 0.160649 0.0686266 0.956895 0.864872 -0.200245 0.102199 0.417839 0.720283 -0.35354 -0.0510965 0.264543 0.566987 0.682359 0.543901 0.0592036 -0.0792537 0.956374 0.817917 0.333219 0.194762 -0.102028 0.146722 0.324834 0.573584 -0.16916 0.0795901 0.257702 0.506452 0.452356 0.181874 1.15396 0.883481 0.816151 0.545669 1.51776 1.24728; 0.196256 0.206963 0.196872 0.20758 0.997729 1.00844 0.998346 1.00905 0.0677451 0.601282 -0.0855504 0.447986 0.502301 1.03584 0.349005 0.882542 0.159301 0.18809 0.433316 0.462105 0.797002 0.825792 1.07102 1.09981 0.1446 0.377404 0.0774682 0.310272 0.580364 0.813168 0.513232 0.746036 0.403805 1.13971 0.767599 1.5035 0.249344 0.985248 0.613139 1.34904], Array{Int64,1}[[1,2,3,4],[5,6,7,8],[1,2,5,6],[3,4,7,8],[1,3,5,7],[2,4,6,8],[9,10,11,12],[13,14,15,16],[9,10,13,14],[11,12,15,16],[9,11,13,15],[10,12,14,16],[17,18,19,20],[21,22,23,24],[17,18,21,22],[19,20,23,24],[17,19,21,23],[18,20,22,24],[25,26,27,28],[29,30,31,32],[25,26,29,30],[27,28,31,32],[25,27,29,31],[26,28,30,32],[33,34,35,36],[37,38,39,40],[33,34,37,38],[35,36,39,40],[33,35,37,39],[34,36,38,40]],Array{Int64,1}[[1,2],[3,4],[5,6],[7,8],[1,3],[2,4],[5,7],[6,8],[1,5],[2,6],[3,7],[4,8],[9,10],[11,12],[13,14],[15,16],[9,11],[10,12],[13,15],[14,16],[9,13],[10,14],[11,15],[12,16],[17,18],[19,20],[21,22],[23,24],[17,19],[18,20],[21,23],[22,24],[17,21],[18,22],[19,23],[20,24],[25,26],[27,28],[29,30],[31,32],[25,27],[26,28],[29,31],[30,32],[25,29],[26,30],[27,31],[28,32],[33,34],[35,36],[37,38],[39,40],[33,35],[34,36],[37,39],[38,40],[33,37],[34,38],[35,39],[36,40]])
module ColorTypes using Color, FixedPointNumbers, Base.Cartesian import Color: Fractional, _convert import Base: ==, abs, abs2, clamp, convert, div, isfinite, isinf, isnan, isless, length, one, promote_array_type, promote_rule, zero, trunc, floor, round, ceil, itrunc, ifloor, iceil, iround, bswap, mod, rem export ARGB, BGR, RGB1, RGB4, BGRA, AbstractGray, Gray, GrayAlpha, Gray24, AGray32, YIQ, AlphaColor, ColorType, noeltype typealias ColorType Union(ColorValue, AbstractAlphaColorValue) # An alpha-channel-first memory layout immutable AlphaColor{C<:ColorValue, T<:Fractional} <: AbstractAlphaColorValue{C,T} alpha::T c::C AlphaColor(x1::Real, x2::Real, x3::Real, alpha::Real = 1.0) = new(alpha, C(x1, x2, x3)) AlphaColor(c::ColorValue, alpha::Real) = new(alpha, c) end AlphaColor{T<:Fractional}(c::ColorValue{T}, alpha::T = one(T)) = AlphaColor{typeof(c),T}(c, alpha) typealias ARGB{T} AlphaColor{RGB{T}, T} # Little-endian RGB (useful for BGRA & Cairo) immutable BGR{T<:Fractional} <: AbstractRGB{T} b::T g::T r::T BGR(r::Real, g::Real, b::Real) = new(b, g, r) end BGR(r::Integer, g::Integer, b::Integer) = BGR{Float64}(r, g, b) BGR(r::Fractional, g::Fractional, b::Fractional) = (T = promote_type(typeof(r), typeof(g), typeof(b)); BGR{T}(r, g, b)) typealias BGRA{T} AlphaColorValue{BGR{T}, T} # Some readers return a byte for an alpha channel even if it's not meaningful immutable RGB1{T<:Fractional} <: AbstractRGB{T} alphadummy::T r::T g::T b::T RGB1(r::Real, g::Real, b::Real) = new(one(T), r, g, b) end RGB1(r::Integer, g::Integer, b::Integer) = RGB1{Float64}(r, g, b) RGB1(r::Fractional, g::Fractional, b::Fractional) = (T = promote_type(typeof(r), typeof(g), typeof(b)); RGB1{T}(r, g, b)) immutable RGB4{T<:Fractional} <: AbstractRGB{T} r::T g::T b::T alphadummy::T RGB4(r::Real, g::Real, b::Real) = new(r, g, b, one(T)) end RGB4(r::Integer, g::Integer, b::Integer) = RGB4{Float64}(r, g, b) RGB4(r::Fractional, g::Fractional, b::Fractional) = (T = promote_type(typeof(r), typeof(g), typeof(b)); RGB4{T}(r, g, b)) for CV in subtypes(AbstractRGB) CV == RGB && continue @eval begin convert{T}(::Type{$CV{T}}, c::$CV{T}) = c convert(::Type{$CV}, c::$CV) = c convert{T}(::Type{$CV{T}}, c::$CV) = $CV{T}(convert(T, c.r), convert(T, c.g), convert(T, c.b)) convert{T<:Fractional}(::Type{$CV}, c::ColorValue{T}) = convert($CV{T}, c) convert(::Type{$CV}, c::AbstractRGB) = $CV(c.r, c.g, c.b) convert{T}(::Type{$CV{T}}, c::AbstractRGB) = $CV{T}(c.r, c.g, c.b) end end convert(::Type{RGB}, c::AbstractRGB) = RGB(c.r, c.g, c.b) convert{T}(::Type{RGB{T}}, c::AbstractRGB) = RGB{T}(c.r, c.g, c.b) # Sometimes you want to be explicit about grayscale. Also needed for GrayAlpha. abstract AbstractGray{T} <: ColorValue{T} immutable Gray{T<:Fractional} <: AbstractGray{T} val::T end convert{T}(::Type{Gray{T}}, x::Gray{T}) = x convert{T,S}(::Type{Gray{T}}, x::Gray{S}) = Gray{T}(x.val) convert{T<:Real}(::Type{T}, x::Gray) = convert(T, x.val) convert{T}(::Type{Gray{T}}, x::Real) = Gray{T}(x) convert{T}(::Type{Gray{T}}, x::AbstractRGB) = convert(Gray{T}, 0.299*x.r + 0.587*x.g + 0.114*x.b) # Rec 601 luma conversion zero{T}(::Type{Gray{T}}) = Gray{T}(zero(T)) one{T}(::Type{Gray{T}}) = Gray{T}(one(T)) immutable Gray24 <: ColorValue{Uint8} color::Uint32 end Gray24() = Gray24(0) Gray24(val::Uint8) = (g = uint32(val); g<<16 | g<<8 | g) Gray24(val::Ufixed8) = Gray24(reinterpret(val)) convert(::Type{Uint32}, g::Gray24) = g.color typealias GrayAlpha{T} AlphaColorValue{Gray{T}, T} immutable AGray32 <: AbstractAlphaColorValue{Gray24, Uint8} color::Uint32 end AGray32() = AGray32(0) AGray32(val::Uint8, alpha::Uint8) = (g = uint32(val); uint32(alpha)<<24 | g<<16 | g<<8 | g) AGray32(val::Ufixed8, alpha::Ufixed8) = AGray32(reinterpret(val), reinterpret(alpha)) convert(::Type{Uint32}, g::AGray32) = g.color convert(::Type{RGB}, x::Gray) = RGB(x.val, x.val, x.val) convert{T}(::Type{RGB{T}}, x::Gray) = (g = convert(T, x.val); RGB{T}(g, g, g)) # YIQ (NTSC) immutable YIQ{T<:FloatingPoint} <: ColorValue{T} y::T i::T q::T YIQ(y::Real, i::Real, q::Real) = new(y, i, q) end YIQ(y::FloatingPoint, i::FloatingPoint, q::FloatingPoint) = (T = promote_type(typeof(y), typeof(i), typeof(q)); YIQ{T}(y, i, q)) clamp{T}(c::YIQ{T}) = YIQ{T}(clamp(c.y, zero(T), one(T)), clamp(c.i, convert(T,-0.5957), convert(T,0.5957)), clamp(c.q, convert(T,-0.5226), convert(T,0.5226))) function convert{T}(::Type{YIQ{T}}, c::AbstractRGB) rgb = clamp(c) YIQ{T}(0.299*rgb.r+0.587*rgb.g+0.114*rgb.b, 0.595716*rgb.r-0.274453*rgb.g-0.321263*rgb.b, 0.211456*rgb.r-0.522591*rgb.g+0.311135*rgb.b) end convert{T}(::Type{YIQ}, c::AbstractRGB{T}) = convert(YIQ{T}, c) function _convert{T}(::Type{RGB{T}}, c::YIQ) cc = clamp(c) RGB{T}(cc.y+0.9563*cc.i+0.6210*cc.q, cc.y-0.2721*cc.i-0.6474*cc.q, cc.y-1.1070*cc.i+1.7046*cc.q) end # Y'CbCr immutable YCbCr{T<:FloatingPoint} <: ColorValue{T} y::T cb::T cr::T YCbCr(y::Real, cb::Real, cr::Real) = new(y, cb, cr) end function YCbCr(y::FloatingPoint, cb::FloatingPoint, cr::FloatingPoint) T = promote_type(typeof(y), typeof(cb), typeof(cr)) YCbCr{T}(y, cb, cr) end clamp{T}(c::YCbCr{T}) = YCbCr{T}(clamp(c.y, convert(T,16), convert(T,235)), clamp(c.cb, convert(T,16), convert(T,240)), clamp(c.cr, convert(T,16), convert(T,240))) function convert{T}(::Type{YCbCr{T}}, c::AbstractRGB) rgb = clamp(c) YCbCr{T}(16+65.481*rgb.r+128.553*rgb.g+24.966*rgb.b, 128-37.797*rgb.r-74.203*rgb.g+112*rgb.b, 128+112*rgb.r-93.786*rgb.g-18.214*rgb.b) end convert{T}(::Type{YCbCr}, c::AbstractRGB{T}) = convert(YCbCr{T}, c) function _convert{T}(::Type{RGB{T}}, c::YCbCr) cc = clamp(c) ny = cc.y - 16 ncb = cc.cb - 128 ncr = cc.cr - 128 RGB{T}(0.004567ny - 1.39135e-7ncb + 0.0062586ncr, 0.004567ny - 0.00153646ncb - 0.0031884ncr, 0.004567ny + 0.00791058ncb - 2.79201e-7ncr) end # HSI immutable HSI{T<:FloatingPoint} <: ColorValue{T} h::T s::T i::T HSI(h::Real, s::Real, i::Real) = new(h, s, i) end function HSI(h::FloatingPoint, s::FloatingPoint, i::FloatingPoint) T = promote_type(typeof(h), typeof(s), typeof(i)) HSI{T}(h, s, i) end function convert{T}(::Type{HSI{T}}, c::AbstractRGB) rgb = clamp(c) α = (2rgb.r - rgb.g - rgb.b)/2 β = 0.8660254*(rgb.g - rgb.b) h = atan2(β, α) i = (rgb.r + rgb.g + rgb.b)/3 s = 1-min(rgb.r, rgb.g, rgb.b)/i s = ifelse(i > 0, s, zero(s)) HSI{T}(h, s, i) end convert{T}(::Type{HSI}, c::AbstractRGB{T}) = convert(HSI{T}, c) # TODO: HSI->RGB ## Generic algorithms length(cv::ColorType) = div(sizeof(cv), sizeof(eltype(cv))) # Because this can be called as `length(RGB)`, we might need to fill in a default element type. # But the compiler chokes if we ask it to create RGB{Float64}{Float64}, even if that's inside # the non-evaluated branch of a ternary expression, so we have to be sneaky about this. length{CV<:ColorValue}(::Type{CV}) = _length(CV, eltype(CV)) _length{CV<:ColorValue}(::Type{CV}, ::Type{Any}) = length(CV{Float64}) _length{CV<:ColorValue}(::Type{CV}, ::DataType) = div(sizeof(CV), sizeof(eltype(CV))) length{CV,T}(::Type{AlphaColorValue{CV,T}}) = length(CV)+1 length{CV,T}(::Type{AlphaColor{CV,T}}) = length(CV)+1 for ACV in (ColorValue, AbstractRGB, AbstractGray, AbstractAlphaColorValue) for CV in subtypes(ACV) length(CV.parameters) == 1 || continue @eval noeltype{T}(::Type{$CV{T}}) = $CV end end for f in (:trunc, :floor, :round, :ceil, :itrunc, :ifloor, :iceil, :iround, :abs, :abs2, :isfinite, :isnan, :isinf, :bswap) @eval $f{T}(g::Gray{T}) = Gray{T}($f(g.val)) @eval @vectorize_1arg Gray $f end for f in (:mod, :rem, :mod1) @eval $f(x::Gray, m::Gray) = Gray($f(x.val, m.val)) @eval @vectorize_2arg Gray $f end # Return types for arithmetic operations multype(a::Type,b::Type) = typeof(one(a)*one(b)) sumtype(a::Type,b::Type) = typeof(one(a)+one(b)) divtype(a::Type,b::Type) = typeof(one(a)/one(b)) # Math on ColorValues. These implementations encourage inlining and, # for the case of Ufixed types, nearly halve the number of multiplications. for CV in subtypes(AbstractRGB) @eval begin (*){R<:Real,T}(f::R, c::$CV{T}) = $CV{multype(R,T)}(f*c.r, f*c.g, f*c.b) (*){R<:Real,T}(f::R, c::AlphaColorValue{$CV{T},T}) = AlphaColorValue{$CV{multype(R,T)},multype(R,T)}(f*c.c.r, f*c.c.g, f*c.c.b, f*c.alpha) (*){R<:Real,T}(f::R, c::AlphaColor{$CV{T},T}) = AlphaColor{$CV{multype(R,T)},multype(R,T)}(f*c.c.r, f*c.c.g, f*c.c.b, f*c.alpha) function (*){R<:FloatingPoint,T<:Ufixed}(f::R, c::$CV{T}) fs = f/reinterpret(one(T)) $CV{multype(R,T)}(fs*reinterpret(c.r), fs*reinterpret(c.g), fs*reinterpret(c.b)) end function (*){R<:Ufixed,T<:Ufixed}(f::R, c::$CV{T}) fs = reinterpret(f)/widen(reinterpret(one(T)))^2 $CV{multype(R,T)}(fs*reinterpret(c.r), fs*reinterpret(c.g), fs*reinterpret(c.b)) end function (/){R<:FloatingPoint,T<:Ufixed}(c::$CV{T}, f::R) fs = one(R)/(f*reinterpret(one(T))) $CV{divtype(R,T)}(fs*reinterpret(c.r), fs*reinterpret(c.g), fs*reinterpret(c.b)) end (+){S,T}(a::$CV{S}, b::$CV{T}) = $CV{sumtype(S,T)}(a.r+b.r, a.g+b.g, a.b+b.b) (-){S,T}(a::$CV{S}, b::$CV{T}) = $CV{sumtype(S,T)}(a.r-b.r, a.g-b.g, a.b-b.b) (+){S,T}(a::AlphaColorValue{$CV{S},S}, b::AlphaColorValue{$CV{T},T}) = AlphaColorValue{$CV{sumtype(S,T)},sumtype(S,T)}(a.c.r+b.c.r, a.c.g+b.c.g, a.c.b+b.c.b, a.alpha+b.alpha) (+){S,T}(a::AlphaColor{$CV{S},S}, b::AlphaColor{$CV{T},T}) = AlphaColor{$CV{sumtype(S,T)},sumtype(S,T)}(a.c.r+b.c.r, a.c.g+b.c.g, a.c.b+b.c.b, a.alpha+b.alpha) (-){S,T}(a::AlphaColorValue{$CV{S},S}, b::AlphaColorValue{$CV{T},T}) = AlphaColorValue{$CV{sumtype(S,T)},sumtype(S,T)}(a.c.r-b.c.r, a.c.g-b.c.g, a.c.b-b.c.b, a.alpha-b.alpha) (-){S,T}(a::AlphaColor{$CV{S},S}, b::AlphaColor{$CV{T},T}) = AlphaColor{$CV{sumtype(S,T)},sumtype(S,T)}(a.c.r-b.c.r, a.c.g-b.c.g, a.c.b-b.c.b, a.alpha-b.alpha) function (.+){T}(A::AbstractArray{$CV{T}}, b::AbstractRGB) bT = convert($CV{T}, b) out = similar(A) add!(out, A, bT) end function (.+){T}(A::Union(AbstractArray{AlphaColorValue{$CV{T},T}}, AbstractArray{AlphaColor{$CV{T},T}}), b::AbstractAlphaColorValue) bT = convert($CV{T}, b) out = similar(A) add!(out, A, bT) end (.+){T}(b::AbstractRGB, A::AbstractArray{$CV{T}}) = (.+)(A, b) (.+){T}(b::AbstractAlphaColorValue, A::Union(AbstractArray{AlphaColorValue{$CV{T},T}}, AbstractArray{AlphaColor{$CV{T},T}})) = (.+)(A, b) function (.-){T}(A::AbstractArray{$CV{T}}, b::AbstractRGB) bT = convert($CV{T}, b) out = similar(A) sub!(out, A, bT) end function (.-){T}(A::Union(AbstractArray{AlphaColorValue{$CV{T},T}}, AbstractArray{AlphaColor{$CV{T},T}}), b::AbstractAlphaColorValue) bT = convert($CV{T}, b) out = similar(A) sub!(out, A, bT) end function (.-){T}(b::AbstractRGB, A::AbstractArray{$CV{T}}) bT = convert($CV{T}, b) out = similar(A) sub!(out, bT, A) end function (.-){T}(b::AbstractAlphaColorValue, A::Union(AbstractArray{AlphaColorValue{$CV{T},T}}, AbstractArray{AlphaColor{$CV{T},T}})) bT = convert($CV{T}, b) out = similar(A) sub!(out, bT, A) end isfinite{T<:Ufixed}(c::$CV{T}) = true isfinite{T<:Ufixed}(c::AbstractAlphaColorValue{$CV{T},T}) = true isfinite{T<:FloatingPoint}(c::$CV{T}) = isfinite(c.r) && isfinite(c.g) && isfinite(c.b) isfinite{T<:FloatingPoint}(c::AbstractAlphaColorValue{$CV{T},T}) = isfinite(c.c.r) && isfinite(c.c.g) && isfinite(c.c.b) && isfinite(c.alpha) isnan{T<:Ufixed}(c::$CV{T}) = false isnan{T<:Ufixed}(c::AbstractAlphaColorValue{$CV{T},T}) = false isnan{T<:FloatingPoint}(c::$CV{T}) = isnan(c.r) || isnan(c.g) || isnan(c.b) isnan{T<:FloatingPoint}(c::AbstractAlphaColorValue{$CV{T},T}) = isnan(c.c.r) || isnan(c.c.g) || isnan(c.c.b) || isnan(c.alpha) isinf{T<:Ufixed}(c::$CV{T}) = false isinf{T<:Ufixed}(c::AbstractAlphaColorValue{$CV{T},T}) = false isinf{T<:FloatingPoint}(c::$CV{T}) = isinf(c.r) || isinf(c.g) || isinf(c.b) isinf{T<:FloatingPoint}(c::AbstractAlphaColorValue{$CV{T},T}) = isinf(c.c.r) || isinf(c.c.g) || isinf(c.c.b) || isinf(c.alpha) abs(c::$CV) = abs(c.r)+abs(c.g)+abs(c.b) # should this have a different name? abs{T<:Ufixed}(c::$CV{T}) = float32(c.r)+float32(c.g)+float32(c.b) # should this have a different name? one{T<:ColorType}(::T) = one(T) one{T}(::Type{$CV{T}}) = $CV{T}(one(T),one(T),one(T)) one{T}(::Type{AlphaColorValue{$CV{T},T}}) = AlphaColorValue{$CV{T},T}(one(T),one(T),one(T),one(T)) one{T}(::Type{AlphaColor{$CV{T},T}}) = AlphaColorValue{$CV{T},T}(one(T),one(T),one(T),one(T)) zero{T<:ColorType}(::T) = zero(T) zero{T}(::Type{$CV{T}}) = $CV{T}(zero(T),zero(T),zero(T)) zero{T}(::Type{AlphaColorValue{$CV{T},T}}) = AlphaColorValue{$CV{T},T}(zero(T),zero(T),zero(T),zero(T)) zero{T}(::Type{AlphaColor{$CV{T},T}}) = AlphaColorValue{$CV{T},T}(zero(T),zero(T),zero(T),zero(T)) end end (*)(c::AbstractRGB, f::Real) = (*)(f, c) (*){CV<:AbstractRGB}(c::AlphaColorValue{CV}, f::Real) = (*)(f, c) (*){CV<:AbstractRGB}(c::AlphaColor{CV}, f::Real) = (*)(f, c) (.*)(f::Real, c::AbstractRGB) = (*)(f, c) (.*){CV<:AbstractRGB}(f::Real, c::AlphaColorValue{CV}) = (*)(f, c) (.*){CV<:AbstractRGB}(f::Real, c::AlphaColor{CV}) = (*)(f, c) (.*)(c::AbstractRGB, f::Real) = (*)(f, c) (.*){CV<:AbstractRGB}(c::AlphaColorValue{CV}, f::Real) = (*)(f, c) (.*){CV<:AbstractRGB}(c::AlphaColor{CV}, f::Real) = (*)(f, c) (/)(c::AbstractRGB, f::Real) = (one(f)/f)*c (/){CV<:AbstractRGB}(c::AlphaColorValue{CV}, f::Real) = (one(f)/f)*c (/){CV<:AbstractRGB}(c::AlphaColor{CV}, f::Real) = (one(f)/f)*c (/)(c::AbstractRGB, f::Integer) = (one(eltype(c))/f)*c (/){CV<:AbstractRGB}(c::AlphaColorValue{CV}, f::Integer) = (one(eltype(c))/f)*c (/){CV<:AbstractRGB}(c::AlphaColor{CV}, f::Integer) = (one(eltype(c))/f)*c (./)(c::AbstractRGB, f::Real) = (/)(c, f) (./){CV<:AbstractRGB}(c::AlphaColorValue{CV}, f::Real) = (/)(c, f) (./){CV<:AbstractRGB}(c::AlphaColor{CV}, f::Real) = (/)(c, f) (+){CV<:AbstractRGB}(A::AbstractArray{CV}, b::AbstractRGB) = (.+)(A, b) (+){CV<:AbstractRGB,T,CV2<:AbstractRGB}(A::AbstractArray{AlphaColorValue{CV,T}}, b::AbstractAlphaColorValue{CV2}) = (.+)(A, b) (+){CV<:AbstractRGB,T,CV2<:AbstractRGB}(A::AbstractArray{AlphaColor{CV,T}}, b::AbstractAlphaColorValue{CV2}) = (.+)(A, b) (-){CV<:AbstractRGB}(A::AbstractArray{CV}, b::AbstractRGB) = (.-)(A, b) (-){CV<:AbstractRGB,T,CV2<:AbstractRGB}(A::AbstractArray{AlphaColorValue{CV,T}}, b::AbstractAlphaColorValue{CV2}) = (.-)(A, b) (-){CV<:AbstractRGB,T,CV2<:AbstractRGB}(A::AbstractArray{AlphaColor{CV,T}}, b::AbstractAlphaColorValue{CV2}) = (.-)(A, b) (+){CV<:AbstractRGB}(b::AbstractRGB, A::AbstractArray{CV}) = (.+)(b, A) (+){CV<:AbstractRGB,T,CV2<:AbstractRGB}(b::AbstractAlphaColorValue{CV2}, A::AbstractArray{AlphaColorValue{CV,T}}) = (.+)(A, b) (+){CV<:AbstractRGB,T,CV2<:AbstractRGB}(b::AbstractAlphaColorValue{CV2}, A::AbstractArray{AlphaColor{CV,T}}) = (.+)(A, b) (-){CV<:AbstractRGB}(b::AbstractRGB, A::AbstractArray{CV}) = (.-)(b, A) (-){CV<:AbstractRGB,T,CV2<:AbstractRGB}(b::AbstractAlphaColorValue{CV2}, A::AbstractArray{AlphaColorValue{CV,T}}) = (.-)(A, b) (-){CV<:AbstractRGB,T,CV2<:AbstractRGB}(b::AbstractAlphaColorValue{CV2}, A::AbstractArray{AlphaColor{CV,T}}) = (.-)(A, b) # Math on Gray for CV in subtypes(AbstractGray) @eval begin (*){R<:Real,T}(f::R, c::$CV{T}) = $CV{multype(R,T)}(f*c.val) (*)(c::$CV, f::Real) = (*)(f, c) (.*)(f::Real, c::$CV) = (*)(f, c) (.*)(c::$CV, f::Real) = (*)(f, c) (/)(c::$CV, f::Real) = (one(f)/f)*c (/)(c::$CV, f::Integer) = (one(eltype(c))/f)*c (./)(c::$CV, f::Real) = (/)(c, f) (+){S,T}(a::$CV{S}, b::$CV{T}) = $CV{sumtype(S,T)}(a.val+b.val) (-){S,T}(a::$CV{S}, b::$CV{T}) = $CV{sumtype(S,T)}(a.val-b.val) (*){S,T}(a::$CV{S}, b::$CV{T}) = $CV{multype(S,T)}(a.val*b.val) (+)(A::AbstractArray{$CV}, b::AbstractGray) = (.+)(A, b) (-)(A::AbstractArray{$CV}, b::AbstractGray) = (.-)(A, b) (+)(b::AbstractGray, A::AbstractArray{$CV}) = (.+)(b, A) (-)(b::AbstractGray, A::AbstractArray{$CV}) = (.-)(b, A) function (.+){T}(A::AbstractArray{$CV{T}}, b::AbstractGray) bT = convert($CV{T}, b) out = similar(A) add!(out, A, bT) end (.+){T}(b::AbstractGray, A::AbstractArray{$CV{T}}) = (.+)(A, b) function (.-){T}(A::AbstractArray{$CV{T}}, b::AbstractGray) bT = convert($CV{T}, b) out = similar(A) sub!(out, A, bT) end function (.-){T}(A::AbstractArray{$CV{T}}, b::AbstractGray) bT = convert($CV{T}, b) out = similar(A) sub!(out, A, bT) end function (.-){T}(b::AbstractGray, A::AbstractArray{$CV{T}}) bT = convert($CV{T}, b) out = similar(A) sub!(out, bT, A) end (*)(A::AbstractArray, b::AbstractGray) = A .* b (*)(b::AbstractGray, A::AbstractArray) = b .* A (/)(A::AbstractArray, b::AbstractGray) = A ./ b function (.*){T,S}(A::AbstractArray{$CV{T}}, b::AbstractGray{S}) Tout = multype(T,S) out = similar(A, $CV{Tout}) mul!(out, A, b) end (.*){T,S}(b::AbstractGray{S}, A::AbstractArray{$CV{T}}) = A .* b function (./){T,S}(A::AbstractArray{$CV{T}}, b::AbstractGray{S}) Tout = divtype(T,S) out = similar(A, $CV{Tout}) div!(out, A, b) end isfinite{T<:Ufixed}(c::$CV{T}) = true isfinite{T<:FloatingPoint}(c::$CV{T}) = isfinite(c.val) isnan{T<:Ufixed}(c::$CV{T}) = false isnan{T<:FloatingPoint}(c::$CV{T}) = isnan(c.val) isinf{T<:Ufixed}(c::$CV{T}) = false isinf{T<:FloatingPoint}(c::$CV{T}) = isinf(c.val) abs(c::$CV) = abs(c.val) # should this have a different name? abs{T<:Ufixed}(c::$CV{T}) = float32(c.val) # should this have a different name? (<)(c::$CV, r::Real) = c.val < r (<)(r::Real, c::$CV) = r < c.val isless(c::$CV, r::Real) = c.val < r isless(r::Real, c::$CV) = r < c.val (<)(a::$CV, b::AbstractGray) = a.val < b.val end end (/)(a::AbstractGray, b::AbstractGray) = a.val/b.val div(a::AbstractGray, b::AbstractGray) = div(a.val, b.val) (+)(a::AbstractGray, b::Number) = a.val+b (-)(a::AbstractGray, b::Number) = a.val-b (+)(a::Number, b::AbstractGray) = a+b.val (-)(a::Number, b::AbstractGray) = a-b.val (.+)(a::AbstractGray, b::Number) = a.val+b (.-)(a::AbstractGray, b::Number) = a.val-b (.+)(a::Number, b::AbstractGray) = a+b.val (.-)(a::Number, b::AbstractGray) = a-b.val @ngenerate N typeof(out) function add!{T,N}(out, A::AbstractArray{T,N}, b) @inbounds begin @nloops N i A begin @nref(N, out, i) = @nref(N, A, i) + b end end out end # need a separate sub! because of unsigned types @ngenerate N typeof(out) function sub!{T,N}(out, A::AbstractArray{T,N}, b::ColorType) # TODO: change to b::T when julia #8045 fixed @inbounds begin @nloops N i A begin @nref(N, out, i) = @nref(N, A, i) - b end end out end @ngenerate N typeof(out) function sub!{T,N}(out, b::ColorType, A::AbstractArray{T,N}) @inbounds begin @nloops N i A begin @nref(N, out, i) = b - @nref(N, A, i) end end out end @ngenerate N typeof(out) function mul!{T,N}(out, A::AbstractArray{T,N}, b) @inbounds begin @nloops N i A begin @nref(N, out, i) = @nref(N, A, i) * b end end out end @ngenerate N typeof(out) function div!{T,N}(out, A::AbstractArray{T,N}, b) @inbounds begin @nloops N i A begin @nref(N, out, i) = @nref(N, A, i) / b end end out end # To help type inference for ACV in (ColorValue, AbstractRGB, AbstractGray) for CV in subtypes(ACV) (length(CV.parameters) == 1 && !(CV.abstract)) || continue @eval promote_array_type{T<:Real,S<:Real}(::Type{T}, ::Type{$CV{S}}) = $CV{promote_type(T, S)} @eval promote_rule{T<:Fractional,S<:Fractional}(::Type{$CV{T}}, ::Type{$CV{S}}) = $CV{promote_type(T, S)} for AC in subtypes(AbstractAlphaColorValue) (length(AC.parameters) == 2 && !(AC.abstract)) || continue @eval promote_array_type{T<:Real,S<:Real}(::Type{T}, ::Type{$AC{$CV{S},S}}) = (TS = promote_type(T, S); $AC{$CV{TS}, TS}) @eval promote_rule{T<:Fractional,S<:Fractional}(::Type{$CV{T}}, ::Type{$CV{S}}) = $CV{promote_type(T, S)} @eval promote_rule{T<:Fractional,S<:Integer}(::Type{$CV{T}}, ::Type{S}) = $CV{promote_type(T, S)} # for Array{RGB}./Array{Int} end end end for (CV, CVstr, fields) in ((BGR, "BGR", (:(c.r),:(c.g),:(c.b))), (RGB1, "RGB1", (:(c.r),:(c.g),:(c.b))), (RGB4, "RGB4", (:(c.r),:(c.g),:(c.b))), (ARGB, "ARGB", (:(c.c.r),:(c.c.g),:(c.c.b),:(c.alpha))), (BGRA, "BGRA", (:(c.c.r),:(c.c.g),:(c.c.b),:(c.alpha))), (Gray, "Gray", (:(c.val),)), (GrayAlpha, "GrayAlpha", (:(c.c.val),:(c.alpha)))) Color.makeshow(CV, CVstr, fields) end for T in (RGB24, ARGB32, Gray24, AGray32) @eval begin ==(x::Uint32, y::$T) = x == convert(Uint32, y) ==(x::$T, y::Uint32) = ==(y, x) end end =={T}(x::Gray{T}, y::Gray{T}) = x.val == y.val =={T}(x::T, y::Gray{T}) = x == convert(T, y) =={T}(x::Gray{T}, y::T) = ==(y, x) end
import Data.Vect --data Option t = Some t | None data Option : (t:Type) -> Type where Some : (value:t) -> Option t None : Option t add : Int -> Int -> Int add x y = x + y StringOrNat : Nat -> Type StringOrNat Z = String StringOrNat (S K) = Nat divide : (x:Nat) -> (y:Nat) -> StringOrNat y divide x Z = "Divisor was 0" divide x y @ (S k) = div x y
import functools from absl.testing import absltest from absl.testing import parameterized import jax from jax import numpy as jnp from daves_rl_lib.brax_stuff import trivial_environment class TrivialEnvironmentTests(parameterized.TestCase): def test_one_dim_transitions(self): env = trivial_environment.DiscreteTargetEnvironment(size=3, dim=1) self.assertEqual(env.action_size, 2) state = env.reset(seed=None) self.assertSequenceEqual(state.obs, [0]) # Move left until we bounce off the edge. for expected_idx in (-1, -2, -3, -3, -3): state = env.step(state, 0) self.assertSequenceEqual(state.obs, [expected_idx]) self.assertFalse(state.done) self.assertEqual(state.reward, 0.) # Now move right for expected_idx in (-2, -1, 0, 1, 2): state = env.step(state, 1) self.assertSequenceEqual(state.obs, [expected_idx]) self.assertFalse(state.done) self.assertEqual(state.reward, 0.) # Transition to terminal state state = env.step(state, 1) self.assertSequenceEqual(state.obs, [3]) self.assertTrue(state.done) self.assertEqual(state.reward, 1.) # Actions in terminal state are no-ops with no reward. state = env.step(state, 0) self.assertSequenceEqual(state.obs, [3]) self.assertTrue(state.done) self.assertEqual(state.reward, 0.) def test_multi_dim_transitions(self): env = trivial_environment.DiscreteTargetEnvironment(size=2, dim=2) self.assertEqual(env.action_size, 4) state = env.reset(seed=None) self.assertSequenceEqual(state.obs, (0, 0)) for (action, expected_obs) in ((1, (0, -1)), (1, (0, -2)), (1, (0, -2)), (0, (-1, -2)), (2, (0, -2)), (2, (1, -2)), (2, (2, -2)), (3, (2, -1))): state = env.step(state, action) self.assertSequenceEqual(state.obs, expected_obs) self.assertFalse(state.done) self.assertEqual(state.reward, 0.) # Transition to terminal state state = env.step(state, 3) self.assertSequenceEqual(state.obs, (2, 0)) self.assertTrue(state.done) self.assertEqual(state.reward, 1.) # Actions in terminal state are no-ops with no reward. state = env.step(state, 0) self.assertSequenceEqual(state.obs, (2, 0)) self.assertTrue(state.done) self.assertEqual(state.reward, 0.) if __name__ == '__main__': absltest.main()
Require Import CodeDeps. Require Import Ident. Local Open Scope Z_scope. Definition _cntp_ctl := 1%positive. Definition _cntv_ctl := 2%positive. Definition _emulated_timer_state := 3%positive. Definition _g := 4%positive. Definition _g_rec := 5%positive. Definition _granule := 6%positive. Definition _i := 7%positive. Definition _lock := 8%positive. Definition _rec := 9%positive. Definition _rec__1 := 10%positive. Definition _rec_rvic_state := 11%positive. Definition _ret := 12%positive. Definition _t'1 := 13%positive. Definition _t'2 := 14%positive. Definition _t'3 := 15%positive. Definition _t'4 := 16%positive. Definition _t'5 := 17%positive. Definition _t'6 := 18%positive. Definition _t'7 := 19%positive. Definition check_pending_ptimers_body := (Ssequence (Ssequence (Scall (Some _t'1) (Evar _get_rec_g_rec (Tfunction (Tcons (tptr Tvoid) Tnil) (tptr Tvoid) cc_default)) ((Etempvar _rec (tptr Tvoid)) :: nil)) (Sset _g_rec (Etempvar _t'1 (tptr Tvoid)))) (Ssequence (Ssequence (Scall (Some _t'2) (Evar _sysreg_read (Tfunction (Tcons tuint Tnil) tulong cc_default)) ((Econst_int (Int.repr 32) tuint) :: nil)) (Sset _cntp_ctl (Etempvar _t'2 tulong))) (Ssequence (Ssequence (Scall (Some _t'6) (Evar _get_rec_ptimer (Tfunction (Tcons (tptr Tvoid) Tnil) (tptr Tvoid) cc_default)) ((Etempvar _rec (tptr Tvoid)) :: nil)) (Scall (Some _t'7) (Evar _check_timer_became_asserted (Tfunction (Tcons (tptr Tvoid) (Tcons tulong Tnil)) tuint cc_default)) ((Etempvar _t'6 (tptr Tvoid)) :: (Etempvar _cntp_ctl tulong) :: nil))) (Sifthenelse (Ebinop Oeq (Etempvar _t'7 tuint) (Econst_int (Int.repr 1) tuint) tint) (Ssequence (Scall None (Evar _granule_lock (Tfunction (Tcons (tptr Tvoid) Tnil) tvoid cc_default)) ((Etempvar _g_rec (tptr Tvoid)) :: nil)) (Ssequence (Sset _cntp_ctl (Ebinop Oor (Etempvar _cntp_ctl tulong) (Econst_long (Int64.repr 2) tulong) tulong)) (Ssequence (Scall None (Evar _sysreg_write (Tfunction (Tcons tuint (Tcons tulong Tnil)) tvoid cc_default)) ((Econst_int (Int.repr 32) tuint) :: (Etempvar _cntp_ctl tulong) :: nil)) (Ssequence (Ssequence (Scall (Some _t'3) (Evar _get_rec_sysregs (Tfunction (Tcons (tptr Tvoid) (Tcons tuint Tnil)) tulong cc_default)) ((Etempvar _rec (tptr Tvoid)) :: (Econst_int (Int.repr 69) tuint) :: nil)) (Scall None (Evar _set_rec_sysregs (Tfunction (Tcons (tptr Tvoid) (Tcons tuint (Tcons tulong Tnil))) tvoid cc_default)) ((Etempvar _rec (tptr Tvoid)) :: (Econst_int (Int.repr 69) tuint) :: (Ebinop Oand (Etempvar _t'3 tulong) (Econst_long (Int64.repr (18446744073709549567)) tulong) tulong) :: nil))) (Ssequence (Ssequence (Scall (Some _t'4) (Evar _get_rec_sysregs (Tfunction (Tcons (tptr Tvoid) (Tcons tuint Tnil)) tulong cc_default)) ((Etempvar _rec (tptr Tvoid)) :: (Econst_int (Int.repr 69) tuint) :: nil)) (Scall None (Evar _sysreg_write (Tfunction (Tcons tuint (Tcons tulong Tnil)) tvoid cc_default)) ((Econst_int (Int.repr 69) tuint) :: (Etempvar _t'4 tulong) :: nil))) (Ssequence (Scall None (Evar _set_rec_ptimer_asserted (Tfunction (Tcons (tptr Tvoid) (Tcons tuint Tnil)) tvoid cc_default)) ((Etempvar _rec (tptr Tvoid)) :: (Econst_int (Int.repr 1) tuint) :: nil)) (Ssequence (Ssequence (Scall (Some _t'5) (Evar _get_rec_rvic (Tfunction (Tcons (tptr Tvoid) Tnil) (tptr Tvoid) cc_default)) ((Etempvar _rec (tptr Tvoid)) :: nil)) (Scall None (Evar _rvic_set_pending (Tfunction (Tcons (tptr Tvoid) (Tcons tulong Tnil)) tvoid cc_default)) ((Etempvar _t'5 (tptr Tvoid)) :: (Econst_long (Int64.repr 30) tulong) :: nil))) (Scall None (Evar _granule_unlock (Tfunction (Tcons (tptr Tvoid) Tnil) tvoid cc_default)) ((Etempvar _g_rec (tptr Tvoid)) :: nil))))))))) Sskip)))) . Definition f_check_pending_ptimers := {| fn_return := tvoid; fn_callconv := cc_default; fn_params := ((_rec, (tptr Tvoid)) :: nil); fn_vars := nil; fn_temps := ((_cntv_ctl, tulong) :: (_cntp_ctl, tulong) :: (_g_rec, (tptr Tvoid)) :: (_t'7, tuint) :: (_t'6, (tptr Tvoid)) :: (_t'5, (tptr Tvoid)) :: (_t'4, tulong) :: (_t'3, tulong) :: (_t'2, tulong) :: (_t'1, (tptr Tvoid)) :: nil); fn_body := check_pending_ptimers_body |}.
// MIT License // // Copyright (c) 2018 Lennart Braun // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #ifndef TCP_CONNECTION_HPP #define TCP_CONNECTION_HPP #include <boost/asio/ip/tcp.hpp> #include "connection.hpp" enum class Role; /** * Implementation of a bidirectional channel over tcp */ class TCPConnection : public Connection { public: /** * Constructor given a tcp socket */ TCPConnection(boost::asio::ip::tcp::socket socket); ~TCPConnection() = default; TCPConnection(TCPConnection&&) = default; TCPConnection& operator=(TCPConnection&&) = default; /** * Dispatch to connect/listen according to role */ static Conn_p from_role(Role role, boost::asio::io_context &io_service, std::string address, uint16_t port); /** * Connect to another party */ static Conn_p connect(boost::asio::io_context& io_service, std::string address, uint16_t port); /** * Listen and wait for connection of another party */ static Conn_p listen(boost::asio::io_context& io_service, std::string address, uint16_t port); /** * Send/receive message prefixed with its length. */ virtual void send_message(const uint8_t * buffer, size_t length) override; virtual bytes_t recv_message() override; /** * Send/receive without length prefix. */ void send(const uint8_t* buffer, size_t length) override; void recv(uint8_t* buffer, size_t length) override; std::future<size_t> async_send(const uint8_t* buffer, size_t length) override; std::future<size_t> async_recv(uint8_t* buffer, size_t length) override; private: void send_length(size_t length); size_t recv_length(); const static size_t header_size = 4; boost::asio::ip::tcp::socket socket_; }; #endif // TCP_CONNECTION_HPP
(* * Copyright 2019, NTU * * 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. * * Author: Albert Rizaldi, NTU Singapore *) theory VHDL_Hoare_Typed imports VHDL_Hoare_Complete begin term "wityping" definition seq_hoare_valid2_wt :: "'signal tyenv \<Rightarrow> 'signal assn2 \<Rightarrow> 'signal seq_stmt \<Rightarrow> 'signal assn2 \<Rightarrow> bool" ("(1_) \<Turnstile> [(1_)]/ (_)/ [(1_)]" 50) where "\<Gamma> \<Turnstile> [P] s [Q] \<longleftrightarrow> (\<forall>tw tw'. wityping \<Gamma> (snd tw) \<and> P tw \<and> (tw, s \<Rightarrow>\<^sub>s tw') \<longrightarrow> Q tw')" fun eval_logical :: "val \<Rightarrow> val \<Rightarrow> (bool \<Rightarrow> bool \<Rightarrow> bool) \<Rightarrow> val" where "eval_logical v1 v2 ope = (case (v1, v2) of (Bv val1 , Bv val2 ) \<Rightarrow> Bv (ope val1 val2) | (Lv ki1 bs1, Lv ki2 bs2) \<Rightarrow> Lv ki1 (map2 ope bs1 bs2))" fun eval_arith :: "val \<Rightarrow> val \<Rightarrow> (nat \<Rightarrow> nat \<Rightarrow> nat) \<Rightarrow> (int \<Rightarrow> int \<Rightarrow> int) \<Rightarrow> val" where "eval_arith v1 v2 ope1 ope2 = (case (v1, v2) of (Lv Uns bs1, Lv Uns bs2) \<Rightarrow> (let len = ope1 (length bs1) (length bs2); res = bin_to_bl len (ope2 (bl_to_bin bs1) (bl_to_bin bs2)) in Lv Uns res) | (Lv Sig bs1, Lv Sig bs2) \<Rightarrow> (let len = ope1 (length bs1) (length bs2); res = bin_to_bl len (ope2 (sbl_to_bin bs1) (sbl_to_bin bs2)) in Lv Sig res))" function eval_world_raw :: "nat \<Rightarrow> 'signal worldline_init \<Rightarrow> 'signal bexp \<Rightarrow> val" where "eval_world_raw t w (Band e1 e2) = eval_logical (eval_world_raw t w e1) (eval_world_raw t w e2) (\<and>)" | "eval_world_raw t w (Bor e1 e2) = eval_logical (eval_world_raw t w e1) (eval_world_raw t w e2) (\<or>)" | "eval_world_raw t w (Bnand e1 e2) = eval_logical (eval_world_raw t w e1) (eval_world_raw t w e2) (\<lambda>x y. \<not> (x \<and> y))" | "eval_world_raw t w (Bnor e1 e2) = eval_logical (eval_world_raw t w e1) (eval_world_raw t w e2) (\<lambda>x y. \<not> (x \<or> y))" | "eval_world_raw t w (Bxor e1 e2) = eval_logical (eval_world_raw t w e1) (eval_world_raw t w e2) xor" | "eval_world_raw t w (Bxnor e1 e2) = eval_logical (eval_world_raw t w e1) (eval_world_raw t w e2) (\<lambda>x y. \<not> xor x y)" | "eval_world_raw t w (Badd e1 e2) = eval_arith (eval_world_raw t w e1) (eval_world_raw t w e2) max (+)" | "eval_world_raw t w (Bmult e1 e2) = eval_arith (eval_world_raw t w e1) (eval_world_raw t w e2) (+) (*)" | "eval_world_raw t w (Bsub e1 e2) = eval_arith (eval_world_raw t w e1) (eval_world_raw t w e2) max (-)" | "eval_world_raw t w (Bsig sig) = snd w sig t" | "eval_world_raw t w (Btrue) = Bv True" | "eval_world_raw t w (Bfalse) = Bv False" | "eval_world_raw t w (Bsig_delayed sig dly) = (if t - dly < t then snd w sig (t - dly) else if 0 < t then snd w sig (t - 1) else fst w sig)" | "eval_world_raw t w (Bsig_event sig) = Bv (sig \<in> event_of (t, w))" | "eval_world_raw t w (Bnot e) = (case eval_world_raw t w e of Bv bool \<Rightarrow> Bv (\<not> bool) | Lv ki bs \<Rightarrow> Lv ki (map Not bs))" | "eval_world_raw t w (Bslice sig l r) = (case eval_world_raw t w (Bsig sig) of Lv ki bs \<Rightarrow> Lv ki (nths bs {length bs - l - 1 .. length bs - r - 1}))" | "eval_world_raw t w (Bindex sig idx) = (case eval_world_raw t w (Bsig sig) of Lv ki bs \<Rightarrow> Bv (bs ! idx))" | "eval_world_raw t w (Bshiftl e n) = (case eval_world_raw t w e of Lv Uns bs \<Rightarrow> Lv Uns (drop n (bs @ replicate n False)) | Lv Sig bs \<Rightarrow> Lv Sig (drop n (bs @ replicate n False)))" | "eval_world_raw t w (Bshiftr e n) = (case eval_world_raw t w e of Lv Uns bs \<Rightarrow> Lv Uns (take (length bs) (replicate n False @ bs)) | Lv Sig bs \<Rightarrow> Lv Sig (take (length bs) (replicate n (hd bs) @ bs)))" | "eval_world_raw t w (Bwhen th guard el) = (case eval_world_raw t w guard of Bv True \<Rightarrow> eval_world_raw t w th | Bv False \<Rightarrow> eval_world_raw t w el)" | "eval_world_raw t w (Bliteral sign val) = (Lv sign val)" by pat_completeness auto termination by size_change lemma eval_world_raw_bv: assumes "bexp_wt \<Gamma> exp Bty" and "wityping \<Gamma> w" shows "\<exists>v. eval_world_raw t w exp = Bv v" using assms proof (induction rule:eval_world_raw.induct) case (1 t w e1 e2) show ?case apply (rule bexp_wt.cases[OF 1(3)]) using 1 by auto next case (2 t w e1 e2) show ?case apply (rule bexp_wt.cases[OF 2(3)]) using 2 by auto next case (3 t w e1 e2) show ?case apply (rule bexp_wt.cases[OF 3(3)]) using 3 by auto next case (4 t w e1 e2) show ?case apply (rule bexp_wt.cases[OF 4(3)]) using 4 by auto next case (5 t w e1 e2) show ?case apply (rule bexp_wt.cases[OF 5(3)]) using 5 by auto next case (6 t w e1 e2) show ?case apply (rule bexp_wt.cases[OF 6(3)]) using 6 by auto next case (7 t w e1 e2) show ?case apply (rule bexp_wt.cases[OF 7(3)]) using 7 by auto next case (8 t w e1 e2) show ?case apply (rule bexp_wt.cases[OF 8(3)]) using 8 by auto next case (9 t w e1 e2) show ?case by (rule bexp_wt.cases[OF 9(3)]) auto next case (10 t w sig) show ?case apply (rule bexp_wt_cases_slice(2)[OF 10(1)]) using 10 by (metis (no_types, hide_lams) eval_world_raw.simps(10) ty.distinct(1) type_of.elims wityping_def wtyping_def) next case (11 t w) then show ?case by auto next case (12 t w) then show ?case by auto next case (13 t w sig dly) show ?case apply (rule bexp_wt_cases_del[OF 13(1)]) using 13 unfolding wityping_def wtyping_def by (metis (full_types) eval_world_raw.simps(13) styping_def ty.distinct(1) type_of.elims) next case (14 t w sig) show ?case by auto next case (15 t w e) hence *: "\<exists>v. eval_world_raw t w e = Bv v" using bexp_wt_cases(1) by blast show ?case apply (rule bexp_wt_cases(1)[OF 15(2)]) using 15 * by auto next case (16 t w sig l r) then show ?case by (meson bexp_wt_cases_slice(1) ty.distinct(1)) next case (17 t w sig idx) then show ?case by (metis (no_types, lifting) bexp_wt_cases_slice(3) bexp_wt_cases_slice(2) eval_world_raw.simps(10) eval_world_raw.simps(17) is_Bv_def ty.simps(3) type_of.simps(1) val.case_eq_if wityping_def wtyping_def) next case (18 t w e n) then show ?case by (meson bexp_wt_cases_shiftl ty.distinct(1)) next case (19 t w e n) then show ?case by (meson bexp_wt_cases_shiftr ty.distinct(1)) next case (20 t w th guard el) hence *: "\<exists>v. eval_world_raw t w guard = Bv v" using bexp_wt_cases_when by blast show ?case apply (rule bexp_wt_cases_when[OF 20(4)]) using * 20 by (smt eval_world_raw.simps(20) val.simps(5)) next case (21 t w sign val) then show ?case using bexp_wt_cases_lit by blast qed lemma bexp_wt_add: assumes "bexp_wt \<Gamma> (Badd e1 e2) (Lty ki len)" shows "\<exists>len1 len2. bexp_wt \<Gamma> e1 (Lty ki len1) \<and> bexp_wt \<Gamma> e2 (Lty ki len2) \<and> len = max len1 len2 \<and> (ki = Uns \<or> ki = Sig)" by (rule bexp_wt_cases_add[OF assms]) blast+ lemma bexp_wt_mult: assumes "bexp_wt \<Gamma> (Bmult e1 e2) (Lty ki len)" shows "\<exists>len1 len2. bexp_wt \<Gamma> e1 (Lty ki len1) \<and> bexp_wt \<Gamma> e2 (Lty ki len2) \<and> len = len1 + len2 \<and> (ki = Uns \<or> ki = Sig)" by (rule bexp_wt_cases_mult[OF assms]) blast+ lemma bexp_wt_sub: assumes "bexp_wt \<Gamma> (Bsub e1 e2) (Lty ki len)" shows "\<exists>len1 len2. bexp_wt \<Gamma> e1 (Lty ki len1) \<and> bexp_wt \<Gamma> e2 (Lty ki len2) \<and> len = max len1 len2 \<and> (ki = Uns \<or> ki = Sig)" by (rule bexp_wt_cases_sub[OF assms]) blast+ lemma card_slice: assumes "l < len" and "r \<le> l" shows "card {i. i < len \<and> i \<in> {len - Suc l..len - Suc r}} = Suc (l - r)" (is "card ?lhs = _") using assms proof - have "\<forall>i \<in> {len - Suc l .. len - Suc r}. i < len" proof (rule) fix i assume "i \<in> {len - Suc l .. len - Suc r}" hence "len - Suc l \<le> i" and "i \<le> len - Suc r" by auto thus "i < len" using assms by linarith qed hence "{len - Suc l .. len - Suc r} \<subseteq> {i. i < len}" by auto have "?lhs = ({len - Suc l .. len - Suc r})" using assms by auto hence "card ?lhs = card {len - Suc l .. len - Suc r}" by auto also have "... = Suc (l - r)" unfolding card_atLeastAtMost using assms by auto finally show ?thesis by auto qed lemma eval_world_raw_lv: assumes "bexp_wt \<Gamma> exp (Lty ki len)" and "wityping \<Gamma> w" shows "\<exists>bs. eval_world_raw t w exp = Lv ki bs \<and> length bs = len" using assms proof (induction arbitrary: len rule:eval_world_raw.induct) case (1 t w e1 e2) show ?case apply (rule bexp_wt.cases[OF 1(3)]) using 1 by (auto split:val.split) blast+ next case (2 t w e1 e2) show ?case apply (rule bexp_wt.cases[OF 2(3)]) using 2 by (auto split:val.split) blast+ next case (3 t w e1 e2) show ?case apply (rule bexp_wt.cases[OF 3(3)]) using 3 by (auto split:val.split) blast+ next case (4 t w e1 e2) show ?case apply (rule bexp_wt.cases[OF 4(3)]) using 4 by (auto split:val.split) blast+ next case (5 t w e1 e2) show ?case apply (rule bexp_wt.cases[OF 5(3)]) using 5 by (auto split:val.split) blast+ next case (6 t w e1 e2) show ?case apply (rule bexp_wt.cases[OF 6(3)]) using 6 by (auto split:val.split) blast+ next case (7 t w e1 e2) then obtain len1 len2 where *: "bexp_wt \<Gamma> e1 (Lty ki len1) \<and> bexp_wt \<Gamma> e2 (Lty ki len2) \<and> len = max len1 len2 \<and> (ki = Uns \<or> ki = Sig)" using bexp_wt_add by blast then obtain bs1 bs2 where "eval_world_raw t w e1 = Lv ki bs1 \<and> length bs1 = len1" and "eval_world_raw t w e2 = Lv ki bs2 \<and> length bs2 = len2" using 7 by blast thus ?case using * size_bin_to_bl by (auto split: signedness.split) next case (8 t w e1 e2) then obtain len1 len2 where *: "bexp_wt \<Gamma> e1 (Lty ki len1) \<and> bexp_wt \<Gamma> e2 (Lty ki len2) \<and> len = len1 + len2 \<and> (ki = Uns \<or> ki = Sig)" using bexp_wt_mult by blast then obtain bs1 bs2 where "eval_world_raw t w e1 = Lv ki bs1 \<and> length bs1 = len1" and "eval_world_raw t w e2 = Lv ki bs2 \<and> length bs2 = len2" using 8 by blast thus ?case using * size_bin_to_bl by (auto split: signedness.split val.split) next case (9 t w e1 e2) then obtain len1 len2 where *: "bexp_wt \<Gamma> e1 (Lty ki len1) \<and> bexp_wt \<Gamma> e2 (Lty ki len2) \<and> len = max len1 len2 \<and> (ki = Uns \<or> ki = Sig)" using bexp_wt_sub by blast then obtain bs1 bs2 where "eval_world_raw t w e1 = Lv ki bs1 \<and> length bs1 = len1" and "eval_world_raw t w e2 = Lv ki bs2 \<and> length bs2 = len2" using 9 by blast thus ?case using * size_bin_to_bl by (auto split: signedness.split val.split) next case (10 t w sig) show ?case apply (rule bexp_wt_cases_slice(2)[OF 10(1)]) using 10 by (smt eval_world_raw.simps(10) ty.distinct(1) ty.inject type_of.elims wityping_def wtyping_def) next case (11 t w) then show ?case using bexp_wt.cases[OF 11(1)] by blast+ next case (12 t w) then show ?case using bexp_wt.cases[OF 12(1)] by blast+ next case (13 t w sig dly) show ?case apply (rule bexp_wt_cases_del[OF 13(1)]) using 13 unfolding wityping_def wtyping_def by (smt eval_world_raw.simps(13) styping_def ty.distinct(1) ty.inject type_of.elims) next case (14 t w sig) show ?case using bexp_wt.cases[OF 14(1)] by blast+ next case (15 t w e) hence *: "\<exists>bs. eval_world_raw t w e = Lv ki bs \<and> length bs = len" using bexp_wt_cases(1) by blast show ?case using 15 * by (metis eval_world_raw.simps(15) length_map val.simps(6)) next case (16 t w sig l r) show ?case apply (rule bexp_wt_cases_slice(1)[OF 16(2)]) using 16 apply (auto split:val.split) unfolding length_nths using card_slice by auto next case (17 t w sig idx) then show ?case using bexp_wt_cases_slice(3) by fastforce next case (18 t w e n) show ?case apply (rule bexp_wt_cases_shiftl[OF 18(2)]) apply (auto split:val.split) using 18 by auto next case (19 t w e n) show ?case apply (rule bexp_wt_cases_shiftr[OF 19(2)]) apply (auto split:val.split) using 19 by auto next case (20 t w th guard el) hence *: "\<exists>v. eval_world_raw t w guard = Bv v" using bexp_wt_cases_when by (metis eval_world_raw_bv) show ?case apply (rule bexp_wt_cases_when[OF 20(4)]) using * 20 by (smt eval_world_raw.simps(20) val.simps(5)) next case (21 t w sign val) then show ?case using bexp_wt_cases_lit by fastforce qed lemma eval_world_raw_correctness_if: assumes "eval_world_raw t w exp = res" assumes "wityping \<Gamma> w" and "bexp_wt \<Gamma> exp ty" shows "beval_world_raw w t exp res" using assms proof (induct arbitrary: res ty rule: eval_world_raw.induct) case (1 t w e1 e2) then consider (bool) "ty = Bty" | (vector) ki len where "ty = Lty ki len" by (meson ty.exhaust) then show ?case proof (cases) case bool hence "bexp_wt \<Gamma> e1 Bty" and "bexp_wt \<Gamma> e2 Bty" using 1(5) bexp_wt.cases by auto then obtain res1 res2 where "eval_world_raw t w e1 = Bv res1" and "eval_world_raw t w e2 = Bv res2" using eval_world_raw_bv using "1.prems"(2) by blast hence " beval_world_raw w t e1 (Bv res1)" and " beval_world_raw w t e2 (Bv res2)" using "1.hyps" "1.prems" \<open>bexp_wt \<Gamma> e1 Bty\<close> \<open>bexp_wt \<Gamma> e2 Bty\<close> by blast+ moreover have "res = Bv (res1 \<and> res2)" using "1.prems"(1) \<open>eval_world_raw t w e1 = Bv res1\<close> \<open>eval_world_raw t w e2 = Bv res2\<close> by auto ultimately show ?thesis by (simp add: beval_raw.intros(8) beval_world_raw.simps) next case vector hence "bexp_wt \<Gamma> e1 (Lty ki len)" and "bexp_wt \<Gamma> e2 (Lty ki len)" using 1(5) bexp_wt.cases by auto then obtain res1 res2 where "eval_world_raw t w e1 = Lv ki res1" and "length res1 = len" and "eval_world_raw t w e2 = Lv ki res2" and "length res2 = len" using eval_world_raw_lv using "1.prems"(2) by blast hence " beval_world_raw w t e1 (Lv ki res1) \<and> beval_world_raw w t e2 (Lv ki res2)" using "1.hyps"(1) "1.prems"(2) \<open>bexp_wt \<Gamma> e1 (Lty ki len)\<close> "1.hyps"(2) \<open>bexp_wt \<Gamma> e2 (Lty ki len)\<close> by blast moreover have "res = Lv ki (map2 (\<and>) res1 res2)" using 1(3) `eval_world_raw t w e1 = Lv ki res1` `eval_world_raw t w e2 = Lv ki res2` by auto ultimately show ?thesis by (metis \<open>length res1 = len\<close> \<open>length res2 = len\<close> beval_raw.intros(9) beval_world_raw.cases beval_world_raw.intros) qed next case (2 t w e1 e2) then consider (bool) "ty = Bty" | (vector) ki len where "ty = Lty ki len" by (meson ty.exhaust) then show ?case proof (cases) case bool hence "bexp_wt \<Gamma> e1 Bty" and "bexp_wt \<Gamma> e2 Bty" using 2(5) bexp_wt.cases by auto then obtain res1 res2 where "eval_world_raw t w e1 = Bv res1" and "eval_world_raw t w e2 = Bv res2" using eval_world_raw_bv using "2.prems"(2) by blast hence " beval_world_raw w t e1 (Bv res1)" and " beval_world_raw w t e2 (Bv res2)" using "2.hyps" "2.prems" \<open>bexp_wt \<Gamma> e1 Bty\<close> \<open>bexp_wt \<Gamma> e2 Bty\<close> by blast+ moreover have "res = Bv (res1 \<or> res2)" using "2.prems"(1) \<open>eval_world_raw t w e1 = Bv res1\<close> \<open>eval_world_raw t w e2 = Bv res2\<close> by auto ultimately show ?thesis by (meson beval_raw.intros(10) beval_world_raw.cases beval_world_raw.intros) next case vector hence "bexp_wt \<Gamma> e1 (Lty ki len)" and "bexp_wt \<Gamma> e2 (Lty ki len)" using 2(5) bexp_wt.cases by auto then obtain res1 res2 where "eval_world_raw t w e1 = Lv ki res1" and "length res1 = len" and "eval_world_raw t w e2 = Lv ki res2" and "length res2 = len" using eval_world_raw_lv using "2.prems"(2) by blast hence " beval_world_raw w t e1 (Lv ki res1) \<and> beval_world_raw w t e2 (Lv ki res2)" using "2.hyps"(1) "2.prems"(2) \<open>bexp_wt \<Gamma> e1 (Lty ki len)\<close> "2.hyps"(2) \<open>bexp_wt \<Gamma> e2 (Lty ki len)\<close> by blast moreover have "res = Lv ki (map2 (\<or>) res1 res2)" using 2(3) `eval_world_raw t w e1 = Lv ki res1` `eval_world_raw t w e2 = Lv ki res2` by auto ultimately show ?thesis by (metis \<open>length res1 = len\<close> \<open>length res2 = len\<close> beval_raw.intros(11) beval_world_raw.cases beval_world_raw.intros) qed next case (3 t w e1 e2) then consider (bool) "ty = Bty" | (vector) ki len where "ty = Lty ki len" by (meson ty.exhaust) then show ?case proof (cases) case bool hence "bexp_wt \<Gamma> e1 Bty" and "bexp_wt \<Gamma> e2 Bty" using 3(5) bexp_wt.cases by auto then obtain res1 res2 where "eval_world_raw t w e1 = Bv res1" and "eval_world_raw t w e2 = Bv res2" using eval_world_raw_bv using "3.prems"(2) by blast hence " beval_world_raw w t e1 (Bv res1)" and " beval_world_raw w t e2 (Bv res2)" using "3.hyps" "3.prems" \<open>bexp_wt \<Gamma> e1 Bty\<close> \<open>bexp_wt \<Gamma> e2 Bty\<close> by blast+ moreover have "res = Bv (\<not> (res1 \<and> res2))" using "3.prems"(1) \<open>eval_world_raw t w e1 = Bv res1\<close> \<open>eval_world_raw t w e2 = Bv res2\<close> by auto ultimately show ?thesis by (meson beval_raw.intros(12) beval_world_raw.cases beval_world_raw.intros) next case vector hence "bexp_wt \<Gamma> e1 (Lty ki len)" and "bexp_wt \<Gamma> e2 (Lty ki len)" using 3(5) bexp_wt.cases by auto then obtain res1 res2 where "eval_world_raw t w e1 = Lv ki res1" and "length res1 = len" and "eval_world_raw t w e2 = Lv ki res2" and "length res2 = len" using eval_world_raw_lv using "3.prems"(2) by blast hence " beval_world_raw w t e1 (Lv ki res1) \<and> beval_world_raw w t e2 (Lv ki res2)" using "3.hyps"(1) "3.prems"(2) \<open>bexp_wt \<Gamma> e1 (Lty ki len)\<close> "3.hyps"(2) \<open>bexp_wt \<Gamma> e2 (Lty ki len)\<close> by blast moreover have "res = Lv ki (map2 (\<lambda>x y. \<not> (x \<and> y)) res1 res2)" using 3(3) `eval_world_raw t w e1 = Lv ki res1` `eval_world_raw t w e2 = Lv ki res2` by auto ultimately show ?thesis by (metis \<open>length res1 = len\<close> \<open>length res2 = len\<close> beval_raw.intros(13) beval_world_raw.cases beval_world_raw.intros) qed next case (4 t w e1 e2) then consider (bool) "ty = Bty" | (vector) ki len where "ty = Lty ki len" by (meson ty.exhaust) then show ?case proof (cases) case bool hence "bexp_wt \<Gamma> e1 Bty" and "bexp_wt \<Gamma> e2 Bty" using 4(5) bexp_wt.cases by auto then obtain res1 res2 where "eval_world_raw t w e1 = Bv res1" and "eval_world_raw t w e2 = Bv res2" using eval_world_raw_bv using "4.prems"(2) by blast hence " beval_world_raw w t e1 (Bv res1)" and " beval_world_raw w t e2 (Bv res2)" using "4.hyps" "4.prems" \<open>bexp_wt \<Gamma> e1 Bty\<close> \<open>bexp_wt \<Gamma> e2 Bty\<close> by blast+ moreover have "res = Bv (\<not> (res1 \<or> res2))" using "4.prems"(1) \<open>eval_world_raw t w e1 = Bv res1\<close> \<open>eval_world_raw t w e2 = Bv res2\<close> by auto ultimately show ?thesis by (meson beval_raw.intros(14) beval_world_raw.cases beval_world_raw.intros) next case vector hence "bexp_wt \<Gamma> e1 (Lty ki len)" and "bexp_wt \<Gamma> e2 (Lty ki len)" using 4(5) bexp_wt.cases by auto then obtain res1 res2 where "eval_world_raw t w e1 = Lv ki res1" and "length res1 = len" and "eval_world_raw t w e2 = Lv ki res2" and "length res2 = len" using eval_world_raw_lv using "4.prems"(2) by blast hence " beval_world_raw w t e1 (Lv ki res1) \<and> beval_world_raw w t e2 (Lv ki res2)" using "4.hyps"(1) "4.prems"(2) \<open>bexp_wt \<Gamma> e1 (Lty ki len)\<close> "4.hyps"(2) \<open>bexp_wt \<Gamma> e2 (Lty ki len)\<close> by blast moreover have "res = Lv ki (map2 (\<lambda>x y. \<not> (x \<or> y)) res1 res2)" using 4(3) `eval_world_raw t w e1 = Lv ki res1` `eval_world_raw t w e2 = Lv ki res2` by auto ultimately show ?thesis by (metis \<open>length res1 = len\<close> \<open>length res2 = len\<close> beval_raw.intros(15) beval_world_raw.cases beval_world_raw.intros) qed next case (5 t w e1 e2) then consider (bool) "ty = Bty" | (vector) ki len where "ty = Lty ki len" by (meson ty.exhaust) then show ?case proof (cases) case bool hence "bexp_wt \<Gamma> e1 Bty" and "bexp_wt \<Gamma> e2 Bty" using 5(5) bexp_wt.cases by auto then obtain res1 res2 where "eval_world_raw t w e1 = Bv res1" and "eval_world_raw t w e2 = Bv res2" using eval_world_raw_bv using "5.prems"(2) by blast hence " beval_world_raw w t e1 (Bv res1)" and " beval_world_raw w t e2 (Bv res2)" using "5.hyps" "5.prems" \<open>bexp_wt \<Gamma> e1 Bty\<close> \<open>bexp_wt \<Gamma> e2 Bty\<close> by blast+ moreover have "res = Bv (xor res1 res2)" using "5.prems"(1) \<open>eval_world_raw t w e1 = Bv res1\<close> \<open>eval_world_raw t w e2 = Bv res2\<close> by auto ultimately show ?thesis by (meson beval_raw.intros(16) beval_world_raw.cases beval_world_raw.intros) next case vector hence "bexp_wt \<Gamma> e1 (Lty ki len)" and "bexp_wt \<Gamma> e2 (Lty ki len)" using 5(5) bexp_wt.cases by auto then obtain res1 res2 where "eval_world_raw t w e1 = Lv ki res1" and "length res1 = len" and "eval_world_raw t w e2 = Lv ki res2" and "length res2 = len" using eval_world_raw_lv using "5.prems"(2) by blast hence " beval_world_raw w t e1 (Lv ki res1) \<and> beval_world_raw w t e2 (Lv ki res2)" using "5.hyps"(1) "5.prems"(2) \<open>bexp_wt \<Gamma> e1 (Lty ki len)\<close> "5.hyps"(2) \<open>bexp_wt \<Gamma> e2 (Lty ki len)\<close> by blast moreover have "res = Lv ki (map2 xor res1 res2)" using 5(3) `eval_world_raw t w e1 = Lv ki res1` `eval_world_raw t w e2 = Lv ki res2` by auto ultimately show ?thesis by (metis \<open>length res1 = len\<close> \<open>length res2 = len\<close> beval_raw.intros(17) beval_world_raw.cases beval_world_raw.intros) qed next case (6 t w e1 e2) then consider (bool) "ty = Bty" | (vector) ki len where "ty = Lty ki len" by (meson ty.exhaust) then show ?case proof (cases) case bool hence "bexp_wt \<Gamma> e1 Bty" and "bexp_wt \<Gamma> e2 Bty" using 6(5) bexp_wt.cases by auto then obtain res1 res2 where "eval_world_raw t w e1 = Bv res1" and "eval_world_raw t w e2 = Bv res2" using eval_world_raw_bv using "6.prems"(2) by blast hence " beval_world_raw w t e1 (Bv res1)" and " beval_world_raw w t e2 (Bv res2)" using "6.hyps" "6.prems" \<open>bexp_wt \<Gamma> e1 Bty\<close> \<open>bexp_wt \<Gamma> e2 Bty\<close> by blast+ moreover have "res = Bv (\<not> (xor res1 res2))" using "6.prems"(1) \<open>eval_world_raw t w e1 = Bv res1\<close> \<open>eval_world_raw t w e2 = Bv res2\<close> by auto ultimately show ?thesis by (meson beval_raw.intros(18) beval_world_raw.cases beval_world_raw.intros) next case vector hence "bexp_wt \<Gamma> e1 (Lty ki len)" and "bexp_wt \<Gamma> e2 (Lty ki len)" using 6(5) bexp_wt.cases by auto then obtain res1 res2 where "eval_world_raw t w e1 = Lv ki res1" and "length res1 = len" and "eval_world_raw t w e2 = Lv ki res2" and "length res2 = len" using eval_world_raw_lv using "6.prems"(2) by blast hence " beval_world_raw w t e1 (Lv ki res1) \<and> beval_world_raw w t e2 (Lv ki res2)" using "6.hyps"(1) "6.prems"(2) \<open>bexp_wt \<Gamma> e1 (Lty ki len)\<close> "6.hyps"(2) \<open>bexp_wt \<Gamma> e2 (Lty ki len)\<close> by blast moreover have "res = Lv ki (map2 (\<lambda>x y. \<not> xor x y) res1 res2)" using 6(3) `eval_world_raw t w e1 = Lv ki res1` `eval_world_raw t w e2 = Lv ki res2` by auto ultimately show ?thesis by (metis \<open>length res1 = len\<close> \<open>length res2 = len\<close> beval_raw.intros(19) beval_world_raw.cases beval_world_raw.intros) qed next case (7 t w e1 e2) obtain res1 res2 where " eval_world_raw t w e1 = res1" and " eval_world_raw t w e2 = res2" by auto obtain ki len1 len2 where "bexp_wt \<Gamma> e1 (Lty ki len1)" and "bexp_wt \<Gamma> e2 (Lty ki len2)" and "ty = Lty ki (max len1 len2)" using bexp_wt_cases_add[OF ` bexp_wt \<Gamma> (Badd e1 e2) ty`] by metis hence IH1: "beval_world_raw w t e1 res1" and IH2: "beval_world_raw w t e2 res2" using 7(1)[OF `eval_world_raw t w e1 = res1` `wityping \<Gamma> w`] 7(2)[OF `eval_world_raw t w e2 = res2` `wityping \<Gamma> w`] by auto let ?len1 = "length (lval_of res1)" let ?len2 = "length (lval_of res2)" have "?len1 = len1" and "?len2 = len2" using IH1 `bexp_wt \<Gamma> e1 (Lty ki len1)` `bexp_wt \<Gamma> e2 (Lty ki len2)` IH2 by (metis (no_types, lifting) "7.prems"(2) beval_raw_preserve_well_typedness beval_world_raw_cases ty.distinct(1) ty.inject type_of.simps(1) type_of.simps(2) val.exhaust_sel wityping_def wityping_ensure_styping wityping_ensure_ttyping)+ consider (Uns) "ki = Uns" | (Sig) "ki = Sig" using `ty = Lty ki (max len1 len2)` "7.prems"(3) bexp_wt_add by blast thus ?case proof (cases) case Uns then obtain bs1 bs2 where "res1 = Lv Uns bs1" and "length bs1 = len1" and "res2 = Lv Uns bs2" and "length bs2 = len2" using "7.prems"(2) \<open>bexp_wt \<Gamma> e1 (Lty ki len1)\<close> \<open>eval_world_raw t w e1 = res1\<close> eval_world_raw_lv by (metis \<open>bexp_wt \<Gamma> e2 (Lty ki len2)\<close> \<open>eval_world_raw t w e2 = res2\<close>) hence "res = Lv Uns (bin_to_bl (max len1 len2) ((bl_to_bin bs1) + (bl_to_bin bs2)))" using 7(3) `eval_world_raw t w e1 = res1` `eval_world_raw t w e2 = res2` by auto then show ?thesis using IH1 IH2 `res1 = Lv Uns bs1` `res2 = Lv Uns bs2` by (metis \<open>length bs1 = len1\<close> \<open>length bs2 = len2\<close> beval_raw.intros(22) beval_world_raw.cases beval_world_raw.intros) next case Sig then obtain bs1 bs2 where "res1 = Lv Sig bs1" and "length bs1 = len1" and "res2 = Lv Sig bs2" and "length bs2 = len2" using "7.prems"(2) \<open>bexp_wt \<Gamma> e1 (Lty ki len1)\<close> \<open>eval_world_raw t w e1 = res1\<close> eval_world_raw_lv by (metis \<open>bexp_wt \<Gamma> e2 (Lty ki len2)\<close> \<open>eval_world_raw t w e2 = res2\<close>) hence "res = Lv Sig (bin_to_bl (max len1 len2) ((sbl_to_bin bs1) + (sbl_to_bin bs2)))" using 7(3) `eval_world_raw t w e1 = res1` `eval_world_raw t w e2 = res2` by auto then show ?thesis using IH1 IH2 `res1 = Lv Sig bs1` `res2 = Lv Sig bs2` by (metis \<open>length bs1 = len1\<close> \<open>length bs2 = len2\<close> beval_raw.intros(23) beval_world_raw.cases beval_world_raw.intros) qed next case (8 t w e1 e2) obtain res1 res2 where " eval_world_raw t w e1 = res1" and " eval_world_raw t w e2 = res2" by auto obtain ki len1 len2 where "bexp_wt \<Gamma> e1 (Lty ki len1)" and "bexp_wt \<Gamma> e2 (Lty ki len2)" and "ty = Lty ki (len1 + len2)" using bexp_wt_cases_mult[OF ` bexp_wt \<Gamma> (Bmult e1 e2) ty`] by metis hence IH1: "beval_world_raw w t e1 res1" and IH2: "beval_world_raw w t e2 res2" using 8(1)[OF `eval_world_raw t w e1 = res1` `wityping \<Gamma> w`] 8(2)[OF `eval_world_raw t w e2 = res2` `wityping \<Gamma> w`] by auto let ?len1 = "length (lval_of res1)" let ?len2 = "length (lval_of res2)" have "?len1 = len1" and "?len2 = len2" using IH1 `bexp_wt \<Gamma> e1 (Lty ki len1)` `bexp_wt \<Gamma> e2 (Lty ki len2)` IH2 by (metis (no_types, lifting) "8.prems"(2) beval_raw_preserve_well_typedness beval_world_raw_cases ty.distinct(1) ty.inject type_of.simps(1) type_of.simps(2) val.exhaust_sel wityping_def wityping_ensure_styping wityping_ensure_ttyping)+ consider (Uns) "ki = Uns" | (Sig) "ki = Sig" using `ty = Lty ki (len1 + len2)` "8.prems"(3) bexp_wt_mult by blast thus ?case proof (cases) case Uns then obtain bs1 bs2 where "res1 = Lv Uns bs1" and "length bs1 = len1" and "res2 = Lv Uns bs2" and "length bs2 = len2" using "8.prems"(2) \<open>bexp_wt \<Gamma> e1 (Lty ki len1)\<close> \<open>eval_world_raw t w e1 = res1\<close> eval_world_raw_lv by (metis \<open>bexp_wt \<Gamma> e2 (Lty ki len2)\<close> \<open>eval_world_raw t w e2 = res2\<close>) hence "res = Lv Uns (bin_to_bl (len1 + len2) ((bl_to_bin bs1) * (bl_to_bin bs2)))" using 8(3) `eval_world_raw t w e1 = res1` `eval_world_raw t w e2 = res2` by auto then show ?thesis using IH1 IH2 `res1 = Lv Uns bs1` `res2 = Lv Uns bs2` by (metis \<open>length bs1 = len1\<close> \<open>length bs2 = len2\<close> beval_raw.intros(24) beval_world_raw.cases beval_world_raw.intros) next case Sig then obtain bs1 bs2 where "res1 = Lv Sig bs1" and "length bs1 = len1" and "res2 = Lv Sig bs2" and "length bs2 = len2" using "8.prems"(2) \<open>bexp_wt \<Gamma> e1 (Lty ki len1)\<close> \<open>eval_world_raw t w e1 = res1\<close> eval_world_raw_lv by (metis \<open>bexp_wt \<Gamma> e2 (Lty ki len2)\<close> \<open>eval_world_raw t w e2 = res2\<close>) hence "res = Lv Sig (bin_to_bl (len1 + len2) ((sbl_to_bin bs1) * (sbl_to_bin bs2)))" using 8(3) `eval_world_raw t w e1 = res1` `eval_world_raw t w e2 = res2` by auto then show ?thesis using IH1 IH2 `res1 = Lv Sig bs1` `res2 = Lv Sig bs2` by (metis \<open>length bs1 = len1\<close> \<open>length bs2 = len2\<close> beval_raw.intros(25) beval_world_raw.cases beval_world_raw.intros) qed next case (9 t w e1 e2) obtain res1 res2 where " eval_world_raw t w e1 = res1" and " eval_world_raw t w e2 = res2" by auto obtain ki len1 len2 where "bexp_wt \<Gamma> e1 (Lty ki len1)" and "bexp_wt \<Gamma> e2 (Lty ki len2)" and "ty = Lty ki (max len1 len2)" using bexp_wt_cases_sub[OF ` bexp_wt \<Gamma> (Bsub e1 e2) ty`] by metis hence IH1: "beval_world_raw w t e1 res1" and IH2: "beval_world_raw w t e2 res2" using 9(1)[OF `eval_world_raw t w e1 = res1` `wityping \<Gamma> w`] 9(2)[OF `eval_world_raw t w e2 = res2` `wityping \<Gamma> w`] by auto let ?len1 = "length (lval_of res1)" let ?len2 = "length (lval_of res2)" have "?len1 = len1" and "?len2 = len2" using IH1 `bexp_wt \<Gamma> e1 (Lty ki len1)` `bexp_wt \<Gamma> e2 (Lty ki len2)` IH2 by (metis (no_types, lifting) "9.prems"(2) beval_raw_preserve_well_typedness beval_world_raw_cases ty.distinct(1) ty.inject type_of.simps(1) type_of.simps(2) val.exhaust_sel wityping_def wityping_ensure_styping wityping_ensure_ttyping)+ consider (Uns) "ki = Uns" | (Sig) "ki = Sig" using `ty = Lty ki (max len1 len2)` "9.prems"(3) bexp_wt_sub by blast thus ?case proof (cases) case Uns then obtain bs1 bs2 where "res1 = Lv Uns bs1" and "length bs1 = len1" and "res2 = Lv Uns bs2" and "length bs2 = len2" using "9.prems"(2) \<open>bexp_wt \<Gamma> e1 (Lty ki len1)\<close> \<open>eval_world_raw t w e1 = res1\<close> eval_world_raw_lv by (metis \<open>bexp_wt \<Gamma> e2 (Lty ki len2)\<close> \<open>eval_world_raw t w e2 = res2\<close>) hence "res = Lv Uns (bin_to_bl (max len1 len2) ((bl_to_bin bs1) - (bl_to_bin bs2)))" using 9(3) `eval_world_raw t w e1 = res1` `eval_world_raw t w e2 = res2` by auto then show ?thesis using IH1 IH2 `res1 = Lv Uns bs1` `res2 = Lv Uns bs2` by (metis \<open>length bs1 = len1\<close> \<open>length bs2 = len2\<close> beval_raw.intros(26) beval_world_raw.cases beval_world_raw.intros) next case Sig then obtain bs1 bs2 where "res1 = Lv Sig bs1" and "length bs1 = len1" and "res2 = Lv Sig bs2" and "length bs2 = len2" using "9.prems"(2) \<open>bexp_wt \<Gamma> e1 (Lty ki len1)\<close> \<open>eval_world_raw t w e1 = res1\<close> eval_world_raw_lv by (metis \<open>bexp_wt \<Gamma> e2 (Lty ki len2)\<close> \<open>eval_world_raw t w e2 = res2\<close>) hence "res = Lv Sig (bin_to_bl (max len1 len2) ((sbl_to_bin bs1) - (sbl_to_bin bs2)))" using 9(3) `eval_world_raw t w e1 = res1` `eval_world_raw t w e2 = res2` by auto then show ?thesis using IH1 IH2 `res1 = Lv Sig bs1` `res2 = Lv Sig bs2` by (metis \<open>length bs1 = len1\<close> \<open>length bs2 = len2\<close> beval_raw.intros(27) beval_world_raw.cases beval_world_raw.intros) qed next case (10 t w sig) then show ?case by (auto intro!: beval_world_raw.intros beval_raw.intros simp add: state_of_world_def) next case (11 t w) then show ?case by (auto intro!: beval_world_raw.intros beval_raw.intros) next case (12 t w) then show ?case by (auto intro!: beval_world_raw.intros beval_raw.intros) next case (13 t w sig dly) have res_def: "res = (if t - dly < t then snd w sig (t - dly) else if 0 < t then snd w sig (t - 1) else fst w sig)" using 13 by auto have "t - dly < t \<or> t - dly = t" by linarith moreover { assume "t - dly < t" hence "signal_of (fst w sig) (derivative_hist_raw w t) sig (t - dly) = snd w sig (t - dly)" using signal_of_derivative_hist_raw by metis also have "... = res" unfolding res_def using `t - dly < t` by auto finally have "signal_of (fst w sig) (derivative_hist_raw w t) sig (t - dly) = res" by auto } moreover { assume "t - dly = t" have "0 < t \<or> t = 0" by auto moreover { assume " 0 < t" hence "signal_of (fst w sig) (derivative_hist_raw w t) sig (t - dly) = snd w sig (t - 1)" using `t - dly = t` signal_of_derivative_hist_raw2 by (metis diff_le_self) also have "... = res" unfolding res_def using `t - dly = t` `0 < t` by auto finally have "signal_of (fst w sig) (derivative_hist_raw w t) sig (t - dly) = res" by auto } moreover { assume "t = 0" hence "signal_of (fst w sig) (derivative_hist_raw w t) sig (t - dly) = fst w sig" using signal_of_derivative_hist_raw3 by (metis \<open>t - dly = t\<close> diff_le_self) also have "... = res" unfolding res_def using `t = 0` by auto finally have "signal_of (fst w sig) (derivative_hist_raw w t) sig (t - dly) = res" by auto } ultimately have "signal_of (fst w sig) (derivative_hist_raw w t) sig (t - dly) = res" by auto } ultimately have "signal_of (fst w sig) (derivative_hist_raw w t) sig (t - dly) = res" by auto thus ?case by (meson beval_raw.intros(4) beval_world_raw.intros) next case (14 t w sig) then show ?case by (auto intro!: beval_world_raw.intros beval_raw.intros simp add: event_of_world_def event_of_alt_def) (smt beval_raw.intros(5) mem_Collect_eq)+ next case (15 t w e) hence "bexp_wt \<Gamma> e ty" using bexp_wt_cases(1) by blast obtain bool ki bs where "eval_world_raw t w e = Bv bool \<or> eval_world_raw t w e = Lv ki bs" using val.exhaust_sel by blast moreover { assume "eval_world_raw t w e = Bv bool" hence " beval_world_raw w t e (Bv bool)" using 15(1) "15.prems"(2) \<open>bexp_wt \<Gamma> e ty\<close> by blast hence " res = Bv (\<not> bool)" using 15(2) `eval_world_raw t w e = Bv bool` by auto hence ?case using `beval_world_raw w t e (Bv bool)` beval_raw.intros(6) by (intro beval_world_raw.intros) blast+ } moreover { assume "eval_world_raw t w e = Lv ki bs" hence "res = Lv ki (map Not bs)" using 15(2) by auto hence IH : "beval_world_raw w t e (Lv ki bs)" using 15 \<open>bexp_wt \<Gamma> e ty\<close> \<open>eval_world_raw t w e = Lv ki bs\<close> by blast hence ?case using `res = Lv ki (map Not bs)` beval_raw.intros(7) by (intro beval_world_raw.intros) blast+ } ultimately show ?case by auto next case (16 t w sig l r) then obtain ki bs where *: "eval_world_raw t w (Bsig sig) = Lv ki bs" by (meson bexp_wt_cases_slice(1) eval_world_raw_lv) hence IH: "beval_world_raw w t (Bsig sig) (Lv ki bs)" using 16 bexp_wt.intros(3) by fastforce have "res = Lv ki (nths bs {length bs - l - 1..length bs - r - 1})" using * 16 unfolding eval_world_raw.simps by auto then show ?case using IH beval_raw.intros(20) by (metis beval_world_raw.cases beval_world_raw.intros) next case (17 t w sig idx) then obtain ki bs where *: "eval_world_raw t w (Bsig sig) = Lv ki bs" by (meson bexp_wt_cases_slice(3) eval_world_raw_lv) hence IH: " beval_world_raw w t (Bsig sig) (Lv ki bs)" using 17 using bexp_wt.intros(3) by fastforce have "eval_world_raw t w (Bsig sig) = snd w sig t" by simp hence "res = Bv (bs ! idx)" using 17 * unfolding eval_world_raw.simps by auto then show ?case using IH beval_raw.intros(21) by (metis beval_world_raw.cases beval_world_raw.intros) next case (18 t w e n) then obtain ki bs where *: "eval_world_raw t w e = Lv ki bs" by (meson bexp_wt_cases_shiftl eval_world_raw_lv) hence IH : "beval_world_raw w t e (Lv ki bs)" using 18 bexp_wt_cases_shiftl by force have "ki = Uns \<or> ki = Sig" using `bexp_wt \<Gamma> (Bshiftl e n) ty` by (metis "*" "18.prems"(2) bexp_wt_cases_shiftl eval_world_raw_lv val.inject(2)) hence "res = Lv ki (drop n (bs @ replicate n False))" using * 18 unfolding eval_world_raw.simps by auto then show ?case using IH by (smt "18.prems"(2) "18.prems"(3) beval_raw.intros(28) beval_raw.intros(29) beval_raw_preserve_well_typedness beval_world_raw.cases beval_world_raw.intros bexp_wt_cases_shiftl ty.inject type_of.simps(2) wityping_def wityping_ensure_styping wityping_ensure_ttyping) next case (19 t w e n) then obtain ki bs where *: "eval_world_raw t w e = Lv ki bs" by (meson bexp_wt_cases_shiftr eval_world_raw_lv) hence IH : "beval_world_raw w t e (Lv ki bs)" using 19 by (metis bexp_wt_cases_shiftr) have "ki = Uns \<or> ki = Sig" using `bexp_wt \<Gamma> (Bshiftr e n) ty` by (metis "*" "19.prems"(2) bexp_wt_cases_shiftr eval_world_raw_lv val.inject(2)) moreover { assume "ki = Uns" hence "res = Lv Uns (take (length bs) (replicate n False @ bs))" using 19(2) * unfolding eval_world_raw.simps by auto hence ?case using IH unfolding `ki = Uns` by (meson beval_raw.intros(30) beval_world_raw.cases beval_world_raw.intros) } moreover { assume "ki = Sig" hence "res = Lv Sig (take (length bs) (replicate n (hd bs) @ bs))" using 19(2) * unfolding eval_world_raw.simps by auto hence ?case using IH unfolding `ki = Sig` by (meson beval_raw.intros(31) beval_world_raw.cases beval_world_raw.intros) } ultimately show ?case by auto next case (20 t w th guard el) hence "bexp_wt \<Gamma> guard Bty" using bexp_wt_cases_when[OF 20(6)] by auto have " eval_world_raw t w guard = Bv True \<or> eval_world_raw t w guard = Bv False" by (metis "20.prems"(2) \<open>bexp_wt \<Gamma> guard Bty\<close> eval_world_raw_bv val.inject(1)) moreover { assume "eval_world_raw t w guard = Bv True" hence IH0: "beval_world_raw w t guard (Bv True)" using 20(1) "20.prems"(2) \<open>bexp_wt \<Gamma> guard Bty\<close> by blast have "res = eval_world_raw t w th" using `eval_world_raw t w guard = Bv True` 20(4) by auto hence " beval_world_raw w t th res" using 20(2) "20.prems"(2) "20.prems"(3) \<open>eval_world_raw t w guard = Bv True\<close> bexp_wt_cases_when by blast hence ?case using IH0 by (meson beval_raw.intros(32) beval_world_raw.cases beval_world_raw.intros) } moreover { assume "eval_world_raw t w guard = Bv False" hence IH0: "beval_world_raw w t guard (Bv False)" using 20(1) "20.prems"(2) \<open>bexp_wt \<Gamma> guard Bty\<close> by blast have "res = eval_world_raw t w el" using `eval_world_raw t w guard = Bv False` 20(4) by auto hence " beval_world_raw w t el res" using 20(3) "20.prems"(2) "20.prems"(3) \<open>eval_world_raw t w guard = Bv False\<close> bexp_wt_cases_when by blast hence ?case by (meson IH0 beval_raw.intros(33) beval_world_raw.cases beval_world_raw.intros) } ultimately show ?case by auto next case (21 t w sign val) then show ?case by (metis beval_raw.intros(34) beval_world_raw.intros eval_world_raw.simps(21)) qed lemma eval_world_raw_correctness_only_if: assumes "beval_world_raw w t exp res" assumes "wityping \<Gamma> w" and "bexp_wt \<Gamma> exp ty" shows "eval_world_raw t w exp = res" using assms by (metis beval_raw_deterministic beval_world_raw.cases eval_world_raw_correctness_if) section \<open>Typed hoare logic for sequential statements\<close> abbreviation eval_world_raw2 where "eval_world_raw2 tw exp \<equiv> eval_world_raw (fst tw) (snd tw) exp" lemma eval_world_raw2_irrelevant: assumes "sig \<notin> set_bexp v" shows "eval_world_raw2 a[ sig, dly :=\<^sub>2 eval_world_raw2 a exp] v = eval_world_raw2 a v" using assms by (induction v) (auto simp add: worldline_upd2_def worldline_upd_def event_of_alt_def split: val.splits bool.splits) lemma eval_world_raw2_irrelevant_inert: assumes "sig \<notin> set_bexp v" shows "eval_world_raw2 a\<lbrakk> sig, dly :=\<^sub>2 eval_world_raw2 a exp\<rbrakk> v = eval_world_raw2 a v" using assms proof (induction v) case (Bsig x) then show ?case apply (induction "eval_world_raw2 a exp") unfolding worldline_inert_upd2_def by (smt bexp.simps(944) eval_world_raw.simps(10) fst_worldline_inert_upd2 insertCI sndI worldline_inert_upd2.simps(1) fstI fun_upd_def insertCI snd_conv worldline_inert_upd2.simps(2) worldline_inert_upd2_def worldline_inert_upd_def)+ next case (Bsig_event x) then show ?case unfolding worldline_inert_upd2_def apply (induction "eval_world_raw2 a exp") apply (smt bexp.simps(945) comp_apply eval_world_raw.simps(14) event_of_alt_def fstI insertCI mem_Collect_eq snd_conv worldline_inert_upd2.simps(1) worldline_inert_upd_def) by (smt bexp.simps(945) comp_apply eval_world_raw.simps(14) event_of_alt_def fstI fun_upd_def insertCI mem_Collect_eq snd_conv worldline_inert_upd2.simps(2)) next case (Bsig_delayed x1a x2a) then show ?case unfolding worldline_inert_upd2_def apply (induction "eval_world_raw2 a exp") apply (smt bexp.simps(946) eval_world_raw.simps(13) insertCI prod.collapse prod.simps(1) worldline_inert_upd2.simps(1) worldline_inert_upd_def) by (smt bexp.simps(946) eval_world_raw.simps(13) fstI fun_upd_def insertCI snd_conv worldline_inert_upd2.simps(2)) next case (Bnot v) then show ?case unfolding worldline_inert_upd2_def apply (induction "eval_world_raw2 a exp") apply (smt bexp.simps eval_world_raw.simps insertCI prod.collapse prod.simps(1) worldline_inert_upd2.simps(1) worldline_inert_upd_def) by (smt bexp.simps eval_world_raw.simps fstI fun_upd_def insertCI snd_conv worldline_inert_upd2.simps(2)) next case (Band v1 v2) then show ?case unfolding worldline_inert_upd2_def by (induction "eval_world_raw2 a exp") auto next case (Bor v1 v2) then show ?case unfolding worldline_inert_upd2_def by (induction "eval_world_raw2 a exp")auto next case (Bnand v1 v2) then show ?case unfolding worldline_inert_upd2_def by (induction "eval_world_raw2 a exp")auto next case (Bnor v1 v2) then show ?case unfolding worldline_inert_upd2_def by (induction "eval_world_raw2 a exp")auto next case (Bxor v1 v2) then show ?case unfolding worldline_inert_upd2_def by (induction "eval_world_raw2 a exp")auto next case (Bxnor v1 v2) then show ?case unfolding worldline_inert_upd2_def by (induction "eval_world_raw2 a exp")auto next case Btrue then show ?case unfolding worldline_inert_upd2_def by (induction "eval_world_raw2 a exp")auto next case Bfalse then show ?case unfolding worldline_inert_upd2_def by (induction "eval_world_raw2 a exp")auto next case (Bslice x1a x2a x3) then show ?case unfolding worldline_inert_upd2_def apply (induction "eval_world_raw2 a exp") apply (smt bexp.simps(956) eval_world_raw.simps(10) eval_world_raw.simps(16) fst_conv insertCI sndI worldline_inert_upd2.simps(1) worldline_inert_upd_def) by (smt bexp.simps(956) eval_world_raw.simps(10) eval_world_raw.simps(16) fstI fun_upd_apply insertCI snd_conv worldline_inert_upd2.simps(2)) next case (Bindex x1a x2a) then show ?case unfolding worldline_inert_upd2_def apply (induction "eval_world_raw2 a exp") apply (smt bexp.simps(957) eval_world_raw.simps(10) eval_world_raw.simps(17) fst_conv insertCI sndI worldline_inert_upd2.simps(1) worldline_inert_upd_def) by (smt bexp.simps(957) eval_world_raw.simps(10) eval_world_raw.simps(17) fstI fun_upd_apply insertCI snd_conv worldline_inert_upd2.simps(2)) next case (Badd v1 v2) then show ?case unfolding worldline_inert_upd2_def by (induction "eval_world_raw2 a exp") auto next case (Bmult v1 v2) then show ?case by (induction "eval_world_raw2 a exp") auto next case (Bsub v1 v2) then show ?case by (induction "eval_world_raw2 a exp") auto next case (Bshiftl v x2a) then show ?case by (induction "eval_world_raw2 a exp") auto next case (Bshiftr v x2a) then show ?case by (induction "eval_world_raw2 a exp") auto next case (Bwhen v1 v2 v3) then show ?case by (induction "eval_world_raw2 a exp") (auto simp add: worldline_inert_upd2_def worldline_inert_upd_def event_of_alt_def split: val.splits bool.splits) next case (Bliteral x1a x2a) then show ?case by (induction "eval_world_raw2 a exp") auto qed lemma eval_world_raw2_simp: assumes "0 < dly" shows " eval_world_raw2 tw[ sig, dly :=\<^sub>2 v] expr = eval_world_raw2 tw expr" using assms by (induction expr) (auto simp add: worldline_upd2_def worldline_upd_def event_of_alt_def split:val.splits bool.splits) lemma eval_world_raw2_suc[simp]: "eval_world_raw2 (tw[ sig, 1 :=\<^sub>2 v]) exp = eval_world_raw2 tw exp" by (induction exp) (auto simp add: worldline_upd2_def worldline_upd_def event_of_alt_def split:val.splits bool.splits) lemma type_of_eval_world_raw2: assumes "bexp_wt \<Gamma> expr ty" shows "\<And>tw. wityping \<Gamma> (snd tw) \<Longrightarrow> type_of (eval_world_raw2 tw expr) = ty" using assms proof (induction expr arbitrary: ty) case (Bsig x) then show ?case by (metis bexp_wt_cases_slice(2) eval_world_raw.simps(10) wityping_def wtyping_def) next case (Bsig_event x) have "ty = Bty" using bexp_wt_cases_all[OF Bsig_event(2)] by auto then show ?case by auto next case (Bsig_delayed x1a x2a) hence "ty = \<Gamma> x1a" using bexp_wt_cases_all[OF Bsig_delayed(2)] by auto then show ?case using Bsig_delayed(1) unfolding wityping_def wtyping_def styping_def by auto next case (Bnot expr) hence "bexp_wt \<Gamma> expr ty" using bexp_wt_cases(1)[OF Bnot(3)] by blast then show ?case using Bnot(1)[OF Bnot(2)] by (auto split:val.splits) next case (Band expr1 expr2) moreover hence " type_of (eval_world_raw2 tw expr1) = ty" using bexp_wt_cases(2) by blast moreover have "type_of (eval_world_raw2 tw expr2) = ty" using Band.IH(2) Band.prems(1) Band.prems(2) bexp_wt_cases(2) by blast ultimately show ?case by (auto split:val.splits) next case (Bor expr1 expr2) moreover hence " type_of (eval_world_raw2 tw expr1) = ty" using bexp_wt_cases(3) by blast moreover have "type_of (eval_world_raw2 tw expr2) = ty" by (meson bexp_wt_cases(3) calculation(2) calculation(3) calculation(4)) ultimately show ?case by (auto split: val.splits) next case (Bnand expr1 expr2) moreover hence " type_of (eval_world_raw2 tw expr1) = ty" using bexp_wt_cases(4) by blast moreover have "type_of (eval_world_raw2 tw expr2) = ty" by (meson bexp_wt_cases(4) calculation(2) calculation(3) calculation(4)) ultimately show ?case by (auto split:val.splits) next case (Bnor expr1 expr2) moreover hence " type_of (eval_world_raw2 tw expr1) = ty" using bexp_wt_cases(5) by blast moreover have "type_of (eval_world_raw2 tw expr2) = ty" by (meson bexp_wt_cases(5) calculation(2) calculation(3) calculation(4)) ultimately show ?case by (auto split:val.splits) next case (Bxor expr1 expr2) moreover hence " type_of (eval_world_raw2 tw expr1) = ty" using bexp_wt_cases(6) by blast moreover have "type_of (eval_world_raw2 tw expr2) = ty" by (meson bexp_wt_cases(6) calculation(2) calculation(3) calculation(4)) ultimately show ?case by (auto split:val.splits) next case (Bxnor expr1 expr2) moreover hence " type_of (eval_world_raw2 tw expr1) = ty" using bexp_wt_cases(7) by blast moreover have "type_of (eval_world_raw2 tw expr2) = ty" by (meson bexp_wt_cases(7) calculation(2) calculation(3) calculation(4)) ultimately show ?case by (auto split:val.splits) next case Btrue have "ty = Bty" using bexp_wt_cases_all[OF Btrue(2)] by auto then show ?case by auto next case Bfalse have "ty = Bty" using bexp_wt_cases_all[OF Bfalse(2)] by auto then show ?case by auto next case (Bslice x1a x2a x3) show ?case by (metis Bslice.prems(1) Bslice.prems(2) bexp_wt_cases_slice(1) eval_world_raw_lv type_of.simps(2)) next case (Bindex x1a x2a) then show ?case by (metis bexp_wt_cases_slice(3) eval_world_raw_bv type_of.simps(1)) next case (Badd expr1 expr2) then obtain ki len1 where *: " type_of (eval_world_raw2 tw expr1) = Lty ki len1" using bexp_wt_cases_add[OF Badd(4)] by (metis eval_world_raw_lv type_of.simps(2)) then obtain ki len2 where **: "type_of (eval_world_raw2 tw expr2) = Lty ki len2" using bexp_wt_cases_add[OF Badd(4)] by (metis Badd(3) eval_world_raw_lv type_of.simps(2)) hence "ty = Lty ki (max len1 len2)" using bexp_wt_cases_add[OF Badd(4)] by (smt Badd.prems(1) * eval_world_raw_lv ty.inject type_of.simps(2)) then show ?case using * ** by (metis Badd.prems(1) Badd.prems(2) eval_world_raw_lv type_of.simps(2)) next case (Bmult expr1 expr2) then obtain ki len1 where *: " type_of (eval_world_raw2 tw expr1) = Lty ki len1" using bexp_wt_cases_mult[OF Bmult(4)] by (metis eval_world_raw_lv type_of.simps(2)) then obtain ki len2 where **: "type_of (eval_world_raw2 tw expr2) = Lty ki len2" using bexp_wt_cases_mult[OF Bmult(4)] by (metis Bmult(3) eval_world_raw_lv type_of.simps(2)) hence "ty = Lty ki (len1 + len2)" using bexp_wt_cases_mult[OF Bmult(4)] by (smt "*" Bmult(3) eval_world_raw_lv ty.inject type_of.simps(2)) then show ?case using * ** by (metis Bmult.prems(1) Bmult.prems(2) eval_world_raw_lv type_of.simps(2)) next case (Bsub expr1 expr2) then obtain ki len1 where *: " type_of (eval_world_raw2 tw expr1) = Lty ki len1" using bexp_wt_cases_sub[OF Bsub(4)] by (metis eval_world_raw_lv type_of.simps(2)) then obtain ki len2 where **: "type_of (eval_world_raw2 tw expr2) = Lty ki len2" using bexp_wt_cases_sub[OF Bsub(4)] by (metis Bsub.prems(1) eval_world_raw_lv type_of.simps(2)) hence "ty = Lty ki (max len1 len2)" using bexp_wt_cases_sub[OF Bsub(4)] by (smt "*" Bsub.prems(1) eval_world_raw_lv ty.inject type_of.simps(2)) then show ?case using * ** by (metis Bsub.prems(1) Bsub.prems(2) eval_world_raw_lv type_of.simps(2)) next case (Bshiftl expr x2a) then obtain ki len where "ty = Lty ki len" and "0 < len" using bexp_wt_cases_shiftl[OF Bshiftl(3)] by metis then show ?case by (metis Bshiftl.prems(1) Bshiftl.prems(2) eval_world_raw_lv type_of.simps(2)) next case (Bshiftr expr x2a) then obtain ki len where "ty = Lty ki len" and "0 < len" using bexp_wt_cases_shiftr[OF Bshiftr(3)] by metis then show ?case by (metis Bshiftr.prems(1) Bshiftr.prems(2) eval_world_raw_lv type_of.simps(2)) next case (Bwhen expr1 expr2 expr3) hence "bexp_wt \<Gamma> expr2 Bty" using bexp_wt_cases_when[OF Bwhen(5)] by blast hence *: "type_of (eval_world_raw2 tw expr2) = Bty" using Bwhen by blast have "bexp_wt \<Gamma> expr3 ty" and "bexp_wt \<Gamma> expr1 ty" using bexp_wt_cases_when[OF Bwhen(5)] by blast+ hence "type_of (eval_world_raw2 tw expr1) = ty" and "type_of (eval_world_raw2 tw expr3) = ty" using Bwhen by blast+ then show ?case using * by (auto split:val.splits bool.splits) next case (Bliteral x1a x2a) then show ?case using bexp_wt_cases_lit by fastforce qed lemma worldline_upd_eval_world_raw_preserve_wityping: assumes "wityping \<Gamma> (snd tw)" assumes "bexp_wt \<Gamma> expr (\<Gamma> sig)" shows "wityping \<Gamma> (snd (tw[ sig, t :=\<^sub>2 eval_world_raw2 tw expr]))" using assms by (simp add: type_of_eval_world_raw2 worldline_upd2_def worldline_upd_preserve_wityping) lemma worldline_upd_eval_world_raw_preserve_wityping2: assumes "wityping \<Gamma> (snd tw)" assumes "type_of v = \<Gamma> sig" shows "wityping \<Gamma> (snd (tw[ sig, t :=\<^sub>2 v]))" using assms by (simp add: worldline_upd2_def worldline_upd_preserve_wityping) inductive seq_hoare3 :: "'signal tyenv \<Rightarrow> 'signal assn2 \<Rightarrow> 'signal seq_stmt \<Rightarrow> 'signal assn2 \<Rightarrow> bool" (" (1_) \<turnstile> ([(1_)]/ (_)/ [(1_)])" 50) where Null3: " \<Gamma> \<turnstile> [P] Bnull [P]" | Assign3: "\<Gamma> \<turnstile> [\<lambda>tw. P(tw[sig, dly :=\<^sub>2 eval_world_raw2 tw exp])] Bassign_trans sig exp dly [P]" | AssignI3: "\<Gamma> \<turnstile> [\<lambda>tw. P( tw\<lbrakk>sig, dly :=\<^sub>2 eval_world_raw2 tw exp\<rbrakk>)] Bassign_inert sig exp dly [P]" | Comp3: "\<lbrakk> \<Gamma> \<turnstile> [P] s1 [Q]; \<Gamma> \<turnstile> [Q] s2 [R]\<rbrakk> \<Longrightarrow> \<Gamma> \<turnstile> [P] Bcomp s1 s2 [R]" | If3: "\<lbrakk>\<Gamma> \<turnstile> [\<lambda>tw. P tw \<and> eval_world_raw2 tw g = (Bv True)] s1 [Q]; \<Gamma> \<turnstile> [\<lambda>tw. P tw \<and> eval_world_raw2 tw g = (Bv False)] s2 [Q]\<rbrakk> \<Longrightarrow> \<Gamma> \<turnstile> [P] Bguarded g s1 s2 [Q]" | Conseq3: "\<lbrakk>\<forall>tw. wityping \<Gamma> (snd tw) \<and> P' tw \<longrightarrow> P tw; \<Gamma> \<turnstile> [P] s [Q]; \<forall>tw. Q tw \<longrightarrow> Q' tw\<rbrakk> \<Longrightarrow> \<Gamma> \<turnstile> [P'] s [Q']" | Conj3: "\<Gamma> \<turnstile> [P] s [Q1] \<Longrightarrow> \<Gamma> \<turnstile> [P] s [Q2] \<Longrightarrow> \<Gamma> \<turnstile> [P] s [\<lambda>tw. Q1 tw \<and> Q2 tw]" | Bcase_empty_choices3: " \<Gamma> \<turnstile> [P] Bcase exp [] [P]" | Bcase_others3: " \<Gamma> \<turnstile> [P] ss [Q] \<Longrightarrow> \<Gamma> \<turnstile> [P] Bcase exp ((Others, ss) # choices) [Q]" | Bcase_if3: "\<Gamma> \<turnstile> [\<lambda>tw. P tw \<and> (eval_world_raw2 tw exp = eval_world_raw2 tw exp')] ss [Q] \<Longrightarrow> \<Gamma> \<turnstile> [\<lambda>tw. P tw \<and> (eval_world_raw2 tw exp \<noteq> eval_world_raw2 tw exp')] Bcase exp choices [Q] \<Longrightarrow> \<Gamma> \<turnstile> [P] Bcase exp ((Explicit exp', ss) # choices) [Q]" lemma seq_hoare3_soundness: assumes "\<Gamma> \<turnstile> [P] ss [Q]" assumes "seq_wt \<Gamma> ss" and "nonneg_delay ss" shows "\<Gamma> \<Turnstile> [P] ss [Q]" using assms proof (induction rule:seq_hoare3.induct) case (Null3 P) then show ?case unfolding seq_hoare_valid2_wt_def using world_seq_exec_bnull world_seq_exec_deterministic by blast next case (Assign3 \<Gamma> P sig dly exp) then obtain ty where "bexp_wt \<Gamma> exp ty" and "0 < dly" by auto then show ?case unfolding seq_hoare_valid2_wt_def by (metis beval_world_raw2_def eval_world_raw_correctness_only_if lift_world_trans_worldline_upd2) next case (AssignI3 \<Gamma> P sig dly exp) then obtain ty where "bexp_wt \<Gamma> exp ty" and "0 < dly" by auto then show ?case unfolding seq_hoare_valid2_wt_def by (metis beval_world_raw2_def eval_world_raw_correctness_only_if lift_world_inert_worldline_upd2) next case (Comp3 \<Gamma> P s1 Q s2 R) hence " \<Gamma> \<Turnstile> [P] s1 [Q]" and " \<Gamma> \<Turnstile> [Q] s2 [R]" using nonneg_delay.simps(2) by blast+ then show ?case unfolding seq_hoare_valid2_wt_def using Comp3(6) world_seq_exec_comp by (smt Comp3.prems(1) nonneg_delay.simps(2) seq_hoare_valid2_def seq_stmt_preserve_wityping_hoare seq_wt_cases(2) soundness_hoare2 world_seq_exec_alt_cases(2) world_seq_exec_alt_imp_world_seq_exec world_seq_exec_imp_world_seq_exec_alt) next case (If3 \<Gamma> P g s1 Q s2) have "nonneg_delay s1" and "nonneg_delay s2" using If3 nonneg_delay.simps(3) by blast+ have "\<Gamma> \<Turnstile> [\<lambda>a. P a \<and> eval_world_raw2 a g = Bv True] s1 [Q]" and " \<Gamma> \<Turnstile> [\<lambda>a. P a \<and> eval_world_raw2 a g = Bv False] s2 [Q]" using If3 nonneg_delay.simps(3) by blast+ then show ?case unfolding seq_hoare_valid2_wt_def world_seq_exec_alt_def[OF If3(6), THEN sym] world_seq_exec_alt_def[OF `nonneg_delay s1`, THEN sym] world_seq_exec_alt_def[OF `nonneg_delay s2`, THEN sym] by (metis If3.prems(1) beval_world_raw2_def eval_world_raw_correctness_only_if seq_wt_cases(3) world_seq_exec_alt_cases(3)) next case (Conseq3 \<Gamma> P' P s Q Q') hence " \<Gamma> \<Turnstile> [P] s [Q]" by blast then show ?case using Conseq3(1) Conseq3(3) unfolding seq_hoare_valid2_wt_def by blast next case (Conj3 \<Gamma> P s Q1 Q2) hence "\<Gamma> \<Turnstile> [P] s [Q1]" and "\<Gamma> \<Turnstile> [P] s [Q1]" by blast+ then show ?case unfolding seq_hoare_valid2_wt_def by (metis Conj3.IH(2) Conj3.prems(1) Conj3.prems(2) seq_hoare_valid2_wt_def) next case (Bcase_empty_choices3 \<Gamma> P exp) then show ?case unfolding seq_hoare_valid2_wt_def using world_seq_exec_bcase_empty world_seq_exec_deterministic by blast next case (Bcase_others3 \<Gamma> P ss Q exp choices) hence "seq_wt \<Gamma> ss " using seq_wt.cases by auto moreover have "nonneg_delay ss" using Bcase_others3 by auto ultimately have " \<Gamma> \<Turnstile> [P] ss [Q]" using Bcase_others3(2) by auto then show ?case unfolding seq_hoare_valid2_wt_def using bcase_others_tw_elim by blast next case (Bcase_if3 \<Gamma> P exp exp' ss Q choices) hence "seq_wt \<Gamma> ss" and "seq_wt \<Gamma> (Bcase exp choices)" using seq_wt_cases_bcase by auto moreover obtain ty where ty: "bexp_wt \<Gamma> exp ty \<and> bexp_wt \<Gamma> exp' ty" using Bcase_if3.prems(1) seq_wt_cases_bcase by force moreover have " nonneg_delay ss" and "nonneg_delay (Bcase exp choices)" using Bcase_if3(6) by auto ultimately have 1: "\<Gamma> \<Turnstile> [\<lambda>a. P a \<and> eval_world_raw2 a exp = eval_world_raw2 a exp'] ss [Q]" and 2: "\<Gamma> \<Turnstile> [\<lambda>a. P a \<and> eval_world_raw2 a exp \<noteq> eval_world_raw2 a exp'] Bcase exp choices [Q]" using Bcase_if3(3-4) by auto show ?case unfolding seq_hoare_valid2_wt_def world_seq_exec_alt_def[OF Bcase_if3(6), THEN sym] proof (intro allI, intro impI) fix tw tw' :: "nat \<times> ('a \<Rightarrow> val) \<times> ('a \<Rightarrow> nat \<Rightarrow> val)" assume asm: "wityping \<Gamma> (snd tw) \<and> P tw \<and> world_seq_exec_alt tw (Bcase exp ((Explicit exp', ss) # choices)) tw'" hence "world_seq_exec_alt tw (Bcase exp ((Explicit exp', ss) # choices)) tw'" by auto have "eval_world_raw2 tw exp = eval_world_raw2 tw exp' \<or> eval_world_raw2 tw exp \<noteq> eval_world_raw2 tw exp'" by auto moreover { assume "eval_world_raw2 tw exp = eval_world_raw2 tw exp'" obtain res where " beval_world_raw (snd tw) (fst tw) exp res" using eval_world_raw_correctness_if ty asm by blast obtain res' where "beval_world_raw (snd tw) (fst tw) exp' res'" using eval_world_raw_correctness_if ty asm by blast hence "world_seq_exec_alt tw ss tw'" using world_seq_exec_alt.cases[OF `world_seq_exec_alt tw (Bcase exp ((Explicit exp', ss) # choices)) tw'`] by (smt Pair_inject \<open>eval_world_raw2 tw exp = eval_world_raw2 tw exp'\<close> asm beval_world_raw2_def choices.inject eval_world_raw_correctness_only_if list.distinct(1) list.inject seq_stmt.distinct(29) seq_stmt.distinct(9) seq_stmt.inject(5) seq_stmt.simps(23) seq_stmt.simps(29) seq_stmt.simps(33) ty) hence "Q tw'" by (metis (mono_tags, lifting) "1" \<open>eval_world_raw2 tw exp = eval_world_raw2 tw exp'\<close> \<open>nonneg_delay ss\<close> asm seq_hoare_valid2_wt_def world_seq_exec_alt_imp_world_seq_exec) } moreover { assume "eval_world_raw2 tw exp \<noteq> eval_world_raw2 tw exp'" obtain res where " beval_world_raw (snd tw) (fst tw) exp res" using eval_world_raw_correctness_if ty asm by blast obtain res' where "beval_world_raw (snd tw) (fst tw) exp' res'" using eval_world_raw_correctness_if ty asm by blast hence "world_seq_exec_alt tw (Bcase exp choices) tw'" using world_seq_exec_alt.cases[OF `world_seq_exec_alt tw (Bcase exp ((Explicit exp', ss) # choices)) tw'`] by (smt Pair_inject \<open>eval_world_raw2 tw exp \<noteq> eval_world_raw2 tw exp'\<close> asm beval_world_raw2_def choices.distinct(1) choices.inject eval_world_raw_correctness_only_if list.distinct(1) list.inject seq_stmt.distinct(29) seq_stmt.distinct(9) seq_stmt.inject(5) seq_stmt.simps(23) seq_stmt.simps(29) seq_stmt.simps(33) ty) hence "Q tw'" by (smt "2" \<open>eval_world_raw2 tw exp \<noteq> eval_world_raw2 tw exp'\<close> \<open>nonneg_delay (Bcase exp choices)\<close> asm seq_hoare_valid2_wt_def world_seq_exec_alt_imp_world_seq_exec) } ultimately show "Q tw'" by auto qed qed text \<open>weakest precondition for typed hoare logic\<close> definition wp3 :: "'signal tyenv \<Rightarrow> 'signal seq_stmt \<Rightarrow> 'signal assn2 \<Rightarrow> 'signal assn2" where "wp3 \<Gamma> ss Q = (\<lambda>tw. wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. (tw, ss \<Rightarrow>\<^sub>s tw') \<longrightarrow> Q tw'))" lemma wp3_bnull: "wp3 \<Gamma> Bnull Q = (\<lambda>tw. Q tw \<and> wityping \<Gamma> (snd tw))" apply (rule ext) unfolding wp3_def using world_seq_exec_bnull world_seq_exec_deterministic by blast lemma wp3_bcomp: assumes "seq_wt \<Gamma> (Bcomp ss1 ss2)" and "nonneg_delay (Bcomp ss1 ss2)" shows "wp3 \<Gamma> (Bcomp ss1 ss2) Q = wp3 \<Gamma> ss1 (wp3 \<Gamma> ss2 Q)" apply (rule ext) unfolding wp3_def proof (rule, rule, simp, rule, rule, rule) fix x tw' :: "nat \<times> ('a \<Rightarrow> val) \<times> ('a \<Rightarrow> nat \<Rightarrow> val)" have "seq_wt \<Gamma> ss1" and "seq_wt \<Gamma> ss2" using assms by blast+ assume asm: "wityping \<Gamma> (snd x) \<and> (\<forall>tw'. x, Bcomp ss1 ss2 \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw')" and "x, ss1 \<Rightarrow>\<^sub>s tw'" thus " wityping \<Gamma> (snd tw')" using soundness_hoare2[OF seq_stmt_preserve_wityping_hoare[OF `seq_wt \<Gamma> ss1`]] assms(2) unfolding seq_hoare_valid2_def using nonneg_delay.simps(2) by blast { fix tw2 assume "tw', ss2 \<Rightarrow>\<^sub>s tw2" hence "x, Bcomp ss1 ss2 \<Rightarrow>\<^sub>s tw2" using `x, ss1 \<Rightarrow>\<^sub>s tw'` using assms(2) world_seq_exec_comp by blast with asm have " Q tw2" by blast moreover have "wityping \<Gamma> (snd tw2)" using `wityping \<Gamma> (snd tw')` `tw', ss2 \<Rightarrow>\<^sub>s tw2` soundness_hoare2[OF seq_stmt_preserve_wityping_hoare[OF `seq_wt \<Gamma> ss2`]] assms(2) unfolding seq_hoare_valid2_def using nonneg_delay.simps(2) by blast ultimately have "Q tw2 \<and> wityping \<Gamma> (snd tw2)" by auto } thus " \<forall>tw'a. tw', ss2 \<Rightarrow>\<^sub>s tw'a \<longrightarrow> Q tw'a" by auto next fix x assume *: " wityping \<Gamma> (snd x) \<and> (\<forall>tw'. x, ss1 \<Rightarrow>\<^sub>s tw' \<longrightarrow> wityping \<Gamma> (snd tw') \<and> (\<forall>tw'a. tw', ss2 \<Rightarrow>\<^sub>s tw'a \<longrightarrow> Q tw'a))" hence "(\<forall>tw'. x, Bcomp ss1 ss2 \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw')" by (meson assms(2) nonneg_delay.simps(2) world_seq_exec_alt_cases(2) world_seq_exec_alt_imp_world_seq_exec world_seq_exec_imp_world_seq_exec_alt) moreover have "wityping \<Gamma> (snd x)" using * by auto ultimately show "wityping \<Gamma> (snd x) \<and> (\<forall>tw'. x, Bcomp ss1 ss2 \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw')" by auto qed lemma wp3_bguarded: assumes "seq_wt \<Gamma> (Bguarded g ss1 ss2)" and "nonneg_delay (Bguarded g ss1 ss2)" shows "wp3 \<Gamma> (Bguarded g ss1 ss2) Q = (\<lambda>tw. if eval_world_raw2 tw g = Bv True then wp3 \<Gamma> ss1 Q tw else wp3 \<Gamma> ss2 Q tw)" apply (rule ext) unfolding wp3_def proof (rule) fix tw obtain ty where bwt: "bexp_wt \<Gamma> g ty" and "seq_wt \<Gamma> ss1" and "seq_wt \<Gamma> ss2" using assms by blast assume asm: " wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, Bguarded g ss1 ss2 \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw')" hence wt: "wityping \<Gamma> (snd tw)" by auto have "eval_world_raw2 tw g = Bv True \<or> eval_world_raw2 tw g \<noteq> Bv True" by auto moreover { assume "eval_world_raw2 tw g = Bv True" hence "beval_world_raw2 tw g (Bv True)" using eval_world_raw_correctness_if[OF _ wt bwt] by (simp add: beval_world_raw2_def) { fix tw' assume "tw, ss1 \<Rightarrow>\<^sub>s tw'" hence "Q tw'" using asm world_seq_exec_guarded[OF `beval_world_raw2 tw g (Bv True)` `tw, ss1 \<Rightarrow>\<^sub>s tw'`] by blast moreover have "wityping \<Gamma> (snd tw')" using soundness_hoare2[OF seq_stmt_preserve_wityping_hoare[OF `seq_wt \<Gamma> ss1`]] assms(2) unfolding seq_hoare_valid2_def using `tw, ss1 \<Rightarrow>\<^sub>s tw'` using nonneg_delay.simps(3) wt by blast ultimately have "Q tw' \<and> wityping \<Gamma> (snd tw')" by auto } hence "(\<forall>tw'. tw, ss1 \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw' \<and> wityping \<Gamma> (snd tw'))" by auto hence "if eval_world_raw2 tw g = Bv True then wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, ss1 \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw' \<and> wityping \<Gamma> (snd tw')) else wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, ss2 \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw' \<and> wityping \<Gamma> (snd tw'))" using wt `eval_world_raw2 tw g = Bv True` by auto } moreover { assume "eval_world_raw2 tw g \<noteq> Bv True" hence "eval_world_raw2 tw g = Bv False" by (metis assms(1) eval_world_raw_bv seq_wt_cases(3) wt) hence "beval_world_raw2 tw g (Bv False)" using eval_world_raw_correctness_if[OF _ wt bwt] by (simp add: beval_world_raw2_def) { fix tw' assume "tw, ss2 \<Rightarrow>\<^sub>s tw'" hence "Q tw'" using asm world_seq_exec_guarded_not[OF `beval_world_raw2 tw g (Bv False)` `tw, ss2 \<Rightarrow>\<^sub>s tw'`] by blast moreover have "wityping \<Gamma> (snd tw')" using soundness_hoare2[OF seq_stmt_preserve_wityping_hoare[OF `seq_wt \<Gamma> ss2`]] assms(2) unfolding seq_hoare_valid2_def using `tw, ss2 \<Rightarrow>\<^sub>s tw'` using nonneg_delay.simps(3) wt by blast ultimately have "Q tw' \<and> wityping \<Gamma> (snd tw')" by auto } hence "(\<forall>tw'. tw, ss2 \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw' \<and> wityping \<Gamma> (snd tw'))" by auto hence "if eval_world_raw2 tw g = Bv True then wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, ss1 \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw' \<and> wityping \<Gamma> (snd tw')) else wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, ss2 \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw' \<and> wityping \<Gamma> (snd tw'))" using wt `eval_world_raw2 tw g = Bv False` by auto } ultimately show "if eval_world_raw2 tw g = Bv True then wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, ss1 \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw') else wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, ss2 \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw')" by auto next fix tw assume *: "if eval_world_raw2 tw g = Bv True then wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, ss1 \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw') else wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, ss2 \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw')" hence " wityping \<Gamma> (snd tw)" by presburger { fix tw' assume "tw, Bguarded g ss1 ss2 \<Rightarrow>\<^sub>s tw'" hence "Q tw'" using * by (smt assms(1) assms(2) beval_world_raw2_def eval_world_raw_correctness_only_if nonneg_delay.simps(3) seq_wt_cases(3) val.simps(1) world_seq_exec_alt_cases(3) world_seq_exec_alt_imp_world_seq_exec world_seq_exec_imp_world_seq_exec_alt) } thus "wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, Bguarded g ss1 ss2 \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw')" using `wityping \<Gamma> (snd tw)` by auto qed lemma wp3_bcase_empty: "wp3 \<Gamma> (Bcase exp []) Q = (\<lambda>tw. Q tw \<and> wityping \<Gamma> (snd tw))" apply (rule ext) unfolding wp3_def using world_seq_exec_bcase_empty world_seq_exec_deterministic by blast lemma wp3_bcase_others: assumes "seq_wt \<Gamma> (Bcase exp ((Others, ss) # choices))" and "nonneg_delay (Bcase exp ((Others, ss) # choices))" shows "wp3 \<Gamma> (Bcase exp ((Others, ss) # choices)) Q = wp3 \<Gamma> ss Q" apply (rule ext) unfolding wp3_def proof (rule, rule, simp, rule, rule) fix x tw' have "seq_wt \<Gamma> ss " using assms seq_wt_cases_bcase by auto assume *: "wityping \<Gamma> (snd x) \<and> (\<forall>tw'. x, Bcase exp ((Others, ss) # choices) \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw')" and "x, ss \<Rightarrow>\<^sub>s tw'" thus "Q tw'" using world_seq_exec_bcase_others by blast next fix x assume *: " wityping \<Gamma> (snd x) \<and> (\<forall>tw'. x, ss \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw') " hence "wityping \<Gamma> (snd x)" by auto { fix tw' assume "x, Bcase exp ((Others, ss) # choices) \<Rightarrow>\<^sub>s tw'" hence "x, ss \<Rightarrow>\<^sub>s tw'" using bcase_others_tw_elim by blast with * have "Q tw'" by blast } with `wityping \<Gamma> (snd x)` show " wityping \<Gamma> (snd x) \<and> (\<forall>tw'. x, Bcase exp ((Others, ss) # choices) \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw')" by auto qed lemma wp3_bcase_explicit: assumes "seq_wt \<Gamma> (Bcase exp ((Explicit exp', ss) # choices))" and "nonneg_delay (Bcase exp ((Explicit exp', ss) # choices))" shows "wp3 \<Gamma> (Bcase exp ((Explicit exp', ss) # choices)) Q = (\<lambda>tw. if eval_world_raw2 tw exp = eval_world_raw2 tw exp' then wp3 \<Gamma> ss Q tw else wp3 \<Gamma> (Bcase exp choices) Q tw)" apply (rule ext) unfolding wp3_def proof (rule) fix tw assume *: "wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, Bcase exp ((Explicit exp', ss) # choices) \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw')" hence wt : "wityping \<Gamma> (snd tw)" by auto obtain ty where "bexp_wt \<Gamma> exp ty" and " bexp_wt \<Gamma> exp' ty" using assms(1) by (smt choices.distinct(1) choices.sel fst_conv list.distinct(1) list.sel(1) seq_stmt.inject(5) seq_stmt.simps(15) seq_stmt.simps(23) seq_stmt.simps(29) seq_stmt.simps(33) seq_stmt.simps(35) seq_wt.cases) have "seq_wt \<Gamma> ss" and "nonneg_delay ss" and "seq_wt \<Gamma> (Bcase exp choices)" and "nonneg_delay (Bcase exp choices)" using assms seq_wt.cases by auto have "eval_world_raw2 tw exp = eval_world_raw2 tw exp' \<or> eval_world_raw2 tw exp \<noteq> eval_world_raw2 tw exp'" by auto moreover { assume "eval_world_raw2 tw exp = eval_world_raw2 tw exp'" then obtain match where match: "beval_world_raw2 tw exp match \<and> beval_world_raw2 tw exp' match" using eval_world_raw_correctness_if[OF _ `wityping \<Gamma> (snd tw)` `bexp_wt \<Gamma> exp ty`] eval_world_raw_correctness_if[OF _ `wityping \<Gamma> (snd tw)` `bexp_wt \<Gamma> exp' ty`] by (metis beval_world_raw2_def) { fix tw' assume "tw, ss \<Rightarrow>\<^sub>s tw'" hence "Q tw'" using * world_seq_exec_explicit_match match by blast moreover have "wityping \<Gamma> (snd tw')" using soundness_hoare2[ OF seq_stmt_preserve_wityping_hoare[OF `seq_wt \<Gamma> ss`] `nonneg_delay ss`] unfolding seq_hoare_valid2_def using wt `tw, ss\<Rightarrow>\<^sub>s tw'` by blast ultimately have "Q tw' \<and> wityping \<Gamma> (snd tw')" by auto } hence "if eval_world_raw2 tw exp = eval_world_raw2 tw exp' then wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, ss \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw' \<and> wityping \<Gamma> (snd tw')) else wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, Bcase exp choices \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw' \<and> wityping \<Gamma> (snd tw'))" using `eval_world_raw2 tw exp = eval_world_raw2 tw exp'` wt by simp } moreover { assume neq: "eval_world_raw2 tw exp \<noteq> eval_world_raw2 tw exp'" obtain res1 res2 where "eval_world_raw2 tw exp = res1" and "eval_world_raw2 tw exp' = res2" by auto hence neq': "beval_world_raw2 tw exp res1 \<and> beval_world_raw2 tw exp' res2 \<and> res1 \<noteq> res2" using eval_world_raw_correctness_if[OF `eval_world_raw2 tw exp = res1` `wityping \<Gamma> (snd tw)` `bexp_wt \<Gamma> exp ty`] eval_world_raw_correctness_if[OF `eval_world_raw2 tw exp' = res2` `wityping \<Gamma> (snd tw)` `bexp_wt \<Gamma> exp' ty`] neq unfolding beval_world_raw2_def by auto { fix tw' assume " tw, Bcase exp choices \<Rightarrow>\<^sub>s tw'" hence "Q tw'" using * neq' world_seq_exec_explicit_no_match by blast moreover have "wityping \<Gamma> (snd tw')" using soundness_hoare2[ OF seq_stmt_preserve_wityping_hoare[OF `seq_wt \<Gamma> (Bcase exp choices)`] `nonneg_delay (Bcase exp choices)`] unfolding seq_hoare_valid2_def using wt `tw, Bcase exp choices \<Rightarrow>\<^sub>s tw'` by blast ultimately have "Q tw' \<and> wityping \<Gamma> (snd tw')" by auto } hence "if eval_world_raw2 tw exp = eval_world_raw2 tw exp' then wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, ss \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw' \<and> wityping \<Gamma> (snd tw')) else wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, Bcase exp choices \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw' \<and> wityping \<Gamma> (snd tw'))" using `eval_world_raw2 tw exp \<noteq> eval_world_raw2 tw exp'` wt by simp } ultimately show "if eval_world_raw2 tw exp = eval_world_raw2 tw exp' then wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, ss \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw') else wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, Bcase exp choices \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw')" by auto next fix tw assume *: " if eval_world_raw2 tw exp = eval_world_raw2 tw exp' then wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, ss \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw') else wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, Bcase exp choices \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw') " hence "wityping \<Gamma> (snd tw)" by presburger obtain ty where "bexp_wt \<Gamma> exp ty" and "bexp_wt \<Gamma> exp' ty" using assms(1) by (smt choices.distinct(1) choices.sel fst_conv list.distinct(1) list.sel(1) seq_stmt.inject(5) seq_stmt.simps(15) seq_stmt.simps(23) seq_stmt.simps(29) seq_stmt.simps(33) seq_stmt.simps(35) seq_wt.cases) have "nonneg_delay ss" and "nonneg_delay (Bcase exp choices)" using assms(2) by auto { fix tw' assume "tw, Bcase exp ((Explicit exp', ss) # choices) \<Rightarrow>\<^sub>s tw'" hence **: "world_seq_exec_alt tw (Bcase exp ((Explicit exp', ss) # choices)) tw'" using assms(2) world_seq_exec_imp_world_seq_exec_alt by blast have "Q tw'" proof (rule world_seq_exec_alt_cases(6)[OF **]) fix x assume "beval_world_raw2 tw exp x" and "beval_world_raw2 tw exp' x" hence "eval_world_raw2 tw exp = x" and "eval_world_raw2 tw exp' = x" using eval_world_raw_correctness_only_if[OF _ `wityping \<Gamma> (snd tw)` `bexp_wt \<Gamma> exp ty`] using eval_world_raw_correctness_only_if[OF _ `wityping \<Gamma> (snd tw)` `bexp_wt \<Gamma> exp' ty`] by (simp add: beval_world_raw2_def)+ assume "world_seq_exec_alt tw ss tw'" hence "tw, ss \<Rightarrow>\<^sub>s tw'" using world_seq_exec_alt_imp_world_seq_exec[OF _ `nonneg_delay ss`] by auto thus "Q tw'" using * by (simp add: \<open>if eval_world_raw2 tw exp = eval_world_raw2 tw exp' then wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, ss \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw') else wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, Bcase exp choices \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw')\<close> \<open>eval_world_raw2 tw exp = x\<close> \<open>eval_world_raw2 tw exp' = x\<close>) next fix x x' assume "beval_world_raw2 tw exp x" and "beval_world_raw2 tw exp' x'" and "x \<noteq> x'" hence "eval_world_raw2 tw exp = x" and "eval_world_raw2 tw exp' = x'" using eval_world_raw_correctness_only_if[OF _ `wityping \<Gamma> (snd tw)` `bexp_wt \<Gamma> exp ty`] using eval_world_raw_correctness_only_if[OF _ `wityping \<Gamma> (snd tw)` `bexp_wt \<Gamma> exp' ty`] using beval_world_raw2_deterministic by (simp add: beval_world_raw2_def)+ assume "world_seq_exec_alt tw (Bcase exp choices) tw'" hence "tw, Bcase exp choices \<Rightarrow>\<^sub>s tw'" using world_seq_exec_alt_imp_world_seq_exec[OF _ `nonneg_delay (Bcase exp choices)`] by blast thus "Q tw'" using * by (simp add: \<open>if eval_world_raw2 tw exp = eval_world_raw2 tw exp' then wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, ss \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw') else wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, Bcase exp choices \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw')\<close> \<open>eval_world_raw2 tw exp = x\<close> \<open>eval_world_raw2 tw exp' = x'\<close> \<open>x \<noteq> x'\<close>) qed } thus "wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, Bcase exp ((Explicit exp', ss) # choices) \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw')" using `wityping \<Gamma> (snd tw)` by auto qed lemma wp3_assign_trans: assumes "seq_wt \<Gamma> (Bassign_trans sig exp dly)" and " nonneg_delay (Bassign_trans sig exp dly)" shows "wp3 \<Gamma> (Bassign_trans sig exp dly) Q = (\<lambda>tw. wityping \<Gamma> (snd tw) \<and> Q(tw[sig, dly :=\<^sub>2 eval_world_raw2 tw exp]))" apply (rule ext) unfolding wp3_def proof (rule, rule, simp) fix tw assume prem: "wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, Bassign_trans sig exp dly \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw')" obtain tw' where "tw, Bassign_trans sig exp dly \<Rightarrow>\<^sub>s tw'" by (metis assms(1) assms(2) beval_world_raw2_def eval_world_raw_correctness_if nonneg_delay.simps(4) prem seq_wt_cases(4) world_seq_exec_trans) have "beval_world_raw2 tw exp (eval_world_raw2 tw exp)" by (metis assms(1) beval_world_raw2_def eval_world_raw_correctness_if prem seq_wt_cases(4)) thus "Q tw[ sig, dly :=\<^sub>2 eval_world_raw2 tw exp]" using prem by (meson assms(2) nonneg_delay.simps(4) world_seq_exec_trans) next fix tw assume *: "wityping \<Gamma> (snd tw) \<and> Q tw[ sig, dly :=\<^sub>2 eval_world_raw2 tw exp] " hence wt : "wityping \<Gamma> (snd tw)" by auto { fix tw' assume "tw, Bassign_trans sig exp dly \<Rightarrow>\<^sub>s tw'" hence "Q tw'" using * by (metis assms(1) assms(2) beval_world_raw2_def eval_world_raw_correctness_only_if lift_world_trans_worldline_upd2 nonneg_delay.simps(4) seq_wt_cases(4)) } thus "wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, Bassign_trans sig exp dly \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw')" using wt by auto qed lemma wp3_assign_inert: assumes "seq_wt \<Gamma> (Bassign_inert sig exp dly)" and " nonneg_delay (Bassign_inert sig exp dly)" shows "wp3 \<Gamma> (Bassign_inert sig exp dly) Q = (\<lambda>tw. wityping \<Gamma> (snd tw) \<and> Q(tw\<lbrakk>sig, dly :=\<^sub>2 eval_world_raw2 tw exp\<rbrakk>))" apply (rule ext) unfolding wp3_def proof (rule, rule, simp) fix tw assume prem: "wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, Bassign_inert sig exp dly \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw')" obtain tw' where "tw, Bassign_inert sig exp dly \<Rightarrow>\<^sub>s tw'" by (metis assms(1) assms(2) beval_world_raw2_def eval_world_raw_correctness_if nonneg_delay.simps(5) prem seq_wt_cases(5) world_seq_exec_inert) have "beval_world_raw2 tw exp (eval_world_raw2 tw exp)" by (metis assms(1) beval_world_raw2_def eval_world_raw_correctness_if prem seq_wt_cases(5)) thus "Q tw\<lbrakk> sig, dly :=\<^sub>2 eval_world_raw2 tw exp\<rbrakk>" using prem by (meson assms(2) nonneg_delay.simps(5) world_seq_exec_inert) next fix tw assume *: "wityping \<Gamma> (snd tw) \<and> Q tw\<lbrakk>sig, dly :=\<^sub>2 eval_world_raw2 tw exp\<rbrakk> " hence wt : "wityping \<Gamma> (snd tw)" by auto { fix tw' assume "tw, Bassign_inert sig exp dly \<Rightarrow>\<^sub>s tw'" hence "Q tw'" using * by (metis assms(1) assms(2) beval_world_raw2_def eval_world_raw_correctness_only_if lift_world_inert_worldline_upd2 nonneg_delay.simps(5) seq_wt_cases(5)) } thus "wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw, Bassign_inert sig exp dly \<Rightarrow>\<^sub>s tw' \<longrightarrow> Q tw')" using wt by auto qed fun wp3_fun :: "'signal tyenv \<Rightarrow> 'signal seq_stmt \<Rightarrow> 'signal assn2 \<Rightarrow> 'signal assn2" where "wp3_fun \<Gamma> Bnull Q = (\<lambda>tw. Q tw \<and> wityping \<Gamma> (snd tw))" | "wp3_fun \<Gamma> (Bassign_trans sig exp dly) Q = (\<lambda>tw. wityping \<Gamma> (snd tw) \<and> Q(tw[sig, dly :=\<^sub>2 eval_world_raw2 tw exp]))" | "wp3_fun \<Gamma> (Bassign_inert sig exp dly) Q = (\<lambda>tw. wityping \<Gamma> (snd tw) \<and> Q(tw\<lbrakk>sig, dly :=\<^sub>2 eval_world_raw2 tw exp\<rbrakk>))" | "wp3_fun \<Gamma> (Bcase exp ((Explicit exp', ss) # choices)) Q = (\<lambda>tw. if eval_world_raw2 tw exp = eval_world_raw2 tw exp' then wp3_fun \<Gamma> ss Q tw else wp3_fun \<Gamma> (Bcase exp choices) Q tw)" | "wp3_fun \<Gamma> (Bcase exp ((Others, ss) # choices)) Q = wp3_fun \<Gamma> ss Q" | "wp3_fun \<Gamma> (Bcase exp []) Q = (\<lambda>tw. Q tw \<and> wityping \<Gamma> (snd tw))" | "wp3_fun \<Gamma> (Bguarded g ss1 ss2) Q = (\<lambda>tw. if eval_world_raw2 tw g = Bv True then wp3_fun \<Gamma> ss1 Q tw else wp3_fun \<Gamma> ss2 Q tw)" | "wp3_fun \<Gamma> (Bcomp ss1 ss2) Q = wp3_fun \<Gamma> ss1 (wp3_fun \<Gamma> ss2 Q)" lemma wp3_fun_eq_wp3: assumes "seq_wt \<Gamma> ss" and "nonneg_delay ss" shows "wp3_fun \<Gamma> ss Q = wp3 \<Gamma> ss Q" using assms apply (induction ss arbitrary: Q) by (auto simp add: wp3_bnull wp3_bcomp wp3_bguarded wp3_assign_trans wp3_assign_inert wp3_bcase_empty wp3_bcase_others wp3_bcase_explicit seq_wt.intros) lemma wp3_fun_is_pre: assumes "seq_wt \<Gamma> ss" and "nonneg_delay ss" shows "\<Gamma> \<turnstile> [wp3_fun \<Gamma> ss Q] ss [Q]" using assms proof (induction ss arbitrary:Q) case (1 \<Gamma>) then show ?case using wp3_bnull by (metis Conseq3 Null3 seq_wt.intros(1) wp3_fun_eq_wp3) next case (2 \<Gamma> s1 s2) then show ?case using wp3_fun_eq_wp3 wp3_bcomp by (metis Comp3 nonneg_delay.simps(2) wp3_fun.simps(8)) next case (3 \<Gamma> g s1 s2) then show ?case using wp3_fun_eq_wp3 wp3_bguarded by (smt Conseq3 If3 nonneg_delay.simps(3) seq_wt.intros(3) val.inject(1)) next case (4 \<Gamma> exp sig dly) then show ?case using wp3_fun_eq_wp3 wp3_assign_trans by (smt Conseq3 seq_hoare3.intros(2) wp3_fun.simps(2)) next case (5 \<Gamma> exp sig dly) then show ?case using wp3_fun_eq_wp3 wp3_assign_inert by (smt Conseq3 seq_hoare3.intros(3) wp3_fun.simps(3)) next case (6 \<Gamma> exp ty) then show ?case using wp3_fun_eq_wp3 wp3_bcase_empty by (smt Bcase_empty_choices3 Conseq3 wp3_fun.simps(6)) next case (7 \<Gamma> exp ty ss choices) hence "nonneg_delay ss" by auto hence IH: " \<Gamma> \<turnstile> [wp3_fun \<Gamma> ss Q] ss [Q]" using 7(3) by auto show ?case apply (rule Conseq3[rotated]) apply (rule Bcase_others3) apply (rule IH, simp) by (simp add: "7.hyps"(2) \<open>nonneg_delay ss\<close> wp3_fun_eq_wp3) next case (8 \<Gamma> exp ty exp' ss choices) hence " \<Gamma> \<turnstile> [wp3_fun \<Gamma> ss Q] ss [Q]" and *: " \<Gamma> \<turnstile> [wp3_fun \<Gamma> (Bcase exp choices) Q] Bcase exp choices [Q]" by auto hence IH1: "\<Gamma> \<turnstile> [\<lambda>tw. (if eval_world_raw2 tw exp = eval_world_raw2 tw exp' then wp3_fun \<Gamma> ss Q tw else wp3_fun \<Gamma> (Bcase exp choices) Q tw) \<and> eval_world_raw2 tw exp = eval_world_raw2 tw exp'] ss [Q]" by (smt Conseq3) have IH2: "\<Gamma> \<turnstile> [\<lambda>tw. (if eval_world_raw2 tw exp = eval_world_raw2 tw exp' then wp3_fun \<Gamma> ss Q tw else wp3_fun \<Gamma> (Bcase exp choices) Q tw) \<and> eval_world_raw2 tw exp \<noteq> eval_world_raw2 tw exp'] Bcase exp choices [Q]" using * by (smt Conseq3) have swt: "seq_wt \<Gamma> (Bcase exp ((Explicit exp', ss) # choices))" using 8 seq_wt.intros(8) by blast have nss: "nonneg_delay ss" and not: "nonneg_delay (Bcase exp choices)" using 8 by auto show ?case apply (rule Conseq3[rotated]) apply (rule Bcase_if3) apply (rule IH1, rule IH2, simp) unfolding wp3_fun_eq_wp3[OF swt 8(7)] wp3_bcase_explicit[OF swt 8(7)] wp3_fun_eq_wp3[OF 8(3) nss] wp3_fun_eq_wp3[OF 8(4) not] by auto qed lemma strengthen_pre_hoare2: assumes "\<forall>tw. P' tw \<and> wityping \<Gamma> (snd tw) \<longrightarrow> P tw" and "\<Gamma> \<turnstile> [P] s [Q]" shows "\<Gamma> \<turnstile> [P'] s [Q]" using assms by (blast intro: Conseq3) lemma seq_hoare_wt_complete: assumes "seq_wt \<Gamma> ss" and "nonneg_delay ss" assumes "\<Gamma> \<Turnstile> [P] ss [Q]" shows "\<Gamma> \<turnstile> [P] ss [Q]" proof (rule strengthen_pre_hoare2) show "\<forall>w. P w \<and> wityping \<Gamma> (snd w) \<longrightarrow> wp3 \<Gamma> ss Q w" using assms unfolding seq_hoare_valid2_wt_def wp3_def by auto show " \<Gamma> \<turnstile> [wp3 \<Gamma> ss Q] ss [Q]" using assms wp3_fun_is_pre wp3_fun_eq_wp3 by fastforce qed definition conc_hoare_valid_wt :: "'signal tyenv \<Rightarrow>'signal assn2 \<Rightarrow> 'signal conc_stmt \<Rightarrow> 'signal assn2 \<Rightarrow> bool" ("(1_) \<Turnstile> \<lbrace>(1_)\<rbrace>/ (_)/ \<lbrace>(1_)\<rbrace>" 50) where "\<Gamma> \<Turnstile> \<lbrace>P\<rbrace> c \<lbrace>Q\<rbrace> \<longleftrightarrow> (\<forall>tw tw'. wityping \<Gamma> (snd tw) \<and> P tw \<and> (tw, c \<Rightarrow>\<^sub>c tw') \<longrightarrow> Q tw')" lemma conc_hoare_valid_wt_commute: assumes "conc_stmt_wf (cs1 || cs2)" shows "\<Gamma> \<Turnstile> \<lbrace>P\<rbrace> cs1 || cs2 \<lbrace>Q\<rbrace> \<longleftrightarrow> \<Gamma> \<Turnstile> \<lbrace>P\<rbrace> cs2 || cs1 \<lbrace>Q\<rbrace>" unfolding conc_hoare_valid_wt_def using world_conc_exec_commute[OF _ _ assms] by (smt assms parallel_comp_commute world_conc_exec.simps) inductive conc_hoare_wt :: "'signal tyenv \<Rightarrow> 'signal assn2 \<Rightarrow> 'signal conc_stmt \<Rightarrow> 'signal assn2 \<Rightarrow> bool" ("(1_) \<turnstile> (\<lbrace>(1_)\<rbrace>/ (_)/ \<lbrace>(1_)\<rbrace>)" 50) where Single: "\<Gamma> \<turnstile> [\<lambda>tw. P tw \<and> \<not> disjnt sl (event_of tw)] ss [Q] \<Longrightarrow> \<forall>tw. P tw \<and> disjnt sl (event_of tw) \<longrightarrow> Q tw \<Longrightarrow> \<Gamma> \<turnstile> \<lbrace>P\<rbrace> process sl : ss \<lbrace>Q\<rbrace>" | Parallel: "\<Gamma> \<turnstile> \<lbrace>P\<rbrace> cs\<^sub>1 \<lbrace>R\<rbrace> \<Longrightarrow> \<Gamma> \<turnstile> \<lbrace>R\<rbrace> cs\<^sub>2 \<lbrace>Q\<rbrace> \<Longrightarrow> conc_stmt_wf (cs\<^sub>1 || cs\<^sub>2) \<Longrightarrow> \<Gamma> \<turnstile> \<lbrace>P\<rbrace> cs\<^sub>1 || cs\<^sub>2 \<lbrace>Q\<rbrace>" | Parallel2: "\<Gamma> \<turnstile> \<lbrace>P\<rbrace> cs\<^sub>2 \<lbrace>R\<rbrace> \<Longrightarrow> \<Gamma> \<turnstile> \<lbrace>R\<rbrace> cs\<^sub>1 \<lbrace>Q\<rbrace> \<Longrightarrow> conc_stmt_wf (cs\<^sub>1 || cs\<^sub>2) \<Longrightarrow> \<Gamma> \<turnstile> \<lbrace>P\<rbrace> cs\<^sub>1 || cs\<^sub>2 \<lbrace>Q\<rbrace>" | Conseq': "\<lbrakk>\<forall>w. wityping \<Gamma> (snd w) \<and> P' w \<longrightarrow> P w; \<Gamma> \<turnstile> \<lbrace>P\<rbrace> c \<lbrace>Q\<rbrace>; \<forall>w. Q w \<longrightarrow> Q' w\<rbrakk> \<Longrightarrow> \<Gamma> \<turnstile> \<lbrace>P'\<rbrace> c \<lbrace>Q'\<rbrace>" | Conj2: "\<Gamma> \<turnstile> \<lbrace>P\<rbrace> s \<lbrace>Q1\<rbrace> \<Longrightarrow> \<Gamma> \<turnstile> \<lbrace>P\<rbrace> s \<lbrace>Q2\<rbrace> \<Longrightarrow> \<Gamma> \<turnstile> \<lbrace>P\<rbrace> s \<lbrace>\<lambda>tw. Q1 tw \<and> Q2 tw\<rbrace>" inductive_cases conc_hoare_wt_cases : "\<Gamma> \<turnstile> \<lbrace>P\<rbrace> cs \<lbrace>Q\<rbrace>" lemma parallel_valid: assumes "\<Gamma> \<Turnstile> \<lbrace>P\<rbrace> c1 \<lbrace>R\<rbrace>" and "\<Gamma> \<Turnstile> \<lbrace>R\<rbrace> c2 \<lbrace>Q\<rbrace>" and "conc_stmt_wf (c1 || c2)" assumes "nonneg_delay_conc (c1 || c2)" assumes "conc_wt \<Gamma> (c1 || c2)" shows "\<Gamma> \<Turnstile> \<lbrace>P\<rbrace> c1 || c2 \<lbrace>Q\<rbrace>" unfolding conc_hoare_valid_wt_def proof rule+ fix tw tw':: "nat \<times> 'a worldline_init" assume "wityping \<Gamma> (snd tw) \<and> P tw \<and> tw , c1 || c2 \<Rightarrow>\<^sub>c tw'" hence "wityping \<Gamma> (snd tw)" and "P tw" and "tw, c1 || c2 \<Rightarrow>\<^sub>c tw'" by auto then obtain t \<sigma> \<gamma> \<theta> \<tau> def \<tau>' where des: "destruct_worldline tw = (t, \<sigma>, \<gamma>, \<theta>, def, \<tau>)" and *: "t, \<sigma>, \<gamma>, \<theta>, def \<turnstile> <c1 || c2, \<tau>> \<longrightarrow>\<^sub>c \<tau>'" and w'_def: "worldline2 t \<sigma> \<theta> def \<tau>' = tw'" and ci: "context_invariant t \<sigma> \<gamma> \<theta> def \<tau>" using destruct_worldline_exist by (smt world_conc_exec_cases worldline2_constructible) have "\<And>s. non_stuttering (to_trans_raw_sig \<tau>) \<sigma> s" using destruct_worldline_ensure_non_stuttering[OF des] by auto obtain \<tau>1 where "b_conc_exec t \<sigma> \<gamma> \<theta> def c1 \<tau> \<tau>1" using "*" by blast hence ci1: "context_invariant t \<sigma> \<gamma> \<theta> def \<tau>1" using b_conc_exec_preserves_context_invariant[OF _ ci] assms(4) by auto have "\<And>n. n \<le> t \<Longrightarrow> \<tau> n = 0" using destruct_worldline_trans_zero_upto_now[OF des] by auto have "\<forall>s. non_stuttering (to_trans_raw_sig \<tau>1) \<sigma> s" proof fix s have "t, \<sigma>, \<gamma>, \<theta>, def \<turnstile> <c1, \<tau>> \<longrightarrow>\<^sub>c \<tau>1" using \<open>t , \<sigma> , \<gamma> , \<theta>, def \<turnstile> <c1 , \<tau>> \<longrightarrow>\<^sub>c \<tau>1\<close> by blast moreover have "non_stuttering (to_trans_raw_sig \<tau>) \<sigma> s" by (simp add: \<open>\<And>s. non_stuttering (to_trans_raw_sig \<tau>) \<sigma> s\<close>) moreover have "conc_stmt_wf c1" and "nonneg_delay_conc c1" using assms by auto ultimately show "non_stuttering (to_trans_raw_sig \<tau>1) \<sigma> s" using b_conc_exec_preserves_non_stuttering[OF _ _ `\<And>n. n \<le> t \<Longrightarrow> \<tau> n = 0`] by auto qed obtain \<tau>2 where "b_conc_exec t \<sigma> \<gamma> \<theta> def c2 \<tau> \<tau>2" using "*" by blast hence ci2: "context_invariant t \<sigma> \<gamma> \<theta> def \<tau>2" using b_conc_exec_preserves_context_invariant[OF _ ci] assms(4) by auto have \<tau>'_def: "b_conc_exec t \<sigma> \<gamma> \<theta> def c2 \<tau>1 \<tau>'" using b_conc_exec_sequential[OF assms(3) * `t, \<sigma>, \<gamma>, \<theta>, def \<turnstile> <c1, \<tau>> \<longrightarrow>\<^sub>c \<tau>1`] by auto define tw1 where "tw1 = worldline2 t \<sigma> \<theta> def \<tau>1" have "tw, c1 \<Rightarrow>\<^sub>c tw1" using des \<open>t , \<sigma> , \<gamma> , \<theta>, def \<turnstile> <c1 , \<tau>> \<longrightarrow>\<^sub>c \<tau>1\<close> tw1_def world_conc_exec.intros by blast hence "R tw1" using assms(1) `P tw` `wityping \<Gamma> (snd tw)` unfolding conc_hoare_valid_wt_def by presburger have "conc_wt \<Gamma> c1" and "conc_stmt_wf c1" and "nonneg_delay_conc c1" using `conc_wt \<Gamma> (c1 || c2)` `conc_stmt_wf (c1 || c2)` assms(4) by auto hence "wityping \<Gamma> (snd tw1)" using conc_stmt_preserve_wityping_hoare_semantic[OF `conc_wt \<Gamma> c1` `conc_stmt_wf c1`] `tw, c1 \<Rightarrow>\<^sub>c tw1` unfolding conc_hoare_valid_def using \<open>wityping \<Gamma> (snd tw)\<close> by presburger have "\<forall>s. non_stuttering (to_trans_raw_sig \<theta>) def s" using des destruct_worldline_ensure_non_stuttering_hist_raw by blast hence des2: "destruct_worldline tw1 = (t, \<sigma>, \<gamma>, \<theta>, def, \<tau>1)" using destruct_worldline_correctness3[OF ci1 `\<forall>s. non_stuttering (to_trans_raw_sig \<tau>1) \<sigma> s`] unfolding tw1_def by auto moreover have "nonneg_delay_conc c2" using assms(4) by auto hence "tw1, c2 \<Rightarrow>\<^sub>c tw'" using des2 apply (intro world_conc_exec.intros) apply assumption apply (rule \<tau>'_def) apply (simp add: w'_def) done with `R tw1` show "Q tw'" using assms(2) `wityping \<Gamma> (snd tw1)` unfolding conc_hoare_valid_wt_def by meson qed lemma conseq_valid: shows "\<lbrakk>\<forall>w. wityping \<Gamma> (snd w) \<and> P' w \<longrightarrow> P w; \<Gamma> \<Turnstile> \<lbrace>P\<rbrace> c \<lbrace>Q\<rbrace>; \<forall>w. Q w \<longrightarrow> Q' w\<rbrakk> \<Longrightarrow> \<Gamma> \<Turnstile> \<lbrace>P'\<rbrace> c \<lbrace>Q'\<rbrace>" unfolding conc_hoare_valid_wt_def by meson lemma soundness_conc_hoare: assumes "\<Gamma> \<turnstile> \<lbrace>P\<rbrace> c \<lbrace>Q\<rbrace>" assumes "conc_wt \<Gamma> c" and "conc_stmt_wf c" and "nonneg_delay_conc c" shows "\<Gamma> \<Turnstile> \<lbrace>P\<rbrace> c \<lbrace>Q\<rbrace>" using assms proof (induction rule:conc_hoare_wt.induct) case (Single \<Gamma> P sl ss Q) show ?case unfolding conc_hoare_valid_wt_def proof (rule, rule, rule) fix tw tw' assume *: "wityping \<Gamma> (snd tw) \<and> P tw \<and> tw, process sl : ss \<Rightarrow>\<^sub>c tw'" hence 0: "world_conc_exec_alt tw (process sl : ss) tw'" using world_conc_exec_eq_world_conc_exec_alt[OF Single(4) Single(5)] by auto have "disjnt sl (event_of tw) \<or> \<not> disjnt sl (event_of tw)" by auto moreover { assume "disjnt sl (event_of tw)" hence "tw' = tw" using 0 by (meson \<open>wityping \<Gamma> (snd tw) \<and> P tw \<and> tw , process sl : ss \<Rightarrow>\<^sub>c tw'\<close> world_conc_exec_deterministic world_conc_exec_disjnt) hence "Q tw'" using Single(2) * `disjnt sl (event_of tw)` by blast } moreover { assume "\<not> disjnt sl (event_of tw)" hence "world_seq_exec_alt tw ss tw'" using 0 by (metis "*" Single.prems(3) event_of_def nonneg_delay_conc.simps(1) world_seq_exec_imp_world_seq_exec_alt wp_conc_def wp_conc_single wp_def) hence "tw, ss \<Rightarrow>\<^sub>s tw'" using world_seq_exec_alt_imp_world_seq_exec Single(5) nonneg_delay_conc.simps(1) by blast moreover have "\<Gamma> \<Turnstile> [\<lambda>tw. P tw \<and> \<not> disjnt sl (event_of tw)] ss [Q]" using seq_hoare3_soundness[OF Single(1)] Single(3) Single(5) by auto ultimately have "Q tw'" using `\<not> disjnt sl (event_of tw)` unfolding seq_hoare_valid2_wt_def using "*" by blast } ultimately show "Q tw'" by auto qed next case (Parallel \<Gamma> P cs\<^sub>1 R cs\<^sub>2 Q) then show ?case using parallel_valid by (metis conc_stmt_wf_def conc_wt_cases(2) distinct_append nonneg_delay_conc.simps(2) signals_from.simps(2)) next case (Parallel2 \<Gamma> P cs\<^sub>2 R cs\<^sub>1 Q) hence "conc_stmt_wf cs\<^sub>1" and "conc_stmt_wf cs\<^sub>2" by (simp add: conc_stmt_wf_def)+ moreover have "nonneg_delay_conc cs\<^sub>1" and "nonneg_delay_conc cs\<^sub>2" using Parallel2 by auto ultimately have cs2: " \<Gamma> \<Turnstile> \<lbrace>P\<rbrace> cs\<^sub>2 \<lbrace>R\<rbrace>" and cs1: " \<Gamma> \<Turnstile> \<lbrace>R\<rbrace> cs\<^sub>1 \<lbrace>Q\<rbrace>" using Parallel2 by auto have "conc_stmt_wf (cs\<^sub>2 || cs\<^sub>1)" using Parallel2(3) unfolding conc_stmt_wf_def by auto moreover have " nonneg_delay_conc (cs\<^sub>2 || cs\<^sub>1) " using Parallel2(8) by auto moreover have " conc_wt \<Gamma> (cs\<^sub>2 || cs\<^sub>1)" using Parallel2(6) conc_wt.intros(2) by blast ultimately have "\<Gamma> \<Turnstile> \<lbrace>P\<rbrace> cs\<^sub>2 || cs\<^sub>1 \<lbrace>Q\<rbrace>" using parallel_valid[OF cs2 cs1] by auto thus ?case using world_conc_exec_commute[OF _ _ Parallel2(3)] unfolding conc_hoare_valid_wt_def by (smt Parallel2.prems(2) parallel_comp_commute' world_conc_exec.intros world_conc_exec_alt_cases(2)) next case (Conseq' \<Gamma> P' P c Q Q') then show ?case unfolding conc_hoare_valid_wt_def by metis next case (Conj2 \<Gamma> P s Q1 Q2) then show ?case by (simp add: conc_hoare_valid_wt_def) qed definition wp3_conc :: "'signal tyenv \<Rightarrow> 'signal conc_stmt \<Rightarrow> 'signal assn2 \<Rightarrow> 'signal assn2" where "wp3_conc \<Gamma> cs Q = (\<lambda>tw. wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. (tw, cs \<Rightarrow>\<^sub>c tw') \<longrightarrow> Q tw'))" lemma wp3_conc_single: "wp3_conc \<Gamma> (process sl : ss) Q = (\<lambda>tw. if disjnt sl (event_of tw) then Q tw \<and> wityping \<Gamma> (snd tw) else wp3 \<Gamma> ss Q tw)" apply (rule ext) unfolding wp3_conc_def wp3_def by (smt conc_cases(1) event_of_def o_apply prod.sel(1) snd_conv world_conc_exec_alt_cases(1) world_conc_exec_disjnt world_conc_exec_not_disjnt world_seq_exec.intros) lemma wp3_conc_single': assumes "conc_wt \<Gamma> (process sl : ss)" and "nonneg_delay_conc (process sl : ss) " shows "wp3_conc \<Gamma> (process sl : ss) Q = (\<lambda>tw. if disjnt sl (event_of tw) then Q tw \<and> wityping \<Gamma> (snd tw) else wp3_fun \<Gamma> ss Q tw)" unfolding wp3_conc_single using wp3_fun_eq_wp3 assms by fastforce lemma exist_middle_worldline: assumes "tw, cs \<Rightarrow>\<^sub>c tw'" and "cs = c1 || c2" assumes "conc_stmt_wf cs" and "nonneg_delay_conc cs" shows "\<exists>tw_temp. tw, c1 \<Rightarrow>\<^sub>c tw_temp \<and> tw_temp, c2 \<Rightarrow>\<^sub>c tw'" using assms proof (induction rule: world_conc_exec.induct) case (1 tw t \<sigma> \<gamma> \<theta> def \<tau> c \<tau>' tw') then obtain \<tau>_temp where \<tau>_temp: " t , \<sigma> , \<gamma> , \<theta>, def \<turnstile> <c1 , \<tau>> \<longrightarrow>\<^sub>c \<tau>_temp" by auto then obtain tw_temp where "tw, c1 \<Rightarrow>\<^sub>c tw_temp" and "tw_temp = worldline2 t \<sigma> \<theta> def \<tau>_temp" using 1 using world_conc_exec.intros by blast have *: "t , \<sigma> , \<gamma> , \<theta>, def \<turnstile> <c1 || c2, \<tau>> \<longrightarrow>\<^sub>c \<tau>'" using 1 by auto hence 2: "t , \<sigma> , \<gamma> , \<theta>, def \<turnstile> <c2 , \<tau>_temp> \<longrightarrow>\<^sub>c \<tau>'" using b_conc_exec_sequential[OF _ * \<tau>_temp] 1 by auto have "context_invariant t \<sigma> \<gamma> \<theta> def \<tau>" using worldline2_constructible 1 by blast hence "context_invariant t \<sigma> \<gamma> \<theta> def \<tau>_temp" using \<tau>_temp b_conc_exec_preserves_context_invariant using "1.prems"(1) "1.prems"(3) nonneg_delay_conc.simps(2) by blast have ns: " \<forall>s. non_stuttering (to_trans_raw_sig \<tau>) \<sigma> s" using "1.hyps"(1) destruct_worldline_ensure_non_stuttering by blast have "\<And>n. n \<le> t \<Longrightarrow> \<tau> n = 0" using `context_invariant t \<sigma> \<gamma> \<theta> def \<tau>` unfolding context_invariant_def by auto hence "\<forall>s. non_stuttering (to_trans_raw_sig \<tau>_temp) \<sigma> s" using b_conc_exec_preserves_non_stuttering[OF \<tau>_temp _ _ ] ns 1(5-6) `c = c1 || c2` by (simp add: conc_stmt_wf_def) moreover have " \<forall>s. non_stuttering (to_trans_raw_sig \<theta>) def s" using "1.hyps"(1) destruct_worldline_ensure_non_stuttering_hist_raw by blast ultimately have "destruct_worldline tw_temp = (t, \<sigma>, \<gamma>, \<theta>, def, \<tau>_temp)" using destruct_worldline_correctness2 by (simp add: \<open>context_invariant t \<sigma> \<gamma> \<theta> def \<tau>_temp\<close> \<open>tw_temp = worldline2 t \<sigma> \<theta> def \<tau>_temp\<close> destruct_worldline_correctness3) hence "tw_temp, c2 \<Rightarrow>\<^sub>c tw'" using 2 1(3) using world_conc_exec.intros by blast thus ?case by (meson \<open>tw , c1 \<Rightarrow>\<^sub>c tw_temp\<close>) qed lemma exist_middle_worldline': assumes "conc_stmt_wf (c1 || c2)" and "nonneg_delay_conc (c1 || c2)" shows "tw, c1 || c2 \<Rightarrow>\<^sub>c tw' \<longleftrightarrow> (\<exists>tw_temp. tw, c1 \<Rightarrow>\<^sub>c tw_temp \<and> tw_temp, c2 \<Rightarrow>\<^sub>c tw')" using exist_middle_worldline[OF _ _ assms] by (smt assms(1) assms(2) conc_stmt_wf_def distinct_append nonneg_delay_conc.simps(2) signals_from.simps(2) world_conc_exec_alt.intros(3) world_conc_exec_alt_imp_world_conc_exec world_conc_exec_imp_world_conc_exec_alt) lemma wp3_conc_parallel: assumes "conc_stmt_wf (cs1 || cs2)" and "nonneg_delay_conc (cs1 || cs2)" assumes "conc_wt \<Gamma> (cs1 || cs2)" shows "wp3_conc \<Gamma> (cs1 || cs2) Q = wp3_conc \<Gamma> cs1 (wp3_conc \<Gamma> cs2 Q)" proof (rule ext, rule) fix x have "conc_stmt_wf cs1" and "conc_stmt_wf cs2" using assms by (simp add: conc_stmt_wf_def)+ have "nonneg_delay_conc cs1" and "nonneg_delay_conc cs2" using assms by auto assume "wp3_conc \<Gamma> (cs1 || cs2) Q x " hence "(\<forall>tw'. x , cs1 || cs2 \<Rightarrow>\<^sub>c tw' \<longrightarrow> Q tw')" and "wityping \<Gamma> (snd x)" unfolding wp3_conc_def by auto then show " wp3_conc \<Gamma> cs1 (wp3_conc \<Gamma> cs2 Q) x" unfolding wp3_conc_def sym[OF world_conc_exec_eq_world_conc_exec_alt[OF assms(1-2)]] sym[OF world_conc_exec_eq_world_conc_exec_alt[OF `conc_stmt_wf cs1` `nonneg_delay_conc cs1`]] sym[OF world_conc_exec_eq_world_conc_exec_alt[OF `conc_stmt_wf cs2` `nonneg_delay_conc cs2`]] proof (intro conjI, simp, intro allI, intro impI) fix tw' assume "\<forall>tw'. world_conc_exec_alt x (cs1 || cs2) tw' \<longrightarrow> Q tw'" assume "wityping \<Gamma> (snd x)" assume " world_conc_exec_alt x cs1 tw'" hence "x, cs1 \<Rightarrow>\<^sub>c tw'" using world_conc_exec_alt_imp_world_conc_exec[OF _ `conc_stmt_wf cs1` `nonneg_delay_conc cs1`] by auto moreover have "conc_wt \<Gamma> cs1" using assms(3) by auto hence "wityping \<Gamma> (snd tw')" using conc_stmt_preserve_wityping_hoare_semantic[OF `conc_wt \<Gamma> cs1` `conc_stmt_wf cs1` `nonneg_delay_conc cs1`] unfolding conc_hoare_valid_def using `wityping \<Gamma> (snd x)` `x, cs1 \<Rightarrow>\<^sub>c tw'` by meson moreover have "(\<forall>tw'a. world_conc_exec_alt tw' cs2 tw'a \<longrightarrow> Q tw'a)" using \<open>\<forall>tw'. world_conc_exec_alt x (cs1 || cs2) tw' \<longrightarrow> Q tw'\<close> \<open>world_conc_exec_alt x cs1 tw'\<close> world_conc_exec_alt.intros(3) by blast ultimately show "wityping \<Gamma> (snd tw') \<and> (\<forall>tw'a. world_conc_exec_alt tw' cs2 tw'a \<longrightarrow> Q tw'a)" by auto qed next fix x have "conc_stmt_wf cs1" and "conc_stmt_wf cs2" using assms by (simp add: conc_stmt_wf_def)+ have "nonneg_delay_conc cs1" and "nonneg_delay_conc cs2" using assms by auto assume "wp3_conc \<Gamma> cs1 (wp3_conc \<Gamma> cs2 Q) x" hence "\<forall>tw tw'. x , cs1 \<Rightarrow>\<^sub>c tw \<and> tw , cs2 \<Rightarrow>\<^sub>c tw' \<longrightarrow> Q tw'" and "wityping \<Gamma> (snd x)" unfolding wp3_conc_def by meson+ thus "wp3_conc \<Gamma> (cs1 || cs2) Q x" unfolding wp3_conc_def sym[OF world_conc_exec_eq_world_conc_exec_alt[OF assms(1-2)]] proof (intro conjI, simp, intro allI, intro impI) fix tw' assume "\<forall>tw tw'. x , cs1 \<Rightarrow>\<^sub>c tw \<and> tw , cs2 \<Rightarrow>\<^sub>c tw' \<longrightarrow> Q tw'" assume " wityping \<Gamma> (snd x)" assume "world_conc_exec_alt x (cs1 || cs2) tw'" hence "x, (cs1 || cs2) \<Rightarrow>\<^sub>c tw'" using world_conc_exec_alt_imp_world_conc_exec[OF _ `conc_stmt_wf (cs1 || cs2)` `nonneg_delay_conc (cs1 || cs2)`] by auto obtain tw_temp where "x, cs1 \<Rightarrow>\<^sub>c tw_temp \<and> tw_temp, cs2 \<Rightarrow>\<^sub>c tw'" using exist_middle_worldline by (metis \<open>x , cs1 || cs2 \<Rightarrow>\<^sub>c tw'\<close> assms(1) assms(2)) thus "Q tw'" by (simp add: \<open>\<forall>tw tw'. x , cs1 \<Rightarrow>\<^sub>c tw \<and> tw , cs2 \<Rightarrow>\<^sub>c tw' \<longrightarrow> Q tw'\<close>) qed qed lemma wp3_conc_parallel2: assumes "conc_stmt_wf (cs1 || cs2)" and "nonneg_delay_conc (cs1 || cs2)" assumes "conc_wt \<Gamma> (cs1 || cs2)" shows "wp3_conc \<Gamma> (cs1 || cs2) Q = wp3_conc \<Gamma> cs2 (wp3_conc \<Gamma> cs1 Q)" proof (rule ext, rule) fix x have "conc_stmt_wf cs1" and "conc_stmt_wf cs2" using assms by (simp add: conc_stmt_wf_def)+ have "nonneg_delay_conc cs1" and "nonneg_delay_conc cs2" using assms by auto assume "wp3_conc \<Gamma> (cs1 || cs2) Q x" hence "\<forall>tw'. x , cs1 || cs2 \<Rightarrow>\<^sub>c tw' \<longrightarrow> Q tw'" and "wityping \<Gamma> (snd x)" unfolding wp3_conc_def by auto thus" wp3_conc \<Gamma> cs2 (wp3_conc \<Gamma> cs1 Q) x" unfolding wp3_conc_def sym[OF world_conc_exec_eq_world_conc_exec_alt[OF assms(1-2)]] sym[OF world_conc_exec_eq_world_conc_exec_alt[OF `conc_stmt_wf cs1` `nonneg_delay_conc cs1`]] sym[OF world_conc_exec_eq_world_conc_exec_alt[OF `conc_stmt_wf cs2` `nonneg_delay_conc cs2`]] proof (intro conjI, simp, intro allI, intro impI) fix tw' have "conc_stmt_wf (cs2 || cs1)" and "nonneg_delay_conc (cs2 || cs1)" using `conc_stmt_wf (cs1 || cs2)` `nonneg_delay_conc (cs1 || cs2)` unfolding conc_stmt_wf_def by auto assume "\<forall>tw'. world_conc_exec_alt x (cs1 || cs2) tw' \<longrightarrow> Q tw'" hence "\<forall>tw'. world_conc_exec_alt x (cs2 || cs1) tw' \<longrightarrow> Q tw'" using world_conc_exec_alt_imp_world_conc_exec[OF _ `conc_stmt_wf (cs1 || cs2)` `nonneg_delay_conc (cs1 || cs2)`] world_conc_exec_imp_world_conc_exec_alt[OF _ `conc_stmt_wf (cs2 || cs1)` `nonneg_delay_conc (cs2 || cs1)`] by (metis \<open>\<And>tw. world_conc_exec tw cs1 = world_conc_exec_alt tw cs1\<close> \<open>\<And>tw. world_conc_exec tw cs2 = world_conc_exec_alt tw cs2\<close> \<open>conc_stmt_wf (cs2 || cs1)\<close> \<open>nonneg_delay_conc (cs2 || cs1)\<close> exist_middle_worldline world_conc_exec_alt.intros(4) world_conc_exec_alt_imp_world_conc_exec) assume "wityping \<Gamma> (snd x)" assume " world_conc_exec_alt x cs2 tw'" hence "x, cs2 \<Rightarrow>\<^sub>c tw'" using world_conc_exec_alt_imp_world_conc_exec[OF _ `conc_stmt_wf cs2` `nonneg_delay_conc cs2`] by auto moreover have "conc_wt \<Gamma> cs2" using assms(3) by auto hence "wityping \<Gamma> (snd tw')" using conc_stmt_preserve_wityping_hoare_semantic[OF `conc_wt \<Gamma> cs2` `conc_stmt_wf cs2` `nonneg_delay_conc cs2`] unfolding conc_hoare_valid_def using `wityping \<Gamma> (snd x)` `x, cs2 \<Rightarrow>\<^sub>c tw'` by meson moreover have "(\<forall>tw'a. world_conc_exec_alt tw' cs1 tw'a \<longrightarrow> Q tw'a)" using \<open>\<forall>tw'. world_conc_exec_alt x (cs2 || cs1) tw' \<longrightarrow> Q tw'\<close> \<open>world_conc_exec_alt x cs2 tw'\<close> world_conc_exec_alt.intros(3) by blast ultimately show "wityping \<Gamma> (snd tw') \<and> (\<forall>tw'a. world_conc_exec_alt tw' cs1 tw'a \<longrightarrow> Q tw'a)" by auto qed next fix x have "conc_stmt_wf cs1" and "conc_stmt_wf cs2" using assms by (simp add: conc_stmt_wf_def)+ have "nonneg_delay_conc cs1" and "nonneg_delay_conc cs2" using assms by auto have "conc_stmt_wf (cs2 || cs1)" and "nonneg_delay_conc (cs2 || cs1)" using assms by (metis conc_stmt_wf_def disjoint_iff_not_equal distinct_append signals_from.simps(2)) (simp add: \<open>nonneg_delay_conc cs1\<close> \<open>nonneg_delay_conc cs2\<close>) assume "wp3_conc \<Gamma> cs2 (wp3_conc \<Gamma> cs1 Q) x" hence "\<forall>tw tw'. x , cs2 \<Rightarrow>\<^sub>c tw \<and> tw , cs1 \<Rightarrow>\<^sub>c tw' \<longrightarrow> Q tw'" and "wityping \<Gamma> (snd x)" unfolding wp3_conc_def by metis+ hence "wp3_conc \<Gamma> (cs2 || cs1) Q x" unfolding wp3_conc_def using sym[OF world_conc_exec_eq_world_conc_exec_alt[OF `conc_stmt_wf (cs2 || cs1)` `nonneg_delay_conc (cs2 || cs1)`]] by (metis \<open>conc_stmt_wf (cs2 || cs1)\<close> \<open>nonneg_delay_conc (cs2 || cs1)\<close> wp_conc_def wp_conc_parallel) thus "wp3_conc \<Gamma> (cs1 || cs2) Q x" unfolding wp3_conc_def by (smt assms(1) parallel_comp_commute' world_conc_exec.intros world_conc_exec_cases) qed lemma wp3_conc_is_pre: assumes "conc_stmt_wf cs" and "nonneg_delay_conc cs" assumes "conc_wt \<Gamma> cs" shows "\<Gamma> \<turnstile> \<lbrace>wp3_conc \<Gamma> cs Q\<rbrace> cs \<lbrace>Q\<rbrace>" using assms proof (induction cs arbitrary:Q) case (Bpar cs1 cs2) hence "conc_stmt_wf cs1" and "conc_stmt_wf cs2" and "nonneg_delay_conc cs1" and "nonneg_delay_conc cs2" by auto hence "\<And>Q. \<Gamma> \<turnstile> \<lbrace>wp3_conc \<Gamma> cs1 Q\<rbrace> cs1 \<lbrace>Q\<rbrace>" and "\<And>Q. \<Gamma> \<turnstile> \<lbrace>wp3_conc \<Gamma> cs2 Q\<rbrace> cs2 \<lbrace>Q\<rbrace>" using Bpar(1-2) Bpar.prems(3) by blast+ then show ?case unfolding wp3_conc_parallel[OF Bpar(3-4)] by (metis Bpar.prems(1) Bpar.prems(3) \<open>\<And>\<Gamma> Q. conc_wt \<Gamma> (cs1 || cs2) \<Longrightarrow> wp3_conc \<Gamma> (cs1 || cs2) Q = wp3_conc \<Gamma> cs1 (wp3_conc \<Gamma> cs2 Q)\<close> conc_hoare_wt.Parallel) next case (Bsingle sl ss) hence "nonneg_delay ss" by auto then show ?case unfolding wp3_conc_single apply (intro Single) by (smt Bsingle.prems(3) Conseq3 conc_wt_cases(1) wp3_fun_eq_wp3 wp3_fun_is_pre) auto qed lemma wp3_conc_is_pre_valid: assumes "conc_stmt_wf cs" and "nonneg_delay_conc cs" assumes "conc_wt \<Gamma> cs" shows "\<Gamma> \<Turnstile> \<lbrace>wp3_conc \<Gamma> cs Q\<rbrace> cs \<lbrace>Q\<rbrace>" using assms by (simp add: VHDL_Hoare_Typed.soundness_conc_hoare wp3_conc_is_pre) definition sim_hoare_valid_wt :: "'signal tyenv \<Rightarrow> 'signal assn2 \<Rightarrow> 'signal conc_stmt \<Rightarrow> 'signal assn2 \<Rightarrow> bool" ("(1_) \<Turnstile>\<^sub>s \<lbrace>(1_)\<rbrace>/ (_)/ \<lbrace>(1_)\<rbrace>" 50) where "\<Gamma> \<Turnstile>\<^sub>s \<lbrace>P\<rbrace> cs \<lbrace>Q\<rbrace> \<longleftrightarrow> (\<forall>tw T tw'. wityping \<Gamma> (snd tw) \<and> P tw \<and> (tw, T, cs \<Rightarrow>\<^sub>S tw') \<longrightarrow> Q tw')" lemma true_program_true: \<open>\<Gamma> \<Turnstile>\<^sub>s \<lbrace>\<lambda>tw. True\<rbrace> cs \<lbrace>\<lambda>tw. True\<rbrace>\<close> unfolding sim_hoare_valid_wt_def by auto inductive sim_hoare :: "'signal tyenv \<Rightarrow> 'signal assn2 \<Rightarrow> 'signal conc_stmt \<Rightarrow> 'signal assn2 \<Rightarrow> bool" ("(1_) \<turnstile>\<^sub>s (\<lbrace>(1_)\<rbrace>/ (_)/ \<lbrace>(1_)\<rbrace>)" 50) where While_Suc: "\<Gamma> \<turnstile> \<lbrace>\<lambda>tw. P tw\<rbrace> cs \<lbrace> \<lambda>tw. P (fst tw + 1, snd tw)\<rbrace> \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>s \<lbrace>P\<rbrace> cs \<lbrace>P\<rbrace>" | Conseq_sim: "\<forall>tw. wityping \<Gamma> (snd tw) \<and> P' tw \<longrightarrow> P tw \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>s \<lbrace>P\<rbrace> cs \<lbrace>Q\<rbrace> \<Longrightarrow> \<forall>tw. Q tw \<longrightarrow> Q' tw \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>s \<lbrace>P'\<rbrace> cs \<lbrace>Q'\<rbrace>" | Conj_sim : "\<Gamma> \<turnstile>\<^sub>s \<lbrace>P\<rbrace> cs \<lbrace>Q1\<rbrace> \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>s \<lbrace>P\<rbrace> cs \<lbrace>Q2\<rbrace> \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>s \<lbrace>P\<rbrace> cs \<lbrace>\<lambda>tw. Q1 tw \<and> Q2 tw\<rbrace>" inductive_cases sim_hoare_cases: "\<Gamma> \<turnstile>\<^sub>s \<lbrace>P\<rbrace> cs \<lbrace>Q\<rbrace>" lemma while_soundness: assumes "\<Gamma> \<Turnstile> \<lbrace>P\<rbrace> cs \<lbrace>\<lambda>tw. P (fst tw + 1, snd tw)\<rbrace>" assumes "tw, T, cs \<Rightarrow>\<^sub>S tw'" assumes "P tw" assumes "nonneg_delay_conc cs" and "conc_stmt_wf cs" and "conc_wt \<Gamma> cs" and "wityping \<Gamma> (snd tw)" shows "P tw'" proof - have " world_sim_fin2 tw T cs tw'" using only_context_matters_for_sim_fin2[OF assms(2) assms(4-5)] world_sim_fin_semi_equivalent[OF assms(2) _ assms(4-5)] by auto hence "world_sim_fin2_alt tw T cs tw'" unfolding world_sim_fin2_eq_world_sim_fin2_alt[OF assms(5) assms(4), THEN sym] by auto thus ?thesis using assms(1) assms(3-7) proof (induction rule: world_sim_fin2_alt.inducts) case (1 tw T cs tw2 tw3) hence "tw, cs \<Rightarrow>\<^sub>c tw2" unfolding world_conc_exec_eq_world_conc_exec_alt[OF ` conc_stmt_wf cs` `nonneg_delay_conc cs`] by auto hence "P (get_time tw2 + 1, snd tw2)" using `\<Gamma> \<Turnstile> \<lbrace>\<lambda>tw. P tw\<rbrace> cs \<lbrace>\<lambda>tw. P (get_time tw + 1, snd tw)\<rbrace>` `fst tw < T` `P tw` `wityping \<Gamma> (snd tw)` unfolding conc_hoare_valid_wt_def by presburger moreover have "wityping \<Gamma> (snd (get_time tw2 + 1, snd tw2))" using `wityping \<Gamma> (snd tw)` conc_stmt_preserve_wityping_hoare_semantic[OF `conc_wt \<Gamma> cs` `conc_stmt_wf cs` `nonneg_delay_conc cs`] unfolding conc_hoare_valid_def using `tw, cs\<Rightarrow>\<^sub>c tw2` by (metis snd_conv) ultimately show ?case using 1(4)[OF `\<Gamma> \<Turnstile> \<lbrace>\<lambda>tw. P tw\<rbrace> cs \<lbrace>\<lambda>tw. P (get_time tw + 1, snd tw)\<rbrace>`] using "1.prems"(3) "1.prems"(4) ` conc_wt \<Gamma> cs` by auto next case (2 tw T cs) then show ?case by auto qed qed lemma conc_sim_soundness: assumes "\<Gamma> \<turnstile>\<^sub>s \<lbrace>P\<rbrace> cs \<lbrace>Q\<rbrace>" assumes "nonneg_delay_conc cs" and "conc_stmt_wf cs" and "conc_wt \<Gamma> cs" shows "\<Gamma> \<Turnstile>\<^sub>s \<lbrace>P\<rbrace> cs \<lbrace>Q\<rbrace>" using assms proof (induction rule:sim_hoare.induct) case (While_Suc \<Gamma> P cs) hence " \<Gamma> \<Turnstile> \<lbrace>\<lambda>tw. P tw\<rbrace> cs \<lbrace>\<lambda>tw. P (fst tw + 1, snd tw)\<rbrace>" using soundness_conc_hoare[OF While_Suc(1)] by auto then show ?case unfolding sim_hoare_valid_wt_def using while_soundness4[OF _ _ _ While_Suc(2-3)] by (metis (mono_tags, lifting) While_Suc.prems(1) While_Suc.prems(2) While_Suc.prems(3) while_soundness) next case (Conseq_sim \<Gamma> P' P cs Q Q') then show ?case by (smt sim_hoare_valid_wt_def) next case (Conj_sim \<Gamma> P cs Q1 Q2) then show ?case by (simp add: sim_hoare_valid_wt_def) qed lemma While_Suc': assumes "nonneg_delay_conc cs" and "conc_stmt_wf cs" and "conc_wt \<Gamma> cs" shows "\<Gamma> \<Turnstile> \<lbrace>\<lambda>tw. P tw\<rbrace> cs \<lbrace> \<lambda>tw. P (fst tw + 1, snd tw)\<rbrace> \<Longrightarrow> \<Gamma> \<Turnstile>\<^sub>s \<lbrace>P\<rbrace> cs \<lbrace>P\<rbrace>" using While_Suc conc_sim_soundness[OF _ assms] soundness_conc_hoare[OF _ assms(3) assms(2) assms(1)] using assms(1) assms(2) assms(3) sim_hoare_valid_wt_def while_soundness by fastforce lemma conseq_sim_valid: "\<forall>tw. wityping \<Gamma> (snd tw) \<and> P' tw \<longrightarrow> P tw \<Longrightarrow> \<Gamma> \<Turnstile>\<^sub>s \<lbrace>P\<rbrace> cs \<lbrace>Q\<rbrace> \<Longrightarrow> \<forall>tw. Q tw \<longrightarrow> Q' tw \<Longrightarrow> \<Gamma> \<Turnstile>\<^sub>s \<lbrace>P'\<rbrace> cs \<lbrace>Q'\<rbrace>" unfolding sim_hoare_valid_wt_def by blast lemma conc_wt_progress_world_sim: assumes "fst tw \<le> T" assumes \<open>conc_wt \<Gamma> cs\<close> assumes \<open>nonneg_delay_conc cs\<close> assumes \<open>wityping \<Gamma> (snd tw)\<close> assumes \<open>conc_stmt_wf cs\<close> shows "\<exists>tw'. tw, T, cs \<Rightarrow>\<^sub>S tw'" proof - obtain t \<sigma> \<gamma> \<theta> def \<tau> where "destruct_worldline tw = (t, \<sigma>, \<gamma>, \<theta>, def, \<tau>)" using destruct_worldline_exist by blast hence "ttyping \<Gamma> \<tau>" using `wityping \<Gamma> (snd tw)` wityping_ensure_ttyping2 by (metis (no_types, lifting) destruct_worldline_def snd_conv) have "ttyping \<Gamma> \<theta>" using wityping_ensure_ttyping by (smt Pair_inject \<open>destruct_worldline tw = (t, \<sigma>, \<gamma>, \<theta>, def, \<tau>)\<close> assms(4) destruct_worldline_def) have "styping \<Gamma> \<sigma>" by (metis (no_types, lifting) Pair_inject \<open>destruct_worldline tw = (t, \<sigma>, \<gamma>, \<theta>, def, \<tau>)\<close> assms(4) destruct_worldline_def styping_def wityping_def wtyping_def) have "styping \<Gamma> def" by (metis (mono_tags, lifting) \<open>destruct_worldline tw = (t, \<sigma>, \<gamma>, \<theta>, def, \<tau>)\<close> assms(4) destruct_worldline_def fst_conv snd_conv wityping_def) obtain t' \<sigma>' \<theta>' \<tau>' where " T, t, \<sigma>, \<gamma>, \<theta>, def \<turnstile> <cs, \<tau>> \<leadsto>s (t', \<sigma>', \<theta>', \<tau>')" using conc_wt_simulation_progress[OF assms(2-3) `ttyping \<Gamma> \<tau>` `ttyping \<Gamma> \<theta>` `styping \<Gamma> \<sigma>` `styping \<Gamma> def`] by (metis (full_types) \<open>destruct_worldline tw = (t, \<sigma>, \<gamma>, \<theta>, def, \<tau>)\<close> assms(1) fst_conv fst_destruct_worldline prod_cases4) hence "\<exists>tw'. world_sim_fin2 tw T cs tw'" using \<open>destruct_worldline tw = (t, \<sigma>, \<gamma>, \<theta>, def, \<tau>)\<close> world_sim_fin2.intros by blast thus ?thesis using world_sim_fin2_imp_fin using assms(3) assms(5) by blast qed lemma simulation_semi_complete: assumes \<open>\<Gamma> \<Turnstile>\<^sub>s \<lbrace>P\<rbrace> cs \<lbrace>P\<rbrace>\<close> assumes "nonneg_delay_conc cs" and "conc_stmt_wf cs" and "conc_wt \<Gamma> cs" shows \<open>\<Gamma> \<Turnstile> \<lbrace>P\<rbrace> cs \<lbrace>\<lambda>tw. P (fst tw + 1, snd tw)\<rbrace>\<close> proof - have *: "\<And>tw T tw'. wityping \<Gamma> (snd tw) \<Longrightarrow> P tw \<Longrightarrow> tw, T, cs \<Rightarrow>\<^sub>S tw' \<Longrightarrow> P tw'" using assms(1) unfolding sim_hoare_valid_wt_def by auto { fix tw tw' assume "wityping \<Gamma> (snd tw)" and "P tw" assume " tw , cs \<Rightarrow>\<^sub>c tw'" obtain tw_fin where "tw, fst tw + 1, cs \<Rightarrow>\<^sub>S tw_fin" using conc_wt_progress_world_sim by (metis \<open>wityping \<Gamma> (snd tw)\<close> add.commute assms(2) assms(3) assms(4) le_add2) hence "P tw_fin" using *[OF `wityping \<Gamma> (snd tw)` `P tw`] by blast have "tw_fin = (fst tw + 1, snd tw_fin)" using \<open>tw, get_time tw + 1, cs \<Rightarrow>\<^sub>S tw_fin\<close> world_maxtime_lt_fst_tres by fastforce have "world_sim_fin2 tw (fst tw + 1) cs tw_fin" using \<open>tw, get_time tw + 1, cs \<Rightarrow>\<^sub>S tw_fin\<close> assms(2) assms(3) world_sim_fin_imp_fin2 by blast hence "world_sim_fin2_alt tw (fst tw + 1) cs tw_fin" by (simp add: assms(2) assms(3) world_sim_fin2_eq_world_sim_fin2_alt) then obtain tw2 where "world_conc_exec_alt tw cs tw2" and "world_sim_fin2_alt (fst tw2 + 1, snd tw2) (fst tw + 1) cs tw_fin" by (metis (no_types, lifting) less_add_one not_add_less1 world_sim_fin2_alt.simps) hence " tw , cs \<Rightarrow>\<^sub>c tw2" using assms(2) assms(3) world_conc_exec_alt_imp_world_conc_exec by blast have "tw_fin = (fst tw2 + 1, snd tw2)" by (metis (no_types, lifting) One_nat_def \<open>tw , cs \<Rightarrow>\<^sub>c tw2\<close> \<open>world_sim_fin2_alt (get_time tw2 + 1, snd tw2) (get_time tw + 1) cs tw_fin\<close> fst_conv fst_world_conc_exec group_cancel.add1 not_add_less1 plus_1_eq_Suc world_sim_fin2_alt.cases) hence "P (get_time tw' + 1, snd tw')" by (metis \<open>P tw_fin\<close> \<open>tw , cs \<Rightarrow>\<^sub>c tw'\<close> \<open>tw , cs \<Rightarrow>\<^sub>c tw2\<close> world_conc_exec_deterministic) } thus ?thesis unfolding conc_hoare_valid_wt_def by metis qed lemma sim_hoare_valid_wt_parallel_commute: assumes "conc_stmt_wf (cs1 || cs2)" shows " \<Gamma> \<Turnstile>\<^sub>s \<lbrace>P\<rbrace> (cs1 || cs2) \<lbrace>Q\<rbrace> \<longleftrightarrow> \<Gamma> \<Turnstile>\<^sub>s \<lbrace>P\<rbrace> (cs2 || cs1) \<lbrace>Q\<rbrace>" unfolding sim_hoare_valid_wt_def world_sim_fin_parallel_commute[OF assms] by auto lemma sim_hoare_valid_wt_parallel_distrib: assumes "conc_stmt_wf ((cs1 || cs2) || cs3)" shows "\<Gamma> \<Turnstile>\<^sub>s \<lbrace>P\<rbrace> (cs1 || cs2) || cs3 \<lbrace>Q\<rbrace> \<longleftrightarrow> \<Gamma> \<Turnstile>\<^sub>s \<lbrace>P\<rbrace> (cs1 || cs3) || (cs2 || cs3) \<lbrace>Q\<rbrace>" unfolding sim_hoare_valid_wt_def world_sim_fin_parallel_distrib[OF assms] by blast lemma sim_hoare_valid_wt_parallel_associative: assumes "conc_stmt_wf ((cs1 || cs2) || cs3)" shows "\<Gamma> \<Turnstile>\<^sub>s \<lbrace>P\<rbrace> (cs1 || cs2) || cs3 \<lbrace>Q\<rbrace> \<longleftrightarrow> \<Gamma> \<Turnstile>\<^sub>s \<lbrace>P\<rbrace> cs1 || cs2 || cs3 \<lbrace>Q\<rbrace>" unfolding sim_hoare_valid_wt_def world_sim_fin_parallel_associative[OF assms] by blast lemma comb_sim_hoare_valid_wt: assumes "\<Gamma> \<Turnstile>\<^sub>s \<lbrace>P1\<rbrace> cs \<lbrace>Q1\<rbrace>" and "\<Gamma> \<Turnstile>\<^sub>s \<lbrace>P2\<rbrace> cs \<lbrace>Q2\<rbrace>" shows "\<Gamma> \<Turnstile>\<^sub>s \<lbrace>\<lambda>tw. P1 tw \<and> P2 tw\<rbrace> cs \<lbrace>\<lambda>tw. Q1 tw \<and> Q2 tw\<rbrace>" using assms unfolding sim_hoare_valid_wt_def by blast inductive init_hoare :: "'signal tyenv \<Rightarrow> 'signal assn2 \<Rightarrow> 'signal conc_stmt \<Rightarrow> 'signal assn2 \<Rightarrow> bool" ("(1_) \<turnstile>\<^sub>I (\<lbrace>(1_)\<rbrace>/ (_)/ \<lbrace>(1_)\<rbrace>)" 50) where SingleI: "\<Gamma> \<turnstile> [P] ss [Q] \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>I \<lbrace>P\<rbrace> process sl : ss \<lbrace>Q\<rbrace>" | ParallelI: "\<Gamma> \<turnstile>\<^sub>I \<lbrace>P\<rbrace> cs\<^sub>1 \<lbrace>R\<rbrace> \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>I \<lbrace>R\<rbrace> cs\<^sub>2 \<lbrace>Q\<rbrace> \<Longrightarrow> conc_stmt_wf (cs\<^sub>1 || cs\<^sub>2) \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>I \<lbrace>P\<rbrace> cs\<^sub>1 || cs\<^sub>2 \<lbrace>Q\<rbrace>" | ParallelI2: "\<Gamma> \<turnstile>\<^sub>I \<lbrace>P\<rbrace> cs\<^sub>2 \<lbrace>R\<rbrace> \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>I \<lbrace>R\<rbrace> cs\<^sub>1 \<lbrace>Q\<rbrace> \<Longrightarrow> conc_stmt_wf (cs\<^sub>1 || cs\<^sub>2) \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>I \<lbrace>P\<rbrace> cs\<^sub>1 || cs\<^sub>2 \<lbrace>Q\<rbrace>" | ConseqI: "\<lbrakk>\<forall>w. P' w \<longrightarrow> P w; \<Gamma> \<turnstile>\<^sub>I \<lbrace>P\<rbrace> cs \<lbrace>Q\<rbrace>; \<forall>w. Q w \<longrightarrow> Q' w\<rbrakk> \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>I \<lbrace>P'\<rbrace> cs \<lbrace>Q\<rbrace>" | ConjI: "\<Gamma> \<turnstile>\<^sub>I \<lbrace>P\<rbrace> cs \<lbrace>Q1\<rbrace> \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>I \<lbrace>P\<rbrace> cs \<lbrace>Q2\<rbrace> \<Longrightarrow> \<Gamma> \<turnstile>\<^sub>I \<lbrace>P\<rbrace> cs \<lbrace>\<lambda>tw. Q1 tw \<and> Q2 tw\<rbrace>" definition init_hoare_valid_wt :: "'signal tyenv \<Rightarrow> 'signal assn2 \<Rightarrow> 'signal conc_stmt \<Rightarrow> 'signal assn2 \<Rightarrow> bool" ("(1_) \<Turnstile>\<^sub>I \<lbrace>(1_)\<rbrace>/ (_)/ \<lbrace>(1_)\<rbrace>" 50) where "\<Gamma> \<Turnstile>\<^sub>I \<lbrace>P\<rbrace> cs \<lbrace>Q\<rbrace> \<longleftrightarrow> (\<forall>tw tw'. wityping \<Gamma> (snd tw) \<and> P tw \<and> (tw, cs \<Rightarrow>\<^sub>I tw') \<longrightarrow> Q tw')" lemma exist_middle_worldline_init: assumes "tw, cs \<Rightarrow>\<^sub>I tw'" and "cs = c1 || c2" assumes "conc_stmt_wf cs" and "nonneg_delay_conc cs" shows "\<exists>tw_temp. tw, c1 \<Rightarrow>\<^sub>I tw_temp \<and> tw_temp, c2 \<Rightarrow>\<^sub>I tw'" using assms proof (induction rule: world_init_exec.induct) case (1 tw t \<sigma> \<gamma> \<theta> def \<tau> cs \<tau>' tw') then obtain \<tau>_temp where \<tau>_temp: " init' t \<sigma> \<gamma> \<theta> def c1 \<tau> \<tau>_temp" by auto then obtain tw_temp where "tw, c1 \<Rightarrow>\<^sub>I tw_temp" and "tw_temp = worldline2 t \<sigma> \<theta> def \<tau>_temp" using 1 using world_init_exec.intros by blast have *: "init' t \<sigma> \<gamma> \<theta> def (c1 || c2) \<tau> \<tau>'" using 1 by auto hence 2: "init' t \<sigma> \<gamma> \<theta> def c2 \<tau>_temp \<tau>'" using init'_sequential[OF _ * \<tau>_temp] 1 by auto have "context_invariant t \<sigma> \<gamma> \<theta> def \<tau>" using worldline2_constructible 1 by blast hence "context_invariant t \<sigma> \<gamma> \<theta> def \<tau>_temp" using \<tau>_temp init'_preserves_context_invariant using "1.prems"(1) "1.prems"(3) nonneg_delay_conc.simps(2) by blast have ns: " \<forall>s. non_stuttering (to_trans_raw_sig \<tau>) \<sigma> s" using "1.hyps"(1) destruct_worldline_ensure_non_stuttering by blast have "\<And>n. n \<le> t \<Longrightarrow> \<tau> n = 0" using `context_invariant t \<sigma> \<gamma> \<theta> def \<tau>` unfolding context_invariant_def by auto hence "\<forall>s. non_stuttering (to_trans_raw_sig \<tau>_temp) \<sigma> s" using init'_preserves_non_stuttering[OF \<tau>_temp _ _ ] ns 1(5-6) `cs = c1 || c2` by (simp add: conc_stmt_wf_def) moreover have " \<forall>s. non_stuttering (to_trans_raw_sig \<theta>) def s" using "1.hyps"(1) destruct_worldline_ensure_non_stuttering_hist_raw by blast ultimately have "destruct_worldline tw_temp = (t, \<sigma>, \<gamma>, \<theta>, def, \<tau>_temp)" using destruct_worldline_correctness2 by (simp add: \<open>context_invariant t \<sigma> \<gamma> \<theta> def \<tau>_temp\<close> \<open>tw_temp = worldline2 t \<sigma> \<theta> def \<tau>_temp\<close> destruct_worldline_correctness3) hence "tw_temp, c2 \<Rightarrow>\<^sub>I tw'" using 2 1(3) using world_init_exec.intros by blast thus ?case by (meson \<open>tw , c1 \<Rightarrow>\<^sub>I tw_temp\<close>) qed lemma parallelI_valid: assumes "\<Gamma> \<Turnstile>\<^sub>I \<lbrace>P\<rbrace> c1 \<lbrace>R\<rbrace>" and "\<Gamma> \<Turnstile>\<^sub>I \<lbrace>R\<rbrace> c2 \<lbrace>Q\<rbrace>" and "conc_stmt_wf (c1 || c2)" assumes "nonneg_delay_conc (c1 || c2)" and "conc_wt \<Gamma> (c1 || c2)" shows "\<Gamma> \<Turnstile>\<^sub>I \<lbrace>P\<rbrace> c1 || c2 \<lbrace>Q\<rbrace>" unfolding init_hoare_valid_wt_def proof (rule, rule, rule) fix tw tw' assume *: "wityping \<Gamma> (snd tw) \<and> P tw \<and> tw , c1 || c2 \<Rightarrow>\<^sub>I tw'" then obtain tw_temp where "tw, c1 \<Rightarrow>\<^sub>I tw_temp" and "tw_temp, c2 \<Rightarrow>\<^sub>I tw'" using exist_middle_worldline_init[OF _ _ `conc_stmt_wf (c1 || c2)` `nonneg_delay_conc (c1 || c2)`] by metis hence "R tw_temp" using assms(1) * unfolding init_hoare_valid_wt_def by blast have "wityping \<Gamma> (snd tw_temp)" using init_preserve_wityping_semantic `conc_wt \<Gamma> (c1 || c2)` `conc_stmt_wf (c1 || c2)` `nonneg_delay_conc (c1 || c2)` * `tw, c1 \<Rightarrow>\<^sub>I tw_temp` unfolding init_hoare_valid_def conc_stmt_wf_def proof - assume "distinct (signals_from (c1 || c2))" then show ?thesis by (metis (no_types) "*" \<open>conc_wt \<Gamma> (c1 || c2)\<close> \<open>nonneg_delay_conc (c1 || c2)\<close> \<open>tw , c1 \<Rightarrow>\<^sub>I tw_temp\<close> conc_stmt_wf_def conc_wt_cases(2) distinct_append init_hoare_valid_def init_preserve_wityping_semantic nonneg_delay_conc.simps(2) signals_from.simps(2)) qed thus "Q tw'" using assms(2) `R tw_temp` `tw_temp, c2 \<Rightarrow>\<^sub>I tw'` unfolding init_hoare_valid_wt_def by blast qed lemma soundness_init_hoare: assumes "\<Gamma> \<turnstile>\<^sub>I \<lbrace>P\<rbrace> c \<lbrace>Q\<rbrace>" assumes "conc_stmt_wf c" and "nonneg_delay_conc c" and "conc_wt \<Gamma> c" shows "\<Gamma> \<Turnstile>\<^sub>I \<lbrace>P\<rbrace> c \<lbrace>Q\<rbrace>" using assms proof (induction rule:init_hoare.induct) case (SingleI \<Gamma> P ss Q sl) hence " \<Gamma> \<Turnstile> [P] ss [Q]" using seq_hoare3_soundness by auto then show ?case unfolding init_hoare_valid_wt_def seq_hoare_valid2_wt_def using world_seq_exec.intros by fastforce next case (ParallelI \<Gamma> P cs\<^sub>1 R cs\<^sub>2 Q) hence "\<Gamma> \<Turnstile>\<^sub>I \<lbrace>P\<rbrace> cs\<^sub>1 \<lbrace>R\<rbrace>" and "\<Gamma> \<Turnstile>\<^sub>I \<lbrace>R\<rbrace> cs\<^sub>2 \<lbrace>Q\<rbrace>" unfolding conc_stmt_wf_def by auto then show ?case using parallelI_valid by (metis ParallelI.prems(1) ParallelI.prems(2) ParallelI.prems(3)) next case (ParallelI2 \<Gamma> P cs\<^sub>2 R cs\<^sub>1 Q) hence "\<Gamma> \<Turnstile>\<^sub>I \<lbrace>P\<rbrace> cs\<^sub>2 \<lbrace>R\<rbrace>" and "\<Gamma> \<Turnstile>\<^sub>I \<lbrace>R\<rbrace> cs\<^sub>1 \<lbrace>Q\<rbrace>" unfolding conc_stmt_wf_def by auto have "\<Gamma> \<Turnstile>\<^sub>I \<lbrace>P\<rbrace> cs\<^sub>2 || cs\<^sub>1 \<lbrace>Q\<rbrace>" using parallelI_valid[OF `\<Gamma> \<Turnstile>\<^sub>I \<lbrace>P\<rbrace> cs\<^sub>2 \<lbrace>R\<rbrace>` `\<Gamma> \<Turnstile>\<^sub>I \<lbrace>R\<rbrace> cs\<^sub>1 \<lbrace>Q\<rbrace>`] `conc_stmt_wf (cs\<^sub>1 || cs\<^sub>2)` ` nonneg_delay_conc (cs\<^sub>1 || cs\<^sub>2)` `conc_wt \<Gamma> (cs\<^sub>1 || cs\<^sub>2)` unfolding conc_stmt_wf_def by (metis conc_wt.intros(2) conc_wt_cases(2) disjoint_iff_not_equal distinct_append nonneg_delay_conc.simps(2) signals_from.simps(2)) thus ?case using world_init_exec_commute unfolding init_hoare_valid_wt_def by (smt ParallelI2.prems(1) parallelI_comp_commute' world_init_exec.intros world_init_exec_cases(2)) next case (ConseqI \<Gamma> P' P cs Q Q') then show ?case by (smt init_hoare_valid_wt_def) next case (ConjI \<Gamma> P cs Q1 Q2) then show ?case by (simp add: init_hoare_valid_wt_def) qed definition wp3_init :: "'signal tyenv \<Rightarrow> 'signal conc_stmt \<Rightarrow> 'signal assn2 \<Rightarrow> 'signal assn2" where "wp3_init \<Gamma> cs Q = (\<lambda>tw. wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. (tw, cs \<Rightarrow>\<^sub>I tw') \<longrightarrow> Q tw'))" lemma wp3_init_single: "wp3_init \<Gamma> (process sl : ss) Q = wp3 \<Gamma> ss Q" apply (rule ext) unfolding wp3_init_def wp3_def by (smt init'_cases(1) world_init_exec_cases(1) world_init_exec_process world_seq_exec.intros) lemma wp3_init_parallel: assumes "conc_stmt_wf (cs1 || cs2)" and "nonneg_delay_conc (cs1 || cs2)" and "conc_wt \<Gamma> (cs1 || cs2)" shows "wp3_init \<Gamma> (cs1 || cs2) Q = wp3_init \<Gamma> cs1 (wp3_init \<Gamma> cs2 Q)" unfolding wp3_init_def proof (rule, rule, rule_tac[!] conjI, simp, rule, rule, rule) fix tw tw' assume *: "wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw , cs1 || cs2 \<Rightarrow>\<^sub>I tw' \<longrightarrow> Q tw')" assume "tw, cs1 \<Rightarrow>\<^sub>I tw'" thus "wityping \<Gamma> (snd tw')" using init_preserve_wityping_semantic * unfolding init_hoare_valid_def by (metis (no_types) \<open>tw , cs1 \<Rightarrow>\<^sub>I tw'\<close> assms(1) assms(2) assms(3) conc_stmt_wf_def conc_wt_cases(2) distinct_append init_hoare_valid_def init_preserve_wityping_semantic nonneg_delay_conc.simps(2) signals_from.simps(2)) { fix tw2 assume "tw', cs2 \<Rightarrow>\<^sub>I tw2" hence "Q tw2" using * `tw, cs1 \<Rightarrow>\<^sub>I tw'` by (metis assms(1) assms(2) conc_stmt_wf_def distinct_append nonneg_delay_conc.simps(2) signals_from.simps(2) world_init_equality world_init_exec_alt.intros(2)) } thus " \<forall>tw'a. tw' , cs2 \<Rightarrow>\<^sub>I tw'a \<longrightarrow> Q tw'a" by auto next fix tw assume *: "wityping \<Gamma> (snd tw) \<and> (\<forall>tw'. tw , cs1 \<Rightarrow>\<^sub>I tw' \<longrightarrow> wityping \<Gamma> (snd tw') \<and> (\<forall>tw'a. tw' , cs2 \<Rightarrow>\<^sub>I tw'a \<longrightarrow> Q tw'a))" thus "wityping \<Gamma> (snd tw)" by auto { fix tw' assume "tw, cs1 || cs2 \<Rightarrow>\<^sub>I tw'" hence "Q tw'" using * by (meson assms(1) assms(2) exist_middle_worldline_init) } thus "\<forall>tw'. tw , cs1 || cs2 \<Rightarrow>\<^sub>I tw' \<longrightarrow> Q tw'" by auto qed fun wp3_init_fun :: "'signal tyenv \<Rightarrow> 'signal conc_stmt \<Rightarrow> 'signal assn2 \<Rightarrow> 'signal assn2" where "wp3_init_fun \<Gamma> (process sl : ss) Q = wp3 \<Gamma> ss Q" | "wp3_init_fun \<Gamma> (cs1 || cs2) Q = wp3_init_fun \<Gamma> cs1 (wp3_init_fun \<Gamma> cs2 Q)" lemma wp3_init_fun_is_wp3_init: assumes "conc_stmt_wf cs" and "nonneg_delay_conc cs" and "conc_wt \<Gamma> cs" shows "wp3_init_fun \<Gamma> cs Q = wp3_init \<Gamma> cs Q" using assms apply (induction cs arbitrary: Q) using wp3_init_parallel apply (metis conc_stmt_wf_def conc_wt_cases(2) distinct_append nonneg_delay_conc.simps(2) signals_from.simps(2) wp3_init_fun.simps(2)) by (simp add: wp3_init_single) definition init_sim2_valid_wt :: "'signal tyenv \<Rightarrow> 'signal assn2 \<Rightarrow> 'signal conc_stmt \<Rightarrow> 'signal assn2 \<Rightarrow> bool" where "init_sim2_valid_wt \<Gamma> P cs Q = (\<forall>tw tw'. wityping \<Gamma> (snd tw) \<and> P tw \<and> init_sim2 tw cs tw' \<longrightarrow> Q tw')" inductive init_sim2_hoare_wt :: "'signal tyenv \<Rightarrow> 'signal assn2 \<Rightarrow> 'signal conc_stmt \<Rightarrow> 'signal assn2 \<Rightarrow> bool" where AssignI_suc: "\<Gamma> \<turnstile>\<^sub>I \<lbrace>P\<rbrace> cs \<lbrace>\<lambda>tw. Q (fst tw + 1, snd tw)\<rbrace> \<Longrightarrow> init_sim2_hoare_wt \<Gamma> P cs Q" | ConseqI_suc_sim: "\<forall>tw. P' tw \<longrightarrow> P tw \<Longrightarrow> init_sim2_hoare_wt \<Gamma> P cs Q \<Longrightarrow> \<forall>tw. Q tw \<longrightarrow> Q' tw \<Longrightarrow> init_sim2_hoare_wt \<Gamma> P' cs Q'" | ConjI_suc_sim: "init_sim2_hoare_wt \<Gamma> P cs Q1 \<Longrightarrow> init_sim2_hoare_wt \<Gamma> P cs Q2 \<Longrightarrow> init_sim2_hoare_wt \<Gamma> P cs (\<lambda>tw. Q1 tw \<and> Q2 tw)" lemma init_sim2_hoare_wt_soundness: assumes "init_sim2_hoare_wt \<Gamma> P cs Q" assumes "conc_stmt_wf cs" and "nonneg_delay_conc cs" and "conc_wt \<Gamma> cs" shows "init_sim2_valid_wt \<Gamma> P cs Q" using assms proof (induction rule:init_sim2_hoare_wt.induct) case (AssignI_suc \<Gamma> P cs Q) have *: "\<Gamma> \<Turnstile>\<^sub>I \<lbrace>P\<rbrace> cs \<lbrace>\<lambda>tw. Q (fst tw + 1, snd tw)\<rbrace>" using soundness_init_hoare[OF AssignI_suc] by auto { fix tw tw' assume "P tw" assume "wityping \<Gamma> (snd tw)" assume "tw, cs \<Rightarrow>\<^sub>I tw'" hence "Q (fst tw' + 1, snd tw')" (is ?imp1) using * \<open>P tw\<close> `wityping \<Gamma> (snd tw)` unfolding init_hoare_valid_wt_def by blast have "init_sim2 tw cs (fst tw' + 1, snd tw')" (is ?imp2) using \<open>tw, cs \<Rightarrow>\<^sub>I tw'\<close> using init_sim2.intros by blast hence "?imp1 \<and> ?imp2" using \<open>?imp1\<close> by auto } then show ?case unfolding init_sim2_valid_wt_def by auto next case (ConseqI_suc_sim \<Gamma> P' P cs Q Q') then show ?case by (smt init_sim2_valid_wt_def) next case (ConjI_suc_sim \<Gamma> P cs Q1 Q2) then show ?case by (simp add: init_sim2_valid_wt_def) qed lemma init_sim2_preserves_wityping: assumes "init_sim2 tw cs tw'" and "conc_wt \<Gamma> cs" and "conc_stmt_wf cs" and "nonneg_delay_conc cs" assumes "wityping \<Gamma> (snd tw)" shows "wityping \<Gamma> (snd tw')" using assms proof (induction cs arbitrary: tw tw') case (Bpar cs1 cs2) then obtain tw2 where "tw, (cs1 || cs2) \<Rightarrow>\<^sub>I tw2" and "tw' = (fst tw2 + 1, snd tw2)" by (meson init_sim2.cases) then obtain tw_temp where "tw, cs1 \<Rightarrow>\<^sub>I tw_temp" and "tw_temp, cs2 \<Rightarrow>\<^sub>I tw2" by (meson Bpar.prems(3) Bpar.prems(4) exist_middle_worldline_init) hence "init_sim2 tw cs1 (fst tw_temp + 1, snd tw_temp)" using init_sim2.intros by blast note IH = Bpar(1)[OF this] hence " wityping \<Gamma> (snd tw_temp)" using Bpar unfolding conc_stmt_wf_def by auto have "init_sim2 tw_temp cs2 tw'" using `tw_temp, cs2 \<Rightarrow>\<^sub>I tw2` using \<open>tw' = (get_time tw2 + 1, snd tw2)\<close> init_sim2.intros by blast note IH2 = Bpar(2)[OF this] thus "wityping \<Gamma> (snd tw')" using Bpar `wityping \<Gamma> (snd tw_temp)` unfolding conc_stmt_wf_def by auto next case (Bsingle sl ss) then obtain tw2 where *: "tw, process sl : ss \<Rightarrow>\<^sub>I tw2" and "tw' = (fst tw2 + 1, snd tw2)" by (meson init_sim2.cases) have "seq_wt \<Gamma> ss" using Bsingle by auto hence "wityping \<Gamma> (snd tw2)" using * VHDL_Hoare_Complete.soundness_init_hoare[OF single_conc_stmt_preserve_wityping_init_hoare[OF `seq_wt \<Gamma> ss`]] Bsingle(3-) unfolding init_hoare_valid_def by meson thus ?case using `tw' = (fst tw2 + 1 , snd tw2)` by auto qed lemma world_seq_exec_preserves_wityping: assumes "world_seq_exec_alt tw seq tw2" and "seq_wt \<Gamma> seq" assumes "wityping \<Gamma> (snd tw)" shows "wityping \<Gamma> (snd tw2)" using assms proof (induction rule:world_seq_exec_alt.inducts) case (7 tw exp x exp' ss tw' choices) then show ?case using seq_wt_cases_bcase by auto next case (8 tw exp x exp' x' choices tw' ss) then show ?case using seq_wt_cases_bcase by fastforce next case (9 tw ss tw' exp choices) then show ?case using seq_wt_cases_bcase by auto next case (5 tw exp x tw' sig dly) hence "bexp_wt \<Gamma> exp (\<Gamma> sig)" by blast hence "type_of x = \<Gamma> sig" by (metis "5.hyps"(1) "5.prems"(2) beval_world_raw2_def eval_world_raw_correctness_only_if type_of_eval_world_raw2) then show ?case using worldline_upd_eval_world_raw_preserve_wityping2 by (simp add: worldline_upd_eval_world_raw_preserve_wityping2 "5.hyps"(2) "5.prems"(2)) next case (6 tw exp x tw' sig dly) then show ?case by (smt beval_world_raw2_def eval_world_raw_correctness_only_if seq_wt_cases(5) sndI type_of_eval_world_raw2 worldline_inert_upd2_def worldline_inert_upd_preserve_wityping') qed auto lemma world_conc_exec_preserves_wityping: assumes "world_conc_exec_alt tw cs tw2" and "conc_wt \<Gamma> cs" assumes "wityping \<Gamma> (snd tw)" shows "wityping \<Gamma> (snd tw2)" using assms proof (induction rule:world_conc_exec_alt.inducts) case (2 tw ss tw' sl) then show ?case using world_seq_exec_preserves_wityping by blast qed auto lemma world_sim_fin_preserves_wityping: assumes "tw, x, cs \<Rightarrow>\<^sub>S tw'" and "conc_wt \<Gamma> cs" and "conc_stmt_wf cs" and "nonneg_delay_conc cs" assumes "wityping \<Gamma> (snd tw)" shows "wityping \<Gamma> (snd tw')" proof - have "world_sim_fin2_alt tw x cs tw'" using assms only_context_matters_for_sim_fin2 world_sim_fin2_imp_world_sim_fin2_alt world_sim_fin_semi_equivalent by blast thus ?thesis using assms(2-5) proof (induction rule:world_sim_fin2_alt.induct) case (1 tw T cs tw2 tw3) hence "wityping \<Gamma> (snd tw2)" using world_conc_exec_preserves_wityping by blast then show ?case using 1 by auto next case (2 tw T cs) then show ?case by auto qed qed lemma world_sim_fin2_alt_preserves_wityping: assumes "world_sim_fin2_alt tw x cs tw'" and "conc_wt \<Gamma> cs" and "conc_stmt_wf cs" and "nonneg_delay_conc cs" assumes "wityping \<Gamma> (snd tw)" shows "wityping \<Gamma> (snd tw')" using world_sim_fin_preserves_wityping[OF _ assms(2-)] world_sim_fin_eq_world_sim_fin2_alt[OF assms(3-4)] assms(1) by auto lemma sim_fin2_preserves_wityping: assumes "sim_fin2 w x cs tw'" and "conc_wt \<Gamma> cs" and "conc_stmt_wf cs" and "nonneg_delay_conc cs" assumes "wityping \<Gamma> w" shows "wityping \<Gamma> (snd tw')" proof (rule sim_fin2_ic[OF assms(1)]) fix tw assume "init_sim2 (0, w) cs tw" hence "wityping \<Gamma> (snd tw)" using init_sim2_preserves_wityping by (metis assms(2) assms(3) assms(4) assms(5) snd_conv) assume "tw, x, cs \<Rightarrow>\<^sub>S tw'" thus "wityping \<Gamma> (snd tw')" using world_sim_fin_preserves_wityping \<open>wityping \<Gamma> (snd tw)\<close> assms(2) assms(3) assms(4) by blast qed lemma grand_correctness: assumes "sim_fin2 w (i + 1) cs tw'" and "wityping \<Gamma> w" assumes "conc_stmt_wf cs" and "conc_wt \<Gamma> cs" and "nonneg_delay_conc cs" assumes "\<Gamma> \<turnstile>\<^sub>s \<lbrace>Inv\<rbrace> cs \<lbrace>Inv\<rbrace>" assumes "init_sim2_hoare_wt \<Gamma> (\<lambda>tw. fst tw = 0) cs Inv" shows "Inv tw'" proof - obtain tw where "init_sim2 (0, w) cs tw" and "tw, i + 1, cs \<Rightarrow>\<^sub>S tw'" using sim_fin2.cases[OF `sim_fin2 w (i + 1) cs tw'`] by metis hence "i + 1 = fst tw'" using world_maxtime_lt_fst_tres by blast have "wityping \<Gamma> (snd tw)" using init_sim2_preserves_wityping by (metis \<open>init_sim2 (0, w) cs tw\<close> assms(2-5) snd_conv) have "init_sim2_valid_wt \<Gamma> (\<lambda>tw. fst tw = 0) cs Inv" using init_sim2_hoare_wt_soundness[OF assms(7)] assms(2-5) by auto hence "Inv tw" using \<open>init_sim2 (0, w) cs tw\<close> fst_conv assms(2) unfolding init_sim2_valid_wt_def by (metis snd_conv) moreover have "\<Gamma> \<Turnstile>\<^sub>s \<lbrace>Inv\<rbrace> cs \<lbrace>Inv\<rbrace>" using conc_sim_soundness[OF assms(6)] assms(2-5) by auto ultimately have "Inv tw'" using \<open>tw, i + 1, cs \<Rightarrow>\<^sub>S tw'\<close> `wityping \<Gamma> (snd tw)` unfolding sim_hoare_valid_wt_def by blast thus ?thesis by auto qed lemma grand_correctness2: assumes "sim_fin2 w endtime cs tw'" and "wityping \<Gamma> w" assumes "conc_stmt_wf cs" and "conc_wt \<Gamma> cs" and "nonneg_delay_conc cs" assumes "\<Gamma> \<turnstile>\<^sub>s \<lbrace>Inv\<rbrace> cs \<lbrace>Inv\<rbrace>" assumes "Q (0, w)" assumes "init_sim2_hoare_wt \<Gamma> (\<lambda>tw. fst tw = 0 \<and> Q tw) cs Inv" shows "Inv tw'" proof - obtain tw where "init_sim2 (0, w) cs tw" and "tw, endtime, cs \<Rightarrow>\<^sub>S tw'" using sim_fin2.cases[OF `sim_fin2 w endtime cs tw'`] by metis hence "endtime = fst tw'" using world_maxtime_lt_fst_tres by blast have "wityping \<Gamma> (snd tw)" using init_sim2_preserves_wityping by (metis \<open>init_sim2 (0, w) cs tw\<close> assms(2-5) snd_conv) have "init_sim2_valid_wt \<Gamma> (\<lambda>tw. fst tw = 0 \<and> Q tw) cs Inv" using init_sim2_hoare_wt_soundness[OF assms(8)] assms(2-5) by auto hence "Inv tw" using \<open>init_sim2 (0, w) cs tw\<close> fst_conv assms(2) unfolding init_sim2_valid_wt_def by (metis assms(7) snd_conv) moreover have "\<Gamma> \<Turnstile>\<^sub>s \<lbrace>Inv\<rbrace> cs \<lbrace>Inv\<rbrace>" using conc_sim_soundness[OF assms(6)] assms(2-5) by auto ultimately have "Inv tw'" using \<open>tw, endtime, cs \<Rightarrow>\<^sub>S tw'\<close> `wityping \<Gamma> (snd tw)` unfolding sim_hoare_valid_wt_def by blast thus ?thesis by auto qed lemma grand_correctness2_sem: assumes "sim_fin2 w endtime cs tw'" and "wityping \<Gamma> w" assumes "conc_stmt_wf cs" and "conc_wt \<Gamma> cs" and "nonneg_delay_conc cs" assumes "\<Gamma> \<Turnstile>\<^sub>s \<lbrace>Inv\<rbrace> cs \<lbrace>Inv\<rbrace>" assumes "Q (0, w)" assumes "init_sim2_hoare_wt \<Gamma> (\<lambda>tw. fst tw = 0 \<and> Q tw) cs Inv" shows "Inv tw'" proof - obtain tw where "init_sim2 (0, w) cs tw" and "tw, endtime, cs \<Rightarrow>\<^sub>S tw'" using sim_fin2.cases[OF `sim_fin2 w endtime cs tw'`] by metis hence "endtime = fst tw'" using world_maxtime_lt_fst_tres by blast have "wityping \<Gamma> (snd tw)" using init_sim2_preserves_wityping by (metis \<open>init_sim2 (0, w) cs tw\<close> assms(2-5) snd_conv) have "init_sim2_valid_wt \<Gamma> (\<lambda>tw. fst tw = 0 \<and> Q tw) cs Inv" using init_sim2_hoare_wt_soundness[OF assms(8)] assms(2-5) by auto hence "Inv tw" using \<open>init_sim2 (0, w) cs tw\<close> fst_conv assms(2) unfolding init_sim2_valid_wt_def by (metis assms(7) snd_conv) hence "Inv tw'" using \<open>tw, endtime, cs \<Rightarrow>\<^sub>S tw'\<close> `wityping \<Gamma> (snd tw)` unfolding sim_hoare_valid_wt_def using assms sim_hoare_valid_wt_def by fast thus ?thesis by auto qed end
State Before: R : Type u S : Type v a b c d : R n m : ℕ inst✝ : Semiring R p q : R[X] ι : Type ?u.644630 ⊢ leadingCoeff X = 1 State After: no goals Tactic: simpa only [pow_one] using @leadingCoeff_X_pow R _ 1
module SelectionProbit using WGLMakie, GLMakie, Distributions, Colors, JSServe include("plot.jl") export showplot end # module
"""Handler for Next Generation.""" import base64 import copy import io import json import logging import random from PIL import Image import numpy as np try: from config import Config from cppn import CPPN except ModuleNotFoundError: from nextGeneration.config import Config from nextGeneration.cppn import CPPN HEADERS = { "Access-Control-Allow-Headers": "Content-Type", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "OPTIONS,POST,GET" } def evaluate_population(population, config)->str: """Evaluate the population to generate images and return the json data.""" for individual in population: if individual.selected: continue # frontend already has image data for previous gen # evaluate the CPPN individual.get_image() # convert from numpy to bytes individual.image = Image.fromarray(individual.image) # convert to RGB if not RGB if individual.image.mode != 'RGB': individual.image = individual.image.convert('RGB') with io.BytesIO() as img_byte_arr: individual.image.save(img_byte_arr, format='PNG') im_b64 = base64.b64encode(img_byte_arr.getvalue()).decode("utf8") individual.image = im_b64 img_byte_arr.close() # convert to json population_json = [individual.to_json() for individual in population] json_data = {"config":config.to_json(), "population": population_json} json_data = json.dumps(json_data) return json_data def selection_procedure(config, population, selected): """Creates a new population given the selected individuals in-place Args: config (Config): The configuration for evolution population (list[CPPN]): The current population selected (list[CPPN]): The selected individuals """ for index, _ in enumerate(population): if not population[index].selected: do_crossover = config.do_crossover and np.random.random() < config.prob_crossover if do_crossover: # crossover two selected individuals parent1 = np.random.choice(selected) parent2 = np.random.choice(selected) population[index] = parent1.crossover(parent2) else: # replace with a mutated version of a random selected individual random_parent = np.random.choice(selected) population[index] = copy.deepcopy(random_parent) # make a copy # mutate population[index].mutate() population[index].selected = False # deselect def initial_population(config): """Create the initial population.""" population = [] # create population for _ in range(config.population_size): population.append(CPPN(config)) # evaluate population json_data = evaluate_population(population, config) return json_data def next_generation(config, population_data): """Create the next generation.""" population = [] if population_data is None or len(population_data) == 0: # return an initial population return initial_population(config) # create population for individual in population_data: population.append(CPPN.create_from_json(individual, config)) # build list of selected individuals selected = list(filter(lambda x: x.selected, population)) # replace the unselected individuals with new individuals selection_procedure(config, population, selected) # evaluate population json_data = evaluate_population(population, config) return json_data def save_images(config, population_data): """Return the images in the population, generated with save resolution."""# create population population = [] for individual in population_data: population.append(CPPN.create_from_json(individual, config)) for individual in population: if individual.selected: # apply save resolution before evaluating individual.config.res_h = config.save_h individual.config.res_w = config.save_w individual.selected = not individual.selected # invert selection json_data = evaluate_population(population, config) return json_data def lambda_handler(event, context): """Handle an incoming request from Next Generation.""" # pylint: disable=unused-argument #(context required by lambda) body = None status = 200 try: data = event['body'] if 'body' in event else event if isinstance(data, str): # load the data to a json object data = json.loads(data, strict=False) operation = data['operation'] config = Config.create_from_json(data['config']) # use the seed from the config random.seed(int(config.seed)) np.random.seed(int(config.seed)) if operation == 'reset': body = initial_population(config) elif operation == 'next_gen': raw_pop = data['population'] body = next_generation(config, raw_pop) elif operation == 'save_images': raw_pop = data['population'] body = save_images(config, raw_pop) except Exception as exception: # pylint: disable=broad-except print("ERROR while handling lambda:", type(exception), exception) status = 500 body = json.dumps(f"error in lambda: {type(exception)}: {exception}") logging.exception(exception) # okay to disable broad-except return { 'statusCode': status, 'headers': HEADERS, 'body': body }
{-# OPTIONS --without-K --safe #-} module Fragment.Examples.Semigroup.Arith.Functions where open import Fragment.Examples.Semigroup.Arith.Base -- Fully dynamic associativity +-dyn-assoc₁ : ∀ {f : ℕ → ℕ} {m n o} → (f m + n) + o ≡ f m + (n + o) +-dyn-assoc₁ = fragment SemigroupFrex +-semigroup +-dyn-assoc₂ : ∀ {f g : ℕ → ℕ} {m n o p} → ((f m + n) + o) + g p ≡ f m + (n + (o + g p)) +-dyn-assoc₂ = fragment SemigroupFrex +-semigroup +-dyn-assoc₃ : ∀ {f g h : ℕ → ℕ} {m n o p q} → (f m + n) + g o + (p + h q) ≡ f m + (n + g o + p) + h q +-dyn-assoc₃ = fragment SemigroupFrex +-semigroup *-dyn-assoc₁ : ∀ {f : ℕ → ℕ} {m n o} → (f m * n) * o ≡ f m * (n * o) *-dyn-assoc₁ = fragment SemigroupFrex *-semigroup *-dyn-assoc₂ : ∀ {f g : ℕ → ℕ} {m n o p} → ((f m * n) * o) * g p ≡ f m * (n * (o * g p)) *-dyn-assoc₂ = fragment SemigroupFrex *-semigroup *-dyn-assoc₃ : ∀ {f g h : ℕ → ℕ} {m n o p q} → (f m * n) * g o * (p * h q) ≡ f m * (n * g o * p) * h q *-dyn-assoc₃ = fragment SemigroupFrex *-semigroup -- Partially static associativity +-sta-assoc₁ : ∀ {f : ℕ → ℕ} {m} → (m + 2) + (3 + f 0) ≡ m + (5 + f 0) +-sta-assoc₁ = fragment SemigroupFrex +-semigroup +-sta-assoc₂ : ∀ {f g : ℕ → ℕ} {m n o p} → (((f m + g n) + 5) + o) + p ≡ f m + (g n + (2 + (3 + (o + p)))) +-sta-assoc₂ = fragment SemigroupFrex +-semigroup +-sta-assoc₃ : ∀ {f : ℕ → ℕ} {m n o p} → f (n + m) + (n + 2) + (3 + (o + p)) ≡ f (n + m) + (((n + 1) + (4 + o)) + p) +-sta-assoc₃ = fragment SemigroupFrex +-semigroup *-sta-assoc₁ : ∀ {f : ℕ → ℕ} {m} → (m * 2) * (3 * f 0) ≡ m * (6 * f 0) *-sta-assoc₁ = fragment SemigroupFrex *-semigroup *-sta-assoc₂ : ∀ {f g : ℕ → ℕ} {m n o p} → (((f m * g n) * 6) * o) * p ≡ f m * (g n * (2 * (3 * (o * p)))) *-sta-assoc₂ = fragment SemigroupFrex *-semigroup *-sta-assoc₃ : ∀ {f : ℕ → ℕ} {m n o p} → f (n + m) * (n * 4) * (3 * (o * p)) ≡ f (n + m) * (((n * 2) * (6 * o)) * p) *-sta-assoc₃ = fragment SemigroupFrex *-semigroup
repeat process ACV_lasers { /tp @e[type=armor_stand,name=ACV_Cube] ~ ~ ~ ~ 0 /scoreboard players tag @e[type=area_effect_cloud,name=ACV_Laser] remove ACV_InCube /scoreboard players tag @e[type=area_effect_cloud,name=ACV_Laser] remove ACV_EnteringCube /scoreboard players tag @e[type=area_effect_cloud,name=ACV_Laser] remove ACV_InAir /execute @e[type=area_effect_cloud,name=ACV_Laser] ~ ~ ~ particle reddust ~ ~ ~ 0.1 0.1 0.1 0 10 force /execute @e[type=armor_stand,name=ACV_Cube,tag=ACV_Redirecting] ~ ~2 ~ scoreboard players tag @e[type=area_effect_cloud,name=ACV_Laser,dy=0] add ACV_InCube /tp @e[type=area_effect_cloud,name=ACV_Laser,rym=169,ry=-168,rxm=0,rx=0] ~0 ~ ~-0.5 /tp @e[type=area_effect_cloud,name=ACV_Laser,rym=-167,ry=-146,rxm=0,rx=0] ~0.1913417161825448858642299920152 ~ ~-0.46193976625564337806409159469839 /tp @e[type=area_effect_cloud,name=ACV_Laser,rym=-145,ry=-123,rxm=0,rx=0] ~0.35355339059327376220042218105242 ~ ~-0.35355339059327376220042218105242 /tp @e[type=area_effect_cloud,name=ACV_Laser,rym=-122,ry=-101,rxm=0,rx=0] ~0.46193976625564337806409159469839 ~ ~-0.1913417161825448858642299920152 /tp @e[type=area_effect_cloud,name=ACV_Laser,rym=-100,ry=-78,rxm=0,rx=0] ~0.5 ~ ~0 /tp @e[type=area_effect_cloud,name=ACV_Laser,rym=-77,ry=-56,rxm=0,rx=0] ~0.46193976625564337806409159469839 ~ ~0.1913417161825448858642299920152 /tp @e[type=area_effect_cloud,name=ACV_Laser,rym=-55,ry=-33,rxm=0,rx=0] ~0.35355339059327376220042218105242 ~ ~0.35355339059327376220042218105242 /tp @e[type=area_effect_cloud,name=ACV_Laser,rym=-32,ry=-11,rxm=0,rx=0] ~0.1913417161825448858642299920152 ~ ~0.46193976625564337806409159469839 /tp @e[type=area_effect_cloud,name=ACV_Laser,rym=-10,ry=11,rxm=0,rx=0] ~0 ~ ~0.5 /tp @e[type=area_effect_cloud,name=ACV_Laser,rym=12,ry=33,rxm=0,rx=0] ~-0.1913417161825448858642299920152 ~ ~0.46193976625564337806409159469839 /tp @e[type=area_effect_cloud,name=ACV_Laser,rym=34,ry=56,rxm=0,rx=0] ~-0.35355339059327376220042218105242 ~ ~0.35355339059327376220042218105242 /tp @e[type=area_effect_cloud,name=ACV_Laser,rym=57,ry=78,rxm=0,rx=0] ~-0.46193976625564337806409159469839 ~ ~0.1913417161825448858642299920152 /tp @e[type=area_effect_cloud,name=ACV_Laser,rym=79,ry=101,rxm=0,rx=0] ~-0.5 ~ ~0 /tp @e[type=area_effect_cloud,name=ACV_Laser,rym=102,ry=123,rxm=0,rx=0] ~-0.46193976625564337806409159469839 ~ ~-0.1913417161825448858642299920152 /tp @e[type=area_effect_cloud,name=ACV_Laser,rym=124,ry=146,rxm=0,rx=0] ~-0.35355339059327376220042218105242 ~ ~-0.35355339059327376220042218105242 /tp @e[type=area_effect_cloud,name=ACV_Laser,rym=147,ry=168,rxm=0,rx=0] ~-0.1913417161825448858642299920152 ~ ~-0.46193976625564337806409159469839 /tp @e[type=area_effect_cloud,name=ACV_Laser,rxm=1,rx=90] ~ ~-0.5 ~ /tp @e[type=area_effect_cloud,name=ACV_Laser,rxm=-90,rx=-1] ~ ~0.5 ~ /execute @e[type=armor_stand,name=ACV_Cube,tag=!ACV_Redirecting] ~ ~1.5 ~ kill @e[type=area_effect_cloud,name=ACV_Laser,dy=0] /execute @e[type=armor_stand,name=ACV_Cube,tag=ACV_Redirecting] ~ ~1.5 ~ scoreboard players tag @e[type=area_effect_cloud,name=ACV_Laser,tag=!ACV_InCube,dy=0] add ACV_EnteringCube /execute @e[type=armor_stand,name=ACV_Cube,tag=ACV_Redirecting] ~ ~1.5 ~ tp @e[type=area_effect_cloud,name=ACV_Laser,tag=ACV_EnteringCube,dy=0] @e[type=armor_stand,name=ACV_Cube,r=2,c=1] /execute @e[type=armor_stand,name=ACV_Cube,tag=ACV_Redirecting] ~ ~ ~ tp @e[type=area_effect_cloud,name=ACV_Laser,tag=ACV_EnteringCube,dy=0] ~ ~1.7 ~ /execute @e[type=area_effect_cloud,name=ACV_Laser] ~ ~ ~ detect ~ ~ ~ air -1 scoreboard players tag @e[type=area_effect_cloud,name=ACV_Laser,r=1,c=1] add ACV_InAir /execute @e[type=area_effect_cloud,name=ACV_Laser] ~ ~ ~ detect ~ ~ ~ piston_extension -1 scoreboard players tag @e[type=area_effect_cloud,name=ACV_Laser,r=1,c=1] add ACV_InAir /execute @e[type=area_effect_cloud,name=ACV_Laser] ~ ~ ~ detect ~ ~ ~ carpet -1 scoreboard players tag @e[type=area_effect_cloud,name=ACV_Laser,r=1,c=1] add ACV_InAir /execute @e[type=area_effect_cloud,name=ACV_Laser] ~ ~ ~ detect ~ ~ ~ glass -1 scoreboard players tag @e[type=area_effect_cloud,name=ACV_Laser,r=1,c=1] add ACV_InAir /execute @e[type=area_effect_cloud,name=ACV_Laser] ~ ~ ~ detect ~ ~ ~ stained_glass -1 scoreboard players tag @e[type=area_effect_cloud,name=ACV_Laser,r=1,c=1] add ACV_InAir /execute @e[type=area_effect_cloud,name=ACV_Laser] ~ ~ ~ detect ~ ~ ~ glass_pane -1 scoreboard players tag @e[type=area_effect_cloud,name=ACV_Laser,r=1,c=1] add ACV_InAir /execute @e[type=area_effect_cloud,name=ACV_Laser] ~ ~ ~ detect ~ ~ ~ stained_glass_pane -1 scoreboard players tag @e[type=area_effect_cloud,name=ACV_Laser,r=1,c=1] add ACV_InAir /execute @e[type=area_effect_cloud,name=ACV_Laser] ~ ~ ~ detect ~ ~ ~ iron_bars -1 scoreboard players tag @e[type=area_effect_cloud,name=ACV_Laser,r=1,c=1] add ACV_InAir /kill @e[type=area_effect_cloud,name=ACV_Laser,tag=!ACV_InAir] }
{-# OPTIONS --safe #-} module Cubical.Data.FinSet.Properties where open import Cubical.Foundations.Prelude open import Cubical.Foundations.HLevels open import Cubical.Foundations.Function open import Cubical.Foundations.Structure open import Cubical.Foundations.Isomorphism open import Cubical.Foundations.Univalence open import Cubical.Foundations.Equiv renaming (_∙ₑ_ to _⋆_) open import Cubical.HITs.PropositionalTruncation as Prop open import Cubical.Data.Nat open import Cubical.Data.Unit open import Cubical.Data.Bool open import Cubical.Data.Empty as Empty open import Cubical.Data.Sigma open import Cubical.Data.Fin.Base renaming (Fin to Finℕ) open import Cubical.Data.SumFin open import Cubical.Data.FinSet.Base open import Cubical.Relation.Nullary open import Cubical.Relation.Nullary.DecidableEq open import Cubical.Relation.Nullary.HLevels private variable ℓ ℓ' ℓ'' : Level A : Type ℓ B : Type ℓ' -- operators to more conveniently compose equivalences module _ {A : Type ℓ}{B : Type ℓ'}{C : Type ℓ''} where infixr 30 _⋆̂_ _⋆̂_ : ∥ A ≃ B ∥ → ∥ B ≃ C ∥ → ∥ A ≃ C ∥ _⋆̂_ = Prop.map2 (_⋆_) module _ {A : Type ℓ}{B : Type ℓ'} where ∣invEquiv∣ : ∥ A ≃ B ∥ → ∥ B ≃ A ∥ ∣invEquiv∣ = Prop.map invEquiv -- useful implications EquivPresIsFinSet : A ≃ B → isFinSet A → isFinSet B EquivPresIsFinSet e (_ , p) = _ , ∣ invEquiv e ∣ ⋆̂ p isFinSetFin : {n : ℕ} → isFinSet (Fin n) isFinSetFin = _ , ∣ idEquiv _ ∣ isFinSetUnit : isFinSet Unit isFinSetUnit = 1 , ∣ invEquiv Fin1≃Unit ∣ isFinSetBool : isFinSet Bool isFinSetBool = 2 , ∣ invEquiv SumFin2≃Bool ∣ isFinSet→Discrete : isFinSet A → Discrete A isFinSet→Discrete h = Prop.rec isPropDiscrete (λ p → EquivPresDiscrete (invEquiv p) discreteFin) (h .snd) isContr→isFinSet : isContr A → isFinSet A isContr→isFinSet h = 1 , ∣ isContr→≃Unit* h ⋆ invEquiv Unit≃Unit* ⋆ invEquiv Fin1≃Unit ∣ isDecProp→isFinSet : isProp A → Dec A → isFinSet A isDecProp→isFinSet h (yes p) = isContr→isFinSet (inhProp→isContr p h) isDecProp→isFinSet h (no ¬p) = 0 , ∣ uninhabEquiv ¬p (idfun _) ∣ isDec→isFinSet∥∥ : Dec A → isFinSet ∥ A ∥ isDec→isFinSet∥∥ dec = isDecProp→isFinSet isPropPropTrunc (Dec∥∥ dec) isFinSet→Dec∥∥ : isFinSet A → Dec ∥ A ∥ isFinSet→Dec∥∥ h = Prop.rec (isPropDec isPropPropTrunc) (λ p → EquivPresDec (propTrunc≃ (invEquiv p)) (Dec∥Fin∥ _)) (h .snd) isFinProp→Dec : isFinSet A → isProp A → Dec A isFinProp→Dec p h = subst Dec (propTruncIdempotent h) (isFinSet→Dec∥∥ p) PeirceLaw∥∥ : isFinSet A → NonEmpty ∥ A ∥ → ∥ A ∥ PeirceLaw∥∥ p = Dec→Stable (isFinSet→Dec∥∥ p) PeirceLaw : isFinSet A → NonEmpty A → ∥ A ∥ PeirceLaw p q = PeirceLaw∥∥ p (λ f → q (λ x → f ∣ x ∣)) -- transprot family towards Fin transpFamily : {A : Type ℓ}{B : A → Type ℓ'} → ((n , e) : isFinOrd A) → (x : A) → B x ≃ B (invEq e (e .fst x)) transpFamily {B = B} (n , e) x = pathToEquiv (λ i → B (retEq e x (~ i)))
module Idris.Desugar import Core.Binary import Core.Context import Core.Core import Core.Env import Core.Metadata import Core.Options import Core.TT import Core.Unify import Data.StringMap import Data.ANameMap import Idris.DocString import Idris.Syntax import Idris.Elab.Implementation import Idris.Elab.Interface import Parser.Lexer.Source import TTImp.BindImplicits import TTImp.Parser import TTImp.TTImp import TTImp.Utils import Utils.Shunting import Control.Monad.State import Data.List -- Convert high level Idris declarations (PDecl from Idris.Syntax) into -- TTImp, recording any high level syntax info on the way (e.g. infix -- operators) -- Desugaring from high level Idris syntax to TTImp involves: -- * Shunting infix operators into function applications according to precedence -- * Replacing 'do' notating with applications of (>>=) -- * Replacing pattern matching binds with 'case' -- * Changing tuples to 'Pair/MkPair' -- * List notation -- * Replacing !-notation -- * Dependent pair notation -- * Idiom brackets %default covering public export data Side = LHS | AnyExpr ifThenElse : Bool -> Lazy a -> Lazy a -> a ifThenElse True t e = t ifThenElse False t e = e export extendSyn : {auto s : Ref Syn SyntaxInfo} -> SyntaxInfo -> Core () extendSyn newsyn = do syn <- get Syn put Syn (record { infixes $= mergeLeft (infixes newsyn), prefixes $= mergeLeft (prefixes newsyn), ifaces $= merge (ifaces newsyn), docstrings $= merge (docstrings newsyn), bracketholes $= ((bracketholes newsyn) ++) } syn) mkPrec : Fixity -> Nat -> OpPrec mkPrec InfixL p = AssocL p mkPrec InfixR p = AssocR p mkPrec Infix p = NonAssoc p mkPrec Prefix p = Prefix p toTokList : {auto s : Ref Syn SyntaxInfo} -> PTerm -> Core (List (Tok OpStr PTerm)) toTokList (POp fc opn l r) = do syn <- get Syn let op = nameRoot opn case lookup op (infixes syn) of Nothing => if any isOpChar (unpack op) then throw (GenericMsg fc $ "Unknown operator '" ++ op ++ "'") else do rtoks <- toTokList r pure (Expr l :: Op fc opn backtickPrec :: rtoks) Just (Prefix, _) => throw (GenericMsg fc $ "'" ++ op ++ "' is a prefix operator") Just (fix, prec) => do rtoks <- toTokList r pure (Expr l :: Op fc opn (mkPrec fix prec) :: rtoks) where backtickPrec : OpPrec backtickPrec = NonAssoc 1 toTokList (PPrefixOp fc opn arg) = do syn <- get Syn let op = nameRoot opn case lookup op (prefixes syn) of Nothing => throw (GenericMsg fc $ "'" ++ op ++ "' is not a prefix operator") Just prec => do rtoks <- toTokList arg pure (Op fc opn (Prefix prec) :: rtoks) toTokList t = pure [Expr t] record BangData where constructor MkBangData nextName : Int bangNames : List (Name, FC, RawImp) initBangs : BangData initBangs = MkBangData 0 [] bindBangs : List (Name, FC, RawImp) -> RawImp -> RawImp bindBangs [] tm = tm bindBangs ((n, fc, btm) :: bs) tm = bindBangs bs $ IApp fc (IApp fc (IVar fc (UN ">>=")) btm) (ILam fc top Explicit (Just n) (Implicit fc False) tm) idiomise : FC -> RawImp -> RawImp idiomise fc (IApp afc f a) = IApp fc (IApp fc (IVar fc (UN "<*>")) (idiomise afc f)) a idiomise fc fn = IApp fc (IVar fc (UN "pure")) fn pairname : Name pairname = NS builtinNS (UN "Pair") mkpairname : Name mkpairname = NS builtinNS (UN "MkPair") dpairname : Name dpairname = NS dpairNS (UN "DPair") mkdpairname : Name mkdpairname = NS dpairNS (UN "MkDPair") data Bang : Type where mutual desugarB : {auto s : Ref Syn SyntaxInfo} -> {auto b : Ref Bang BangData} -> {auto c : Ref Ctxt Defs} -> {auto m : Ref MD Metadata} -> {auto u : Ref UST UState} -> Side -> List Name -> PTerm -> Core RawImp desugarB side ps (PRef fc x) = pure $ IVar fc x desugarB side ps (PPi fc rig p mn argTy retTy) = let ps' = maybe ps (:: ps) mn in pure $ IPi fc rig !(traverse (desugar side ps') p) mn !(desugarB side ps argTy) !(desugarB side ps' retTy) desugarB side ps (PLam fc rig p (PRef _ n@(UN _)) argTy scope) = pure $ ILam fc rig !(traverse (desugar side ps) p) (Just n) !(desugarB side ps argTy) !(desugar side (n :: ps) scope) desugarB side ps (PLam fc rig p (PRef _ n@(MN _ _)) argTy scope) = pure $ ILam fc rig !(traverse (desugar side ps) p) (Just n) !(desugarB side ps argTy) !(desugar side (n :: ps) scope) desugarB side ps (PLam fc rig p (PImplicit _) argTy scope) = pure $ ILam fc rig !(traverse (desugar side ps) p) Nothing !(desugarB side ps argTy) !(desugar side ps scope) desugarB side ps (PLam fc rig p pat argTy scope) = pure $ ILam fc rig !(traverse (desugar side ps) p) (Just (MN "lamc" 0)) !(desugarB side ps argTy) $ ICase fc (IVar fc (MN "lamc" 0)) (Implicit fc False) [!(desugarClause ps True (MkPatClause fc pat scope []))] desugarB side ps (PLet fc rig (PRef _ n) nTy nVal scope []) = pure $ ILet fc rig n !(desugarB side ps nTy) !(desugarB side ps nVal) !(desugar side (n :: ps) scope) desugarB side ps (PLet fc rig pat nTy nVal scope alts) = pure $ ICase fc !(desugarB side ps nVal) !(desugarB side ps nTy) !(traverse (desugarClause ps True) (MkPatClause fc pat scope [] :: alts)) desugarB side ps (PCase fc x xs) = pure $ ICase fc !(desugarB side ps x) (Implicit fc False) !(traverse (desugarClause ps True) xs) desugarB side ps (PLocal fc xs scope) = let ps' = definedIn xs ++ ps in pure $ ILocal fc (concat !(traverse (desugarDecl ps') xs)) !(desugar side ps' scope) desugarB side ps (PApp pfc (PUpdate fc fs) rec) = pure $ IUpdate pfc !(traverse (desugarUpdate side ps) fs) !(desugarB side ps rec) desugarB side ps (PUpdate fc fs) = desugarB side ps (PLam fc top Explicit (PRef fc (MN "rec" 0)) (PImplicit fc) (PApp fc (PUpdate fc fs) (PRef fc (MN "rec" 0)))) desugarB side ps (PApp fc x y) = pure $ IApp fc !(desugarB side ps x) !(desugarB side ps y) desugarB side ps (PWithApp fc x y) = pure $ IWithApp fc !(desugarB side ps x) !(desugarB side ps y) desugarB side ps (PImplicitApp fc x argn y) = pure $ IImplicitApp fc !(desugarB side ps x) argn !(desugarB side ps y) desugarB side ps (PDelayed fc r ty) = pure $ IDelayed fc r !(desugarB side ps ty) desugarB side ps (PDelay fc tm) = pure $ IDelay fc !(desugarB side ps tm) desugarB side ps (PForce fc tm) = pure $ IForce fc !(desugarB side ps tm) desugarB side ps (PEq fc l r) = do l' <- desugarB side ps l r' <- desugarB side ps r pure $ IAlternative fc FirstSuccess [apply (IVar fc (UN "===")) [l', r'], apply (IVar fc (UN "~=~")) [l', r']] desugarB side ps (PBracketed fc e) = desugarB side ps e desugarB side ps (POp fc op l r) = do ts <- toTokList (POp fc op l r) desugarTree side ps !(parseOps ts) desugarB side ps (PPrefixOp fc op arg) = do ts <- toTokList (PPrefixOp fc op arg) desugarTree side ps !(parseOps ts) desugarB side ps (PSectionL fc op arg) = do syn <- get Syn -- It might actually be a prefix argument rather than a section -- so check that first, otherwise desugar as a lambda case lookup (nameRoot op) (prefixes syn) of Nothing => desugarB side ps (PLam fc top Explicit (PRef fc (MN "arg" 0)) (PImplicit fc) (POp fc op (PRef fc (MN "arg" 0)) arg)) Just prec => desugarB side ps (PPrefixOp fc op arg) desugarB side ps (PSectionR fc arg op) = desugarB side ps (PLam fc top Explicit (PRef fc (MN "arg" 0)) (PImplicit fc) (POp fc op arg (PRef fc (MN "arg" 0)))) desugarB side ps (PSearch fc depth) = pure $ ISearch fc depth desugarB side ps (PPrimVal fc (BI x)) = case !fromIntegerName of Nothing => pure $ IAlternative fc (UniqueDefault (IPrimVal fc (BI x))) [IPrimVal fc (BI x), IPrimVal fc (I (fromInteger x))] Just fi => pure $ IApp fc (IVar fc fi) (IPrimVal fc (BI x)) desugarB side ps (PPrimVal fc (Str x)) = case !fromStringName of Nothing => pure $ IPrimVal fc (Str x) Just f => pure $ IApp fc (IVar fc f) (IPrimVal fc (Str x)) desugarB side ps (PPrimVal fc (Ch x)) = case !fromCharName of Nothing => pure $ IPrimVal fc (Ch x) Just f => pure $ IApp fc (IVar fc f) (IPrimVal fc (Ch x)) desugarB side ps (PPrimVal fc x) = pure $ IPrimVal fc x desugarB side ps (PQuote fc tm) = pure $ IQuote fc !(desugarB side ps tm) desugarB side ps (PQuoteName fc n) = pure $ IQuoteName fc n desugarB side ps (PQuoteDecl fc x) = do xs <- traverse (desugarDecl ps) x pure $ IQuoteDecl fc (concat xs) desugarB side ps (PUnquote fc tm) = pure $ IUnquote fc !(desugarB side ps tm) desugarB side ps (PRunElab fc tm) = pure $ IRunElab fc !(desugarB side ps tm) desugarB side ps (PHole fc br holename) = do when br $ do syn <- get Syn put Syn (record { bracketholes $= ((UN holename) ::) } syn) pure $ IHole fc holename desugarB side ps (PType fc) = pure $ IType fc desugarB side ps (PAs fc vname pattern) = pure $ IAs fc UseRight vname !(desugarB side ps pattern) desugarB side ps (PDotted fc x) = pure $ IMustUnify fc UserDotted !(desugarB side ps x) desugarB side ps (PImplicit fc) = pure $ Implicit fc True desugarB side ps (PInfer fc) = pure $ Implicit fc False desugarB side ps (PDoBlock fc ns block) = expandDo side ps fc ns block desugarB side ps (PBang fc term) = do itm <- desugarB side ps term bs <- get Bang let bn = MN "bind" (nextName bs) put Bang (record { nextName $= (+1), bangNames $= ((bn, fc, itm) ::) } bs) pure (IVar fc bn) desugarB side ps (PIdiom fc term) = do itm <- desugarB side ps term pure (idiomise fc itm) desugarB side ps (PList fc args) = expandList side ps fc args desugarB side ps (PPair fc l r) = do l' <- desugarB side ps l r' <- desugarB side ps r let pval = apply (IVar fc mkpairname) [l', r'] pure $ IAlternative fc (UniqueDefault pval) [apply (IVar fc pairname) [l', r'], pval] desugarB side ps (PDPair fc (PRef nfc (UN n)) (PImplicit _) r) = do r' <- desugarB side ps r let pval = apply (IVar fc mkdpairname) [IVar nfc (UN n), r'] pure $ IAlternative fc (UniqueDefault pval) [apply (IVar fc dpairname) [Implicit nfc False, ILam nfc top Explicit (Just (UN n)) (Implicit nfc False) r'], pval] desugarB side ps (PDPair fc (PRef nfc (UN n)) ty r) = do ty' <- desugarB side ps ty r' <- desugarB side ps r pure $ apply (IVar fc dpairname) [ty', ILam nfc top Explicit (Just (UN n)) ty' r'] desugarB side ps (PDPair fc l (PImplicit _) r) = do l' <- desugarB side ps l r' <- desugarB side ps r pure $ apply (IVar fc mkdpairname) [l', r'] desugarB side ps (PDPair fc l ty r) = throw (GenericMsg fc "Invalid dependent pair type") desugarB side ps (PUnit fc) = pure $ IAlternative fc (UniqueDefault (IVar fc (UN "MkUnit"))) [IVar fc (UN "Unit"), IVar fc (UN "MkUnit")] desugarB side ps (PIfThenElse fc x t e) = pure $ ICase fc !(desugarB side ps x) (IVar fc (UN "Bool")) [PatClause fc (IVar fc (UN "True")) !(desugar side ps t), PatClause fc (IVar fc (UN "False")) !(desugar side ps e)] desugarB side ps (PComprehension fc ret conds) = desugarB side ps (PDoBlock fc Nothing (map guard conds ++ [toPure ret])) where guard : PDo -> PDo guard (DoExp fc tm) = DoExp fc (PApp fc (PRef fc (UN "guard")) tm) guard d = d toPure : PTerm -> PDo toPure tm = DoExp fc (PApp fc (PRef fc (UN "pure")) tm) desugarB side ps (PRewrite fc rule tm) = pure $ IRewrite fc !(desugarB side ps rule) !(desugarB side ps tm) desugarB side ps (PRange fc start next end) = case next of Nothing => desugarB side ps (PApp fc (PApp fc (PRef fc (UN "rangeFromTo")) start) end) Just n => desugarB side ps (PApp fc (PApp fc (PApp fc (PRef fc (UN "rangeFromThenTo")) start) n) end) desugarB side ps (PRangeStream fc start next) = case next of Nothing => desugarB side ps (PApp fc (PRef fc (UN "rangeFrom")) start) Just n => desugarB side ps (PApp fc (PApp fc (PRef fc (UN "rangeFromThen")) start) n) desugarB side ps (PUnifyLog fc lvl tm) = pure $ IUnifyLog fc lvl !(desugarB side ps tm) desugarB side ps (PPostfixProjs fc rec projs) = do let isPRef = \case PRef _ _ => True _ => False defs <- get Ctxt when (not (isExtension PostfixProjections defs) && not (all isPRef projs)) $ throw (GenericMsg fc "complex postfix projections require %language PostfixProjections") desugarB side ps $ foldl (\x, proj => PApp fc proj x) rec projs desugarB side ps (PPostfixProjsSection fc projs args) = do let isPRef = \case PRef _ _ => True _ => False defs <- get Ctxt when (not (isExtension PostfixProjections defs)) $ do when (not (all isPRef projs)) $ throw (GenericMsg fc "complex postfix projections require %language PostfixProjections") case args of [] => pure () _ => throw $ GenericMsg fc "postfix projection sections require %language PostfixProjections" desugarB side ps $ PLam fc top Explicit (PRef fc (MN "paRoot" 0)) (PImplicit fc) $ foldl (\r, arg => PApp fc r arg) (foldl (\r, proj => PApp fc proj r) (PRef fc (MN "paRoot" 0)) projs) args desugarB side ps (PWithUnambigNames fc ns rhs) = IWithUnambigNames fc ns <$> desugarB side ps rhs desugarUpdate : {auto s : Ref Syn SyntaxInfo} -> {auto b : Ref Bang BangData} -> {auto c : Ref Ctxt Defs} -> {auto u : Ref UST UState} -> {auto m : Ref MD Metadata} -> Side -> List Name -> PFieldUpdate -> Core IFieldUpdate desugarUpdate side ps (PSetField p v) = pure (ISetField p !(desugarB side ps v)) desugarUpdate side ps (PSetFieldApp p v) = pure (ISetFieldApp p !(desugarB side ps v)) expandList : {auto s : Ref Syn SyntaxInfo} -> {auto b : Ref Bang BangData} -> {auto c : Ref Ctxt Defs} -> {auto u : Ref UST UState} -> {auto m : Ref MD Metadata} -> Side -> List Name -> FC -> List PTerm -> Core RawImp expandList side ps fc [] = pure (IVar fc (UN "Nil")) expandList side ps fc (x :: xs) = pure $ apply (IVar fc (UN "::")) [!(desugarB side ps x), !(expandList side ps fc xs)] addNS : Maybe Namespace -> Name -> Name addNS (Just ns) n@(NS _ _) = n addNS (Just ns) n = NS ns n addNS _ n = n expandDo : {auto s : Ref Syn SyntaxInfo} -> {auto c : Ref Ctxt Defs} -> {auto u : Ref UST UState} -> {auto m : Ref MD Metadata} -> Side -> List Name -> FC -> Maybe Namespace -> List PDo -> Core RawImp expandDo side ps fc ns [] = throw (GenericMsg fc "Do block cannot be empty") expandDo side ps _ _ [DoExp fc tm] = desugar side ps tm expandDo side ps fc ns [e] = throw (GenericMsg (getLoc e) "Last statement in do block must be an expression") expandDo side ps topfc ns (DoExp fc tm :: rest) = do tm' <- desugar side ps tm rest' <- expandDo side ps topfc ns rest -- A free standing 'case' block must return () let ty = case tm' of ICase _ _ _ _ => IVar fc (UN "Unit") _ => Implicit fc False gam <- get Ctxt pure $ IApp fc (IApp fc (IVar fc (addNS ns (UN ">>="))) tm') (ILam fc top Explicit Nothing ty rest') expandDo side ps topfc ns (DoBind fc n tm :: rest) = do tm' <- desugar side ps tm rest' <- expandDo side ps topfc ns rest pure $ IApp fc (IApp fc (IVar fc (addNS ns (UN ">>="))) tm') (ILam fc top Explicit (Just n) (Implicit fc False) rest') expandDo side ps topfc ns (DoBindPat fc pat exp alts :: rest) = do pat' <- desugar LHS ps pat (newps, bpat) <- bindNames False pat' exp' <- desugar side ps exp alts' <- traverse (desugarClause ps True) alts let ps' = newps ++ ps rest' <- expandDo side ps' topfc ns rest pure $ IApp fc (IApp fc (IVar fc (addNS ns (UN ">>="))) exp') (ILam fc top Explicit (Just (MN "_" 0)) (Implicit fc False) (ICase fc (IVar fc (MN "_" 0)) (Implicit fc False) (PatClause fc bpat rest' :: alts'))) expandDo side ps topfc ns (DoLet fc n rig ty tm :: rest) = do b <- newRef Bang initBangs tm' <- desugarB side ps tm ty' <- desugar side ps ty rest' <- expandDo side ps topfc ns rest let bind = ILet fc rig n ty' tm' rest' bd <- get Bang pure $ bindBangs (bangNames bd) bind expandDo side ps topfc ns (DoLetPat fc pat ty tm alts :: rest) = do b <- newRef Bang initBangs pat' <- desugar LHS ps pat ty' <- desugar side ps ty (newps, bpat) <- bindNames False pat' tm' <- desugarB side ps tm alts' <- traverse (desugarClause ps True) alts let ps' = newps ++ ps rest' <- expandDo side ps' topfc ns rest bd <- get Bang pure $ bindBangs (bangNames bd) $ ICase fc tm' ty' (PatClause fc bpat rest' :: alts') expandDo side ps topfc ns (DoLetLocal fc decls :: rest) = do rest' <- expandDo side ps topfc ns rest decls' <- traverse (desugarDecl ps) decls pure $ ILocal fc (concat decls') rest' expandDo side ps topfc ns (DoRewrite fc rule :: rest) = do rest' <- expandDo side ps topfc ns rest rule' <- desugar side ps rule pure $ IRewrite fc rule' rest' desugarTree : {auto s : Ref Syn SyntaxInfo} -> {auto b : Ref Bang BangData} -> {auto c : Ref Ctxt Defs} -> {auto u : Ref UST UState} -> {auto m : Ref MD Metadata} -> Side -> List Name -> Tree OpStr PTerm -> Core RawImp desugarTree side ps (Infix loc (UN "=") l r) -- special case since '=' is special syntax = do l' <- desugarTree side ps l r' <- desugarTree side ps r pure (IAlternative loc FirstSuccess [apply (IVar loc (UN "===")) [l', r'], apply (IVar loc (UN "~=~")) [l', r']]) desugarTree side ps (Infix loc (UN "$") l r) -- special case since '$' is special syntax = do l' <- desugarTree side ps l r' <- desugarTree side ps r pure (IApp loc l' r') desugarTree side ps (Infix loc op l r) = do l' <- desugarTree side ps l r' <- desugarTree side ps r pure (IApp loc (IApp loc (IVar loc op) l') r') -- negation is a special case, since we can't have an operator with -- two meanings otherwise desugarTree side ps (Pre loc (UN "-") arg) = do arg' <- desugarTree side ps arg pure (IApp loc (IVar loc (UN "negate")) arg') desugarTree side ps (Pre loc op arg) = do arg' <- desugarTree side ps arg pure (IApp loc (IVar loc op) arg') desugarTree side ps (Leaf t) = desugarB side ps t desugarType : {auto s : Ref Syn SyntaxInfo} -> {auto c : Ref Ctxt Defs} -> {auto u : Ref UST UState} -> {auto m : Ref MD Metadata} -> List Name -> PTypeDecl -> Core ImpTy desugarType ps (MkPTy fc n d ty) = do addDocString n d syn <- get Syn pure $ MkImpTy fc n !(bindTypeNames (usingImpl syn) ps !(desugar AnyExpr ps ty)) desugarClause : {auto s : Ref Syn SyntaxInfo} -> {auto c : Ref Ctxt Defs} -> {auto u : Ref UST UState} -> {auto m : Ref MD Metadata} -> List Name -> Bool -> PClause -> Core ImpClause desugarClause ps arg (MkPatClause fc lhs rhs wheres) = do ws <- traverse (desugarDecl ps) wheres (bound, blhs) <- bindNames arg !(desugar LHS ps lhs) rhs' <- desugar AnyExpr (bound ++ ps) rhs pure $ PatClause fc blhs (case ws of [] => rhs' _ => ILocal fc (concat ws) rhs') desugarClause ps arg (MkWithClause fc lhs wval flags cs) = do cs' <- traverse (desugarClause ps arg) cs (bound, blhs) <- bindNames arg !(desugar LHS ps lhs) wval' <- desugar AnyExpr (bound ++ ps) wval pure $ WithClause fc blhs wval' flags cs' desugarClause ps arg (MkImpossible fc lhs) = do dlhs <- desugar LHS ps lhs pure $ ImpossibleClause fc (snd !(bindNames arg dlhs)) desugarData : {auto s : Ref Syn SyntaxInfo} -> {auto c : Ref Ctxt Defs} -> {auto u : Ref UST UState} -> {auto m : Ref MD Metadata} -> List Name -> (doc : String) -> PDataDecl -> Core ImpData desugarData ps doc (MkPData fc n tycon opts datacons) = do addDocString n doc syn <- get Syn pure $ MkImpData fc n !(bindTypeNames (usingImpl syn) ps !(desugar AnyExpr ps tycon)) opts !(traverse (desugarType ps) datacons) desugarData ps doc (MkPLater fc n tycon) = do addDocString n doc syn <- get Syn pure $ MkImpLater fc n !(bindTypeNames (usingImpl syn) ps !(desugar AnyExpr ps tycon)) desugarField : {auto s : Ref Syn SyntaxInfo} -> {auto c : Ref Ctxt Defs} -> {auto u : Ref UST UState} -> {auto m : Ref MD Metadata} -> List Name -> Namespace -> PField -> Core IField desugarField ps ns (MkField fc doc rig p n ty) = do addDocStringNS ns n doc syn <- get Syn pure (MkIField fc rig !(traverse (desugar AnyExpr ps) p ) n !(bindTypeNames (usingImpl syn) ps !(desugar AnyExpr ps ty))) -- Get the declaration to process on each pass of a mutual block -- Essentially: types on the first pass -- i.e. type constructors of data declarations -- function types -- interfaces (in full, since it includes function types) -- records (just the generated type constructor) -- implementation headers (i.e. note their existence, but not the bodies) -- Everything else on the second pass getDecl : Pass -> PDecl -> Maybe PDecl getDecl p (PImplementation fc vis opts _ is cons n ps iname nusing ds) = Just (PImplementation fc vis opts p is cons n ps iname nusing ds) getDecl p (PNamespace fc ns ds) = Just (PNamespace fc ns (mapMaybe (getDecl p) ds)) getDecl AsType d@(PClaim _ _ _ _ _) = Just d getDecl AsType (PData fc doc vis (MkPData dfc tyn tyc _ _)) = Just (PData fc doc vis (MkPLater dfc tyn tyc)) getDecl AsType d@(PInterface _ _ _ _ _ _ _ _ _) = Just d getDecl AsType d@(PRecord fc doc vis n ps _ _) = Just (PData fc doc vis (MkPLater fc n (mkRecType ps))) where mkRecType : List (Name, RigCount, PiInfo PTerm, PTerm) -> PTerm mkRecType [] = PType fc mkRecType ((n, c, p, t) :: ts) = PPi fc c p (Just n) t (mkRecType ts) getDecl AsType d@(PFixity _ _ _ _) = Just d getDecl AsType d@(PDirective _ _) = Just d getDecl AsType d = Nothing getDecl AsDef (PClaim _ _ _ _ _) = Nothing getDecl AsDef d@(PData _ _ _ (MkPLater _ _ _)) = Just d getDecl AsDef (PInterface _ _ _ _ _ _ _ _ _) = Nothing getDecl AsDef d@(PRecord _ _ _ _ _ _ _) = Just d getDecl AsDef (PFixity _ _ _ _) = Nothing getDecl AsDef (PDirective _ _) = Nothing getDecl AsDef d = Just d getDecl p (PParameters fc ps pds) = Just (PParameters fc ps (mapMaybe (getDecl p) pds)) getDecl p (PUsing fc ps pds) = Just (PUsing fc ps (mapMaybe (getDecl p) pds)) getDecl Single d = Just d export desugarFnOpt : {auto s : Ref Syn SyntaxInfo} -> {auto c : Ref Ctxt Defs} -> {auto u : Ref UST UState} -> {auto m : Ref MD Metadata} -> List Name -> PFnOpt -> Core FnOpt desugarFnOpt ps (IFnOpt f) = pure f desugarFnOpt ps (PForeign tms) = do tms' <- traverse (desugar AnyExpr ps) tms pure (ForeignFn tms') -- Given a high level declaration, return a list of TTImp declarations -- which process it, and update any necessary state on the way. export desugarDecl : {auto s : Ref Syn SyntaxInfo} -> {auto c : Ref Ctxt Defs} -> {auto u : Ref UST UState} -> {auto m : Ref MD Metadata} -> List Name -> PDecl -> Core (List ImpDecl) desugarDecl ps (PClaim fc rig vis fnopts ty) = do opts <- traverse (desugarFnOpt ps) fnopts pure [IClaim fc rig vis opts !(desugarType ps ty)] where isTotalityOption : FnOpt -> Bool isTotalityOption (Totality _) = True isTotalityOption _ = False desugarDecl ps (PDef fc clauses) -- The clauses won't necessarily all be from the same function, so split -- after desugaring, by function name, using collectDefs from RawImp = do cs <- traverse (desugarClause ps False) clauses defs <- traverse toIDef cs pure (collectDefs defs) where getFn : RawImp -> Core Name getFn (IVar _ n) = pure n getFn (IApp _ f _) = getFn f getFn (IImplicitApp _ f _ _) = getFn f getFn tm = throw (InternalError (show tm ++ " is not a function application")) toIDef : ImpClause -> Core ImpDecl toIDef (PatClause fc lhs rhs) = pure $ IDef fc !(getFn lhs) [PatClause fc lhs rhs] toIDef (WithClause fc lhs rhs flags cs) = pure $ IDef fc !(getFn lhs) [WithClause fc lhs rhs flags cs] toIDef (ImpossibleClause fc lhs) = pure $ IDef fc !(getFn lhs) [ImpossibleClause fc lhs] desugarDecl ps (PData fc doc vis ddecl) = pure [IData fc vis !(desugarData ps doc ddecl)] desugarDecl ps (PParameters fc params pds) = do pds' <- traverse (desugarDecl (ps ++ map fst params)) pds params' <- traverse (\ ntm => do tm' <- desugar AnyExpr ps (snd ntm) pure (fst ntm, tm')) params -- Look for implicitly bindable names in the parameters let pnames = ifThenElse !isUnboundImplicits (concatMap (findBindableNames True (ps ++ map Builtin.fst params) []) (map Builtin.snd params')) [] let paramsb = map (\ ntm => (Builtin.fst ntm, doBind pnames (Builtin.snd ntm))) params' pure [IParameters fc paramsb (concat pds')] desugarDecl ps (PUsing fc uimpls uds) = do syn <- get Syn let oldu = usingImpl syn uimpls' <- traverse (\ ntm => do tm' <- desugar AnyExpr ps (snd ntm) btm <- bindTypeNames oldu ps tm' pure (fst ntm, btm)) uimpls put Syn (record { usingImpl = uimpls' ++ oldu } syn) uds' <- traverse (desugarDecl ps) uds syn <- get Syn put Syn (record { usingImpl = oldu } syn) pure (concat uds') desugarDecl ps (PReflect fc tm) = throw (GenericMsg fc "Reflection not implemented yet") -- pure [IReflect fc !(desugar AnyExpr ps tm)] desugarDecl ps (PInterface fc vis cons_in tn doc params det conname body) = do addDocString tn doc let cons = concatMap expandConstraint cons_in cons' <- traverse (\ ntm => do tm' <- desugar AnyExpr (ps ++ map fst params) (snd ntm) pure (fst ntm, tm')) cons params' <- traverse (\ ntm => do tm' <- desugar AnyExpr ps (snd ntm) pure (fst ntm, tm')) params -- Look for bindable names in all the constraints and parameters let mnames = map dropNS (definedIn body) let bnames = ifThenElse !isUnboundImplicits (concatMap (findBindableNames True (ps ++ mnames ++ map fst params) []) (map Builtin.snd cons') ++ concatMap (findBindableNames True (ps ++ mnames ++ map fst params) []) (map Builtin.snd params')) [] let paramsb = map (\ ntm => (Builtin.fst ntm, doBind bnames (Builtin.snd ntm))) params' let consb = map (\ ntm => (Builtin.fst ntm, doBind bnames (Builtin.snd ntm))) cons' body' <- traverse (desugarDecl (ps ++ mnames ++ map fst params)) body pure [IPragma (\nest, env => elabInterface fc vis env nest consb tn paramsb det conname (concat body'))] where -- Turns pairs in the constraints to individual constraints. This -- is a bit of a hack, but it's necessary to build parent constraint -- chasing functions correctly pairToCons : PTerm -> List PTerm pairToCons (PPair _ l r) = pairToCons l ++ pairToCons r pairToCons t = [t] expandConstraint : (Maybe Name, PTerm) -> List (Maybe Name, PTerm) expandConstraint (Just n, t) = [(Just n, t)] expandConstraint (Nothing, p) = map (\x => (Nothing, x)) (pairToCons p) desugarDecl ps (PImplementation fc vis fnopts pass is cons tn params impname nusing body) = do opts <- traverse (desugarFnOpt ps) fnopts is' <- traverse (\ (n,c,tm) => do tm' <- desugar AnyExpr ps tm pure (n, c, tm')) is let _ = the (List (Name, RigCount, RawImp)) is' cons' <- traverse (\ (n, tm) => do tm' <- desugar AnyExpr ps tm pure (n, tm')) cons let _ = the (List (Maybe Name, RawImp)) cons' params' <- traverse (desugar AnyExpr ps) params let _ = the (List RawImp) params' -- Look for bindable names in all the constraints and parameters let bnames = if !isUnboundImplicits then concatMap (findBindableNames True ps []) (map snd cons') ++ concatMap (findBindableNames True ps []) params' else [] let paramsb = map (doBind bnames) params' let isb = map (\ (n, r, tm) => (n, r, doBind bnames tm)) is' let _ = the (List (Name, RigCount, RawImp)) isb let consb = map (\(n, tm) => (n, doBind bnames tm)) cons' let _ = the (List (Maybe Name, RawImp)) consb body' <- maybe (pure Nothing) (\b => do b' <- traverse (desugarDecl ps) b pure (Just (concat b'))) body pure [IPragma (\nest, env => elabImplementation fc vis opts pass env nest isb consb tn paramsb impname nusing body')] desugarDecl ps (PRecord fc doc vis tn params conname_in fields) = do addDocString tn doc params' <- traverse (\ (n,c,p,tm) => do tm' <- desugar AnyExpr ps tm p' <- mapDesugarPiInfo ps p pure (n, c, p', tm')) params let _ = the (List (Name, RigCount, PiInfo RawImp, RawImp)) params' let fnames = map fname fields let _ = the (List Name) fnames -- Look for bindable names in the parameters let bnames = if !isUnboundImplicits then concatMap (findBindableNames True (ps ++ fnames ++ map fst params) []) (map (\(_,_,_,d) => d) params') else [] let _ = the (List (String, String)) bnames let paramsb = map (\ (n, c, p, tm) => (n, c, p, doBind bnames tm)) params' let _ = the (List (Name, RigCount, PiInfo RawImp, RawImp)) paramsb let recName = nameRoot tn fields' <- traverse (desugarField (ps ++ map fname fields ++ map fst params) (mkNamespace recName)) fields let _ = the (List IField) fields' let conname = maybe (mkConName tn) id conname_in let _ = the Name conname pure [IRecord fc (Just recName) vis (MkImpRecord fc tn paramsb conname fields')] where fname : PField -> Name fname (MkField _ _ _ _ n _) = n mkConName : Name -> Name mkConName (NS ns (UN n)) = NS ns (DN n (MN ("__mk" ++ n) 0)) mkConName n = DN (show n) (MN ("__mk" ++ show n) 0) mapDesugarPiInfo : List Name -> PiInfo PTerm -> Core (PiInfo RawImp) mapDesugarPiInfo ps Implicit = pure Implicit mapDesugarPiInfo ps Explicit = pure Explicit mapDesugarPiInfo ps AutoImplicit = pure AutoImplicit mapDesugarPiInfo ps (DefImplicit tm) = pure $ DefImplicit !(desugar AnyExpr ps tm) desugarDecl ps (PFixity fc Prefix prec (UN n)) = do syn <- get Syn put Syn (record { prefixes $= insert n prec } syn) pure [] desugarDecl ps (PFixity fc fix prec (UN n)) = do syn <- get Syn put Syn (record { infixes $= insert n (fix, prec) } syn) pure [] desugarDecl ps (PFixity fc _ _ _) = throw (GenericMsg fc "Fixity declarations must be for unqualified names") desugarDecl ps (PMutual fc ds) = do let mds = mapMaybe (getDecl AsType) ds ++ mapMaybe (getDecl AsDef) ds mds' <- traverse (desugarDecl ps) mds pure (concat mds') desugarDecl ps (PNamespace fc ns decls) = do ds <- traverse (desugarDecl ps) decls pure [INamespace fc ns (concat ds)] desugarDecl ps (PTransform fc n lhs rhs) = do (bound, blhs) <- bindNames False !(desugar LHS ps lhs) rhs' <- desugar AnyExpr (bound ++ ps) rhs pure [ITransform fc (UN n) blhs rhs'] desugarDecl ps (PRunElabDecl fc tm) = do tm' <- desugar AnyExpr ps tm pure [IRunElabDecl fc tm'] desugarDecl ps (PDirective fc d) = case d of Hide n => pure [IPragma (\nest, env => hide fc n)] Logging i => pure [ILog (topics i, verbosity i)] LazyOn a => pure [IPragma (\nest, env => lazyActive a)] UnboundImplicits a => do setUnboundImplicits a pure [IPragma (\nest, env => setUnboundImplicits a)] AmbigDepth n => pure [IPragma (\nest, env => setAmbigLimit n)] AutoImplicitDepth n => pure [IPragma (\nest, env => setAutoImplicitLimit n)] PairNames ty f s => pure [IPragma (\nest, env => setPair fc ty f s)] RewriteName eq rw => pure [IPragma (\nest, env => setRewrite fc eq rw)] PrimInteger n => pure [IPragma (\nest, env => setFromInteger n)] PrimString n => pure [IPragma (\nest, env => setFromString n)] PrimChar n => pure [IPragma (\nest, env => setFromChar n)] CGAction cg dir => pure [IPragma (\nest, env => addDirective cg dir)] Names n ns => pure [IPragma (\nest, env => addNameDirective fc n ns)] StartExpr tm => pure [IPragma (\nest, env => throw (InternalError "%start not implemented"))] -- TODO! Overloadable n => pure [IPragma (\nest, env => setNameFlag fc n Overloadable)] Extension e => pure [IPragma (\nest, env => setExtension e)] DefaultTotality tot => pure [IPragma (\_, _ => setDefaultTotalityOption tot)] export desugar : {auto s : Ref Syn SyntaxInfo} -> {auto c : Ref Ctxt Defs} -> {auto m : Ref MD Metadata} -> {auto u : Ref UST UState} -> Side -> List Name -> PTerm -> Core RawImp desugar s ps tm = do b <- newRef Bang initBangs tm' <- desugarB s ps tm bd <- get Bang pure $ bindBangs (bangNames bd) tm'
import numpy as np from scipy.ndimage.filters import gaussian_filter from starfish import ImageStack from starfish.core.spots.DecodeSpots.trace_builders import build_traces_nearest_neighbors from starfish.core.spots.FindSpots import BlobDetector from starfish.core.types import Axes def traversing_code() -> ImageStack: """this code walks in a sequential direction, and should only be detectable from some anchors""" img = np.zeros((3, 2, 20, 50, 50), dtype=np.float32) # code 1 img[0, 0, 5, 35, 35] = 10 img[1, 1, 5, 32, 32] = 10 img[2, 0, 5, 29, 29] = 10 # blur points gaussian_filter(img, (0, 0, 0.5, 1.5, 1.5), output=img) return ImageStack.from_numpy(img) def multiple_possible_neighbors() -> ImageStack: """this image is intended to be tested with anchor_round in {0, 1}, last round has more spots""" img = np.zeros((3, 2, 20, 50, 50), dtype=np.float32) # round 1 img[0, 0, 5, 20, 40] = 10 img[0, 0, 5, 40, 20] = 10 # round 2 img[1, 1, 5, 20, 40] = 10 img[1, 1, 5, 40, 20] = 10 # round 3 img[2, 0, 5, 20, 40] = 10 img[2, 0, 5, 35, 35] = 10 img[2, 0, 5, 40, 20] = 10 # blur points gaussian_filter(img, (0, 0, 0.5, 1.5, 1.5), output=img) return ImageStack.from_numpy(img) def jitter_code() -> ImageStack: """this code has some minor jitter <= 3px at the most distant point""" img = np.zeros((3, 2, 20, 50, 50), dtype=np.float32) # code 1 img[0, 0, 5, 35, 35] = 10 img[1, 1, 5, 34, 35] = 10 img[2, 0, 6, 35, 33] = 10 # blur points gaussian_filter(img, (0, 0, 0.5, 1.5, 1.5), output=img) return ImageStack.from_numpy(img) def two_perfect_codes() -> ImageStack: """this code has no jitter""" img = np.zeros((3, 2, 20, 50, 50), dtype=np.float32) # code 1 img[0, 0, 5, 20, 35] = 10 img[1, 1, 5, 20, 35] = 10 img[2, 0, 5, 20, 35] = 10 # code 1 img[0, 0, 5, 40, 45] = 10 img[1, 1, 5, 40, 45] = 10 img[2, 0, 5, 40, 45] = 10 # blur points gaussian_filter(img, (0, 0, 0.5, 1.5, 1.5), output=img) return ImageStack.from_numpy(img) def blob_detector(): return BlobDetector(min_sigma=1, max_sigma=4, num_sigma=30, threshold=.1) def test_local_search_blob_detector_two_codes(): stack = two_perfect_codes() bd = blob_detector() spot_results = bd.run(stack) intensity_table = build_traces_nearest_neighbors(spot_results=spot_results, anchor_round=1, search_radius=1) # Sort features to ensure test stability sorted_intensity_table = intensity_table.sortby(["x", "y", "z"]) assert sorted_intensity_table.shape == (2, 2, 3) assert np.all(sorted_intensity_table[1][Axes.X.value] == 45) assert np.all(sorted_intensity_table[1][Axes.Y.value] == 40) assert np.all(sorted_intensity_table[1][Axes.ZPLANE.value] == 5) def test_local_search_blob_detector_jitter_code(): stack = jitter_code() bd = blob_detector() spot_results = bd.run(stack) intensity_table = build_traces_nearest_neighbors(spot_results=spot_results, anchor_round=1, search_radius=3) assert intensity_table.shape == (1, 2, 3) f, c, r = np.where(~intensity_table.isnull()) assert np.all(f == np.array([0, 0, 0])) assert np.all(c == np.array([0, 0, 1])) assert np.all(r == np.array([0, 2, 1])) # test again with smaller search radius bd = BlobDetector(min_sigma=1, max_sigma=4, num_sigma=30, threshold=.1) per_tile_spot_results = bd.run(stack) intensity_table = build_traces_nearest_neighbors(spot_results=per_tile_spot_results, anchor_round=0, search_radius=1) assert intensity_table.shape == (1, 2, 3) f, c, r = np.where(~intensity_table.isnull()) assert np.all(f == 0) assert np.all(c == 0) assert np.all(r == 0) def test_local_search_blob_detector_traversing_code(): stack = traversing_code() bd = blob_detector() spot_results = bd.run(stack) intensity_table = build_traces_nearest_neighbors(spot_results=spot_results, anchor_round=0, search_radius=5) assert intensity_table.shape == (1, 2, 3) f, c, r = np.where(~intensity_table.isnull()) assert np.all(f == np.array([0, 0])) assert np.all(c == np.array([0, 1])) assert np.all(r == np.array([0, 1])) bd = blob_detector() spot_results = bd.run(stack) intensity_table = build_traces_nearest_neighbors(spot_results=spot_results, anchor_round=1, search_radius=5) f, c, r = np.where(~intensity_table.isnull()) assert np.all(f == np.array([0, 0, 0])) assert np.all(c == np.array([0, 0, 1])) assert np.all(r == np.array([0, 2, 1])) def test_local_search_blob_detector_multiple_neighbors(): stack = multiple_possible_neighbors() bd = blob_detector() spot_results = bd.run(stack) intensity_table = build_traces_nearest_neighbors(spot_results=spot_results, anchor_round=0, search_radius=4) # Sort features to ensure test stability sorted_intensity_table = intensity_table.sortby(["x", "y", "z"]) assert sorted_intensity_table.shape == (2, 2, 3) assert np.all(sorted_intensity_table[Axes.ZPLANE.value] == (5, 5)) assert np.all(sorted_intensity_table[Axes.Y.value] == (40, 20)) assert np.all(sorted_intensity_table[Axes.X.value] == (20, 40))
[STATEMENT] lemma (in module) span_induct[consumes 1, case_names base step, induct set: span]: assumes x: "x \<in> span S" and P: "subspace (Collect P)" and SP: "\<And>x. x \<in> S \<Longrightarrow> P x" shows "P x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. P x [PROOF STEP] using P SP span_subspace_induct x [PROOF STATE] proof (prove) using this: subspace (Collect P) ?x \<in> S \<Longrightarrow> P ?x \<lbrakk>?x \<in> span ?S; subspace ?P; \<And>x. x \<in> ?S \<Longrightarrow> x \<in> ?P\<rbrakk> \<Longrightarrow> ?x \<in> ?P x \<in> span S goal (1 subgoal): 1. P x [PROOF STEP] by fastforce
``` from scipy.integrate import ode from models import nmda, LR, LR_ICa, HH, na_current, cable #from sympy import plot_implicit, symbols, Eq #import sympy %pylab inline %load_ext autoreload %autoreload 2 ``` Populating the interactive namespace from numpy and matplotlib ``` def nmda_impulse(t, y, T=10, t_in=500, t_end=1500): rb = 0.005 dy = nmda(y) if t_in <= t < t_end: dy[0] += -rb * T * y[0] dy[1] += rb * T * y[0] - rb * y[1] * T dy[2] += rb * y[1] return dy def ica(O, V): Mg = 2.0 gNMDA = 1.0 VCa = 100.0 B = 1.0 / (1 + exp(-0.062 * V)*Mg/3.57) ICa = gNMDA * B * O * (V - VCa) return ICa def v_dendrite(t, y): dy = zeros_like(y) dy[:4] = nmda_impulse(t, y[:4]) ICa = ica(y[3], y[4]) dy[4] = -ICa - 0.3*y[4] return dy def nmda_LR(t, y): dy = zeros_like(y) dy[:4] = nmda_impulse(t, y[:4]) ICa = ica(y[3], y[4]) dy[4:] = LR(y[4:], ICa) #dy[6] = 0.007*(-0.0275* ICa - 0.02*y[6]) return dy def nmda_HH(t, y): dy = zeros_like(y) dy[:4] = HH(y[:4]) dy[4:] = nmda_impulse(t, y[4:]) Ica = ca_current(y[7], y[0]) dy[0] -= Ica return dy solver = ['dopri5', 'dop853', 'vode'] ``` # Hodgkin and Huxley ``` x, y = symbols('x y') gna = 120.0 gk = 36.0 gl = 0.3 Vna = 115.0 Vk = -12.0 Vl = 10.6 alpha_m = 0.1 * (25.0 - x) / (sympy.exp((25.0 - x) / 10.0) - 1.0) beta_m = 4.0 * sympy.exp(-x / 18.0) m_inf = alpha_m / (alpha_m + beta_m) INa = gna * m_inf**3 * (0.8 - y) * (x - Vna) IK = gk * y**4 * (x - Vk) IL = gl * (x - Vl) plot_implicit(Eq(INa + IK + IL, 0), (x, -20, 120), (y, 0, 1), adaptive=False); ``` ``` #r = ode( lambda t, y: HH(y) + array([5, 0, 0, 0]) if 5<= t < 7 else HH(y)).set_integrator(solver[0]) HH_input = lambda t, y: HH(y) + array([140, 0, 0, 0]) if 100<= t < 1100 else HH(y) #print(HH_input(array(1, 0, 0, 0),0)) y0 = array([0.0, 0.3176, 0.053, 0.596]) r = ode(HH_input).set_integrator(solver[0]) r.set_initial_value(y0, 0) t1 = 1200.0 dt = .01 v = [] time = [] while r.successful() and r.t < t1: r.integrate(r.t+dt) v.append(r.y[0]) time.append(r.t) figure(1) plot(time, v) xlabel('timepo (ms)') ylabel('V (mV)') grid(True) ``` #Rinzel and Lee $C_m \frac{dv}{dt}=-I_{Ca} −\left(g_K n^4 +\frac{g_{K, Ca} c}{K_d + c}\right) (V − V K ) − g_L (V − V_L )$ $\tau_n \frac{dn}{dt}=n_{\inf}(V)-n$ $\frac{dc}{dt} = f(-k_1 I_{Ca} -k_c c)$ ``` #y0 = array([-50.0, 0.530, 0.7]) #r = ode(lambda t, y: LR(y)).set_integrator(solver[0]) y0 = array([-50.0, 0.530, 0.1]) r = ode(lambda t, y: array([LR(y)[0], LR(y)[1], 0])).set_integrator(solver[0]) r.set_initial_value(y0, 0) t1 = 1000.0 dt = 1.0 v = [] n = [] ca = [] time = [] while r.successful() and r.t < t1: r.integrate(r.t+dt) v.append(r.y[0]) n.append(r.y[1]) ca.append(r.y[2]) time.append(r.t) figure(1) plot(time, v) xlabel('timepo (ms)') ylabel('V (mV)') grid(True) figure(2) plot(time, n) xlabel('timepo (ms)') ylabel('n') grid(True) figure(3) plot(time, ca) xlabel('timepo (ms)') ylabel('[Ca] (M)') grid(True) show() ``` #NMDA Channel ``` y0 = array([1, 0, 0, 0, 0]) #r = ode(lambda t, y: nmda_impulse(t, y)).set_integrator(solver[0]) r = ode(lambda t, y: v_dendrite(t, y)).set_integrator(solver[0]) r.set_initial_value(y0, 0) t1 = 4000.0 dt = 1.0 o = [] ICa = [] v = [] time = [] while r.successful() and r.t < t1: r.integrate(r.t + dt) o.append(r.y[3]) v.append(r.y[4]) time.append(r.t) figure(1) plot(time, o) grid(True) xlabel('timepo (ms)') ylabel('Fraccion de canales abiertos') figure(2) plot(time, v) grid(True) xlabel('timepo (ms)') ylabel('V') show() ``` ``` y0 = array([1, 0, 0, 0, -50.0, 0.530, 0.4]) r = ode(nmda_LR).set_integrator(solver[0]) r.set_initial_value(y0, 0) t1 = 4000.0 dt = 1.0 v = [] ca = [] time = [] while r.successful() and r.t < t1: r.integrate(r.t+dt) v.append(r.y[4]) ca.append(r.y[6]) time.append(r.t) figure(1) plot(time, v) xlabel('timepo (s)') ylabel('V (mV)') grid(True) figure(2) plot(time, ca) grid(True) show() ``` ``` y0 = array([0.0, 0.3176, 0.053, 0.596]) r = ode(lambda t, y: HH(y) + array([5, 0, 0, 0]) if 5<= t < 7 else HH(y)).set_integrator(solver[0]) r.set_initial_value(y0, 0) t1 = 20 dt = 0.01 v = [] time = [] while r.successful() and r.t < t1: r.integrate(r.t+dt) v.append(r.y[0]) time.append(r.t) figure(1) plot(time, v) xlabel('timepo (ms)') ylabel('V (mV)') grid(True) ``` ``` y0 = array([-40.0, 0.3176, 0.053, 0.596, 1, 0, 0, 0]) r = ode(nmda_HH).set_integrator(solver[0]) r.set_initial_value(y0, 0) t1 = 2000.0 dt = 1.0 v = [] o = [] ICa = [] time = [] while r.successful() and r.t < t1: # r.integrate(r.t+dt) v.append(r.y[0]) o.append(r.y[7]) ICa.append(ica(r.y[7], r.y[0])) time.append(r.t) figure(1) plot(time, v) xlabel('timepo (ms)') ylabel('V (mV)') grid(True) figure(2) plot(time, o) xlabel('timepo (ms)') ylabel('fraction open') grid(True) figure(3) plot(time, ICa) xlabel('timepo (ms)') ylabel('Calcium Current') grid(True) ``` #Cable ``` y0 = zeros((100,)) y0[40:50] = 10 * ones(10,) r = ode(lambda t, y: cable(y)).set_integrator(solver[0]) r.set_initial_value(y0, 0) t1 = 10.0 dt = 1.0 v = [y0] time = [] while r.successful() and r.t < t1: # r.integrate(r.t+dt) v.append(r.y) time.append(r.t) figure(1) for x in v: plot(x) xlim([30, 50]) ylim([0, 0.01]) xlabel('distancia') ylabel('V (mV)') grid(True) ``` ``` a = linspace(0, 9, 10) N = a.shape[0] print(a[1:N-1].shape) print(a[:N-2].shape) print(a[2:].shape) ``` (8,) (8,) (8,)
#!/usr/bin/env python from huntlib.util import punctuation_pattern import pandas as pd import numpy as np from unittest import TestCase class TestPunctuationPattern(TestCase): _event_message_1 = '192.168.1.1 - - [10/Oct/2020:12:32:27 +0000] "GET /some/web/app?param=test&param2=another_test" 200 9987' _event_message_2 = 'ERROR: Can\'t resolve "nosuchhost": No such host.' _punct_pattern_1 = '..._-_-_[//:::_+]_\"_///?=&=_\"__' _punct_pattern_2 = ':_\'__\"\":___.' _expected_pattern_result = pd.Series([_punct_pattern_1, _punct_pattern_2]) def test_punctuation_pattern_single_string(self): res = punctuation_pattern(self._event_message_1) self.assertEqual(res, self._punct_pattern_1) def test_punctuation_pattern_list(self): res = punctuation_pattern( [ self._event_message_1, self._event_message_2 ] ) self.assertListEqual(list(res), list(self._expected_pattern_result)) def test_punctuation_pattern_series(self): res = punctuation_pattern( pd.Series( [ self._event_message_1, self._event_message_2 ] ) ) self.assertListEqual(list(res), list(self._expected_pattern_result)) def test_punctuation_pattern_escape_quotes(self): res = punctuation_pattern("\'\"") self.assertEqual(res, '\'\"') res = punctuation_pattern("\'\"", escape_quotes=False) self.assertEqual(res, '\'\"') res = punctuation_pattern("\'\"", escape_quotes=True) self.assertEqual(res, '\\\'\\\"')
Inductive Vec (A:Set) : forall n1 n2:nat, Set := nil : Vec A 0 0. Check Vec. (* Vec : Set -> nat -> nat -> Set When we have cons, we will obviously need A_R. We want to get rid of n1 and n2? Why is that justified? In the type of Vec, there is absolutely no difference between parameters and indices -- we can write another Vec of the same type where all of them are params or all of them are indices. Perhaps the principle is the difference between Sort and Type in the domain of Pi Type. If so, we will not want to erase the indices_R of the following: λ x.x : Type -> Type the translation is λ x1 x2 xr, xr. the input xr is crucial. Another example below, which I dont understand. *) Inductive Monad : Type -> Type := ret : forall T, Monad T. (* If we cannot erase the index here, we will be forced to keep the equalities and implement the hard things anyway. So there is no advantage of trying to enforce irrelevance over small type domains in function types, because that seems ugly to implement, as discussed in this file *)
#pragma once #include <gsl/gsl_fit.h> #include <gsl/gsl_statistics.h> #include <gsl/gsl_movstat.h> #include <gsl/gsl_vector.h> #include <cstdlib> #include "DataFrame.h" #include "Ops.h" namespace adsl { // Evaluate the result of a fit at a given point based on the DataFrame description // double <- DataFrame /* auto evalFit = [](double t) { auto retFunc = [t](DataFrame& df) { if (df.getDesc() == "gsl_fit_linear") { double m = df + select({ "slope" }) + getFirst + single(); double b = df + select({ "intercept" }) + getFirst + single(); return (m * t) + b; } else { return (double)NAN; } }; return retFunc; }; */ // Perform a linear fit using gsl_fit_linear // df must have only 2 columns // DataFrame <- DataFrame auto fitLinear = [](DataFrame& df) { if (df.getCols() == 2) { if (df.getData()[0].type != DBL || df.getData()[1].type != DBL) { std::cout << "[fitLinear] <<ERROR>> At least one of the columns is not of type DBL " << std::endl; exit(1); DataFrame empty_df; return empty_df; } // Setup DataFrame ret; auto xData = df.getData()[0].toVec_dbl(); auto yData = df.getData()[1].toVec_dbl(); size_t length = xData.size(); double* x; double* y; x = (double*)malloc(length * sizeof(double)); y = (double*)malloc(length * sizeof(double)); std::copy(xData.begin(), xData.end(), x); std::copy(yData.begin(), yData.end(), y); // Fitting & r-squared double c0, c1, cov00, cov01, cov11, sumsq; gsl_fit_linear(x, 1, y, 1, length, &c0, &c1, &cov00, &cov01, &cov11, &sumsq); vd tmpSlope = {c1}; DataList slope(&tmpSlope, DataType::DBL, "slope"); vd tmpIntercept = {c0}; DataList intercept(&tmpIntercept, DataType::DBL, "intercept"); vd tmpRsqrd = { gsl_stats_correlation(x, 1, y, 1, length) }; DataList rsqrd(&tmpRsqrd, DataType::DBL, "r-squared"); // Clean up free(x); free(y); // Return ret.addCol(slope); ret.addCol(intercept); ret.addCol(rsqrd); ret.setDesc("gsl_fit_linear"); return ret; } else { std::cout << "[fitLinear] <<ERROR>> DataFrame doesn't have two columns; has " << df.getCols() << std::endl; exit(1); DataFrame empty_df; return empty_df; } }; // TODO: add more fit types // Calculate the moving average of a DataList // DataList <- DataList <- double /* auto SMA = [](double period) { auto retFunc = [period](DataList& dl) { DataFrame ret; double* input; double* output; // TODO }; return retFunc; }; */ }
theory P22 imports Main begin datatype bdd = Leaf bool | Branch bdd bdd primrec eval :: "(nat \<Rightarrow> bool) \<Rightarrow> nat \<Rightarrow> bdd \<Rightarrow> bool" where "eval p i (Leaf b) = b" | "eval p i (Branch b1 b2) = (if (p i) then (eval p (i+1) b2) else (eval p (i+1) b1))" primrec bdd_unop :: "(bool \<Rightarrow> bool) \<Rightarrow> bdd \<Rightarrow> bdd" where "bdd_unop f (Leaf b) = (Leaf (f b))" | "bdd_unop f (Branch b1 b2) = (Branch (bdd_unop f b1) (bdd_unop f b2))" primrec bdd_binop :: "(bool \<Rightarrow> bool \<Rightarrow> bool) \<Rightarrow> bdd \<Rightarrow> bdd \<Rightarrow> bdd" where "bdd_binop f (Leaf b) c = bdd_unop (f b) c" | "bdd_binop f (Branch b1 b2) c = (case c of Leaf x \<Rightarrow> Branch (bdd_binop f b1 (Leaf x)) (bdd_binop f b2 (Leaf x)) | Branch x1 x2 \<Rightarrow> Branch (bdd_binop f b1 x1) (bdd_binop f b2 x2))" theorem bdd_unop_correctness : "\<forall>i. eval g i (bdd_unop f b) = f (eval g i b)" apply (induct b) apply auto done theorem bdd_binop_correctness : "\<forall>i. eval g i (bdd_binop f b1 b2) = f (eval g i b1) (eval g i b2)" apply (induct b1 arbitrary: b2) apply (auto simp add: bdd_unop_correctness) apply (case_tac b2) apply auto apply (case_tac b2) apply auto apply (case_tac b2) apply auto apply (case_tac b2) apply auto done definition bdd_and:: "bdd \<Rightarrow> bdd \<Rightarrow> bdd" where "bdd_and \<equiv> bdd_binop (\<and>)" definition bdd_or:: "bdd \<Rightarrow> bdd \<Rightarrow> bdd" where "bdd_or \<equiv> bdd_binop (\<or>)" definition bdd_not:: "bdd \<Rightarrow> bdd" where "bdd_not \<equiv> bdd_unop (Not)" definition bdd_xor:: "bdd \<Rightarrow> bdd \<Rightarrow> bdd" where "bdd_xor \<equiv> bdd_binop (\<lambda>x y. (x \<and> (\<not> y)) \<or> (\<not>x \<and> y))" lemma bdd_and_correctness: "eval p i (bdd_and b1 b2) = (eval p i b1 \<and> eval p i b2)" apply (auto simp add: bdd_and_def bdd_binop_correctness) done lemma bdd_or_correctness: "eval p i (bdd_or b1 b2) = (eval p i b1 \<or> eval p i b2)" apply (auto simp add: bdd_or_def bdd_binop_correctness) done lemma bdd_not_correctness: "eval p i (bdd_not b) = (\<not> (eval p i b))" apply (auto simp add: bdd_not_def bdd_unop_correctness) done lemma bdd_xor_correctness: "eval p i (bdd_xor b1 b2) = (eval p i b1 \<and> (\<not> eval p i b2)) \<or> (\<not> eval p i b1 \<and> eval p i b2)" apply (auto simp add: bdd_xor_def bdd_binop_correctness) done fun bdd_var :: "nat \<Rightarrow> bdd" where "bdd_var 0 = (Branch (Leaf False) (Leaf True))" | "bdd_var (Suc n) = (Branch (bdd_var n) (bdd_var n))" theorem bdd_var_correctness:"\<forall>n. eval p n (bdd_var m) = p (m+n)" apply (induct m) apply auto done datatype form = T | Var nat | And form form | Xor form form definition xor :: "bool \<Rightarrow> bool \<Rightarrow> bool" where "xor x y \<equiv> (x \<and> \<not> y) \<or> (\<not> x \<and> y)" primrec evalf :: "(nat \<Rightarrow> bool) \<Rightarrow> form \<Rightarrow> bool" where "evalf e T = True" | "evalf e (Var i) = e i" | "evalf e (And f1 f2) = (evalf e f1 \<and> evalf e f2)" | "evalf e (Xor f1 f2) = xor (evalf e f1) (evalf e f2)" fun mk_bdd :: "form \<Rightarrow> bdd" where "mk_bdd T = Leaf True" | "mk_bdd (Var i) = bdd_var i" | "mk_bdd (And f1 f2) = bdd_and (mk_bdd f1) (mk_bdd f2)" | "mk_bdd (Xor f1 f2) = bdd_xor (mk_bdd f1) (mk_bdd f2)" theorem mk_bdd_correct: "eval e 0 (mk_bdd f) = evalf e f" apply (induct f) using bdd_xor_correctness bdd_xor_def apply auto[1] apply (simp add: bdd_var_correctness) apply (simp add: bdd_and_correctness) apply (simp add: bdd_binop_correctness bdd_xor_def xor_def) done end
Require Import Coq.omega.Omega. Set Implicit Arguments. Require Import Coq.Structures.OrderedType. Module W_as_MOT <: MiniOrderedType. Require Import Bedrock.Memory. Definition t := W. Require Import Bedrock.Word. Definition eq := @eq t. Local Open Scope nat. Definition lt (x y : t) := wordToNat x < wordToNat y. Lemma eq_refl : forall x : t, eq x x. unfold eq; eauto. Qed. Lemma eq_sym : forall x y : t, eq x y -> eq y x. unfold eq; eauto. Qed. Lemma eq_trans : forall x y z : t, eq x y -> eq y z -> eq x z. unfold eq; intuition. congruence. Qed. Lemma lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z. unfold lt; intros; omega. Qed. Lemma lt_not_eq : forall x y : t, lt x y -> ~ eq x y. unfold lt; unfold eq; intuition. subst. omega. Qed. Require Import Platform.Cito.WordFacts. Definition compare : forall x y : t, Compare lt eq x y. unfold lt; unfold eq. intros. destruct (Compare_dec.lt_eq_lt_dec (wordToNat x) (wordToNat y)). destruct s. econstructor 1; eauto. econstructor 2; eauto. eapply wordToNat_eq_eq; eauto. econstructor 3; eauto. Defined. End W_as_MOT. Module W_as_OT := MOT_to_OT W_as_MOT. Require Import Coq.Structures.OrdersAlt. Module W_as_OT_new := Update_OT W_as_OT. Require Import Coq.Structures.Equalities. Module W_as_UDT := Make_UDT W_as_OT.
[STATEMENT] lemma integer_composition_enum_not_null: "xs \<in> set (integer_composition_enum n) \<Longrightarrow> 0 \<notin> set xs" [PROOF STATE] proof (prove) goal (1 subgoal): 1. xs \<in> set (integer_composition_enum n) \<Longrightarrow> 0 \<notin> set xs [PROOF STEP] proof(induct xs arbitrary: n) [PROOF STATE] proof (state) goal (2 subgoals): 1. \<And>n. [] \<in> set (integer_composition_enum n) \<Longrightarrow> 0 \<notin> set [] 2. \<And>a xs n. \<lbrakk>\<And>n. xs \<in> set (integer_composition_enum n) \<Longrightarrow> 0 \<notin> set xs; a # xs \<in> set (integer_composition_enum n)\<rbrakk> \<Longrightarrow> 0 \<notin> set (a # xs) [PROOF STEP] case Nil [PROOF STATE] proof (state) this: [] \<in> set (integer_composition_enum n) goal (2 subgoals): 1. \<And>n. [] \<in> set (integer_composition_enum n) \<Longrightarrow> 0 \<notin> set [] 2. \<And>a xs n. \<lbrakk>\<And>n. xs \<in> set (integer_composition_enum n) \<Longrightarrow> 0 \<notin> set xs; a # xs \<in> set (integer_composition_enum n)\<rbrakk> \<Longrightarrow> 0 \<notin> set (a # xs) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: [] \<in> set (integer_composition_enum n) [PROOF STEP] show ?case [PROOF STATE] proof (prove) using this: [] \<in> set (integer_composition_enum n) goal (1 subgoal): 1. 0 \<notin> set [] [PROOF STEP] by simp [PROOF STATE] proof (state) this: 0 \<notin> set [] goal (1 subgoal): 1. \<And>a xs n. \<lbrakk>\<And>n. xs \<in> set (integer_composition_enum n) \<Longrightarrow> 0 \<notin> set xs; a # xs \<in> set (integer_composition_enum n)\<rbrakk> \<Longrightarrow> 0 \<notin> set (a # xs) [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>a xs n. \<lbrakk>\<And>n. xs \<in> set (integer_composition_enum n) \<Longrightarrow> 0 \<notin> set xs; a # xs \<in> set (integer_composition_enum n)\<rbrakk> \<Longrightarrow> 0 \<notin> set (a # xs) [PROOF STEP] case (Cons a xs) [PROOF STATE] proof (state) this: xs \<in> set (integer_composition_enum ?n) \<Longrightarrow> 0 \<notin> set xs a # xs \<in> set (integer_composition_enum n) goal (1 subgoal): 1. \<And>a xs n. \<lbrakk>\<And>n. xs \<in> set (integer_composition_enum n) \<Longrightarrow> 0 \<notin> set xs; a # xs \<in> set (integer_composition_enum n)\<rbrakk> \<Longrightarrow> 0 \<notin> set (a # xs) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: xs \<in> set (integer_composition_enum ?n) \<Longrightarrow> 0 \<notin> set xs a # xs \<in> set (integer_composition_enum n) [PROOF STEP] show ?case [PROOF STATE] proof (prove) using this: xs \<in> set (integer_composition_enum ?n) \<Longrightarrow> 0 \<notin> set xs a # xs \<in> set (integer_composition_enum n) goal (1 subgoal): 1. 0 \<notin> set (a # xs) [PROOF STEP] using integer_composition_enum_not_null_aux integer_composition_enum_tail_elem [PROOF STATE] proof (prove) using this: xs \<in> set (integer_composition_enum ?n) \<Longrightarrow> 0 \<notin> set xs a # xs \<in> set (integer_composition_enum n) ?x # ?xs \<in> set (integer_composition_enum ?n) \<Longrightarrow> ?x \<noteq> 0 ?x # ?xs \<in> set (integer_composition_enum ?n) \<Longrightarrow> ?xs \<in> set (integer_composition_enum (?n - ?x)) goal (1 subgoal): 1. 0 \<notin> set (a # xs) [PROOF STEP] by fastforce [PROOF STATE] proof (state) this: 0 \<notin> set (a # xs) goal: No subgoals! [PROOF STEP] qed
import tactic /- # Quotients The quotient of a type by an equivalence relation. ## Overview A binary relation on a type `X` is just a function `r : X → X → Prop`, that is, a true-false statement attached to each pair of elements of `X`. If `r` is also reflexive, symmetric and transitive, we say it is an equivalence relation. We will use the standard notation `x ≈ y` for `r x y` below. Given a type `X` and an equivalence relation `≈` on it, the type `clX` of equivalence classes for `≈` comes equipped with a canonical function `X → clX` (sending an element to its equivalence class), and it also satisfies a universal property, namely that to give a map from `clX` to a type `T` is to give a map `X → T` which is constant on equivalence classes. Note however that other types other than the type of equivalence classes may also satisfy this universal property. For example if we start with a type `X` and a surjection `p : X → Y` and then define an equivalence relation on `X` by `x₁ ≈ x₂ ↔ p x₁ = p x₂` then `Y` satisfies the same universal property. In general it is a fact in mathematics that things which define universal properties are unique up to unique isomorphism, and things like the type of equivalence classes are just a *model* for this general concept of quotient. Lean does not use the equivalence class model when doing quotients. Here's how it does it. The type `setoid X` is defined to be the type of equivalence relations on `X`. If `s : setoid X` is an equivalence relation then Lean defines `quotient s` to be a new type which satisfies the universal property of quotients. Let us spell out what this means. Firstly, it means that there is a map `p : X → quotient s`, and secondly it means that to give a map `f : quotient s → T` is to give `f ∘ p : X → T`, a map which is constant on equivalence classes. In this file we will learn the various useful functions which Lean has for dealing with quotients -- that is, the key definitions and theorems which mathematicians use, sometimes subconsciously, when dealing with quotients. We will learn them by explicitly working through an example, namely the case where `X = ℕ²` and `(a,b) ≈ (c,d) ↔ a + d = c + b`. In this case, the quotient is a model for the integers. ## More on universal properties. Recall that if `X` and `T` are types, then `X → T` denotes the *type* of functions from `X` to `T`. A mathematician might call this type `Hom(X,T)`. A term `f : X → T` of this type is just a function from `X` to `T`. Let us now spell out the universal property more carefully. Given a type `X` and an equivalence relation `≈` on `X`, we say that a function `f : X → T` is *constant on equivalence classes*, (or `≈`-equivariant for short), if `∀ x y : X, x ≈ y → f x = f y`. We say that a pair `(Q, p)` consisting of a type `Q` and a function `p : X → Q` are a *quotient* of `X` by `≈` if `p` is constant on equivalence classes, and furthermore `p` is *initial* with repect to this property. What does this mean? Let me spell this out. Let `(Q, p)` be a quotient of `X` by `≈`. Note first that if `T` is any type and `g : Q → T` is any function, then `f := g ∘ p : X → T` is constant on equivalence classes (because `p` is). Being *initial* is the claim that this construction, starting with a function `g : Q → T` and giving us a function `f : X → T` which is `≈`-equivariant, is a *bijection* between `Q → T` and the subset of `X → T` consisting of `≈`-equivariant functions. In diagrams, if `f` is constant on equivalence classes, then there's a unique `g` which fills in the diagram. f X ---------> T | /\ | / | p / ∃!g | / | / \/ Q One can easily check that the type of equivalence classes for `≈` satisfies this universal property, with `p` being the map sending a term of type `X` to its equivalence class. One can think of the type of equivalence classes as a "model" for the quotient, in the same way that you might have seen a model for the tensor product `V ⊗ W` of two vector spaces given as a quotient of the vector space generated by pairs `(v,w)` by the subspace generated by an appropriate collection of relations, or a model for the localisation `R[1/S]` of a commutative ring at a multiplicative subset given by `R × S` modulo a certain equivalence relation. Models are useful. A model of an `n`-dimensional real vector space is obtained by choosing a basis; then it can be identified with `ℝⁿ` enabling explicit computations to be done. But there are many other models for quotients. For example let's say `X` and `Q` are any types, and `f : X → Q` is any surjection at all. Define `≈` on `X` by `x ≈ y ↔ f x = f y`. It is easy to check that `Q` is a quotient of `X` by `≈` simply because `Q` naturally bijects with the equivalence classes of `≈`. Lean does not use equivalence classes in its definition of the quotient of `X` by `≈`. It chooses a different model. It is an opaque model, meaning that you cannot actually see what the terms are. But Lean and mathlib give you a very solid API for the quotient. In particular, the quotient satisfies the universal property, so one can prove that it bijects with the type of equivalence classes on `X`. However, after a while one moves away from the "equivalence class" way of thinking, and starts thinking more abstractly about quotients, and so ultimately one does not really need this bijection at all. You might wonder why Lean does not use the type of equivalence classes. The reason is not a mathematical one -- it is simply to do with an implementation issue which I will mention later. Here is a guided tour of the API for Lean's quotients, worked out for a specific example -- the integers, as a quotient of ℕ² by the equivalence relation `(a,b) ≈ (c,d) ↔ a + d = c + b.` -/ -- N2 is much easier to type than `ℕ × ℕ` abbreviation N2 := ℕ × ℕ namespace N2 -- all the functions below will be N2.something -- Hmm, I guess I should run you through the API for products `×`. /- ### products The product of two types `X` and `Y` is `prod X Y`, with notation `X × Y`. Hover over `×` to find out how to type it. -/ section product -- to make a term of a product, use round brackets. def foo : N2 := (3,4) -- To extract the first term of a product, use `.1` or `.fst` example : foo.1 = 3 := begin -- true by definition. refl end example : foo.fst = 3 := begin refl end -- similarly use `.2` or `.snd` to get the second term example : foo.snd = 4 := rfl -- term mode reflexivity of equality -- The extensionality tactic works for products: a product is determined -- by the two parts used to make it. example (X Y : Type) (s t : X × Y) (h1 : s.fst = t.fst) (h2 : s.snd = t.snd) : s = t := begin ext, { exact h1 }, { exact h2 } end -- you can uses `cases x` on a product if you want to take it apart into -- its two pieces example (A B : Type) (x : A × B) : x = (x.1, x.2) := begin -- note that this is not yet `refl` -- you have to take `x` apart. cases x with a b, -- ⊢ (a, b) = ((a, b).fst, (a, b).snd) dsimp only, -- to tidy up: this replaces `(a, b).fst` with `a`. -- ⊢ (a, b) = (a, b) refl, end end product /- ## Worked example: ℤ as a quotient of ℕ² There's a surjection `ℕ × ℕ → ℤ` sending `(a,b)` to `a - b` (where here `a` and `b` are regarded as integers). One checks easily that `(a,b)` and `(c,d)` are sent to the same integer if and only if `a + d = b + c`. Conversely one could just define an equivalence relation on ℕ × ℕ by `ab ≈ cd ↔ ab.1 + cd.2 = cd.1 + ab.2` and then redefine ℤ -- or more precisely define a second ℤ -- to be the quotient by this equivalence relation. Let's set up this equivalence relation and call the quotient `Z`. Recall we're using `N2` to mean `ℕ × ℕ`. -/ def r (ab cd : N2) : Prop := ab.1 + cd.2 = cd.1 + ab.2 -- This is a definition so let's make a little API for it. -- It's nice to be able to `rw` to get rid of explicit occurrences of `r`. -- So let's make two lemmas suitable for rewriting. lemma r_def (ab cd : N2) : r ab cd ↔ ab.1 + cd.2 = cd.1 + ab.2 := begin refl end -- This one is more useful if you've already done `cases` on the pairs. lemma r_def' (a b c d : ℕ) : r (a,b) (c,d) ↔ a + d = c + b := begin refl end def r_refl : reflexive r := begin -- you can start with `unfold reflexive` if you want to see what -- you're supposed to be proving here. sorry, end -- hint: `linarith` is good at linear arithmetic. def r_symm : symmetric r := begin sorry end def r_trans : transitive r := begin sorry end -- now let's give N2 a setoid structure coming from `r`. -- In other words, we tell the type class inference system -- about `r`. Let's call it `setoid` and remember -- we're in the `N2` namespace, so its full name -- is N2.setoid instance setoid : setoid N2 := ⟨r, r_refl, r_symm, r_trans⟩ -- Now we can use `≈` notation example (x y : N2) : x ≈ y ↔ r x y := begin -- true by definition refl end -- `r x y` and `x ≈ y` are definitionally equal but not syntactically equal, -- rather annoyingly, so we need two more lemmas enabling us to rewrite. -- Let's teach them to `simp`, because they're the ones we'll be using -- in practice. @[simp] lemma equiv_def (ab cd : N2) : ab ≈ cd ↔ ab.1 + cd.2 = cd.1 + ab.2 := begin refl end @[simp] lemma equiv_def' (a b c d : ℕ) : (a,b) ≈ (c,d) ↔ a + d = c + b := iff.rfl -- term mode variant end N2 open N2 -- Now we can take the quotient! def Z := quotient N2.setoid namespace Z -- And now we can finally start. -- The map from N2 to Z is called `quotient.mk` -- Recall `foo` is `(3,4)` def bar : Z := quotient.mk foo -- bar is the image of `foo` in the quotient. -- so it's morally -1. -- Notation for `quotient.mk x` is `⟦x⟧` example : bar = ⟦foo⟧ := begin refl end /- ## Z We have a new type `Z` now, and a way of going from `N2` to `Z` (`quotient.mk`, with notation `⟦ ⟧`). Here then are some things we can think about: (1) How to prove the universal property for `Z`? (2) How to put a ring structure on `Z`? (3) How to define a map from `Z` to Lean's `ℤ`, which is not defined as a quotient but also satisfies the universal property? We will do (1) and (2) in this file. Let's start with (1). The claim is that to give a map `Z → T` is to give a map `N2 → T` which is constant on equivalence classes. The construction: given a map `Z → T`, just compose with `quotient.mk : N2 → Z`. What do we need to prove here? First we need to prove that `quotient.mk` is `≈`-equivariant. In other words, we need to prove `x ≈ y → ⟦x⟧ = ⟦y⟧`. -/ example (x y : N2) : x ≈ y → ⟦x⟧ = ⟦y⟧ := quotient.sound -- Of course we know the other implication is also true. -- This is called `quotient.exact`. example (x y : N2) : ⟦x⟧ = ⟦y⟧ → x ≈ y := quotient.exact -- The iff statement (useful for rewrites) is called `quotient.eq` : example (x y : N2) : ⟦x⟧ = ⟦y⟧ ↔ x ≈ y := quotient.eq -- So now we can define the map from `Z → T` to the subtype of `N2 → T` -- consisting of `≈`-equivariant functions. variable {T : Type} /- Given a map `g : Z → T`, make a function `f : N2 → T` which is constant on equivalence classes. -/ def universal1 (g : Z → T) : {f : N2 → T // ∀ x y : N2, x ≈ y → f x = f y} := ⟨λ n2, g ⟦n2⟧, begin sorry end⟩ -- To go the other way, we use a new function called `quotient.lift`. -- Note that this is a weird name for the construction, at least if your -- mental picture has the quotient underneath the type with the relation. -- But we're stuck with it. /- Given a map `f : N2 → T` plus the assumption that it is constant on equivalence classes, "lift" this map to a map `Z → T`. -/ def universal2 (f : N2 → T) (hf : ∀ x y : N2, x ≈ y → f x = f y) : Z → T := quotient.lift f hf -- So now the big question is: how do we prove that these two constructions -- are inverse to each other? In other words, what is the API for -- the definition `quotient.lift`? -- Let's start by showing that going from `N2 → T` to `Z → T` (via `quotient.lift`) -- and then back to `N2 → T` (via composing with `quotient.mk`) is the -- identity function. Recall `⟦⟧` is the notation for `quotient.mk`. -- Another way of writing the example below : universal2 ∘ universal1 = id. example (f : N2 → T) (hf : ∀ x y : N2, x ≈ y → f x = f y) : f = λ n2, quotient.lift f hf ⟦n2⟧ := begin -- true by definition! refl end -- This is the reason quotients are defined as a black box; if we had -- defined them to be equivalence classes this would be true, but -- not by definition. To a mathematician this is not really a big deal, -- but it is what it is. -- To go the other way, proving universal1 ∘ universal2 = id, the key thing -- to know is a function -- called `quotient.induction_on`: example (g : Z → T) : g = quotient.lift (λ n2, g ⟦n2⟧) (universal1 g).2 := begin -- two functions are equal if they agree on all inputs ext z, -- now use `quotient.induction_on` (this is the key move) apply quotient.induction_on z, -- and now we're in the situation of the above example again intro ab, -- so it's true by definition. refl, end -- We have hence proved that `universal1` and `universal2` are inverse -- bijections, at least in this `N2 → Z` case. In `Part_C` we will do -- this in general, but there is a ton of material this week so -- don't worry if you don't get to it. /- ## Giving Z a commutative ring structure Let's now show how to give this quotient object `Z` a commutative ring structure, which it somehow wants to inherit from structures on `ℕ`. Recall that a ring is a choice of `0`, `1`, and functions `+`, `-` and `*` satisfying some axioms. After a while this all becomes straightforward and boring, so I will go through the proof that it's an abelian group under addition carefully and then the multiplication part is just more of the same -- feel free to skip it. ### zero and one We start by giving `Z` a zero and a one. -/ def zero : Z := ⟦(0, 0)⟧ def one : Z := ⟦(1, 0)⟧ -- We don't have the numeral notation yet though: -- #check (0 : Z) -- error about failing to find an instance of `has_zero Z` -- Let's use numeral notation `0` and `1` for `zero` and `one`. instance : has_zero Z := ⟨zero⟩ instance : has_one Z := ⟨one⟩ -- let's start to train the simplifier @[simp] lemma zero_def : (0 : Z) = ⟦(0, 0)⟧ := rfl -- works @[simp] lemma one_def : (1 : Z) = ⟦(1, 0)⟧ := rfl /- ### negation Let's do negation next, by which I mean the function sending `z` to `-z`, because this is a function which only takes one input (addition takes two). Here is how a mathematician might describe defining negation on the equivalence classes of `ℕ × ℕ`. They might say this: 1) choose an element `z` of the quotient `Z`. 2) lift it randomly to a pair `(a, b)` of natural numbers. 3) Define `-z` to be `⟦(b,a)⟧` 4) Now let us check that this definition did not depend on the random lift in (2): [and then they prove a lemma saying the construction is well-defined, i.e. that if `(a, b) ≈ (c,d)` then `⟦(b, a)⟧ = ⟦(d, c)⟧` ] This is the way mathematicians are taught. We will use *the same construction* in Lean but we will phrase it differently. 1') Define an auxiliary map `N2 → Z` by sending `(a,b)` to `⟦(b,a)⟧` 2') I claim that this function is constant on equivalence classes [and then we prove a lemma saying `(a, b) ≈ (c, d) → ⟦(b, a)⟧ = ⟦(d, c)⟧` 3') Now use `quotient.lift` to descend this to a map from `Z` to `Z`. So as you can see, the mathematics is the same, but the emphasis is slightly different. -/ -- Here's the auxiliary map. def neg_aux (ab : N2) : Z := ⟦(ab.2, ab.1)⟧ -- useful for rewriting. Let's teach it to `simp`. @[simp] lemma neg_aux_def (ab : N2) : neg_aux ab = ⟦(ab.2, ab.1)⟧ := rfl -- true by def -- In the process of making this definition we need to prove a theorem -- saying neg_aux is constant on equivalence classes. def neg : Z → Z := quotient.lift neg_aux begin -- ⊢ ∀ (a b : N2), a ≈ b → neg_aux a = neg_aux b sorry, end -- `-z` notation instance : has_neg Z := ⟨neg⟩ -- Let's teach the definition of `neg` to the simplifier. @[simp] lemma neg_def (a b : ℕ) : (-⟦(a, b)⟧ : Z) = ⟦(b, a)⟧ := rfl /- ## Addition If we use `quotient.lift` for defining addition, we'd have to use it twice. We define `⟦(a, b)⟧ + ⟦(c, d)⟧ = ⟦(a + c, b + d)⟧` and would then have to check it was independent of the choice of lift `(a, b)` in one lemma, and then in a second proof check it was independent of the choice of `(c, d)`. The variant `quotient.lift₂` enables us to prove both results in one go. It says that if `f : A → B → C` is a function which and `A` and `B` have equivalence relations on them, and `f` is constant on equivalence classes in both the `A` and the `B` variable, then `f` descends ("lifts") to a function `A/~ → B/~ → C`. -/ -- auxiliary definition of addition (note `(a-b)+(c-d)=(a+c)-(b+d)` ) def add_aux (ab cd : N2) : Z := ⟦(ab.1 + cd.1, ab.2 + cd.2)⟧ -- useful for rewriting @[simp] lemma add_aux_def (ab cd : N2) : add_aux ab cd = ⟦(ab.1 + cd.1, ab.2 + cd.2)⟧ := rfl -- true by def def add : Z → Z → Z := quotient.lift₂ add_aux begin sorry, end -- notation for addition instance : has_add Z := ⟨add⟩ -- train the simplifier, because we have some axioms to prove about `+` @[simp] lemma add_def (a b c d : ℕ) : (⟦(a, b)⟧ + ⟦(c, d)⟧ : Z) = ⟦(a+c, b+d)⟧ := rfl -- may as well get subtraction working def sub (x y : Z) : Z := x + -y instance : has_sub Z := ⟨sub⟩ /- ## Z is a commutative group under addition -/ def add_comm_group : add_comm_group Z := { zero := 0, add := (+), neg := has_neg.neg, sub := has_sub.sub, -- The key is always `quotient.induction_on` -- I'll do the first one for you. zero_add := begin intro x, apply quotient.induction_on x, clear x, rintro ⟨a, b⟩, simp, end, add_zero := begin sorry end, -- Here there are three variables so it's `quotient.induction_on₃` -- Remember the `ring` tactic will prove identities in `ℕ`. add_assoc := begin sorry end, add_left_neg := begin sorry end, add_comm := begin sorry end, } /- ## More of the same : Z is a commutative ring. I would recommend skipping this and going onto Part B. There are no more ideas here, this is just to prove that it can be done. A mild variant: let's do multiplication in a slightly different way. Instead of using `quotient.lift₂` (which descends a map `N2 → N2 → Z` to a map `Z → Z → Z`) we'll use `quotient.map₂`, which descends a map `N2 → N2 → N2` to a map `Z → Z → Z`. -/ -- auxiliary definition of multiplication: `(a-b)*(c-d) = (a*c+b*d)-(a*d+b*c)` def mul_aux (ab cd : N2) : N2 := (ab.1 * cd.1 + ab.2 * cd.2, ab.1 * cd.2 + ab.2 * cd.1) @[simp] lemma mul_aux_def (a b c d : ℕ) : mul_aux (a,b) (c,d) = (a*c+b*d,a*d+b*c) := rfl -- The key result you have to prove here involves multiplication so is -- unfortunately non-linear. However `nlinarith` is OK at non-linear arithmetic... def mul : Z → Z → Z := quotient.map₂ mul_aux begin sorry end -- notation for multiplication instance : has_mul Z := ⟨mul⟩ @[simp] lemma mul_def (a b c d : ℕ) : (⟦(a, b)⟧ * ⟦(c, d)⟧ : Z) = ⟦(a*c+b*d, a*d+b*c)⟧ := rfl -- now let's prove that Z is a commutative ring! def comm_ring : comm_ring Z := { one := 1, add := (+), mul := (*), mul_assoc := begin intros x y z, apply quotient.induction_on₃ x y z, clear x y z, rintros ⟨a, b⟩ ⟨c, d⟩ ⟨e, f⟩, simp, ring, end, -- etc etc one_mul := begin sorry end, mul_one := begin sorry end, left_distrib := begin sorry end, right_distrib := begin sorry end, mul_comm := begin sorry end, ..add_comm_group } end Z
If $c$ and $c'$ are components of $s$, then $c$ and $c'$ are disjoint if and only if $c \neq c'$.
import tactic import .lesson6 noncomputable theory open_locale classical open PreHilbertPlane HilbertPlane section plane_separation variables {Ω : Type*} [HilbertPlane Ω] variables {ℓ r s : Line Ω} variables {B C D: {x : Ω // x ∈ ℓ}} variables {A : Ω} @[simp] def same_side_of_line (hAℓ : A ∈ ℓ) (B C : {x : Ω // x ∈ ℓ}) := ((B : Ω) = C) ∨ (¬ (A : Ω) ∈ (B : Ω) ⬝ C) lemma same_side_of_line.refl (hAℓ : A ∈ ℓ) : same_side_of_line hAℓ B B := begin simp, end lemma same_side_of_line.symm (hAℓ : A ∈ ℓ) : same_side_of_line hAℓ B C → same_side_of_line hAℓ C B := begin simp only [Segment.mem_pts, and_imp, same_side_of_line, between_point_symmetric] at *, tauto, end lemma same_side_line_vs_plane (hr : r ≠ ℓ) (hAℓ : A ∈ ℓ) (hAr : A ∈ r) : same_side_of_line hAℓ B C ↔ same_side r B C := begin obtain rfl | hBC := em(B = C), by exact ⟨ λ h, same_side.refl, λ h, same_side_of_line.refl _⟩, cases B with B hB, cases C with C hC, split, { intro h, unfold same_side_of_line at h, unfold same_side, rcases h with ⟨h1,h2⟩ | hBAC, { tauto, }, by_cases hh : (B : Ω) ∈ r ∧ (C : Ω) ∈ r, left, assumption, replace hh : (B : Ω) ∉ r ∨ (C : Ω) ∉ r, tauto, right, unfold pts, ext1, dsimp, rw iff_false, push_neg, intros H hx, rcases H with (H|H|H), any_goals {subst H, simp only at hx, exfalso}, work_on_goal 3 {have hxℓ : x ∈ ℓ := between_points_share_line hB hC H}, work_on_goal 1 {obtain rfl | ht := em(A = B)}, work_on_goal 3 {obtain rfl | ht := em(A = C)}, work_on_goal 5 {obtain rfl | ht := em(A = x)}, any_goals { apply hBAC, norm_num, try {tauto}, }, all_goals { exfalso, apply hr, apply equal_lines_of_contain_two_points ht, try {repeat {assumption}}, }, }, { intro H, unfold same_side at H, rcases H with (⟨H1,H2⟩|H), simp, repeat{split}, repeat {assumption}, { right, push_neg, exfalso, apply hr, norm_num at hBC, apply equal_lines_of_contain_two_points hBC, try {repeat {assumption}}, }, { unfold same_side_of_line, right, intro hABC, rw set.eq_empty_iff_forall_not_mem at H, specialize H A, apply H, simp only [true_and, set.mem_inter_eq, true_or, eq_self_iff_true, segments_are_symmetric], split, { finish, }, assumption, }, }, end lemma same_side_of_line.trans (hAℓ : A ∈ ℓ) : same_side_of_line hAℓ B C → same_side_of_line hAℓ C D → same_side_of_line hAℓ B D := begin obtain ⟨E, hE⟩ := exists_point_not_on_line ℓ, let r := line_through A E, have hEr : E ∈ r := line_through_right, have hAr : A ∈ r := line_through_left, obtain rfl | hr := em(r = ℓ), by tauto, repeat {rw same_side_line_vs_plane hr}, { exact same_side.trans, }, repeat {assumption}, end @[simp] theorem same_side_of_line_equiv (hAℓ : A ∈ ℓ) : (equivalence (same_side_of_line hAℓ)) := ⟨λ x, same_side_of_line.refl hAℓ, λ x y hxy, same_side_of_line.symm hAℓ hxy, λ x y z hxy hyz, same_side_of_line.trans hAℓ hxy hyz⟩ lemma at_least_two_classes_line (hAℓ : A ∈ ℓ) : ∃ B C : {x : Ω // x ∈ ℓ}, ¬ same_side_of_line hAℓ B C := begin sorry end lemma at_most_two_classes_line (hAℓ : A ∈ ℓ) : ¬ same_side_of_line hAℓ B C → ¬ same_side_of_line hAℓ B D → same_side_of_line hAℓ C D := begin sorry end end plane_separation
Formal statement is: lemma order_unique_lemma: fixes p :: "'a::idom poly" assumes "[:-a, 1:] ^ n dvd p" "\<not> [:-a, 1:] ^ Suc n dvd p" shows "order a p = n" Informal statement is: If $p$ is a polynomial with integer coefficients and $a$ is an integer, then the order of $a$ in $p$ is the largest integer $n$ such that $x^n$ divides $p$.
# To-dos: # # - How do we handle TF/SF? Need a capability to do subpixel smoothing only inside some # region. # # - A symmetry boundary puts the mirror image of the boundary-touching object in the space # behind the boundary. When this happens, not only the shape but also the material of the # object must be flipped with respect to the symmetry boundary. Such material flip is # currently unsupported: only the Bloch boundary condition is valid for the boundary # touching anisotropic materials. export smooth_param! # Given a vector `v` of comparable objects and vector `ind` of indices that sort `v`, return # the number `c` of different objects in `v` and the index `nₑ` of `ind` where the last new # object occurs (i.e., v[ind[nₑ]] is the last new object). # # If v is uniform, nₑ = length(v) + 1 (i.e., it is out of bound). # # For efficiency, this function assumes `v` is a vector of objects assigned to a voxel, i.e., # length(v) = 8. @inline function countdiff(ind::MArray{TP,<:Integer,K,Zᴷ}, v::MArray{TP,<:Real,K,Zᴷ}) where {TP,K,Zᴷ} # Zᴷ = number of entries in MArray c, nₑ = 1, Zᴷ+1 @simd for n = 2:Zᴷ @inbounds v[ind[n-1]] ≠ v[ind[n]] && (c += 1; nₑ = n) end return c, nₑ # c: number of changes in v; nₑ: last n where v[ind[n]] changed end # vectors from voxel corners to the voxel center nout_vxl(::Val{3}) = (SVec(1.,1.,1.), SVec(-1.,1.,1.), SVec(1.,-1.,1.), SVec(-1.,-1.,1.), SVec(1.,1.,-1.), SVec(-1.,1.,-1.), SVec(1.,-1.,-1.), SVec(-1.,-1.,-1.)) nout_vxl(::Val{2}) = (SVec(1.,1.), SVec(-1.,1.), SVec(1.,-1.), SVec(-1.,-1.)) nout_vxl(::Val{1}) = (SVec(1.), SVec(-1.)) # Overall smoothing algorithm # # Below, obj, pind, oind refers to an Object{3} instance, parameter index (integer value) that # distinguishes different material parameters, and oind that distinguishes different objects. # # - Assign oind, pind, shape to arrays object-by-object (see assignment.jl). # - Currently, we assign only oind (in oindKd′), and pind and shape are retrieved from oind by oind2shp and oind2pind. # - For the locations of grid points to assign the objects to, use τlcmp (lcmp created considering BC). # - Using oind and pind, determine voxels to perform subpixel smoothing. # - Inside each voxel, figure out the foreground object with which subpixel smoothing is performed. # - Iterating voxel corners, find the object that is put latest. That object is the foreground object. # - Complication occurs when the voxel corner assigned with the foreground object is outside the domain boundary. # - In that case, to calculate nout and rvol properly, we have to move the voxel center. (This is effectively the same as moving the foreground object.) # - If the corner is outside the periodic boundary, translate the voxel center before calling surfpt_nearby (using ∆fg). # - If the corner is outside the symmetry boundary, zero the nout component normal to the boundary (using σvxl). # - ∆fg and σvxl can be obtained simply by looking at the indices and BC. # Below, the primed quantities are for voxel corner quantities rather than voxel center # quantities. Compare this with the usage of the prime in assignment.el that indicates # complementary material (i.e., magnetic for electric). function smooth_param!(paramKd::AbsArrComplexF{K₊₂}, # parameter array to smooth at voxel centers oindKd′::NTuple{Kf⏐₁,AbsArr{ObjInd,K}}, # object index array at voxel corners; does not change oind2shp::AbsVec{Shape{K,K²}}, # input map from oind to shape oind2pind::AbsVec{ParamInd}, # input map from oind to pind pind2matprm::AbsVec{S²ComplexF{Kf,Kf²}}, # map from pind to electric (magnetic) material parameters; Kf² = Kf^2 gt₀::SVec{K,GridType}, # grid type of voxel corners; generated by ft2gt.(ft, boundft) l::Tuple2{NTuple{K,AbsVecReal}}, # grid locations excluding ghost points (length(l[PRIM][k]) = N[k]); used for locations of field components lg::Tuple2{NTuple{K,AbsVecReal}}, # grid locations including ghost points (length(lg[PRIM][k]) = N[k]+1); used for locations of voxel corners without transformation by boundary conditions σ::Tuple2{NTuple{K,AbsVecBool}}, # false if on symmetry boundary; exclude ghost points (length(σ[PRIM][k]) = N[k]) ∆τ::Tuple2{NTuple{K,AbsVecReal}}, # amount of shift by Bloch boundary conditions; include ghost points (length(∆τ[PRIM][k]) = N[k]+1) isfield˔shp::Bool=isfield_ortho_shape(Kf,K) # true if spaces where field and shapes are defined are orthogonal complement of each other; false if they are the same ) where {K,K²,K₊₂,Kf,Kf²,Kf⏐₁} @assert K²==K^2 && Kf²==Kf^2 && K₊₂==K+2 && (Kf⏐₁==Kf || Kf⏐₁==1) @assert size(paramKd,K+1)==size(paramKd,K+2)==Kf ci_1 = CartesianIndex(ntuple(x->1, Val(K))) for nw = 1:Kf⏐₁ # Set the grid types of the x-, y-, z-locations of Fw. # # I thought I could replace the condition Kf⏐₁==1 with isfield_ortho_shape(Kf,K), # because gt_cmp becomes gt₀ when isfield_ortho_shape(Kf,K) = true. The replacement # is incorrect, however, because we need gt_cmp to become gt₀ even when the shape # and field subspaces coincide (e.g., K = Kf = 3) to assign the off-diagonal entries # of the material parameter tensors at voxel corners. gt_cmp = Kf⏐₁==1 ? gt₀ : gt_w(nw, gt₀) # Set the grid types of the voxel corners surroundnig Fw. gt_cmp′ = alter.(gt_cmp) # Choose various vectors for Fw (which is at the centers of the voxel defined by the # voxel corners below). lcmp = t_ind(l, gt_cmp) σcmp = t_ind(σ, gt_cmp) # Choose various arrays and vectors for voxel corners. lcmp′ = t_ind(lg, gt_cmp′) ∆τcmp′ = t_ind(∆τ, gt_cmp′) oind_cmp′ = oindKd′[nw] ind_c = MArray{Tuple{ntuple(x->2,Val(K))...},Int}(undef) # corner indices inside voxel pind_vxl′ = similar(ind_c) # material parameter indices inside voxel oind_vxl′ = similar(ind_c) # object indices inside voxel # Set various arrays for the current component. CI = CartesianIndices(length.(lcmp)) for ci_cmp = CI # Below, ci_1 is always +1 (i.e., not -1 depending on the grid type of field # component), because the field component locations lcmp exclude the ghost # points whereas the voxel corner locations lcmp′ include the ghost points. ci_vxl′ = (ci_cmp, ci_cmp + ci_1) # Tuple2{SInt{3}} if !is_vxl_uniform!(oind_vxl′, pind_vxl′, ci_vxl′, oind_cmp′, oind2shp, oind2pind) # Note that pind_vxl′ is initialized at this point. sort_ind!(ind_c, pind_vxl′) # pind_vxl′[ind_c[n]] ≤ pind_vxl′[ind_c[n+1]] Nprm_vxl, n_diffp = countdiff(ind_c, pind_vxl′) # n_diffp: last n where pind_vxl′[ind_c[n]] changed if Nprm_vxl ≥ 2 if Nprm_vxl == 2 # Attempt to apply Kottke's subpixel smoothing algorithm. prm_vxl = smooth_param_vxl(ci_vxl′, ind_c, n_diffp, pind_vxl′, oind_vxl′, oind_cmp′, oind2shp, oind2pind, pind2matprm, lcmp, lcmp′, σcmp, ∆τcmp′, isfield˔shp) else # Nprm_vxl ≥ 3 # Give up Kottke's subpixel smoothing and take simple averaging. # See the comments at the next usage of amean_param(). prm_vxl = amean_param(ci_vxl′, oind_cmp′, oind2pind, pind2matprm)::S²ComplexF{Kf,Kf²} end # if Nprm_vxl == 2 # Below, we have four combinations depending on the values of Kf⏐₁ and Kf: # Kf⏐₁ is either ==Kf or ==1, and Kf is either ≥2 or ==1. # # The case of Kf⏐₁ == Kf covers Kf≥2 and Kf==1. When Kf==1, the case # corresponds to Kf⏐₁==1 and Kf==1. Therefore, the "if" case Kf⏐₁ == Kf # covers the two combinations: # - Kf⏐₁==Kf and Kf≥2, # - Kf⏐₁==1 and Kf==1. # # Therefore, the "else" case should cover the remaining two combinations: # - Kf⏐₁==Kf && Kf==1, # - Kf⏐₁==1 && Kf≥2. # However, the first combination is equivalent to Kf⏐₁==1 && Kf==1, which # was already covered in the "if" case. Therefore, the "else" case # deals with only the case of Kf⏐₁==1 && Kf≥2. if Kf⏐₁ == Kf # Kf⏐₁==Kf && Kf≥2, or Kf⏐₁==1 && Kf==1 # Overwrite the (nw,nw)-diagonal entry of paramKd. @inbounds paramKd[ci_cmp,nw,nw] = prm_vxl[nw,nw] else # Kf⏐₁==1 && Kf≥2 # Overwrite the off-diagonal entires of paramKd. # Below the main diagonal. for c = 1:Kf, r = c+1:Kf # column- and row-indices @inbounds paramKd[ci_cmp,r,c] = prm_vxl[r,c] end # Above the main diagonal. for c = 2:Kf, r = 1:c-1 # column- and row-indices @inbounds paramKd[ci_cmp,r,c] = prm_vxl[r,c] end end # if Kf⏐₁ == 1 end # if Nprm_vxl ≥ 2 # If Nprm_vxl = 1, the voxel is filled with the same material, and there is # no need for subpixel smoothing. end # if !is_vxl_uniform! end # for ci_cmp = CI end # for nw = 1:Kf+1 return nothing end function is_vxl_uniform!(oind_vxl′::MArray{TP,Int,K,Zᴷ}, # scratch vector to store object indices inside voxel; TP = Tuple{2,...,2}, Zᴷ = 2^K pind_vxl′::MArray{TP,Int,K,Zᴷ}, # scratch vector to store material parameter indices inside voxel; TP = Tuple{2,...,2}, Zᴷ = 2^K ci_vxl′::Tuple2{CartesianIndex{K}}, oind_cmp′::AbsArr{ObjInd,K}, # object index array; does not change oind2shp::AbsVec{Shape{K,K²}}, # input map from oind to shape oind2pind::AbsVec{ParamInd} # input map from oind to pind ) where {TP,K,K²,Zᴷ} # Retrieve the elements assigned to voxel corners from 3D arrays. # # Unlike the rest of the code that is performed only where subpixel smoothing is # performed, the following for loop is performed at all grid points. Therefore, the # number of assignments to perform in the following for loop can easily reach # several millions even for a simple 3D problem. Simple assignment can # be surprisingly time-consuming when peformed such a large number of times. The # use of @inbounds helps reducing assignment time significantly. nc = 0 for ci = ci_vxl′[1]:ci_vxl′[2] nc += 1 @inbounds oind_vxl′[nc] = oind_cmp′[ci] end is_vxl_uniform = isuniform(oind_vxl′) # Even if the voxel is filled with multiple objects, those objects could be made of # the same material. Then, the voxel is still filled with uniform material if !is_vxl_uniform for nc = 1:Zᴷ @inbounds pind_vxl′[nc] = oind2pind[oind_vxl′[nc]] end # We could use Nprm_vxl calculated below instead of is_vxl_uniform: if # Nprm_vxl = 1, then is_vxl_uniform = true. However, calculating Nprm_vxl # requires calling sort8! and countdiff, which are costly when called for all # voxels. Therefore, by using is_vxl_uniform, we avoid calling those functions # when unnecessary. @inbounds is_vxl_uniform = isuniform(pind_vxl′) end # Note that when is_vxl_uniform = false at this point, pind_vxl′ is initialized. return is_vxl_uniform end # Calculate prm_vxl (averaged material parameter for Fw inside a voxel) when the voxel is # composed of two material parameters (Nprm_vxl = 2). This includes cases where the voxel # is composed of two material parameters but of ≥3 shape (i.e., ≥2 shapes in the voxel have # the same material). # # Below, XXX_cmp has size N, whereas XXX_cmp′ has size N+1 (and corresponds to voxel corners). # Variable names ending with vxl store quantities within a voxel. Primed names store values # at voxel corners; nonprimed names store values representing a voxel. function smooth_param_vxl(ci_vxl′::Tuple2{CartesianIndex{K}}, ind_c::MArray{TP,Int,K,Zᴷ}, # scratch vector to store corner indices inside voxel; TP = Tuple{2,...,2}, Zᴷ = 2^K n_diffp::Int, # last n where pind_vxl′[ind_c[n]] changed pind_vxl′::MArray{TP,Int,K,Zᴷ}, # scratch vector to store material parameter indices inside voxel; TP = Tuple{2,...,2}, Zᴷ = 2^K oind_vxl′::MArray{TP,Int,K,Zᴷ}, # scratch vector to store object indices inside voxel; TP = Tuple{2,...,2}, Zᴷ = 2^K oind_cmp′::AbsArr{ObjInd,K}, # object index array; does not change oind2shp::AbsVec{Shape{K,K²}}, # input map from oind to shape oind2pind::AbsVec{ParamInd}, # input map from oind to pind pind2matprm::AbsVec{S²ComplexF{Kf,Kf²}}, # map from pind to electric (magnetic) material parameters; Kf² = Kf^2 lcmp::NTuple{K,AbsVecReal}, # location of field components lcmp′::NTuple{K,AbsVecReal}, # location of voxel corners without transformation by boundary conditions σcmp::NTuple{K,AbsVecBool}, # false if on symmetry boundary ∆τcmp′::NTuple{K,AbsVecReal}, # amount of shift into domain by Bloch boundary conditions isfield˔shp::Bool=false # true if spaces where material parameters and shapes are defined are orthogonal complement of each other; false if they are the same ) where {TP,K,K²,Kf,Kf²,Zᴷ} # First, attempt to apply Kottke's subpixel smoothing algorithm. nout = @SVector zeros(K) rvol = 0.0 with2objs = true # will be updated, because there could be ≥3 objects in voxel even if Nprm_vxl = 2 @inbounds ind_c1, ind_c2 = ind_c[Zᴷ], ind_c[1]::Int # indices of corners of two different material parameters @inbounds oind_c1, oind_c2 = oind_vxl′[ind_c1], oind_vxl′[ind_c2] # The corners ind_c[n_diffp:8] are occupied with one material parameter because # ind_c is sorted for pind_vxl′. However, those corners can still be occupied with # ≥2 objects. In that case, the voxel is composed of ≥3 objects. # # Note that not having two objects inside the voxel can logically mean having either # one object or ≥3 objects, but because Nprm_vxl ≥ 2, with2objs = false only means # having ≥3 objects inside the voxel. for nc = Zᴷ-1:-1:n_diffp # n = 2^K-1 corresponds to oind_c1 and is omitted @inbounds (with2objs = oind_vxl′[ind_c[nc]]==oind_c1) || break end # At this point, with2objs = false means the corners ind_c[n_diffp:8] are composed # of ≥2 objects. Then, we already know the voxel has ≥3 objects because the corners # ind_c[1:n_diffp-1] have different materials than the corners ind_c[n_diffp:8] # because Nprm_vxl = 2 and therefore have a different object than those occupying # the corners ind_c[n_diffp:8]. Hence, if with2objs = false at this point, we don't # have to test further if the voxel has ≥3 objects: it already has. if with2objs # single object for corners ind_c[n_diffp:8] # The corners ind_c[1:n_diffp-1] are occupied with one material parameter # because ind_c is sorted for pind_vxl′, but those corners can still be occupied # with more than one object. In that case, the voxel is composed of more than # two objects. for nc = 2:n_diffp-1 # n = 1 corresponds oind_c2 and is omitted @inbounds (with2objs = oind_vxl′[ind_c[nc]]==oind_c2) || break end end # Find which of ind_c1 and ind_c2 is the index of the corner occupied by the # foreground object. # # When multiple objects have the same object index (because they are essentially the # same object across a periodic boundary), it doesn't matter which object to choose # as the foreground (or background) object, we translate points properly across the # domain (by ∆fg below) in order to evaluate the surface normal direction on the # correct object. (At least that is the intention, but this needs to be tested # after assigning the same object index is actually implemented.) if oind_c1 > oind_c2 # ind_c1 is foreground corner ind_fg = ind_c1 oind_fg, oind_bg = oind_c1, oind_c2 else # ind_c2 is foreground corner @assert oind_c1≠oind_c2 ind_fg = ind_c2 oind_fg, oind_bg = oind_c2, oind_c1 end @inbounds shp_fg, shp_bg = oind2shp[oind_fg], oind2shp[oind_bg] @inbounds prm_fg, prm_bg = pind2matprm[oind2pind[oind_fg]], pind2matprm[oind2pind[oind_bg]] # Find # - nout (outward normal of the foreground object), and # - rvol (volume fraction of the foreground object inside the voxel). ci_cmp = ci_vxl′[1] # CartesianIndex{K} σvxl = t_ind(σcmp, ci_cmp) if !with2objs # two material parameters but more than two objects in voxel # In this case, the interface between two materials is not defined by the # surface of a single object, so we estimate nout simply from the locations of # the corners occupied by the two materials. nout, rvol = kottke_input_simple(ind_c, n_diffp)::Tuple{SFloat{K},Float} else # two objects # When Nprm_vxl == Nobj_vxl == 2, different material parameters must correspond # to different objects. x₀ = t_ind(lcmp, ci_cmp) # SFloat{3}: location of center of smoothing voxel @inbounds lvxl′ = (t_ind(lcmp′,ci_vxl′[1]), t_ind(lcmp′,ci_vxl′[2])) @inbounds ci_fg = CartesianIndices(ntuple(x->2,Val(K)))[ind_fg] # subscritpt of corner ind_fg ci_1 = CartesianIndex(ntuple(x->1, Val(K))) ∆fg = t_ind(∆τcmp′, ci_cmp + ci_fg - ci_1) # SFloat{3}; nonzero if corner ind_fg is outside periodic boundary # See "Overall smoothing algorithm" above. nout, rvol = kottke_input_accurate(x₀, σvxl, lvxl′, ∆fg, shp_fg, shp_bg)::Tuple{SFloat{K},Float} end # if !with2objs if iszero(nout) # Give up Kottke's subpixel smoothing and take simple averaging. # # Previously this part was using either arithmetic or harmonic averaging, # depending on whether the field is on a primal or dual grid line. The # underlying assumption was that the primal voxels were filled uniformly with # a single material, which is a common case when the user puts box-shaped # objects in the domain. Then, the material interface coincides with a primal # grid plane, and the above choice of averaging scheme has some theoretical # support. # # However, now it is no longer possible to define each field as completely # primal or completely dual. For example, the Ez-field can be on the primal # x-normal grid plane and dual y-normal grid plane simultaneously. Therefore, # it is no longer possible to select the averaging scheme based on whether the # field is primal or dual, even if we assume each primal voxel is filled # uniformly. Therefore, we simply perform arithmetic averaging regardless of # the field type. prm_vxl = amean_param(ci_vxl′, oind_cmp′, oind2pind, pind2matprm)::S²ComplexF{Kf,Kf²} else # Perform Kottke's subpixel smoothing (defined in material.jl). prm_vxl = isfield˔shp ? kottke_avg_param(prm_fg, prm_bg, rvol) : # field is always parallel to shape boundaries kottke_avg_param(prm_fg, prm_bg, nout, rvol) end return prm_vxl end function kottke_input_simple(ind_c::MArray{TP,Int,K,Zᴷ}, n_diffp::Integer) where {TP,K,Zᴷ} nout = @SVector zeros(K) # nout for param_fg for n = n_diffp:Zᴷ # n = Zᴷ corresponds ind_c[Zᴷ] used for param_fg @inbounds nout += nout_vxl(Val(K))[ind_c[n]] end rvol = (Zᴷ+1-n_diffp) / Zᴷ return nout, rvol end function kottke_input_accurate(x₀::SFloat{K}, σvxl::SBool{K}, lvxl′::Tuple2{SFloat{K}}, ∆fg::SFloat{K}, shp_fg::Shape{K,K²}, shp_bg::Shape{K,K²}) where {K,K²} r₀, nout = surfpt_nearby(x₀ + ∆fg, shp_fg) r₀ -= ∆fg nout = σvxl .* nout # if voxel is across symmetry boundary plane, project nout to plane rvol = 0.0 # dummy value if !iszero(nout) rvol = volfrac(lvxl′, nout, r₀) end return nout, rvol end function amean_param(ci_vxl′::Tuple2{CartesianIndex{K}}, oind_cmp′::AbsArr{ObjInd,K}, # object index array; does not change oind2pind::AbsVec{ParamInd}, # input map from oind to pind pind2matprm::AbsVec{S²ComplexF{Kf,Kf²}} # map from pind to electric (magnetic) material parameters; Kf² = Kf^2 ) where {K,Kf,Kf²} p = S²ComplexF{Kf,Kf²}(ntuple(x->0, Val(Kf²))) for ci = ci_vxl′[1]:ci_vxl′[2] @inbounds pc = pind2matprm[oind2pind[oind_cmp′[ci]]] p += pc end return p / 2^K end # function hmean_param(ci_vxl′::Tuple2{CartesianIndex{K}}, # oind_cmp′::AbsArr{ObjInd,K}, # object index array; does not change # oind2pind::AbsVec{ParamInd}, # input map from oind to pind # pind2matprm::AbsVec{S²ComplexF{Kf,Kf²}} # map from pind to electric (magnetic) material parameters; Kf² = Kf^2 # ) where {K,Kf,Kf²} # p = S²ComplexF{Kf,Kf²}(ntuple(x->0, Val(Kf²))) # for ci = ci_vxl′[1]:ci_vxl′[2] # @inbounds pc = pind2matprm[oind2pind[oind_cmp′[ci]]] # p += inv(pc) # end # return inv(p / 2^K) # end
vsa=function(fun,par.mins,par.maxs,nrun){ par.range = par.maxs - par.mins k=length(par.range) M = array(runif(nrun*k),dim=c(nrun,k)) #CREATE U(0,1) n x k MATRIX for (i in 1:k) M[,i] = M[,i] * par.range[i] + par.mins[i] #TRANSFORM TO FIT RANGE OF EACH PAR #Now we are going to make a different input matrix, M2, the same way M2 = array(runif(nrun*k),dim=c(nrun,k)) #CREATE U(0,1) n x k MATRIX for (i in 1:k) M2[,i] = M2[,i] * par.range[i] + par.mins[i] #TRANSFORM TO FIT RANGE OF EACH PAR #Now we are going to make K different matrices, where in the jth matrix, all parameters are taken from M2 except parameter j is taken from M NJ.list = list() for (j in 1:k) { temp = M2 temp[,j] = M[,j] NJ.list[[j]] = temp } #Now, to compute the first-order effects (S) of factor J, we need to compute the values UJ, as discussed in class S = numeric(length=k) ST = numeric(length=k) y1 = y2 = y3 = numeric(length = nrun) for (i in 1:nrun) { y1[i] = fun(M[i,]) y2[i] = fun(M2[i,]) } #Now to compute the expected value (EY) and total variance (VY) of Y, for which we will use M2 EY=mean(y1) # VY=var(y3) #For computational reasons, we will estimate EY^2 using both M and M2 # EY2=mean(y1*y2) # EY2=EY^2 VY=sum(y1*y1)/(nrun-1)-EY^2 for (j in 1:k) { NJ = NJ.list[[j]] for (i in 1:nrun) y3[i] = fun(NJ[i,]) UJ = sum(y1*y3) / (nrun-1) #here everything but factor j is resampled UJ2 = sum(y2*y3) / (nrun-1) #here only factor j is resampled S[j] = (UJ - EY^2) / VY ST[j] = 1.0 - (UJ2 - EY^2) / VY } list(S,ST) }
# Input Optimization Algorithm # ReverseLearning, 2017 # Import dependencies import tensorflow as tf import numpy as np from time import time import pandas # Suppress warnings from warnings import filterwarnings filterwarnings("ignore") class IOA: def __init__(self, model, ins, tensorBoardPath = None): # The model to calculate outputs with self.model = model # Number of inputs self.ins = ins # Path to save tensorboard files (optional) self.tbPath = tensorBoardPath def clean(self, inp): """ Cleans an input TODO: Implememnt """ return inp def optimize(self, target, epochs = 1000, learn_rate = .01, debug = False, loss_function="absolute_distance", restrictions = {}, debug_interval = -1, error_tolerance = None, rangeGradientScalar = 10e10, gradientTolerance = 0.0, startPreset = [], returnDigest = False, digestInterval = 1, title = ""): """ Applies the Input Backprop Algorithm and returns an input with a target output Parameters: target : target value - "max" for maximum value - "min" for minimum value epochs : number of epochs to run (DEFAULT 1000) - (-1) runs until error is below learning rate loss_function : loss function to use (DEFAULT absolute distance) - "absolute_distance" : absolute difference between label and output - "cross_entropy" : cross entropy function - "quadratic_distance" : absolute distance squared debug : on / off debug mode restrictions : a dictionary of range and type restrictions for the optimal - Format: {index0 : restriction0, ..., indexN : restrictionN} - For constant value: restrictionX = value - For range: restricionX = (lower, upper) debug_interval : number of epochs between each debug statement - Use a negative number to only print ending statement error_tolerance : the largest acceptable error before auto-breaking (default is learn_rate) rangeGradientScalar : scalar for the gradients of the range-restricted vars """ # Start a tensorflow session sess = tf.Session() # Reason for breaking the loop (zero grad, finished epocs, etc.) breakReason = None # Initialize returnDigest digest = [] # Clean inputs # Ensure thar epochs is an integer epochs = int(epochs) # Ensure that learning rate is a float learn_rate = float(learn_rate) # If the target us a string (ie. max or min), make sure all lowercase and valid # Otherwise clean input if type(target) == str: target = target.lower() if target not in ["max", "min"]: raise ValueError("'{0}' is not a valid target".format(target)) else: try: target = self.clean(target) except: raise ValueError("'{0}' is not a valid target".format(target)) # If the error tolerance wasn't set, set it to the learning rate if error_tolerance == None: error_tolerance = learn_rate # Chck for valid starting preset if len(startPreset) != self.ins and startPreset != []: raise ValueError("{0} is not a valid starting preset".format(startPreset)) # Get and format the range-restricted restrictions rangeRestrictedIndexes = [] for i in restrictions.keys(): if type(restrictions[i]) in [list, tuple]: rangeRestrictedIndexes.append(i) # - DEFINE PARAMETERS - # Input # Start with mode set by startMode if startPreset == []: startOptimal = [[tf.Variable(0.0, name = "StartOptimal-{0}".format(i)) for i in range(self.ins)]] else: startOptimal = [[tf.Variable(float(i), name = "StartOptimal-{0}".format(i)) for i in startPreset]] # Apply constant restrictions to startOptimal and collect restricted vars rangeRestrictedVars = [] for k in restrictions.keys(): if type(restrictions[k]) in [float, int]: # Apply constant startOptimal[0][k] = tf.constant(float(restrictions[k])) elif type(restrictions[k]) in [list, tuple]: rangeRestrictedVars.append(startOptimal[0][k]) # Get the range-restriction vectors for startOptimal rangeRestrictedVectors = self._getRestrictionVectors(restrictions, startOptimal) # Tensor of the lowest gradients for use when checking if max / min / best is found lowGrad = self._getLowGrad(startOptimal, gradientTolerance) # Finalize optimal optimal = self._applyRestrictionVector(startOptimal, rangeRestrictedVectors) if self.tbPath != None: for i in range(len(optimal[0])): tf.summary.scalar("Optimal-{0}".format(i), optimal[0][i]) # Calculate output from the model (restrictions applied) out = self.model(optimal) if self.tbPath != None: tf.summary.histogram("Output", out) # Target label # If the target is max or min, don't set label if target in ["max", "min"]: label = None else: label = tf.constant(target) # Loss function loss = self._getLossFunction(loss_function, target, label, out) if self.tbPath != None: tf.summary.histogram("Loss", loss) # Get variables (exclude constants) vlist = self._getVarList(startOptimal) # End if there are no variables to optimize if len(vlist) == 0: final = self._evalOptimal(optimal, sess) sess.close() return final # Create an optimizer of the given learning rate optimizer = tf.train.ProximalGradientDescentOptimizer(learn_rate) # Get the gradients from the loss function for each variable gradients = optimizer.compute_gradients(loss, var_list = vlist) if self.tbPath != None: tf.summary.histogram("OriginalGradients", gradients) # Raise range-restricted variables newGrads = [self._raiseGrad(g, rangeGradientScalar) if g[1] in rangeRestrictedVars else g for g in gradients] if self.tbPath != None: tf.summary.histogram("NewGradients", newGrads) # Gradient application applyNewGrads = optimizer.apply_gradients(newGrads, name = "ApplyGradients") # Get the absolute error if target in ["max", "min"]: absoluteError = tf.constant(0.0) else: absoluteError = tf.abs(tf.subtract(label, out), name = "AbsoluteError") # Summarize the error if self.tbPath != None: tf.summary.scalar("error", absoluteError) # Merge and create FileWriter for TensorBoard if self.tbPath != None: mergeTensorBoard = tf.summary.merge_all() writer = tf.summary.FileWriter(self.tbPath, sess.graph) # Initialize the computation graph sess.run(tf.global_variables_initializer()) # - TRAIN - # A counter for counting epochs counter = 0 # If debug is on, print intial debug report if debug and debug_interval > 0: self._printDebugStatus(sess, epochs = counter, startOptimal = startOptimal, optimal = optimal) # The main traing loop while True: # Start timer (for DEBUG profiling) time0 = time() # Break if error is 0 or within learning rate of zero absoluteErrorEvaluated = absoluteError.eval(session = sess) # If absolute error is a single number, put it in a list if type(absoluteErrorEvaluated) not in [list, tuple, np.ndarray]: absoluteErrorEvaluated = [absoluteErrorEvaluated] if sum(absoluteErrorEvaluated) <= error_tolerance \ and target not in ["max", "min"]: breakReason = "Beat Error" break # Break if gradients are all zero gradCheck = self._checkGradients(newGrads, lowGrad, sess) if gradCheck: breakReason = gradCheck break # Break if epochs limit reached if counter >= epochs and epochs != -1: breakReason = "Epoch Limit Reached" break # Apply training step to find optimal sess.run(applyNewGrads) # Increment counter counter += 1 # Write summaries if self.tbPath != None: writer.add_summary(sess.run(mergeTensorBoard), counter) # Debug printing if counter % debug_interval == 0 and debug and debug_interval > 0: # Dont show error for max and min if target == "max" or target == "min": absErrorDebug = None else: absErrorDebug = absoluteErrorEvaluated self._printDebugStatus(sess, epochs = counter, startOptimal = startOptimal, optimal = optimal, absoluteError = absErrorDebug, timer = time() - time0, gradients = newGrads) if counter % digestInterval == 0: if target == "max" or target == "min": absErrorDebug = None else: absErrorDebug = absoluteErrorEvaluated # Add to digest digest = self._addDigest(digest, sess, epochs = counter, startOptimal = startOptimal, optimal = optimal, absoluteError = absErrorDebug, timer = time() - time0, gradients = newGrads) # Print final digest if debug: # Print title print("\n{0}".format(title)) # Print final optimal (remove list endings if a single number) evalOpt = [i.eval(session = sess) for i in optimal[0]] if len(evalOpt) > 1: print("OPTIMAL INPUT :: {0}".format(evalOpt)) else: print("OPTIMAL INPUT :: {0}".format(evalOpt[0])) # Print the calculated output (remove list endings if a single number) calcOut = self.model(optimal).eval(session = sess) if type(calcOut) in [list, tuple, np.ndarray, np.array]: if len(calcOut) > 1: print("CALCULATED OUT :: {0}".format(calcOut[0])) else: if type(calcOut[0]) in [list, tuple, np.ndarray, np.array]: print("CALCULATED OUT :: {0}".format(calcOut[0][0])) else: print("CALCULATED OUT :: {0}".format(calcOut[0])) else: print("CALCULATED OUT :: {0}".format(calcOut)) # Print target if label != None: print("TARGET OUT :: {0}".format(label.eval(session = sess))) err = absoluteError.eval(session=sess) if type(err) in [list, tuple, np.ndarray]: if len(err) > 1: print("ERROR :: {0}".format(err)) print("TOTAL ERROR :: {0}".format(sum(err))) else: print("ERROR :: {0}".format(err[0])) elif target in ["min", "max"]: print("TARGET OUT :: {0}".format(target)) else: print("ERROR :: {0}".format(err)) print("EPOCHS :: {0} ({1})".format(counter, breakReason)) # Don't repeat final data point it digest if counter % debug_interval != 0: # Dont show error for max and min if target == "max" or target == "min": absErrorDebug = None else: absErrorDebug = absoluteErrorEvaluated # Add to digest digest = self._addDigest(digest, sess, epochs=counter, startOptimal=startOptimal, optimal=optimal, absoluteError=absErrorDebug, timer=time() - time0, gradients=newGrads) # Finalize the optimal solution final = self._evalOptimal(optimal, sess) # Close the session, free the memory sess.close() # Return the final solution if returnDigest: return (final, digest) else: return final def feed(self, input_vector): return self.model(input_vector) def _getRestrictionVectors(self, restrictions, vars): rVector = [[], []] for i in range(len(vars[0])): if i in restrictions.keys(): if type(restrictions[i]) in [list, tuple]: rVector[0].append(tf.cast(restrictions[i][0], tf.float32)) rVector[1].append(tf.cast(restrictions[i][1], tf.float32)) else: rVector[0].append(None) rVector[1].append(None) return rVector def _applyRestrictionVector(self, inputs, restrictVector): # Restriction reshaping function def restrict(x, b, t): q = tf.nn.sigmoid(x) w = tf.multiply(q, tf.cast(tf.subtract(t, b), tf.float32)) return tf.add(w, b, name = "restricted") optimal = [[]] for i in range(len(inputs[0])): if len(restrictVector[0]) != 0 and restrictVector[0][i] != None: optimal[0].append(restrict(inputs[0][i], restrictVector[0][i], restrictVector[1][i])) else: optimal[0].append(inputs[0][i]) return optimal def _raiseGrad(self, grad, scaler): """ Scale a gradient Parameter: grad : (gradient, variable) scaler : scaler to raise gradient by """ return (tf.multiply(grad[0], scaler), grad[1]) def _getLossFunction(self, requested, target, label, out): # Use variations / throw errors for max and min if requested == "cross_entropy": if target == "max": raise ValueError("Target 'max' and 'cross_entropy' loss are not compatible") elif target == "min": raise ValueError("Target 'min' and 'cross_entropy' loss are not compatible") else: return tf.reduce_mean(-tf.reduce_sum(label * tf.log(out), reduction_indices=[1])) elif requested == "quadratic": if target == "max": raise ValueError("Target 'max' and 'quadratic' loss are not compatible") elif target == "min": raise ValueError("Target 'min' and 'quadratic' loss are not compatible") else: return tf.reduce_sum(tf.pow(label - out, 2)) else: if target == "max": return tf.multiply(-1.0, out) elif target == "min": return out else: return tf.abs(label - out) def _getVarList(self, vector): # Start list vlist = [] # Iterate through the given vector for i in vector: # If it's another list, iterate through one more dimension if type(i) in [list, tuple]: for j in i: # If it's a variable, add it to the list if type(j) == tf.Variable: vlist.append(j) else: # If it's a variable, add it to the list if type(i) == tf.Variable: vlist.append(i) return vlist def _printDebugStatus(self, session, epochs = None, startOptimal = None, optimal = None, absoluteError = None, timer = None, gradients = None): """Prints the debug information during training""" if epochs != None: print("@ Epoch {0}".format(epochs)) if startOptimal != None: # Evaluate optimal op = [] for i in startOptimal[0]: op.append(i.eval(session = session)) if len(op) == 1: print("Value :: {0}".format(op[0])) else: print("Value :: {0}".format(op)) if optimal != None: q = [] for i in optimal[0]: q.append(i.eval(session = session)) if len(q) == 1: print("Restricted :: {0}".format(q[0])) else: print("Restricted :: {0}".format(q)) fed = self.model(optimal).eval(session = session) if type(fed) in [list, tuple, np.ndarray]: print("Evaluated :: {0}".format(fed[0])) else: print("Evaluated :: {0}".format(fed)) if absoluteError != None: if type(absoluteError) in [list, tuple, np.array, np.ndarray]: print("Error :: {0}".format(absoluteError[0])) if len(absoluteError) != 1: # If the error is only one number then total error is not needed print("Total Error :: {0}".format( sum(absoluteError))) else: print("Error :: {0}".format(absoluteError)) if timer != None: print("Time :: {0}".format(timer)) if gradients != None: print("Gradients :: {0}".format([g[0].eval(session = session) for g in gradients])) print() def _checkGradients(self, gradients, checkAgainst, sess): # Get gradients grads = [abs(p[0]) for p in gradients] # Check for infinite or nan grads for g in grads: if sess.run(tf.is_nan(g)): return "NaN Gradients" elif sess.run(tf.is_inf(g)): return "Inf Gradients" # Check for low grads areSame = sess.run(tf.less_equal(grads, checkAgainst)) # Check each truth value, add to counter if true low = 0 for g in areSame: if g: low += 1 # If all are the same, return true, else false if low == len(grads): return "Low Gradients" else: return False def _getLowGrad(self, optimal, gradTolerance): """Creates a list of the lowest allowed gradient for every variable in optimal for lowest-grad checking""" zs = [] for i in optimal[0]: if type(i) == tf.Variable: zs.append(tf.constant(gradTolerance)) return zs def _evalOptimal(self, optimal, session): o = [] for i in optimal[0]: o.append(i.eval(session = session)) return o def _addDigest(self, current, session, epochs = None, startOptimal = None, optimal = None, absoluteError = None, timer = None, gradients = None): # Save dictionary newDict = {} if epochs != None: newDict["epochs"] = epochs if startOptimal != None: # Evaluate optimal op = [] for i in startOptimal[0]: op.append(i.eval(session=session)) if len(op) == 1: newDict["optimal"] = op[0] else: newDict["optimal"] = op if optimal != None: # Restricted q = [[]] for i in optimal[0]: q[0].append(i.eval(session = session)) if len(q) == 1: newDict["restricted"] = q[0] else: newDict["restricted"] = q # Evaluated fed = self.model(q).eval(session = session) if type(fed) in [list, tuple, np.ndarray]: newDict["output"] = fed[0] else: newDict["output"] = fed if absoluteError != None: if type(absoluteError) in [list, tuple, np.array, np.ndarray]: sumAbsError = sum(absoluteError) if type(sumAbsError) in [list, tuple, np.ndarray]: newDict["error"] = sumAbsError[0] else: newDict["error"] = sumAbsError else: newDict["error"] = absoluteError if timer != None: newDict["time"] = timer if gradients != None: newDict["gradients"] = [g[0].eval(session = session) for g in gradients] # Finalized current.append(newDict) return current def saveDigests(digests, filename): df = pandas.DataFrame(digests) df.to_csv(filename, sep = "\t") def loadDigests(filename): df = pandas.read_csv(filename, sep = "\t") cNames = list(df) for cn in cNames: if "Unnamed" in cn: df = df.drop(cn, axis=1) return df # ------- EXAMPLE ------- class Models: def f1(self, x): return tf.reduce_sum(x) def f2(self, x): return tf.add(tf.add(-tf.square(x), tf.multiply(4.0, x)), 8.0) def f3(self, x): """Not differentiable for x <= 0""" return tf.subtract(tf.pow(tf.add(x, 4.0), tf.div(1.0, 2.0)), 3.0) def test(): # Example model a = Models() # Input Optimization I = IOA(a.f2, 1) final, digest = I.optimize("max", epochs = 100, learn_rate = .1, error_tolerance = .2, restrictions = {}, debug = True, debug_interval = -1, rangeGradientScalar = 1e11, gradientTolerance = 5e-7, startPreset = [], returnDigest = True, digestInterval = 1) saveDigests(digest, "trial.ioa") d = loadDigests("trial.ioa") if __name__ == "__main__": test()
module BioCore.Sequence import Data.List import Data.Strings %default total --Qual-- public export data Qual = ||| Quality data associate with sequence data. UnQual Int public export Show Qual where show (UnQual x) = show x public export Eq Qual where (==) (UnQual x) (UnQual y) = True (==) _ _ = False public export Ord Qual where compare (UnQual x) (UnQual y) = compare x y public export Num Qual where fromInteger = UnQual . fromInteger public export extractUnQual : Qual -> Int extractUnQual (UnQual unQual) = unQual -------- --Offset-- public export data Offset = ||| The offset in the sequence data. UnOff Int public export Show Offset where show (UnOff x) = show x public export Eq Offset where (==) (UnOff x) (UnOff y) = True (==) _ _ = False public export Ord Offset where compare (UnOff x) (UnOff y) = compare x y public export Num Offset where fromInteger = UnOff . fromInteger public export extractUnOff : Offset -> Int extractUnOff (UnOff unOff) = unOff ---------- --SeqData-- public export data SeqData = ||| Sequence data are List String of ASCII characters. UnSD String public export Show SeqData where show (UnSD x) = show x public export Eq SeqData where (==) (UnSD x) (UnSD y) = True (==) _ _ = False public export Ord SeqData where compare (UnSD x) (UnSD y) = compare x y public export extractUnSD : SeqData -> String extractUnSD (UnSD unSD) = unSD ----------- --SeqLabel-- public export data SeqLabel = ||| Sequence labels are List String of ASCII characters. UnSL String public export Show SeqLabel where show (UnSL x) = show x public export Eq SeqLabel where (==) (UnSL x) (UnSL y) = True (==) _ _ = False public export Ord SeqLabel where compare (UnSL x) (UnSL y) = compare x y public export extractUnSL : SeqLabel -> String extractUnSL (UnSL unSL) = unSL ------------ --QualData-- public export data QualData = ||| The quality data associated with the sequence data. UnQD String public export Show QualData where show (UnQD x) = show x public export Eq QualData where (==) (UnQD x) (UnQD y) = True (==) _ _ = False public export Ord QualData where compare (UnQD x) (UnQD y) = compare x y public export extractUnQD : QualData -> String extractUnQD (UnQD unQD) = unQD ------------ public export toFastaSeqData : SeqLabel -> SeqData -> String toFastaSeqData (UnSL seqlabel) (UnSD seqdata) = ">" ++ seqlabel ++ "\n" ++ (wrapSeqData seqdata (unpack seqdata)) where wrapSeqData : String -> List Char -> String wrapSeqData _ [] = "" wrapSeqData s (_::ss') = if isNil (unpack s) then "" else let (ln,rest) = splitAt 60 (unpack s) in (pack ln) ++ "\n" ++ (wrapSeqData (pack rest) ss') public export toFastaQual : SeqLabel -> QualData -> String toFastaQual (UnSL seqlabel) (UnQD qualdata) = ">" ++ seqlabel ++ "\n" ++ (wrapqualdata qualdata (unpack qualdata)) where wrapqualdata : String -> List Char -> String wrapqualdata _ [] = "" wrapqualdata s (_::ss') = if isNil (unpack s) then "" else let (ln,rest) = splitAt 20 (unpack s) in (pack ln) ++ "\n" ++ (wrapqualdata (pack rest) ss')
Why is it Important to See a Dentist in Weatherford While You’re Pregnant? Congratulations! You’re having a baby! This time in your life can be exciting and overwhelming all at once. It’s important to take good care of yourself during your pregnancy and regularly visit all of your healthcare practitioners. Believe it or not, it’s especially important to visit your dentist in Weatherford throughout your pregnancy. Here are the reasons why. Because of the many hormone changes that take place throughout pregnancy, you are more susceptible to periodontal disease, or gum disease during this time. This may not seem like too big a deal, however periodontal disease can lead to tooth, tissue, and bone loss if it’s not properly managed. A condition known as pregnancy gingivitis can occur, and this is actually the first stage of gum disease. If you notice that your gums are red and swollen, or bleed when you brush your dentist may recommend extra cleaning appointments during your pregnancy to help you control the gingivitis. Excellent home care, with daily brushing and flossing is also crucial during this time. If you suffer from morning sickness and vomiting, your dentist can recommend a mouth rinse to help protect your teeth from harmful stomach acids. As you know, your nutrition is very important to you and your baby during pregnancy, did you know however, that your nutrition could affect your baby’s developing teeth? It’s true! Your baby’s teeth will begin to develop around the third to sixth month of your pregnancy and you need lots of vitamin A, C, and D as well as protein and calcium to help your child’s teeth develop properly. You will need to begin oral care for your child as well as soon as their first teeth erupt. Let your dentist know that you’re pregnant and exactly what trimester you’re in. your dentist may want to wait on taking x-rays or performing dental treatment until you’re further along in your pregnancy. If you experience dental pain or an emergency contact your dentist right away. There are a lot of things that can be done for dental pain during your pregnancy even if you don’t have treatment done immediately. Remember, the earlier you contact us if you’re experiencing dental pain, the faster we can diagnose your situation and get you feeling comfortable again. Dr. Deborah Romack and Dr. Garrett Mulkey are your premiere family dentists in Aledo, TX. At Cosmetic & Family Dentistry our team is here to support you through your pregnancy and beyond. We welcome patients of all ages to our practice and we look forward to helping you welcome your little one and serving their dental needs as well when the time comes! by: tntadmin at April 1, 2016 . Comments Off on Why is it Important to See a Dentist in Weatherford While You’re Pregnant?
Formal statement is: lemma emeasure_compl: "s \<in> sets M \<Longrightarrow> emeasure M s \<noteq> \<infinity> \<Longrightarrow> emeasure M (space M - s) = emeasure M (space M) - emeasure M s" Informal statement is: If $s$ is a measurable set and $s$ has finite measure, then the measure of the complement of $s$ is the total measure of the space minus the measure of $s$.
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import set_theory.cardinal_ordinal /-! # Cardinality of continuum In this file we define `cardinal.continuum` (notation: `𝔠`, localized in `cardinal`) to be `2 ^ ω`. We also prove some `simp` lemmas about cardinal arithmetic involving `𝔠`. ## Notation - `𝔠` : notation for `cardinal.continuum` in locale `cardinal`. -/ namespace cardinal universes u v open_locale cardinal /-- Cardinality of continuum. -/ def continuum : cardinal.{u} := 2 ^ omega.{u} localized "notation `𝔠` := cardinal.continuum" in cardinal @[simp] lemma two_power_omega : (2 ^ omega.{u} : cardinal.{u}) = 𝔠 := rfl @[simp] lemma lift_continuum : lift.{v} continuum.{u} = 𝔠 := by rw [← two_power_omega, lift_two_power, lift_omega, two_power_omega] /-! ### Inequalities -/ lemma omega_lt_continuum : ω < 𝔠 := cantor ω lemma omega_le_continuum : ω ≤ 𝔠 := omega_lt_continuum.le lemma nat_lt_continuum (n : ℕ) : ↑n < 𝔠 := (nat_lt_omega n).trans omega_lt_continuum lemma mk_set_nat : #(set ℕ) = 𝔠 := by simp lemma continuum_pos : 0 < 𝔠 := nat_lt_continuum 0 lemma continuum_ne_zero : 𝔠 ≠ 0 := continuum_pos.ne' lemma aleph_one_le_continuum : aleph 1 ≤ 𝔠 := by { rw ← succ_omega, exact succ_le.2 omega_lt_continuum } /-! ### Addition -/ @[simp] lemma omega_add_continuum : ω + 𝔠 = 𝔠 := add_eq_right omega_le_continuum omega_le_continuum @[simp] lemma continuum_add_omega : 𝔠 + ω = 𝔠 := (add_comm _ _).trans omega_add_continuum @[simp] lemma continuum_add_self : 𝔠 + 𝔠 = 𝔠 := add_eq_right omega_le_continuum le_rfl @[simp] lemma nat_add_continuum (n : ℕ) : ↑n + 𝔠 = 𝔠 := add_eq_right omega_le_continuum (nat_lt_continuum n).le @[simp] lemma continuum_add_nat (n : ℕ) : 𝔠 + n = 𝔠 := (add_comm _ _).trans (nat_add_continuum n) /-! ### Multiplication -/ @[simp] lemma continuum_mul_self : 𝔠 * 𝔠 = 𝔠 := mul_eq_left omega_le_continuum le_rfl continuum_ne_zero @[simp] lemma continuum_mul_omega : 𝔠 * ω = 𝔠 := mul_eq_left omega_le_continuum omega_le_continuum omega_ne_zero @[simp] lemma omega_mul_continuum : ω * 𝔠 = 𝔠 := (mul_comm _ _).trans continuum_mul_omega @[simp] lemma nat_mul_continuum {n : ℕ} (hn : n ≠ 0) : ↑n * 𝔠 = 𝔠 := mul_eq_right omega_le_continuum (nat_lt_continuum n).le (nat.cast_ne_zero.2 hn) @[simp] lemma continuum_mul_nat {n : ℕ} (hn : n ≠ 0) : 𝔠 * n = 𝔠 := (mul_comm _ _).trans (nat_mul_continuum hn) /-! ### Power -/ @[simp] lemma omega_power_omega : omega.{u} ^ omega.{u} = 𝔠 := power_self_eq le_rfl @[simp] lemma nat_power_omega {n : ℕ} (hn : 2 ≤ n) : (n ^ omega.{u} : cardinal.{u}) = 𝔠 := nat_power_eq le_rfl hn @[simp] lemma continuum_power_omega : continuum.{u} ^ omega.{u} = 𝔠 := by rw [← two_power_omega, ← power_mul, mul_eq_left le_rfl le_rfl omega_ne_zero] end cardinal
#include <malloc.h> #include <math.h> #include <memory.h> #include <stdio.h> #include <string.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_matrix_double.h> #include "tc_mat.h" struct tc_mat *tc_mat_ctr(uint32_t nr_, uint32_t nc_) { struct tc_mat *A = (struct tc_mat *) malloc(sizeof(struct tc_mat)); memset(A, 0, sizeof(struct tc_mat)); tc_mat_resize(A, nr_, nc_); return A; } void tc_mat_dtr(struct tc_mat *A) { if (!A) return; tc_mat_clear(A); free(A); } void tc_mat_clear(struct tc_mat *A) { if (!A) return; if (A->a) { for(uint32_t r=0; r < A->nr; r++) if (A->a[r]) free(A->a[r]); free(A->a); } A->a = NULL; A->nr = 0; A->nc = 0; } void tc_mat_print(const struct tc_mat *A) { if (!A) return; for(uint32_t i=0; i < A->nr; i++) { for (uint32_t j=0; j < A->nc; j++) printf(" %13.10f", A->a[i][j]); printf("\n"); } } void tc_mat_resize(struct tc_mat *A, uint32_t nr_, uint32_t nc_) { if ((A->nr == nr_) && (A->nc == nc_)) return; tc_mat_clear(A); A->nr = nr_; A->nc = nc_; A->a = (double **) malloc(sizeof(double *) * nr_); for(uint32_t r=0; r < nr_; r++) A->a[r] = (double *) malloc(sizeof(double) * nc_); } void tc_mat_copy(struct tc_mat *B, const struct tc_mat *A) { if (A == B) return; if ((B->nr != A->nr) || (B->nc != A->nc)) tc_mat_resize(B, A->nr, A->nc); for(uint32_t i=0; i < A->nr; i++) for(uint32_t j=0; j < A->nc; j++) B->a[i][j] = A->a[i][j]; } void tc_mat_identity(struct tc_mat *A) { for(uint32_t i=0; i < A->nr; i++) for(uint32_t j=0; j < A->nc; j++) A->a[i][j] = (i==j)? 1.0: 0.0; } void tc_mat_transpose(struct tc_mat *B, const struct tc_mat *A) { if (A == B) { struct tc_mat *b = tc_mat_ctr(A->nc, A->nr); for(uint32_t i=0; i < A->nr; i++) for(uint32_t j=0; j < A->nc; j++) b->a[j][i] = A->a[i][j]; tc_mat_copy(B, b); tc_mat_dtr(b); return; } if ((B->nr != A->nc) || (B->nc != A->nr)) tc_mat_resize(B, A->nc, A->nr); for(uint32_t i=0; i < A->nr; i++) for(uint32_t j=0; j < A->nc; j++) B->a[j][i] = A->a[i][j]; } int tc_mat_add(struct tc_mat *C, const struct tc_mat *A, const struct tc_mat *B) { if (!C || !A || !B || (A->nr != B->nr) || (A->nc != B->nc)) return -1; if ((C->nr != A->nr) || (C->nc != A->nc)) tc_mat_resize(C, A->nr, B->nc); for(uint32_t i=0; i < C->nr; i++) for(uint32_t j=0; j < C->nc; j++) C->a[i][j] = A->a[i][j] + B->a[i][j]; return 0; } int tc_mat_mult(struct tc_mat *C, const struct tc_mat *A, const struct tc_mat *B) { if (!C || !A || !B || (A->nc != B->nr)) return -1; if ((C == A) || (C == B)) { struct tc_mat *c = tc_mat_ctr(A->nr, B->nr); tc_mat_mult(c, A, B); tc_mat_copy(C, c); tc_mat_dtr(c); return 0; } if ((C->nc != B->nc) || (C->nr != A->nr)) tc_mat_resize(C, A->nr, B->nc); for(uint32_t i=0; i < C->nr; i++) { for(uint32_t j=0; j < C->nc; j++) { C->a[i][j] = 0.0; for(uint32_t k=0; k < A->nc; k++) C->a[i][j] += A->a[i][k] * B->a[k][j]; } } return 0; } int tc_mat_mult_scalar(struct tc_mat *C, double a, const struct tc_mat *B) { if (!C || !B) return -1; if ((C->nr != B->nr) || (C->nc != B->nc)) tc_mat_resize(C, B->nr, B->nc); for(uint32_t i=0; i < C->nr; i++) for(uint32_t j=0; j < C->nc; j++) C->a[i][j] = a * B->a[i][j]; return 0; } /* Householder Reduction to Bidiagonal Form * Input m x n matrix A * Output: m x n matrix U, products of Householder matrices * m x n matrix B, bidiagonal * m x n matrix V, products of Householder matrices * such that A = U B V^T * * A Householder matrix P is a reflection transformation of the form * I - tau u u^T where tau = 2 / (u^T u). P is orthonormal since * P^T P = (I - tau u u^T)^T (I - tau u u^T) * = (I - tau u u^T) (I - tau u u^T) * = I - 2 tau u u^T + tau^2 u (u^T u) u^T * = I - 2 tau u u^T + tau^2 u (2 / tau) u^T * = I * Products of orthonomal matrices are orthonormal so U and V will be * orthonormal. * * B is constructed via the algorithm * 1. B <-- A * 2. U <-- I m x n * 3. V <-- I n x n * 4. For k = 1, ..., n * a. construct a Householder matrix P such that * i. P is the identity on the first k-1 components, and * ii. the k-th column of P B is zero below the diagonal. * b. B <--- P B * c. U <--- U P * d. If k < n - 2, increment k and repeat steps a-c for the * operation from the right (the row of B P will be zero * to the right of the superdiagonal). * * Step 4a(i) is equivalent to setting the first k-1 components of u * to be zero. Let v be the k-th column of P B. Since * P v = (I - tau u u^T) v * = (I - tau u u^T) v * = v - tau (u^T v) u (Eq. 1) * we have that step 4a(ii) is equivalent to setting u to be an appropriate * scalar multiple of v for all components above k. The previous steps * would have zeroed out the first k-2 components of v. Let * b^2 = Sum_{i>=k} (v_i)^2 * and choose the sign of b to ensure s = v_k - b is nonzero. Set u = v/s * on all components larger than k and set u_k = 1. Then * tau = 2 / (u^T u) * = 2 / (1 + (b^2 - (v_k)^2) / s^2 ) * = (2 s) / (s + (b^2 - (v_k)^2) / s) * = (2 s) / (s - (b + v_k)) * = (2 s) / ((v_k - b) - (b + v_k)) * = (2 s) / (- 2 b) * = -s / b * This leads to the zeroing out of the lower components of P v since * u^T v = v_k + (b^2 - (v_k)^2) / s * = v_k - (b + v_k) * = b * meaning that Eq 1 is simply * P v = v - (-s/b) (b) u * = v + s u * and so P v is zero on all components larger than k. * * Side note on efficiency 1 (not implemented): * Step c produces U and V as products of Housholder matrices. The actual * computation of these products is not the most computationally efficient * method. A Housholder matrix acts on a vector v as * P v = (I - tau u u^T) v * = v - tau u (v^T u)^T (Eq. 2) * Thus if we've recorded all u's and tau's, we can find U, the product of * all the P's, by sequentially applying Eq 2 to the components e1, e2, etc. * * Side note on efficiency 2 (not implemented): * Since each iteration of B leads to known places where its terms have zeros, * all matrix multiplications involving B can be restricted to the nonzero * terms. * * Side note on efficiency 3 (not implemented): * Since the u's have more zeros in each iteration, the collection of u's * can be stored in the original matrix A (and hence B) so long as the * Side note on efficiency #2 was implemented. */ int tc_mat_bidiag_decomp( const struct tc_mat *A, struct tc_mat *U, struct tc_mat *B, struct tc_mat *V) { if (!A || !U || !B || !V) return -1; if ((U->nr != A->nr) || (U->nc != A->nr)) tc_mat_resize(U, A->nr, A->nr); if ((V->nr != A->nc) || (V->nc != A->nc)) tc_mat_resize(V, A->nc, A->nc); if ((B->nr != A->nr) || (B->nc != A->nc)) tc_mat_resize(B, A->nr, A->nc); tc_mat_copy(B, A); tc_mat_identity(U); tc_mat_identity(V); struct tc_mat *Ic = tc_mat_ctr(A->nc, A->nc); tc_mat_identity(Ic); struct tc_mat *Ir = tc_mat_ctr(A->nr, A->nr); tc_mat_identity(Ir); struct tc_mat *u = tc_mat_ctr(0, 0); struct tc_mat *uT = tc_mat_ctr(0, 0); struct tc_mat *u_uT = tc_mat_ctr(0, 0); struct tc_mat *P = tc_mat_ctr(0, 0); for(uint32_t k=0; (k < A->nc) && (k+1 < A->nr); k++) { /* from the left */ double b_k = B->a[k][k]; double b = 0.0; for(uint32_t i=k; i < A->nr; i++) b += B->a[i][k] * B->a[i][k]; if (b != 0.0) { /* if b = 0, there's nothing to do */ b = ((b_k > 0)? -1.0: 1.0) * sqrt(b); double s = b_k - b; double tau = - s / b; tc_mat_resize(u, A->nr, 1); for(uint32_t i=0; i < A->nr; i++) u->a[i][0] = (i > k)? B->a[i][k]/s: ((i==k)? 1.0: 0.0); /* P = I - tau u u^T */ tc_mat_transpose(uT, u); tc_mat_mult(u_uT, u, uT); tc_mat_mult_scalar(P, -tau, u_uT); tc_mat_add(P, Ir, P); /* U B = (U P) (P B) */ tc_mat_mult(B, P, B); tc_mat_mult(U, U, P); } if (k + 2 < A->nc) { /* from the right */ double b_k = B->a[k][k+1]; double b = 0.0; for(uint32_t j=k+1; j < A->nc; j++) b += B->a[k][j] * B->a[k][j]; b = ((b_k > 0)? -1.0: 1.0) * sqrt(b); if (b != 0.0) { /* if b = 0, there's nothing to do */ double s = b_k - b; double tau = - s / b; tc_mat_resize(u, A->nc, 1); for(uint32_t i=0; i < A->nc; i++) u->a[i][0] = (i > k+1)? B->a[k][i]/s: ((i==k+1)? 1.0: 0.0); /* P = I - tau u u^T */ tc_mat_transpose(uT, u); tc_mat_mult(u_uT, u, uT); tc_mat_mult_scalar(P, -tau, u_uT); tc_mat_add(P, Ic, P); /* B V = (B P) (P V) */ tc_mat_mult(B, B, P); tc_mat_mult(V, P, V); } } } tc_mat_dtr(P); tc_mat_dtr(u); tc_mat_dtr(uT); tc_mat_dtr(u_uT); tc_mat_dtr(Ic); tc_mat_dtr(Ir); return 0; } /* tc_mat_eigenvalues * only implmented for 2x2 matrices * Input 2 x 2 matrix A * Output: 2 x 1 matrix E of eigenvalues * * If we set A = [ a b ] * [ c d ] * Then * 0 = det(A - x I) * = (a - x)(d - x) - bc * = x^2 - (a + d) x + (ad - bc) */ int tc_mat_eigenvalues(struct tc_mat *E, const struct tc_mat *A) { if (!A || !E) return -1; if ((A->nr != 2) || (A->nc != 2)) return -1; if (E->nr != A->nr) tc_mat_resize(E, A->nr, 1); double a = A->a[0][0]; double b = A->a[1][0]; double c = A->a[0][1]; double d = A->a[1][1]; double ad2 = (a + d)/2.0; double det = ad2*ad2 - (a*d - b*c); double s = (det <= 0.0)? 0.0: sqrt(det); E->a[0][0] = ad2 + s; E->a[1][0] = ad2 - s; return 0; } /* Wilkinson Shift * Input: m x 2 matrix A * Output: the Wilkinson shift * * ei= trailing 2x2 matrix of D^T D */ double tc_mat_wilkinson_shift(const struct tc_mat *A) { if (!A) return 0.0; if (A->nc != 2) return 0.0; struct tc_mat *AT = tc_mat_ctr(2, A->nr); tc_mat_transpose(AT, A); struct tc_mat *AT_A = tc_mat_ctr(2, 2); tc_mat_mult(AT_A, AT, A); struct tc_mat *E = tc_mat_ctr(2, 1); tc_mat_eigenvalues(E, AT_A); double l0 = E->a[0][0]; double l1 = E->a[1][0]; double t22 = AT_A->a[1][1]; tc_mat_dtr(AT); tc_mat_dtr(AT_A); tc_mat_dtr(E); return (fabs(l0 - t22) < fabs(l1 - t22))? l0: l1; } int tc_mat_svd( const struct tc_mat *A, struct tc_mat *U, struct tc_mat *D, struct tc_mat *V) { if (!U || !D || !V || !A) return -1; if ((U->nr != A->nr) || (U->nc != A->nc)) tc_mat_resize(U, A->nr, A->nc); if ((V->nr != A->nc) || (V->nc != A->nc)) tc_mat_resize(V, A->nc, A->nc); if ((D->nr != A->nc) || (D->nc != A->nc)) tc_mat_resize(D, A->nc, A->nc); if (A->nr < A->nc) return -2; /* case nc = 1 */ if (A->nc == 1) { V->a[0][0] = 1.0; double normsq = 0.0; for(uint32_t i=0; i < A->nr; i++) normsq += A->a[i][0] * A->a[i][0]; D->a[0][0] = sqrt(normsq); if (D->a[0][0] == 0.0) tc_mat_copy(U, A); else { double inv = 1.0 / D->a[0][0]; for(uint32_t i=0; i < A->nr; i++) U->a[i][0] = A->a[i][0] * inv; } return 0; } /* Step1: A = U D V where D is bi-diagonal * A is nr x nc * U is nr x nr * D is nr x nc * V is nc x nc * * If A was not a square matrix, change U and D * U nr x nc * D nc x nc */ tc_mat_bidiag_decomp(A, U, D, V); if (D->nr != D->nc) { struct tc_mat *U0 = tc_mat_ctr(A->nr, A->nc); for(uint32_t i=0; i < A->nr; i++) for(uint32_t j=0; j < A->nc; j++) U0->a[i][j] = U->a[i][j]; tc_mat_resize(U, A->nr, A->nc); tc_mat_copy(U, U0); tc_mat_dtr(U0); struct tc_mat *D0 = tc_mat_ctr(A->nc, A->nc); for(uint32_t i=0; i < A->nc; i++) for(uint32_t j=0; j < A->nc; j++) D0->a[i][j] = D->a[i][j]; tc_mat_resize(D, A->nc, A->nc); tc_mat_copy(D, D0); tc_mat_dtr(D0); } /* iterate until either max_iterations has been hit * or the largest superdiagonal entry is below the * threshold. Set threshold = 1-e8 * largest element. * Any term less than 0.1 threshold will be considered * to be zero. */ const uint32_t max_iterations = 100 * D->nc; double threshold = D->a[0][0]; for(uint32_t i=0; i < D->nc; i++) if (fabs(D->a[i][i]) > threshold) threshold = fabs(D->a[i][i]); for(uint32_t i=0; i+1 < D->nc; i++) if (fabs(D->a[i][i+1]) > threshold) threshold = fabs(D->a[i][i+1]); threshold *= 1e-12; const double zero_threshold = 0.1 * threshold; /* Always reindex the components so that * D so that has the form * [D1, 0] where D1 is diagonal and * [ 0,D2] D2 is bidiagonal * Let i0 be the starting index of D2 */ uint32_t i0 = 0; for(uint32_t I=0; I < max_iterations; I++) { /* For any zeros on the diagonal, apply a series of * Givens rotations to also zero out its off-diagonal * term. Then move this component into D1. */ for(uint32_t i1=i0; i1 < D->nr; i1++) { if (fabs(D->a[i1][i1]) > zero_threshold) continue; if ((i1+1 == D->nr) && fabs(D->a[i1-1][i1]) > zero_threshold) continue; if ((i1+1 < D->nr) && (fabs(D->a[i1][i1+1]) > zero_threshold)) { for(uint32_t i=i1; i+1 < D->nr; i++) { /* U D = (U G) (G^T D) */ double alpha = D->a[i1][i+1]; if (fabs(alpha) < zero_threshold) break; double beta = D->a[i+1][i+1]; double gamma = sqrt(alpha*alpha + beta*beta); double c = beta / gamma; double s = alpha / gamma; for(uint32_t j=0; j < D->nr; j++) { double a = D->a[i1][j]; double b = D->a[i+1][j]; D->a[i1][j] = a*c - b*s; D->a[i+1][j] = a*s + b*c; } for(uint32_t j=0; j < U->nr; j++) { double a = U->a[j][i1]; double b = U->a[j][i+1]; U->a[j][i1] = a*c - b*s; U->a[j][i+1] = a*s + b*c; } } i1++; } /* move (i0,i1-1) down, i1 -> i0 */ for(uint32_t j=0; j < D->nr; j++) { double tmp = V->a[i1][j]; for(uint32_t k=i1; k > i0; k--) V->a[k][j] = V->a[k-1][j]; V->a[i0][j] = tmp; } for(uint32_t j=0; j < D->nr; j++) { double tmp = U->a[j][i1]; for(uint32_t k=i1; k > i0; k--) U->a[j][k] = U->a[j][k-1]; U->a[j][i0] = tmp; } double tmp = D->a[i1][i1]; double tmp1 = D->a[i1][i1+1]; for(uint32_t k=i1; k > i0; k--) { D->a[k][k] = D->a[k-1][k-1]; if (k+1 < D->nc) D->a[k][k+1] = D->a[k-1][k]; } D->a[i0][i0] = tmp; D->a[i0][i0+1] = tmp1; i0++; } /* For any zeros on the superdiagonal, move the * component to D1. */ for(uint32_t i=i0; i+1 < D->nr; i++) { if (fabs(D->a[i][i+1]) >= zero_threshold) continue; if (i == i0) { i0++; continue; } if (i+2 != D->nr) continue; /* move (i0,i) down, i+1 -> i0 */ for(uint32_t j=0; j < D->nr; j++) { double tmp = V->a[i+1][j]; for(uint32_t k=i+1; k > i0; k--) V->a[k][j] = V->a[k-1][j]; V->a[i0][j] = tmp; } for(uint32_t j=0; j < D->nr; j++) { double tmp = U->a[j][i+1]; for(uint32_t k=i+1; k > i0; k--) U->a[j][k] = U->a[j][k-1]; U->a[j][i0] = tmp; } double tmp = D->a[i+1][i+1]; double tmp1 = D->a[i][i+1]; for(uint32_t k=i+1; k > i0; k--) { D->a[k][k] = D->a[k-1][k-1]; D->a[k-1][k] = (k-1==i0)? tmp1: D->a[k-2][k-1]; } D->a[i0][i0] = tmp; i0++; if ((i+2 == D->nr) && (i0 != i)) i--; /* retry last term */ } if (i0 >= D->nr - 1) break; /* Find largest element on super diagonal.*/ /* Break if less than threshold. */ double largest_off_diag = 0.0; uint32_t n_zeros_on_off_diagonal = 0; for(uint32_t i=i0; i+1 < D->nr; i++) { if (fabs(D->a[i][i+1]) > largest_off_diag) largest_off_diag = fabs(D->a[i][i+1]); if (fabs(D->a[i][i+1]) < zero_threshold) n_zeros_on_off_diagonal++; } if (largest_off_diag < threshold) break; /* Find the next zero on the uper diagonal*/ /* Treat [i0,i1] as a block. */ uint32_t i1 = i0; for( ; i1+1 < D->nr; i1++) if (fabs(D->a[i1][i1+1]) < zero_threshold) break; /* Find Wilkerson shift. */ struct tc_mat *t = tc_mat_ctr(3, 2); for(uint32_t i=0; i < 3; i++) for(uint32_t j=0; j < 2; j++) t->a[i][j] = (i1+i>2)? D->a[i1+i-2][i1+j-1]: 0.0; double mu = tc_mat_wilkinson_shift(t); tc_mat_dtr(t); double alpha = D->a[i0][i0] * D->a[i0][i0] - mu; double beta = D->a[i0][i0] * D->a[i0][i0+1]; /* Apply Givens rotations G from i0 to the bottom, * chasing the nonzero element until off the matrix */ for(uint32_t i=i0; i < i1; i++) { /* D V = (D G) (G^T V) */ double gamma = sqrt(alpha*alpha + beta*beta); double c = alpha / gamma; double s = -beta / gamma; for(uint32_t j=0; j < D->nr; j++) { double a = D->a[j][i+0]; double b = D->a[j][i+1]; D->a[j][i+0] = a*c - b*s; D->a[j][i+1] = a*s + b*c; } for(uint32_t j=0; j < D->nc; j++) { double a = V->a[i+0][j]; double b = V->a[i+1][j]; V->a[i+0][j] = a*c - b*s; V->a[i+1][j] = a*s + b*c; } /* U D = (U G) (G^T D) */ alpha = D->a[i+0][i]; beta = D->a[i+1][i]; gamma = sqrt(alpha*alpha + beta*beta); if (fabs(gamma) > 0.0) { c = alpha / gamma; s = -beta / gamma; for(uint32_t j=0; j < D->nc; j++) { double a = D->a[i+0][j]; double b = D->a[i+1][j]; D->a[i+0][j] = a*c - b*s; D->a[i+1][j] = a*s + b*c; } for(uint32_t j=0; j < U->nr; j++) { double a = U->a[j][i+0]; double b = U->a[j][i+1]; U->a[j][i+0] = a*c - b*s; U->a[j][i+1] = a*s + b*c; } } if (i + 2 < D->nr) { alpha = D->a[i][i+1]; beta = D->a[i][i+2]; } } } /* now swap components to order the diagonal terms * from largest to smallest */ for(uint32_t i=0; i+1 < D->nr; i++) { double largest = fabs(D->a[i][i]); uint32_t largest_i = i; for(uint32_t j=i+1; j < D->nr; j++) { if (fabs(D->a[j][j]) > largest) { largest_i = j; largest = fabs(D->a[j][j]); } } if (largest_i != i) { for(uint32_t j=0; j < D->nr; j++) { double tmp = V->a[i][j]; V->a[i][j] = V->a[largest_i][j]; V->a[largest_i][j] = tmp; tmp = U->a[j][i]; U->a[j][i] = U->a[j][largest_i]; U->a[j][largest_i] = tmp; } double tmp = D->a[i][i]; D->a[i][i] = D->a[largest_i][largest_i]; D->a[largest_i][largest_i] = tmp; } if (D->a[i][i] < 0) { D->a[i][i] = -D->a[i][i]; for(uint32_t j=0; j < D->nr; j++) V->a[i][j] = -V->a[i][j]; } } /* just to be sure, zero out all off-diagonal terms of D */ for(uint32_t i=0; i < D->nr; i++) for(uint32_t j=0; j < D->nc; j++) if (i != j) D->a[i][j] = 0.0; /* transpose V */ tc_mat_transpose(V, V); return 0; }
# Perfect captive # Purpose If the matematical model is not correct or too little data is available this may lead to paramter drift, so that the parameters in the matematical model changes depending on how the fitted data has been sampled. This notebooks showcases the perfect case when you have the correct model and enought data in a captive test to identify the correct model. # Methodology * Sample data of forces from model * Fit the parameters of the same model to this data * Are the parameters correct? * Is the simulation correct? # Setup ```python # %load imports.py ## Local packages: %matplotlib inline %load_ext autoreload %autoreload 2 %config Completer.use_jedi = False ## (To fix autocomplete) ## External packages: import pandas as pd pd.options.display.max_rows = 999 pd.options.display.max_columns = 999 pd.set_option("display.max_columns", None) import numpy as np np.set_printoptions(linewidth=150) import numpy as np import os import matplotlib.pyplot as plt #if os.name == 'nt': # plt.style.use('presentation.mplstyle') # Windows import plotly.express as px import plotly.graph_objects as go import seaborn as sns import sympy as sp from sympy.physics.mechanics import (dynamicsymbols, ReferenceFrame, Particle, Point) from sympy.physics.vector.printing import vpprint, vlatex from IPython.display import display, Math, Latex from src.substitute_dynamic_symbols import run, lambdify import pyro import sklearn import pykalman from statsmodels.sandbox.regression.predstd import wls_prediction_std import statsmodels.api as sm from scipy.integrate import solve_ivp ## Local packages: from src.data import mdl from src.symbols import * from src.parameters import * import src.symbols as symbols from src import prime_system from src.models.regression import ForceRegression, results_summary_to_dataframe from src.models.diff_eq_to_matrix import DiffEqToMatrix from src.visualization.regression import show_pred, show_pred_captive from src.visualization.plot import track_plot,captive_plot ## Load models: # (Uncomment these for faster loading): import src.models.vmm_abkowitz as vmm #import src.models.vmm_martin as vmm_simpler from src.models.vmm import ModelSimulator from src.data.wpcc import ship_parameters, df_parameters, ps, ship_parameters_prime, ps_ship, scale_factor from src.models.captive_variation import variate ``` ```python #format the book import src.visualization.book_format as book_format book_format.set_style() ``` ## Load model ```python model = ModelSimulator.load('../models/model_VCT_abkowitz.pkl') ``` ### Run a zigzag simulation with the model ```python u0_=2 angle_deg = 35 result = model.zigzag(u0=u0_, angle=angle_deg) ``` ```python ``` ```python result.track_plot(); result.plot(compare=False); ``` ```python df_result = result.result.copy() df_result_prime = model.prime_system.prime(df_result, U=df_result['U']) ``` ## Parameter variation (captive test) ```python len(model.parameters) ``` ```python variation_keys = ['u','v','r','delta'] df_inputs = variate(df=df_result_prime, variation_keys=variation_keys, N=3) df_outputs = model.forces(df_inputs) df_captive_all = pd.concat([df_inputs,df_outputs], axis=1) ``` ```python len(df_inputs) ``` ```python 3**(len(variation_keys)) ``` ## Fit model ```python reg_all = ForceRegression(vmm=model, data=df_captive_all) display(reg_all.show_pred_X()) display(reg_all.show_pred_Y()) display(reg_all.show_pred_N()) ``` ### Create a simulation model from the regression model ```python added_masses_ = {key:value for key,value in model.parameters.items() if 'dot' in key} added_masses = pd.DataFrame(added_masses_, index=['prime']).transpose() model_all = reg_all.create_model(added_masses=added_masses, ship_parameters=model.ship_parameters, ps=model.prime_system, control_keys=['delta']) ``` ### Resimulate with the regressed model ```python result_all = model_all.simulate(df_result) ``` ```python result_all.plot_compare(); ``` ```python df_compare_parameters =pd.DataFrame() df_compare_parameters['model'] = model.parameters df_compare_parameters['model captive all'] = model_all.parameters df_compare_parameters['model_abs'] = df_compare_parameters['model'].abs() df_compare_parameters.sort_values(by='model_abs', ascending=False, inplace=True) df_compare_parameters.drop(columns=['model_abs'], inplace=True) df_compare_parameters = df_compare_parameters.divide(df_compare_parameters['model'], axis=0) df_compare_parameters['dof'] = pd.Series(df_compare_parameters.index).apply(lambda x:x[0]).values for dof, df_ in df_compare_parameters.groupby(by='dof', sort=False): fig,ax=plt.subplots() fig.set_size_inches(10,2) df_.plot(kind='bar', ax=ax) fig.suptitle(dof) ``` ```python ```
The real part of the principal square root of a complex number is nonnegative.
using Test using BetweenFlags @testset "Flags" begin for Flag in (StartFlag, StopFlag) flag = Flag("flag") @test flag.flag == "flag" @test flag.flag_boundaries_left == [] @test flag.flag_boundaries_right == [] @test flag.trigger == Dict{Tuple,String}(("", "") => "flag") @test BetweenFlags.grep_type(flag) == GreedyType flag = Flag("flag", ["LB1","LB2"], ["RB1","RB2"]; grep_type=ScopeType()) @test flag.flag == "flag" @test flag.flag_boundaries_left == ["LB1","LB2"] @test flag.flag_boundaries_right == ["RB1","RB2"] @test flag.trigger == Dict{Tuple,String}( ("LB2", "RB1") => "LB2flagRB1", ("LB2", "RB2") => "LB2flagRB2", ("LB1", "RB2") => "LB1flagRB2", ("LB1", "RB1") => "LB1flagRB1") @test BetweenFlags.grep_type(flag) == ScopeType flag = Flag("flag", ["LB1","LB2"], ["RB1","RB2"]; grep_type=ScopeType()) @test flag.flag == "flag" @test flag.flag_boundaries_left == ["LB1","LB2"] @test flag.flag_boundaries_right == ["RB1","RB2"] @test flag.trigger == Dict{Tuple,String}( ("LB2", "RB1") => "LB2flagRB1", ("LB2", "RB2") => "LB2flagRB2", ("LB1", "RB2") => "LB1flagRB2", ("LB1", "RB1") => "LB1flagRB1") @test BetweenFlags.grep_type(flag) == ScopeType end end
#include "kafka/KafkaConsumer.h" #include "kafka/Timestamp.h" #include <boost/algorithm/string.hpp> #include <boost/program_options.hpp> #include <atomic> #include <iostream> #include <signal.h> #include <string> #include <vector> namespace Kafka = KAFKA_API; std::atomic_bool running = {true}; void stopRunning(int sig) { if (sig != SIGINT) return; if (running) { running = false; } else { // Restore the signal handler, -- to avoid stucking with this handler signal(SIGINT, SIG_IGN); } } struct Arguments { std::vector<std::string> brokerList; std::string topic; std::map<std::string, std::string> props; }; std::unique_ptr<Arguments> ParseArguments(int argc, char **argv) { auto args = std::make_unique<Arguments>(); std::vector<std::string> propList; namespace po = boost::program_options; po::options_description desc("Options description"); desc.add_options() ("help,h", "Print usage information.") ("broker-list", po::value<std::vector<std::string>>(&args->brokerList)->multitoken()->required(), "REQUIRED: The server(s) to connect to.") ("topic", po::value<std::string>(&args->topic)->required(), "REQUIRED: The topic to consume from.") ("props", po::value<std::vector<std::string>>(&propList)->multitoken(), "Kafka consumer properties in key=value format."); po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); if (vm.count("help") || argc == 1) { std::cout << "Read data from a given Kafka topic and write it to the standard output" << std::endl; std::cout << " (with librdkafka v" << Kafka::Utility::getLibRdKafkaVersion() << ")" << std::endl; std::cout << desc << std::endl; return nullptr; } po::notify(vm); for (const auto& prop: propList) { std::vector<std::string> keyValue; boost::algorithm::split(keyValue, prop, boost::is_any_of("=")); if (keyValue.size() != 2) { throw std::invalid_argument("Unexpected --props value! Expected key=value format"); } args->props[keyValue[0]] = keyValue[1]; } return args; } void RunConsumer(const std::string& topic, const Kafka::ConsumerConfig& props) { // Create a manual-commit consumer Kafka::KafkaClient::setGlobalLogger(Kafka::Logger()); Kafka::KafkaManualCommitConsumer consumer(props); // Subscribe to topic consumer.subscribe({topic}); std::cout << "--------------------" << std::endl; // Poll & print messages while (running) { const auto POLL_TIMEOUT = std::chrono::milliseconds(100); auto records = consumer.poll(POLL_TIMEOUT); for (const auto& record: records) { if (!record.error()) { std::cout << "Current Local Time [" << Kafka::Utility::getCurrentTime() << "]" << std::endl; std::cout << " Topic : " << record.topic() << std::endl; std::cout << " Partition: " << record.partition() << std::endl; std::cout << " Offset : " << record.offset() << std::endl; std::cout << " Timestamp: " << record.timestamp().toString() << std::endl; std::cout << " Headers : " << Kafka::toString(record.headers()) << std::endl; std::cout << " Key [" << std::setw(4) << record.key().size() << " B]: " << record.key().toString() << std::endl; std::cout << " Value [" << std::setw(4) << record.value().size() << " B]: " << record.value().toString() << std::endl; std::cout << "--------------------" << std::endl; } else { std::cerr << record.toString() << std::endl; } } } } int main (int argc, char **argv) { // Parse input arguments std::unique_ptr<Arguments> args; try { args = ParseArguments(argc, argv); } catch (const std::exception& e) { std::cout << e.what() << std::endl; return EXIT_FAILURE; } if (!args) // Only for "help" { return EXIT_SUCCESS; } // Use Ctrl-C to terminate the program signal(SIGINT, stopRunning); // Prepare consumer properties Kafka::ConsumerConfig props; props.put(Kafka::ConsumerConfig::BOOTSTRAP_SERVERS, boost::algorithm::join(args->brokerList, ",")); // Get client id std::ostringstream oss; oss << "consumer-" << std::this_thread::get_id(); props.put(Kafka::ConsumerConfig::CLIENT_ID, oss.str()); // For other properties user assigned for (const auto& prop: args->props) { props.put(prop.first, prop.second); } // Start consumer try { RunConsumer(args->topic, props); } catch (const Kafka::KafkaException& e) { std::cerr << "Exception thrown by consumer: " << e.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
4 ) forms upon fusing sodium oxide and Sb
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov ! This file was ported from Lean 3 source module order.iterate ! leanprover-community/mathlib commit 2258b40dacd2942571c8ce136215350c702dc78f ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.Logic.Function.Iterate import Mathlib.Order.Monotone.Basic /-! # Inequalities on iterates In this file we prove some inequalities comparing `f^[n] x` and `g^[n] x` where `f` and `g` are two self-maps that commute with each other. Current selection of inequalities is motivated by formalization of the rotation number of a circle homeomorphism. -/ open Function namespace Monotone variable [Preorder α] {f : α → α} {x y : ℕ → α} /-! ### Comparison of two sequences If $f$ is a monotone function, then $∀ k, x_{k+1} ≤ f(x_k)$ implies that $x_k$ grows slower than $f^k(x_0)$, and similarly for the reversed inequalities. If $x_k$ and $y_k$ are two sequences such that $x_{k+1} ≤ f(x_k)$ and $y_{k+1} ≥ f(y_k)$ for all $k < n$, then $x_0 ≤ y_0$ implies $x_n ≤ y_n$, see `Monotone.seq_le_seq`. If some of the inequalities in this lemma are strict, then we have $x_n < y_n$. The rest of the lemmas in this section formalize this fact for different inequalities made strict. -/ theorem seq_le_seq (hf : Monotone f) (n : ℕ) (h₀ : x 0 ≤ y 0) (hx : ∀ k < n, x (k + 1) ≤ f (x k)) (hy : ∀ k < n, f (y k) ≤ y (k + 1)) : x n ≤ y n := by induction' n with n ihn · exact h₀ · refine' (hx _ n.lt_succ_self).trans ((hf $ ihn _ _).trans (hy _ n.lt_succ_self)) exact fun k hk => hx _ (hk.trans n.lt_succ_self) exact fun k hk => hy _ (hk.trans n.lt_succ_self) #align monotone.seq_le_seq Monotone.seq_le_seq theorem seq_pos_lt_seq_of_lt_of_le (hf : Monotone f) {n : ℕ} (hn : 0 < n) (h₀ : x 0 ≤ y 0) (hx : ∀ k < n, x (k + 1) < f (x k)) (hy : ∀ k < n, f (y k) ≤ y (k + 1)) : x n < y n := by induction' n with n ihn · exact hn.false.elim suffices x n ≤ y n from (hx n n.lt_succ_self).trans_le ((hf this).trans $ hy n n.lt_succ_self) cases n with | zero => exact h₀ | succ n => refine' (ihn n.zero_lt_succ (fun k hk => hx _ _) fun k hk => hy _ _).le <;> exact hk.trans n.succ.lt_succ_self #align monotone.seq_pos_lt_seq_of_lt_of_le Monotone.seq_pos_lt_seq_of_lt_of_le theorem seq_pos_lt_seq_of_le_of_lt (hf : Monotone f) {n : ℕ} (hn : 0 < n) (h₀ : x 0 ≤ y 0) (hx : ∀ k < n, x (k + 1) ≤ f (x k)) (hy : ∀ k < n, f (y k) < y (k + 1)) : x n < y n := hf.dual.seq_pos_lt_seq_of_lt_of_le hn h₀ hy hx #align monotone.seq_pos_lt_seq_of_le_of_lt Monotone.seq_pos_lt_seq_of_le_of_lt theorem seq_lt_seq_of_lt_of_le (hf : Monotone f) (n : ℕ) (h₀ : x 0 < y 0) (hx : ∀ k < n, x (k + 1) < f (x k)) (hy : ∀ k < n, f (y k) ≤ y (k + 1)) : x n < y n := by cases n exacts[h₀, hf.seq_pos_lt_seq_of_lt_of_le (Nat.zero_lt_succ _) h₀.le hx hy] #align monotone.seq_lt_seq_of_lt_of_le Monotone.seq_lt_seq_of_lt_of_le theorem seq_lt_seq_of_le_of_lt (hf : Monotone f) (n : ℕ) (h₀ : x 0 < y 0) (hx : ∀ k < n, x (k + 1) ≤ f (x k)) (hy : ∀ k < n, f (y k) < y (k + 1)) : x n < y n := hf.dual.seq_lt_seq_of_lt_of_le n h₀ hy hx #align monotone.seq_lt_seq_of_le_of_lt Monotone.seq_lt_seq_of_le_of_lt /-! ### Iterates of two functions In this section we compare the iterates of a monotone function `f : α → α` to iterates of any function `g : β → β`. If `h : β → α` satisfies `h ∘ g ≤ f ∘ h`, then `h (g^[n] x)` grows slower than `f^[n] (h x)`, and similarly for the reversed inequality. Then we specialize these two lemmas to the case `β = α`, `h = id`. -/ variable {g : β → β} {h : β → α} open Function theorem le_iterate_comp_of_le (hf : Monotone f) (H : h ∘ g ≤ f ∘ h) (n : ℕ) : h ∘ g^[n] ≤ f^[n] ∘ h := fun x => by apply hf.seq_le_seq n <;> intros <;> simp [iterate_succ', -iterate_succ, comp_apply, id_eq, le_refl] case hx => exact H _ #align monotone.le_iterate_comp_of_le Monotone.le_iterate_comp_of_le theorem iterate_comp_le_of_le (hf : Monotone f) (H : f ∘ h ≤ h ∘ g) (n : ℕ) : f^[n] ∘ h ≤ h ∘ g^[n] := hf.dual.le_iterate_comp_of_le H n #align monotone.iterate_comp_le_of_le Monotone.iterate_comp_le_of_le /-- If `f ≤ g` and `f` is monotone, then `f^[n] ≤ g^[n]`. -/ theorem iterate_le_of_le {g : α → α} (hf : Monotone f) (h : f ≤ g) (n : ℕ) : f^[n] ≤ g^[n] := hf.iterate_comp_le_of_le h n #align monotone.iterate_le_of_le Monotone.iterate_le_of_le /-- If `f ≤ g` and `g` is monotone, then `f^[n] ≤ g^[n]`. -/ theorem le_iterate_of_le {g : α → α} (hg : Monotone g) (h : f ≤ g) (n : ℕ) : f^[n] ≤ g^[n] := hg.dual.iterate_le_of_le h n #align monotone.le_iterate_of_le Monotone.le_iterate_of_le end Monotone /-! ### Comparison of iterations and the identity function If $f(x) ≤ x$ for all $x$ (we express this as `f ≤ id` in the code), then the same is true for any iterate of $f$, and similarly for the reversed inequality. -/ namespace Function section Preorder variable [Preorder α] {f : α → α} /-- If $x ≤ f x$ for all $x$ (we write this as `id ≤ f`), then the same is true for any iterate `f^[n]` of `f`. -/ theorem id_le_iterate_of_id_le (h : id ≤ f) (n : ℕ) : id ≤ f^[n] := by simpa only [iterate_id] using monotone_id.iterate_le_of_le h n #align function.id_le_iterate_of_id_le Function.id_le_iterate_of_id_le theorem iterate_le_id_of_le_id (h : f ≤ id) (n : ℕ) : f^[n] ≤ id := @id_le_iterate_of_id_le αᵒᵈ _ f h n #align function.iterate_le_id_of_le_id Function.iterate_le_id_of_le_id theorem monotone_iterate_of_id_le (h : id ≤ f) : Monotone fun m => f^[m] := monotone_nat_of_le_succ $ fun n x => by rw [iterate_succ_apply'] exact h _ #align function.monotone_iterate_of_id_le Function.monotone_iterate_of_id_le theorem antitone_iterate_of_le_id (h : f ≤ id) : Antitone fun m => f^[m] := fun m n hmn => @monotone_iterate_of_id_le αᵒᵈ _ f h m n hmn #align function.antitone_iterate_of_le_id Function.antitone_iterate_of_le_id end Preorder /-! ### Iterates of commuting functions If `f` and `g` are monotone and commute, then `f x ≤ g x` implies `f^[n] x ≤ g^[n] x`, see `Function.Commute.iterate_le_of_map_le`. We also prove two strict inequality versions of this lemma, as well as `iff` versions. -/ namespace Commute section Preorder variable [Preorder α] {f g : α → α} theorem iterate_le_of_map_le (h : Commute f g) (hf : Monotone f) (hg : Monotone g) {x} (hx : f x ≤ g x) (n : ℕ) : (f^[n]) x ≤ (g^[n]) x := by apply hf.seq_le_seq n · rfl · intros; rw [iterate_succ_apply'] · intros; simp [h.iterate_right _ _, hg.iterate _ hx]; #align function.commute.iterate_le_of_map_le Function.Commute.iterate_le_of_map_le theorem iterate_pos_lt_of_map_lt (h : Commute f g) (hf : Monotone f) (hg : StrictMono g) {x} (hx : f x < g x) {n} (hn : 0 < n) : (f^[n]) x < (g^[n]) x := by apply hf.seq_pos_lt_seq_of_le_of_lt hn · rfl · intros; rw [iterate_succ_apply'] · intros; simp [h.iterate_right _ _, hg.iterate _ hx] #align function.commute.iterate_pos_lt_of_map_lt Function.Commute.iterate_pos_lt_of_map_lt theorem iterate_pos_lt_of_map_lt' (h : Commute f g) (hf : StrictMono f) (hg : Monotone g) {x} (hx : f x < g x) {n} (hn : 0 < n) : (f^[n]) x < (g^[n]) x := @iterate_pos_lt_of_map_lt αᵒᵈ _ g f h.symm hg.dual hf.dual x hx n hn #align function.commute.iterate_pos_lt_of_map_lt' Function.Commute.iterate_pos_lt_of_map_lt' end Preorder variable [LinearOrder α] {f g : α → α} theorem iterate_pos_lt_iff_map_lt (h : Commute f g) (hf : Monotone f) (hg : StrictMono g) {x n} (hn : 0 < n) : (f^[n]) x < (g^[n]) x ↔ f x < g x := by rcases lt_trichotomy (f x) (g x) with (H | H | H) · simp only [*, iterate_pos_lt_of_map_lt] · simp only [*, h.iterate_eq_of_map_eq, lt_irrefl] · simp only [lt_asymm H, lt_asymm (h.symm.iterate_pos_lt_of_map_lt' hg hf H hn)] #align function.commute.iterate_pos_lt_iff_map_lt Function.Commute.iterate_pos_lt_iff_map_lt theorem iterate_pos_lt_iff_map_lt' (h : Commute f g) (hf : StrictMono f) (hg : Monotone g) {x n} (hn : 0 < n) : (f^[n]) x < (g^[n]) x ↔ f x < g x := @iterate_pos_lt_iff_map_lt αᵒᵈ _ _ _ h.symm hg.dual hf.dual x n hn #align function.commute.iterate_pos_lt_iff_map_lt' Function.Commute.iterate_pos_lt_iff_map_lt' theorem iterate_pos_le_iff_map_le (h : Commute f g) (hf : Monotone f) (hg : StrictMono g) {x n} (hn : 0 < n) : (f^[n]) x ≤ (g^[n]) x ↔ f x ≤ g x := by simpa only [not_lt] using not_congr (h.symm.iterate_pos_lt_iff_map_lt' hg hf hn) #align function.commute.iterate_pos_le_iff_map_le Function.Commute.iterate_pos_le_iff_map_le theorem iterate_pos_le_iff_map_le' (h : Commute f g) (hf : StrictMono f) (hg : Monotone g) {x n} (hn : 0 < n) : (f^[n]) x ≤ (g^[n]) x ↔ f x ≤ g x := by simpa only [not_lt] using not_congr (h.symm.iterate_pos_lt_iff_map_lt hg hf hn) #align function.commute.iterate_pos_le_iff_map_le' Function.Commute.iterate_pos_le_iff_map_le' end Commute end Function namespace Monotone variable [Preorder α] {f : α → α} {x : α} /-- If `f` is a monotone map and `x ≤ f x` at some point `x`, then the iterates `f^[n] x` form a monotone sequence. -/ theorem monotone_iterate_of_le_map (hf : Monotone f) (hx : x ≤ f x) : Monotone fun n => (f^[n]) x := monotone_nat_of_le_succ $ fun n => by rw [iterate_succ_apply] exact hf.iterate n hx #align monotone.monotone_iterate_of_le_map Monotone.monotone_iterate_of_le_map /-- If `f` is a monotone map and `f x ≤ x` at some point `x`, then the iterates `f^[n] x` form a antitone sequence. -/ theorem antitone_iterate_of_map_le (hf : Monotone f) (hx : f x ≤ x) : Antitone fun n => (f^[n]) x := hf.dual.monotone_iterate_of_le_map hx #align monotone.antitone_iterate_of_map_le Monotone.antitone_iterate_of_map_le end Monotone namespace StrictMono variable [Preorder α] {f : α → α} {x : α} /-- If `f` is a strictly monotone map and `x < f x` at some point `x`, then the iterates `f^[n] x` form a strictly monotone sequence. -/ theorem strictMono_iterate_of_lt_map (hf : StrictMono f) (hx : x < f x) : StrictMono fun n => (f^[n]) x := strictMono_nat_of_lt_succ $ fun n => by rw [iterate_succ_apply] exact hf.iterate n hx #align strict_mono.strict_mono_iterate_of_lt_map StrictMono.strictMono_iterate_of_lt_map /-- If `f` is a strictly antitone map and `f x < x` at some point `x`, then the iterates `f^[n] x` form a strictly antitone sequence. -/ theorem strictAnti_iterate_of_map_lt (hf : StrictMono f) (hx : f x < x) : StrictAnti fun n => (f^[n]) x := hf.dual.strictMono_iterate_of_lt_map hx #align strict_mono.strict_anti_iterate_of_map_lt StrictMono.strictAnti_iterate_of_map_lt end StrictMono
(* Title: HOL/Auth/n_germanish_lemma_on_inv__2.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_germanish Protocol Case Study*} theory n_germanish_lemma_on_inv__2 imports n_germanish_base begin section{*All lemmas on causal relation between inv__2 and some rule r*} lemma n_t3Vsinv__2: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_t3 i)" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__2 p__Inv2)" 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_t3 i" apply fastforce done from a2 obtain p__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__2 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" 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__Inv2)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Para (Ident ''cache'') p__Inv2)) (Const exclusive)) (eqn (IVar (Para (Ident ''home_sharer_list'') i)) (Const true))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_t4Vsinv__2: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_t4 i)" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__2 p__Inv2)" 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_t4 i" apply fastforce done from a2 obtain p__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__2 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" 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__Inv2)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Para (Ident ''cache'') p__Inv2)) (Const exclusive)) (eqn (IVar (Para (Ident ''home_sharer_list'') i)) (Const true))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_t5Vsinv__2: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_t5 i)" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__2 p__Inv2)" 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_t5 i" apply fastforce done from a2 obtain p__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__2 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" 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__Inv2)" 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_t6Vsinv__2: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_t6 N i)" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__2 p__Inv2)" 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_t6 N i" apply fastforce done from a2 obtain p__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__2 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" 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__Inv2)" have "?P1 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_t2Vsinv__2: assumes a1: "\<exists> i. i\<le>N\<and>r=n_t2 i" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__2 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_t1Vsinv__2: assumes a1: "\<exists> i. i\<le>N\<and>r=n_t1 i" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__2 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done end
[STATEMENT] lemma less_multiset\<^sub>H\<^sub>O_imp_less_multiset\<^sub>D\<^sub>M: "less_multiset\<^sub>H\<^sub>O M N \<Longrightarrow> less_multiset\<^sub>D\<^sub>M M N" [PROOF STATE] proof (prove) goal (1 subgoal): 1. less_multiset\<^sub>H\<^sub>O M N \<Longrightarrow> less_multiset\<^sub>D\<^sub>M M N [PROOF STEP] unfolding less_multiset\<^sub>D\<^sub>M_def less_multiset\<^sub>H\<^sub>O_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. M \<noteq> N \<and> (\<forall>y. count N y < count M y \<longrightarrow> (\<exists>x>y. count M x < count N x)) \<Longrightarrow> \<exists>X Y. X \<noteq> {#} \<and> X \<subseteq># N \<and> M = N - X + Y \<and> (\<forall>k. k \<in># Y \<longrightarrow> (\<exists>a. a \<in># X \<and> k < a)) [PROOF STEP] unfolding multp\<^sub>D\<^sub>M_def[symmetric] multp\<^sub>H\<^sub>O_def[symmetric] [PROOF STATE] proof (prove) goal (1 subgoal): 1. multp\<^sub>H\<^sub>O (<) M N \<Longrightarrow> multp\<^sub>D\<^sub>M (<) M N [PROOF STEP] by (rule multp\<^sub>H\<^sub>O_imp_multp\<^sub>D\<^sub>M)
% Created 2021-06-30 Wed 07:58 % Intended LaTeX compiler: pdflatex \documentclass[presentation,aspectratio=169]{beamer} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{graphicx} \usepackage{grffile} \usepackage{longtable} \usepackage{wrapfig} \usepackage{rotating} \usepackage[normalem]{ulem} \usepackage{amsmath} \usepackage{textcomp} \usepackage{amssymb} \usepackage{capt-of} \usepackage{hyperref} \usepackage{khpreamble} \usepackage{amssymb} \usepgfplotslibrary{groupplots} \DeclareMathOperator{\shift}{q} \DeclareMathOperator{\diff}{p} \usetheme{default} \author{Kjartan Halvorsen} \date{2021-06-30} \title{Sampling and aliasing} \hypersetup{ pdfauthor={Kjartan Halvorsen}, pdftitle={Sampling and aliasing}, pdfkeywords={}, pdfsubject={}, pdfcreator={Emacs 26.3 (Org mode 9.4.6)}, pdflang={English}} \begin{document} \maketitle \section{Intro} \label{sec:org685c9c4} \begin{frame}[label={sec:orgcd3f3cb}]{Computer-controlled system} \begin{center} \includegraphics[width=0.7\linewidth]{../../figures/fig7-2.png} \end{center} {\footnotesize Source: Åström \& Wittenmark} \end{frame} \section{The sampling theorem} \label{sec:orgf503a06} \begin{frame}[label={sec:org881e394}]{Challenges with computerized control - aliasing} \begin{columns} \begin{column}{0.6\columnwidth} \begin{center} \begin{tikzpicture} \node {\includegraphics[width=0.99\linewidth]{../../figures/comp-contr-sys.png}}; \node[pin=145:{60Hz mains hum}] at (2.7,2.4) {}; \node[pin=-60:{90Hz sampling freq}] at (0.5,-1.4) {}; \end{tikzpicture} \end{center} \end{column} \begin{column}{0.4\columnwidth} \includegraphics[width=0.99\linewidth]{../../figures/aliasing-example-60Hz} \end{column} \end{columns} \end{frame} \begin{frame}[label={sec:orgc438ec7}]{Spatial aliasing} \begin{center} \includegraphics[width=0.45\linewidth]{../../figures/Moire_pattern_of_bricks.png} \includegraphics[width=0.45\linewidth]{../../figures/Moire_pattern_of_bricks_small.png} \end{center} \end{frame} \begin{frame}[label={sec:org77a96ac}]{The sampling theorem} Shannon and Nyquist: A continuous-time signal with Fourier transform that is zero outside the interval \((-\omega_0, \omega_0)\) can be completely reconstructed from equidistant samples of the signal, as long as the sampling frequency is at least \(2\omega_0\). \begin{center} \begin{tikzpicture}[scale=1.2] \draw[->] (-3,0) -- (3,0) node[below] {$\omega$}; \draw[->] (0,0) -- (0,1.5); \draw[red, thick] (0,1) to (1,0); \draw[red, thick] (0,1) to (-1,0); \node at (1,-0.3) {$\omega_0$}; \node at (-1,-0.3) {$-\omega_0$}; \node at (0,-0.3) {$0$}; \node[coordinate, pin=-90:{$2\omega_0$}] at (2,0) {}; \end{tikzpicture} \end{center} \end{frame} \begin{frame}[label={sec:org1c94273}]{The impulse modulation model} The \alert{impulse train}, a.k.a the \alert{Dirac comb}: \begin{center} \(m(t) = \sum_{k=-\infty}^{\infty} \delta(t-kh)\)\hspace*{10mm} \includegraphics[width=0.4\linewidth]{../../../figures/modulation-model-blocks} \end{center} \[f_s(t) = f(t)m(t) = f(t) \sum_{k=-\infty}^{\infty} \delta(t-kh) = \sum_{k=-\infty}^{\infty} f(t)\delta(t-kh) = \sum_{k=-\infty}^{\infty} f(kh) \delta(t-kh) \] \begin{center} \includegraphics[width=0.8\linewidth]{../../figures/modulation-model-timeseries} \end{center} \end{frame} \begin{frame}[label={sec:org5b6339a}]{Fourier transform of the sampled signal} The Fourier transform of \(f_s\) and the Fourier transform of \(f\) are related as \[ F_s(\omega) = \frac{1}{h} \sum_n F(\omega + n\omega_s). \] Because the Fourier transform of the sampled signal equals the Fourier transform of the continuous-time signal repeated at every multiple of the sampling frequency and added, we get \emph{frequency-folding} or \emph{aliasing}. \begin{center} \includegraphics[width=0.28\linewidth]{../../figures/frequency-folding.png} \end{center} \end{frame} \section{Exercises using line spectra} \label{sec:org57afb82} \begin{frame}[label={sec:org45627d9}]{Fourier transform of a complex exponential} The function \(x(t) = \mathrm{e}^{i\omega_1 t}\) \begin{center} \begin{tikzpicture}[scale=2] \draw[->] (-1.2, 0) -- (1.2,0) node[below] {Re}; \draw[->] (0, -1.2) -- (0,1.2) node[left] {Im}; \draw[domain=0:360, samples=361, dashed] plot ({cos(\x)}, {sin(\x)}); \node[circle, fill, inner sep=2pt, red] (pnt) at (0.868, 0.5) {}; \draw[dashed, blue] (0,0) to (0.868, 0.5); \draw[domain=0:30, samples=20, ->] plot ({0.6*cos(\x)}, {0.6*sin(\x)}); \node at (0.7, 0.2) {$\omega_1 t$}; \node[pin=-135:{1}, coordinate] at (1, 0) {}; \node[right of=pnt, node distance=3mm, anchor=west] {$x(t) = \mathrm{e}^{i\omega_1 t} = \cos(\omega_1 t) + i\sin(\omega_1 t)$}; \end{tikzpicture} \end{center} has Fourier transform \[X(i\omega) = \int_{-\infty}^{\infty} x(t) \mathrm{e}^{-i\omega t}dt = \int_{-\infty}^{\infty} \mathrm{e}^{i(\omega_1 - \omega) t}dt = \delta(\omega_1 - \omega)\] \end{frame} \begin{frame}[label={sec:orgded89dc}]{Fourier transform of a sinusoid} A sinusoidal signal \(y(t) = \sin(\omega_1 t)\) has all its power concentrated at one single frequency, \(\omega=\unit{\omega_1}{rad\per\second}\). \begin{center} \begin{tikzpicture} \small \pgfmathsetmacro{\ww}{1} \pgfmathsetmacro{\TT}{2*pi/\ww} \begin{axis}[ width=14cm, height=2.5cm, xlabel={$t$}, ylabel={$y(t)$}, xmin=0., xmax=30.5, ytick = {0}, xtick = {0, \TT}, xticklabels={0, $T=\frac{2\pi}{\omega_1}$}, ] \addplot+[black, thick,no marks, domain=0:30, samples=400,variable=t] { sin(deg(\ww*t)) }; \end{axis} \end{tikzpicture} \end{center} Since \[y(t) = \sin(\omega_1 t) = \frac{1}{2i} \left( \mathrm{e}^{i\omega_1 t} - \mathrm{e}^{-i \omega_1 t} \right)\] the Fourier transform of a sinusoid becomes \[ Y(i\omega) = \frac{1}{2i} \left( \delta(\omega_1 - \omega) - \delta(\omega_1 + \omega) \right)\] \end{frame} \begin{frame}[label={sec:org419e9da}]{Exercise 1: Fourier transform of a sinusoid} Consider the signal below \begin{center} \begin{tikzpicture} \small \pgfmathsetmacro{\ww}{1} \pgfmathsetmacro{\TT}{2*pi/\ww} \begin{axis}[ width=14cm, height=2.5cm, xlabel={$t$}, ylabel={$y(t)$}, xmin=0., xmax=30.5, ytick = {0}, xtick = {0, \TT}, xticklabels={0, $T$}, ] \addplot+[black, thick,no marks, domain=0:30, samples=400,variable=t] { sin(deg(\ww*t)) }; \end{axis} \end{tikzpicture} \end{center} Which of the below is the correct Fourier transform (magnitude plot shown)? \pgfplotsset{ dirac/.style={ mark=triangle*, mark options={scale=0.6}, ycomb, scatter, visualization depends on={y/abs(y)-1 \as \sign}, scatter/@pre marker code/.code={\scope[rotate=90*\sign,yshift=-2pt]} } } \begin{tikzpicture} \footnotesize \pgfmathsetmacro{\ww}{1} \pgfmathsetmacro{\TT}{2*pi/\ww} \pgfmathsetmacro{\omegaone}{2/\TT} \pgfmathsetmacro{\omegatwo}{pi/\TT} \pgfmathsetmacro{\omegathree}{1/\TT} \pgfmathsetmacro{\omegafour}{2*pi/\TT} \begin{groupplot}[group style={group size=2 by 2, vertical sep=1.2cm, horizontal sep=1.3cm}, width=7cm, height=2.5cm, xlabel={$\omega$ [rad/s]}, ylabel={$|Y(i\omega)|$}, xmin=-1.5, xmax=1.5, ytick = \empty, xtick = \empty, ] \nextgroupplot[xtick={-\omegaone, 0, \omegaone}, xticklabels={$-\frac{2}{T}$, 0, $\frac{2}{T}$}] \addplot[red, thick, dirac] coordinates {(-\omegaone, 1) (\omegaone, 1)}; \nextgroupplot[xtick={-\omegatwo, 0, \omegatwo}, xticklabels={$-\frac{\pi}{T}$, 0, $\frac{\pi}{T}$}] \addplot[red, thick, dirac] coordinates {(-\omegatwo, 1) (\omegatwo, 1)}; \nextgroupplot[xtick={-\omegathree, 0, \omegathree}, xticklabels={$-\frac{1}{T}$, 0, $\frac{1}{T}$}] \addplot[red, thick, dirac] coordinates {(-\omegathree, 1) (\omegathree, 1)}; \nextgroupplot[xtick={-\omegafour, 0, \omegafour}, xticklabels={$-\frac{2\pi}{T}$, 0, $\frac{2\pi}{T}$}] \addplot[red, thick, dirac] coordinates {(-\omegafour, 1) (\omegafour, 1)}; \end{groupplot} \node[red] at (group c1r1.center) {\huge 1}; \node[red] at (group c2r1.center) {\huge 2}; \node[red] at (group c1r2.center) {\huge 3}; \node[red] at (group c2r2.center) {\huge 4}; \end{tikzpicture} \end{frame} \begin{frame}[label={sec:org3cbc6fb}]{Exercise 2: Two sinusoids} Consider a signal with Fourier transform \pgfplotsset{ dirac/.style={ mark=triangle*, mark options={scale=0.6}, ycomb, scatter, visualization depends on={y/abs(y)-1 \as \sign}, scatter/@pre marker code/.code={\scope[rotate=90*\sign,yshift=-2pt]} }} \begin{center} \begin{tikzpicture} \small \pgfmathsetmacro{\wwone}{1} \pgfmathsetmacro{\wwtwo}{5*\wwone} \begin{axis}[ width=14cm, height=2.5cm, xlabel={$\omega$ [rad/s]}, ylabel={$|Y(i\omega)|$}, xmin=-7, xmax=7, ymin=-0.5, ytick=\empty, xtick = {-\wwtwo, -\wwone, 0, \wwone, \wwtwo}, % ticklabels={$-5\omega_1$, $-\omega_1$, 0, $\omega_1$, $5\omega_1$}, ] \addplot[black, thick, dirac] coordinates {(-\wwtwo, 0.3) (-\wwone, 1) (\wwone, 1) (\wwtwo, 0.3)}; \end{axis} \end{tikzpicture} \end{center} Which of the below time series could this Fourier transform correspond to? \begin{tikzpicture} \footnotesize \pgfmathsetmacro{\wwone}{1} \pgfmathsetmacro{\wwtwo}{5*\wwone} \begin{groupplot}[group style={group size=2 by 2, vertical sep=1.2cm, horizontal sep=1.3cm}, width=7cm, height=2.5cm, xlabel={$t$ [s]}, ylabel={$y(t)$}, xmin=0, xmax=15, ytick = \empty, xtick = \empty, domain=0:20, samples=600, variable=t, ] \nextgroupplot[xtick={0, 6.28, 12.56}, xticklabels={0, $2\pi$, $4\pi$},] \addplot[red, thick, no marks] { sin(deg(\wwone*t)) + 0.3*cos(deg(\wwtwo*t))}; \nextgroupplot[xtick={0, 6.28, 12.56}, xticklabels={0, $2\pi$, $4\pi$},] \addplot[red, thick, no marks] { 0.3*cos(deg(\wwone*t)) + sin(deg(\wwtwo*t))}; \nextgroupplot[xtick={0, 6.28, 12.56}, xticklabels={0, $2\pi$, $4\pi$},] \addplot[red, thick, no marks] { cos(deg(0.5*\wwone*t)) + 0.3*cos(deg(0.5*\wwtwo*t))}; \nextgroupplot[xtick={0, 6.28, 12.56}, xticklabels={0, $2\pi$, $4\pi$},] \addplot[red, thick, no marks] { cos(deg(\wwone*t)) + 0.3*cos(deg(2*\wwtwo*t))}; \end{groupplot} \node[red] at (group c1r1.center) {\huge 1}; \node[red] at (group c2r1.center) {\huge 2}; \node[red] at (group c1r2.center) {\huge 3}; \node[red] at (group c2r2.center) {\huge 4}; \end{tikzpicture} \end{frame} \begin{frame}[label={sec:orgda14f17}]{Exercise 3: Fourier transform of a sampled sinusoid} Consider the continuous and sampled signals with sampling period \(h=\frac{2}{3}T\) \pgfplotsset{ dirac/.style={ mark=triangle*, mark options={scale=0.6}, ycomb, scatter, visualization depends on={y/abs(y)-1 \as \sign}, scatter/@pre marker code/.code={\scope[rotate=90*\sign,yshift=-2pt]} } } \begin{center} \begin{tikzpicture} \small \pgfmathsetmacro{\ww}{1} \pgfmathsetmacro{\TT}{2*pi/\ww} \pgfmathsetmacro{\TTT}{2*\TT} \pgfmathsetmacro{\wws}{3*\ww/2} \pgfmathsetmacro{\hh}{2*pi/\wws} \pgfmathsetmacro{\Ttot}{60} \pgfmathsetmacro{\Nsamples}{floor(\Ttot/\hh)} \begin{axis}[ clip=false, width=14cm, height=3.5cm, xlabel={$t$}, ylabel={$y(t)$}, xmin=0., xmax=\Ttot, ytick = {0}, xtick = {0, \hh, \TT, \TTT}, xticklabels={0, $h$, $T$, $2T$}, ] \addplot+[black, thick,no marks, domain=0:\Ttot, samples=400,variable=t] { sin(deg(\ww*t)) } node [coordinate, pos=0.87, pin=45:{$y(t)$}] {}; \addplot+[color=blue!80!red!90, thick,dirac, domain=0:\Ttot, samples=\Nsamples+1,variable=t] { sin(deg(\ww*t))} node [coordinate, pos=0.93, pin=-45:{$y_s(t)$}] {}; \draw[blue!80!red!90, thick] (axis cs: 0,0) -- (axis cs: \Ttot, 0); \end{axis} \end{tikzpicture} \end{center} What is the frequency of the sinusoid? What is the sampling frequency \(\omega_s\) and the Nyquist frequency \(\omega_N\)? \end{frame} \begin{frame}[label={sec:org390eac2}]{Exercise 3: Fourier transform of a sampled sinusoid} Consider the continuous and sampled signals with sampling period \(h=\frac{2}{3}T\) \pgfplotsset{ dirac/.style={ mark=triangle*, mark options={scale=0.6}, ycomb, scatter, visualization depends on={y/abs(y)-1 \as \sign}, scatter/@pre marker code/.code={\scope[rotate=90*\sign,yshift=-2pt]} } } \begin{center} \begin{tikzpicture} \small \pgfmathsetmacro{\ww}{1} \pgfmathsetmacro{\TT}{2*pi/\ww} \pgfmathsetmacro{\TTT}{2*\TT} \pgfmathsetmacro{\wws}{3*\ww/2} \pgfmathsetmacro{\hh}{2*pi/\wws} \pgfmathsetmacro{\Ttot}{60} \pgfmathsetmacro{\Nsamples}{floor(\Ttot/\hh)} \begin{axis}[ clip=false, width=14cm, height=2.2cm, xlabel={$t$}, ylabel={$y(t)$}, xmin=0., xmax=\Ttot, ytick = {0}, xtick = {0, \hh, \TT, \TTT}, xticklabels={0, $h$, $T$, $2T$}, ] \addplot+[black, thick,no marks, domain=0:\Ttot, samples=400,variable=t] { sin(deg(\ww*t)) } node [coordinate, pos=0.87, pin=45:{$y(t)$}] {}; \addplot+[color=blue!80!red!90, thick,dirac, domain=0:\Ttot, samples=\Nsamples+1,variable=t] { sin(deg(\ww*t))} node [coordinate, pos=0.93, pin=-45:{$y_s(t)$}] {}; \draw[blue!80!red!90, thick] (axis cs: 0,0) -- (axis cs: \Ttot, 0); \end{axis} \end{tikzpicture} \end{center} Which of the below corresponds to the Fourier transform of the \alert{sampled signal}? \pgfplotsset{ dirac/.style={ mark=triangle*, mark options={scale=0.6}, ycomb, scatter, visualization depends on={y/abs(y)-1 \as \sign}, scatter/@pre marker code/.code={\scope[rotate=90*\sign,yshift=-2pt]} } } \begin{tikzpicture} \scriptsize \pgfmathsetmacro{\ww}{1} \pgfmathsetmacro{\TT}{2*pi/\ww} \pgfmathsetmacro{\wws}{3*\ww/2} \pgfmathsetmacro{\wwN}{\wws/2} \pgfmathsetmacro{\omegaone}{\ww-\wwN} \pgfmathsetmacro{\omegathree}{\wws - \ww} \pgfmathsetmacro{\omegafour}{\wwN/2} \begin{groupplot}[group style={group size=2 by 2, vertical sep=1.2cm, horizontal sep=1.3cm}, width=8cm, height=2.5cm, xlabel={$\omega$ [rad/s]}, ylabel={$|Y_s(i\omega)|$}, xmin=-1.8, xmax=1.8, ymax=1.2, ytick = \empty, xtick = \empty, ] \nextgroupplot[xtick={-\wws, -\ww, -\omegaone, 0, \omegaone, \ww, \wws}, xticklabels={$-\frac{3\pi}{T}$, $-\frac{2\pi}{T}$, $-\frac{\pi}{2T}$, $$,$\frac{\pi}{2T}$, $\frac{2\pi}{T}$, $\frac{3\pi}{T}$},] \addplot[red, thick, dirac] coordinates {(-\ww, 1) (-\omegaone, 1) (\omegaone, 1) (\ww, 1)}; \addplot+[black, dotted, no marks] coordinates { (-\wwN, 0) (-\wwN, 2) }; \addplot+[black, dotted, no marks] coordinates { (\wwN, 0) (\wwN, 2) }; \nextgroupplot[xtick={-\wws, -\ww, 0, \ww, \wws}, xticklabels={$-\frac{3\pi}{T}$, $-\frac{2\pi}{T}$, $$, $-\frac{2\pi}{T}$, $\frac{3\pi}{T}$},] \addplot[red, thick, dirac] coordinates {(-\ww, 1) (\ww, 1)}; \addplot+[black, dotted, no marks] coordinates { (-\wwN, 0) (-\wwN, 2) }; \addplot+[black, dotted, no marks] coordinates { (\wwN, 0) (\wwN, 2) }; \nextgroupplot[xtick={-\wws, -\ww, -\omegathree, 0, \omegathree, \ww, \wws}, xticklabels={$-\frac{3\pi}{T}$, $-\frac{2\pi}{T}$, $-\frac{\pi}{T}$, $$,$\frac{\pi}{T}$, $\frac{2\pi}{T}$, $\frac{3\pi}{T}$},] \addplot[red, thick, dirac] coordinates {(-\ww, 1) (-\omegathree, 1) (\omegathree, 1) (\ww, 1)}; \addplot+[black, dotted, no marks] coordinates { (-\wwN, 0) (-\wwN, 2) }; \addplot+[black, dotted, no marks] coordinates { (\wwN, 0) (\wwN, 2) }; \nextgroupplot[xtick={-\wws, -\ww, -\omegafour, 0, \omegafour, \ww, \wws}, xticklabels={$-\frac{3\pi}{T}$, $-\frac{2\pi}{T}$, $-\frac{3\pi}{4T}$, $$,$\frac{3\pi}{4T}$, $\frac{2\pi}{T}$, $\frac{3\pi}{T}$},] \addplot[red, thick, dirac] coordinates {(-\ww, 1) (-\omegafour, 1) (\omegafour, 1) (\ww, 1)}; \addplot+[black, dotted, no marks] coordinates { (-\wwN, 0) (-\wwN, 2) }; \addplot+[black, dotted, no marks] coordinates { (\wwN, 0) (\wwN, 2) }; \end{groupplot} \node[red] at (group c1r1.center) {\huge 1}; \node[red] at (group c2r1.center) {\huge 2}; \node[red] at (group c1r2.center) {\huge 3}; \node[red] at (group c2r2.center) {\huge 4}; \end{tikzpicture} \end{frame} \begin{frame}[label={sec:org676d5be}]{Alias frequency} To find the low frequency alias \(\omega_a<\omega_N\) of a high freqency sinusoid \(\omega_1\), The expression \[ \omega_a = \left| \big( (\omega_1 + \omega_N) \, \text{mod}\, \omega_s\big) - \omega_N\right|\] can be used. \end{frame} \begin{frame}[label={sec:orgf12cdf1}]{Aliasing example} If a continuous-time signal with frequency content (bandwidth) \(\omega_B\) is sampled at too low sampling rate ( \(\omega_s < 2\omega_B\) ), then the energy at higher frequencies is folded onto lower frequencies. \begin{center} \includegraphics[width=0.6\linewidth]{../../figures/aliasing-example.png} \end{center} A high-frequency sinusoid ( \(\omega_1 = 1800\pi\) rad/s ) masquerading as a lower frequency sinusoid ( \(200 \pi\) rad/s ) due to aliasing when sampled with \(h=10^{-3}\) s. \alert{Draw the spectrum (lines) of the two sinusoids. Mark the Nyquist frequency and verify that the alias frequency is obtained by folding about the Nyquist frequency.} \end{frame} \section{antialiasing} \label{sec:org9130c47} \begin{frame}[label={sec:org95929b6}]{Noisy measurements} \begin{columns} \begin{column}{0.6\columnwidth} \begin{center} \begin{tikzpicture} \node {\includegraphics[width=0.99\linewidth]{../../figures/comp-contr-sys.png}}; \node[pin=145:{60Hz mains hum}] at (2.7,2.4) {}; \node[pin=-60:{90Hz sampling freq}] at (0.5,-1.4) {}; \end{tikzpicture} \end{center} \end{column} \begin{column}{0.4\columnwidth} \includegraphics[width=0.99\linewidth]{../../figures/aliasing-example-60Hz} \end{column} \end{columns} \end{frame} \begin{frame}[label={sec:orgba81902}]{Antialiasing filter} The \alert{Bessel filter} is often used. From wikipedia: \begin{quote} In electronics and signal processing, a Bessel filter is a type of analog linear filter with a maximally flat group/phase delay (maximally linear phase response), which preserves the wave shape of filtered signals in the passband. Bessel filters are often used in audio systems. \end{quote} Why use a Bessel filter as antialiasing filter? \end{frame} \begin{frame}[label={sec:org0f7beb3}]{Antialiasing filter} The \alert{Bessel filter} is often used. From wikipedia: \begin{quote} In electronics and signal processing, a Bessel filter is a type of analog linear filter with a maximally flat group/phase delay (maximally linear phase response), which preserves the wave shape of filtered signals in the passband. Bessel filters are often used in audio crossover systems. \end{quote} Why use as antialiasing filter? \begin{itemize} \item Preserves wave shapes \(\Rightarrow\) very little distortion of signals in the passband \item Maximally linear phase response \(\Rightarrow\) \(\arg H \approx -T\omega\), Can be modelled as a pure delay \end{itemize} \end{frame} \end{document}
PERSECUTION of Christians is increasing and for millions of its faithful around the world, 2015 has been a “year of fear”, says Open Doors, which once again has placed North Korea as the most dangerous place to be a Christian. Open Doors, has supported the persecuted church since its founding by Brother Andrews 50 years ago, and each year publishes its World Watch list of the top 50 most dangerous countries to be a Christian. “Islamic extremism remains by far the most common driver of persecution: in eight out of the top 10, and 35 out of the top 50 countries, it is the primary cause,” says the 2016 Open Doors World Watch List. “A rise in Islamic extremism sees Pakistan at its highest position ever, and Libya entering the top ten for the first time,” says the Open Doors reported. It says research shows that persecution against Christians has increased so dramatically that persecution has risen even in those countries that have dropped out of its top 50. Open Doors rates the level of persecution as “extreme” in nine countries. For the 14th year in a row, North Korea is top of the list; followed by Iraq, Eritrea, Afghanistan, Syria, Pakistan, Somalia, Sudan and Iran. The north east African reclusive State of Eritrea has entered the top five for the first time. “Religious extremism – Islamic, Hindu and Buddhist – is the greatest source of persecution of Christians,” says Open Doors, while noting that “gender violence is a weapon of persecution: women and girls are on the frontline.”. Open Doors records show that worldwide there were over 7,000 Christians killed for faith-related reasons in the year – almost 3,000 more than the previous year. It says its estimates exclude North Korea, Syria and Iraq, where accurate records do not exist. Around 2,400 churches were attacked or damaged – over double the number for last year. In terms of violence against Christians and Christian property, Nigeria and Central African Republic topped the list. One of its key findings is that never before have so many Christians been on the move. The entry of India, often referred to as the world’s biggest democracy, into the top 20 most dangerous place at17 is a first. Open Doors says, “Persecution in India is extremely violence – and the violence is increasing. “More than 350 Christians were physically attacked, at least nine Christians were killed for their faith and at least three women were raped in the reporting year. “Attacks mainly come from Hindu extremists, although extremist Muslims, Sikhs, Buddhists and Maoists have all targeted Christians.
Educational and training programs place special emphasis on the World War II period and on the occupation . Events and individuals connected with the war are ubiquitous on TV , on radio and in the print media . The theme remains an important element in literature and learning , in film , theater and the fine arts . Not to mention that politicians constantly make use of it . Probably no other country marks anniversaries related to the events of World War II so often or so solemnly .
isSingleton : Bool -> Type isSingleton True = Nat isSingleton False = List Nat mkSingle : (x:Bool) -> isSingleton x mkSingle True = 0 mkSingle False = [] sum : (single : Bool) -> isSingleton single -> Nat sum True x = x sum False [] = 0 sum False (x::xs) = x + sum False xs
State Before: 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i ⊢ ‖↑f m‖ ≤ ‖f‖ * ∏ i : ι, ‖m i‖ State After: 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i A : 0 ≤ ∏ i : ι, ‖m i‖ ⊢ ‖↑f m‖ ≤ ‖f‖ * ∏ i : ι, ‖m i‖ Tactic: have A : 0 ≤ ∏ i, ‖m i‖ := prod_nonneg fun j _ => norm_nonneg _ State Before: 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i A : 0 ≤ ∏ i : ι, ‖m i‖ ⊢ ‖↑f m‖ ≤ ‖f‖ * ∏ i : ι, ‖m i‖ State After: case inl 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i A : 0 ≤ ∏ i : ι, ‖m i‖ h : 0 = ∏ i : ι, ‖m i‖ ⊢ ‖↑f m‖ ≤ ‖f‖ * ∏ i : ι, ‖m i‖ case inr 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i A : 0 ≤ ∏ i : ι, ‖m i‖ hlt : 0 < ∏ i : ι, ‖m i‖ ⊢ ‖↑f m‖ ≤ ‖f‖ * ∏ i : ι, ‖m i‖ Tactic: cases' A.eq_or_lt with h hlt State Before: case inl 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i A : 0 ≤ ∏ i : ι, ‖m i‖ h : 0 = ∏ i : ι, ‖m i‖ ⊢ ‖↑f m‖ ≤ ‖f‖ * ∏ i : ι, ‖m i‖ State After: case inl.intro.intro 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i A : 0 ≤ ∏ i : ι, ‖m i‖ h : 0 = ∏ i : ι, ‖m i‖ i : ι left✝ : i ∈ univ hi : ‖m i‖ = 0 ⊢ ‖↑f m‖ ≤ ‖f‖ * ∏ i : ι, ‖m i‖ Tactic: rcases prod_eq_zero_iff.1 h.symm with ⟨i, _, hi⟩ State Before: case inl.intro.intro 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i A : 0 ≤ ∏ i : ι, ‖m i‖ h : 0 = ∏ i : ι, ‖m i‖ i : ι left✝ : i ∈ univ hi : ‖m i‖ = 0 ⊢ ‖↑f m‖ ≤ ‖f‖ * ∏ i : ι, ‖m i‖ State After: case inl.intro.intro 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i A : 0 ≤ ∏ i : ι, ‖m i‖ h : 0 = ∏ i : ι, ‖m i‖ i : ι left✝ : i ∈ univ hi : m i = 0 ⊢ ‖↑f m‖ ≤ ‖f‖ * ∏ i : ι, ‖m i‖ Tactic: rw [norm_eq_zero] at hi State Before: case inl.intro.intro 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i A : 0 ≤ ∏ i : ι, ‖m i‖ h : 0 = ∏ i : ι, ‖m i‖ i : ι left✝ : i ∈ univ hi : m i = 0 ⊢ ‖↑f m‖ ≤ ‖f‖ * ∏ i : ι, ‖m i‖ State After: case inl.intro.intro 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i A : 0 ≤ ∏ i : ι, ‖m i‖ h : 0 = ∏ i : ι, ‖m i‖ i : ι left✝ : i ∈ univ hi : m i = 0 this : ↑f m = 0 ⊢ ‖↑f m‖ ≤ ‖f‖ * ∏ i : ι, ‖m i‖ Tactic: have : f m = 0 := f.map_coord_zero i hi State Before: case inl.intro.intro 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i A : 0 ≤ ∏ i : ι, ‖m i‖ h : 0 = ∏ i : ι, ‖m i‖ i : ι left✝ : i ∈ univ hi : m i = 0 this : ↑f m = 0 ⊢ ‖↑f m‖ ≤ ‖f‖ * ∏ i : ι, ‖m i‖ State After: case inl.intro.intro 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i A : 0 ≤ ∏ i : ι, ‖m i‖ h : 0 = ∏ i : ι, ‖m i‖ i : ι left✝ : i ∈ univ hi : m i = 0 this : ↑f m = 0 ⊢ 0 ≤ ‖f‖ * ∏ i : ι, ‖m i‖ Tactic: rw [this, norm_zero] State Before: case inl.intro.intro 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i A : 0 ≤ ∏ i : ι, ‖m i‖ h : 0 = ∏ i : ι, ‖m i‖ i : ι left✝ : i ∈ univ hi : m i = 0 this : ↑f m = 0 ⊢ 0 ≤ ‖f‖ * ∏ i : ι, ‖m i‖ State After: no goals Tactic: exact mul_nonneg (op_norm_nonneg f) A State Before: case inr 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i A : 0 ≤ ∏ i : ι, ‖m i‖ hlt : 0 < ∏ i : ι, ‖m i‖ ⊢ ‖↑f m‖ ≤ ‖f‖ * ∏ i : ι, ‖m i‖ State After: case inr 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i A : 0 ≤ ∏ i : ι, ‖m i‖ hlt : 0 < ∏ i : ι, ‖m i‖ ⊢ ‖↑f m‖ / ∏ i : ι, ‖m i‖ ≤ ‖f‖ Tactic: rw [← div_le_iff hlt] State Before: case inr 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i A : 0 ≤ ∏ i : ι, ‖m i‖ hlt : 0 < ∏ i : ι, ‖m i‖ ⊢ ‖↑f m‖ / ∏ i : ι, ‖m i‖ ≤ ‖f‖ State After: case inr 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i A : 0 ≤ ∏ i : ι, ‖m i‖ hlt : 0 < ∏ i : ι, ‖m i‖ ⊢ ∀ (b : ℝ), b ∈ {c | 0 ≤ c ∧ ∀ (m : (i : ι) → E i), ‖↑f m‖ ≤ c * ∏ i : ι, ‖m i‖} → ‖↑f m‖ / ∏ i : ι, ‖m i‖ ≤ b Tactic: apply le_csInf bounds_nonempty State Before: case inr 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i A : 0 ≤ ∏ i : ι, ‖m i‖ hlt : 0 < ∏ i : ι, ‖m i‖ ⊢ ∀ (b : ℝ), b ∈ {c | 0 ≤ c ∧ ∀ (m : (i : ι) → E i), ‖↑f m‖ ≤ c * ∏ i : ι, ‖m i‖} → ‖↑f m‖ / ∏ i : ι, ‖m i‖ ≤ b State After: case inr.intro 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c✝ : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i A : 0 ≤ ∏ i : ι, ‖m i‖ hlt : 0 < ∏ i : ι, ‖m i‖ c : ℝ left✝ : 0 ≤ c hc : ∀ (m : (i : ι) → E i), ‖↑f m‖ ≤ c * ∏ i : ι, ‖m i‖ ⊢ ‖↑f m‖ / ∏ i : ι, ‖m i‖ ≤ c Tactic: rintro c ⟨_, hc⟩ State Before: case inr.intro 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c✝ : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i A : 0 ≤ ∏ i : ι, ‖m i‖ hlt : 0 < ∏ i : ι, ‖m i‖ c : ℝ left✝ : 0 ≤ c hc : ∀ (m : (i : ι) → E i), ‖↑f m‖ ≤ c * ∏ i : ι, ‖m i‖ ⊢ ‖↑f m‖ / ∏ i : ι, ‖m i‖ ≤ c State After: case inr.intro 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c✝ : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i A : 0 ≤ ∏ i : ι, ‖m i‖ hlt : 0 < ∏ i : ι, ‖m i‖ c : ℝ left✝ : 0 ≤ c hc : ∀ (m : (i : ι) → E i), ‖↑f m‖ ≤ c * ∏ i : ι, ‖m i‖ ⊢ ‖↑f m‖ ≤ c * ∏ i : ι, ‖m i‖ Tactic: rw [div_le_iff hlt] State Before: case inr.intro 𝕜 : Type u ι : Type v ι' : Type v' n : ℕ E : ι → Type wE E₁ : ι → Type wE₁ E' : ι' → Type wE' Ei : Fin (Nat.succ n) → Type wEi G : Type wG G' : Type wG' inst✝¹⁴ : Fintype ι inst✝¹³ : Fintype ι' inst✝¹² : NontriviallyNormedField 𝕜 inst✝¹¹ : (i : ι) → NormedAddCommGroup (E i) inst✝¹⁰ : (i : ι) → NormedSpace 𝕜 (E i) inst✝⁹ : (i : ι) → NormedAddCommGroup (E₁ i) inst✝⁸ : (i : ι) → NormedSpace 𝕜 (E₁ i) inst✝⁷ : (i : ι') → NormedAddCommGroup (E' i) inst✝⁶ : (i : ι') → NormedSpace 𝕜 (E' i) inst✝⁵ : (i : Fin (Nat.succ n)) → NormedAddCommGroup (Ei i) inst✝⁴ : (i : Fin (Nat.succ n)) → NormedSpace 𝕜 (Ei i) inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G inst✝¹ : NormedAddCommGroup G' inst✝ : NormedSpace 𝕜 G' c✝ : 𝕜 f g : ContinuousMultilinearMap 𝕜 E G m : (i : ι) → E i A : 0 ≤ ∏ i : ι, ‖m i‖ hlt : 0 < ∏ i : ι, ‖m i‖ c : ℝ left✝ : 0 ≤ c hc : ∀ (m : (i : ι) → E i), ‖↑f m‖ ≤ c * ∏ i : ι, ‖m i‖ ⊢ ‖↑f m‖ ≤ c * ∏ i : ι, ‖m i‖ State After: no goals Tactic: apply hc
We flew into Chisinau not really knowing what to expect, and we were pleasantly surprised! The city doesn’t have many highlights, but there are some great restaurants and bars around. For dinner we went to Gastrobar, a great place serving modern Middle Eastern cuisine, with plenty of veggie options. Make sure to reserve a table in advance. Dinner for two including drinks and tip for 1,000MDL. We also visited Propaganda, a popular restaurant with quirky decor serving yummy food. A light dinner for two including drinks and top for 400MDL. Wine: Moldovan wine is amazing and very cheap! Most restaurants and bars have a great wine list and you can find a good selection in supermarkets too. Stay: We stayed in one of these apartments. It was spotless and ideally located. One of the few places remaining for us to visit in Europe was Liechtenstein, so we flew into Zurich for the weekend to check it out. We were really impressed by the food in Zurich. There are plenty of vegan and veggie options clearly labelled in most places. In supermarkets, vegan items are clearly labelled and options are plentiful. Hiltl Haus: The oldest vegetarian restaurant in Europe is a popular place with a buffet and a la carte options. The food is varied a really delicious. Dinner for two including drinks and tip for 79CHF. Stay: We stayed at Swiss Star Apartments, a good self-catering option located just 10 minutes from the Central Station. Vaduz is a small town surrounded by picturesque snow-capped mountains. The main attraction is the walk from the centre up to Vaduz Castle. The castle itself is not open to tourists but the walk gives you the most amazing views. Kunstmuseum: This modern art museum has a small but good selection of works in a nice space. Tickets for 15CHF. Go: From Zurich to Vaduz in Liechtenstein the best option is to take a train to Sargans where you can get bus n. 11 to Vaduz. You can buy tickets online here (choose option Vaduz, Post, which includes the bus transfers), about one month in advance. We were going to visit San Marino, so we decided to spend a couple of days in nearby Rimini. Rimini is a riviera with sandy beaches overlooked by cool modernist hotels. The Old Town is beautiful and includes a good collection of Roman and Medieval landmarks. It is also the birthplace of Italian filmmaker Federico Fellini. For lunch we visited Bar Lento, a cool cafe serving delicious vegan snacks and drinks (lunch for two including tip for 18.50€). Rimini is definitely a good place to visit and relax for a couple of days! San Marino was one of the few European countries we hadn’t visited yet, so we decided to check in out in January. It is located high up in the mountains, giving it amazing views over the region. Unfortunately when we visited the place was right in the middle of the clouds, and we couldn’t even see further than a few metres ahead. We spent a few hours exploring the narrow roads and visiting the main towers, even without being able to see much. For lunch, we stopped at Laminona, which serves piadinas and offered a few vegan options. San Marino is picturesque and I’m sure we would have enjoyed it more on a sunny day! Go: We flew to Bologna, where you can get semi-frequent buses from the airport to Rimini. You can reach San Marino from Rimini taking a regular bus which departs just outside the train station (return for 10€ per person). The trip takes 50 minutes each way. This was another year full of adventures! We kicked off the year with a weekend with friends in Edinburgh. Then we headed to amazing South Africa for a wedding – we hung out with elephants and enjoyed the breathtaking views. In March we braved the cold to discover fun Riga. In April we travelled around Sicily, eating all sorts of treats along the way. In May we relaxed in sunny Paphos, Cyprus. Then we headed to Berlin for a weekend full of amazing vegan treats. I went to Paris for a beautiful weekend of chilling in the sun. In September we had an adventure in the Balkans: we visited Kosovo, Macedonia and Albania – a great trip! In October we flew to Barcelona and took the train to Andorra. I finished the year with Christmas in Rome! Another year full of amazing adventures! And I have big plans for 2019: I may actually finish visiting every single European country!
(* Title: Psi-calculi Based on the AFP entry by Jesper Bengtson ([email protected]), 2012 *) theory Old_Weak_Simulation imports Old_Simulation Old_Tau_Chain "NewPsi.Weak_Simulation" "NewPsi.Weak_Stat_Imp" "NewPsi.Weak_Cong_Simulation" begin context old_psi begin definition "oldWeakSimulation" :: "'b \<Rightarrow> ('a, 'b, 'c) psi \<Rightarrow> ('b \<times> ('a, 'b, 'c) psi \<times> ('a, 'b, 'c) psi) set \<Rightarrow> ('a, 'b, 'c) psi \<Rightarrow> bool" ("_ \<rhd> _ \<leadsto><_>\<^sub>O _" [80, 80, 80, 80] 80) where "\<Psi> \<rhd> P \<leadsto><Rel>\<^sub>O Q \<equiv> (\<forall>\<Psi>' \<alpha> Q'. \<Psi> \<rhd> Q \<longmapsto>\<^sub>O \<alpha> \<prec> Q' \<longrightarrow> bn \<alpha> \<sharp>* \<Psi> \<longrightarrow> bn \<alpha> \<sharp>* P \<longrightarrow> \<alpha> \<noteq> \<tau> \<longrightarrow> (\<exists>P''. \<Psi> : Q \<rhd> P \<Longrightarrow>\<^sub>O \<alpha> \<prec> P'' \<and> (\<exists>P'. \<Psi> \<otimes> \<Psi>' \<rhd> P'' \<Longrightarrow>\<^sup>^\<^sub>\<tau>\<^sub>O P' \<and> (\<Psi> \<otimes> \<Psi>', P', Q') \<in> Rel))) \<and> (\<forall>Q'. \<Psi> \<rhd> Q \<longmapsto>\<^sub>O \<tau> \<prec> Q' \<longrightarrow> (\<exists>P'. \<Psi> \<rhd> P \<Longrightarrow>\<^sup>^\<^sub>\<tau>\<^sub>O P' \<and> (\<Psi>, P', Q') \<in> Rel))" abbreviation oldWeakSimulationNilJudge ("_ \<leadsto><_>\<^sub>O _" [80, 80, 80] 80) where "P \<leadsto><Rel>\<^sub>O Q \<equiv> \<one> \<rhd> P \<leadsto><Rel>\<^sub>O Q" lemma oldWeakSimulationEq: shows "(\<Psi> \<rhd> P \<leadsto><Rel>\<^sub>O Q) = \<Psi> \<rhd> P \<leadsto><Rel> Q" (is "?A = ?B") proof(rule iffI) show "?A \<Longrightarrow> ?B" by(clarsimp simp add: weakSimulation_def oldWeakSimulation_def old_tau_chain_new old_tau_step_chain_new) (blast dest: old_semantics_complete old_weak_transition_sound old_weak_transition_tau_sound) next show "?B \<Longrightarrow> ?A" by(clarsimp simp add: weakSimulation_def oldWeakSimulation_def old_tau_chain_new old_tau_step_chain_new) (blast dest: old_semantics_tau_sound old_semantics_sound old_weak_transition_complete) qed definition "old_weak_stat_imp" :: "'b \<Rightarrow> ('a, 'b, 'c) psi \<Rightarrow> ('b \<times> ('a, 'b, 'c) psi \<times> ('a, 'b, 'c) psi) set \<Rightarrow> ('a, 'b, 'c) psi \<Rightarrow> bool" ("_ \<rhd> _ \<lessapprox><_>\<^sub>O _" [80, 80, 80, 80] 80) where "\<Psi> \<rhd> P \<lessapprox><Rel>\<^sub>O Q \<equiv> \<forall>\<Psi>'. \<exists>Q' Q''. \<Psi> \<rhd> Q \<Longrightarrow>\<^sup>^\<^sub>\<tau>\<^sub>O Q' \<and> insert_assertion(extract_frame P) \<Psi> \<hookrightarrow>\<^sub>F insert_assertion(extract_frame Q') \<Psi> \<and> \<Psi> \<otimes> \<Psi>' \<rhd> Q' \<Longrightarrow>\<^sup>^\<^sub>\<tau>\<^sub>O Q'' \<and> (\<Psi> \<otimes> \<Psi>', P, Q'') \<in> Rel" lemma old_weak_stat_imp_eq: shows "\<Psi> \<rhd> P \<lessapprox><Rel>\<^sub>O Q = \<Psi> \<rhd> P \<lessapprox><Rel> Q" by(simp add: old_weak_stat_imp_def weak_stat_imp_def old_tau_chain_new) definition "oldWeakCongSimulation" :: "'b \<Rightarrow> ('a, 'b, 'c) psi \<Rightarrow> ('b \<times> ('a, 'b, 'c) psi \<times> ('a, 'b, 'c) psi) set \<Rightarrow> ('a, 'b, 'c) psi \<Rightarrow> bool" ("_ \<rhd> _ \<leadsto>\<guillemotleft>_\<guillemotright>\<^sub>O _" [80, 80, 80, 80] 80) where "\<Psi> \<rhd> P \<leadsto>\<guillemotleft>Rel\<guillemotright>\<^sub>O Q \<equiv> \<forall>Q'. \<Psi> \<rhd> Q \<longmapsto>\<^sub>O \<tau> \<prec> Q' \<longrightarrow> (\<exists>P'. \<Psi> \<rhd> P \<Longrightarrow>\<^sub>\<tau>\<^sub>O P' \<and> (\<Psi>, P', Q') \<in> Rel)" lemma old_weak_cong_simulation_eq: shows "(\<Psi> \<rhd> P \<leadsto>\<guillemotleft>Rel\<guillemotright>\<^sub>O Q) = \<Psi> \<rhd> P \<leadsto>\<guillemotleft>Rel\<guillemotright> Q" (is "?A = ?B") proof(rule iffI) show "?A \<Longrightarrow> ?B" by(clarsimp simp add: weakCongSimulation_def oldWeakCongSimulation_def old_tau_chain_new old_tau_step_chain_new) (blast dest: old_semantics_complete old_weak_transition_sound old_weak_transition_tau_sound) next show "?B \<Longrightarrow> ?A" by(clarsimp simp add: weakCongSimulation_def oldWeakCongSimulation_def old_tau_chain_new old_tau_step_chain_new) (blast dest: old_semantics_tau_sound old_semantics_sound old_weak_transition_complete) qed end end
#Solving circuits with sympy This documents explains how to solve electrical circuits using the **sympy** symbolic math module. # Imports First we need to import the sympy module ```python # Import the sympy module import sympy ``` ## Example DC circuit The following circuit includes one voltage source, one current source and two resistors. The objective is to obtain the output voltage **Vo** as function of the components. The circuit will be solved using the **nodal** method. First we need to locate the circuit **nodes**, assign one as **ground** and assign a number for the rest of them. As the circuit has three nodes and one is ground, we have two nodes left: 1 and 2. We will first generate a set of sympy symbols. There will be: * One symbol for each component: Vs, R1, R2, Is * One current symbol for each power sypply: iVs * One symbol for each measurement we want to obtain: Vo * One symbol for each node voltage that is not ground: V1, V2 ```python # Create the circuit symbols Vs,iVs,R1,R2,Is,Vo, V1, V2 = sympy.symbols('Vs,iVs,R1,R2,Is,Vo,V1,V2') ``` Then we can define the current equations on each node except ground. The current equations add all the currents in the node from each component. All equations we add, are supposed to have a result of **zero**. ```python # Create an empty list of equations equations = [] # Nodal equations equations.append(iVs-(V1-V2)/R1) # Node 1 equations.append(Is-(V2-V1)/R1-V2/R2) # Node 2 ``` Then we add one equation for each voltage source that associates its voltage with the node voltages. If we want to use two sided equations, we can use the sympy **Eq** function that equates the two sides. ```python # Voltage source equations equations.append(sympy.Eq(Vs,V1)) ``` Finally we add one equation for each measurement we want to obtain ```python # Measurement equations equations.append(sympy.Eq(Vo,V2)) ``` Now we can define the unknows for the circuit. The number of unknowns shall be equal to the number of equations. The list includes: * The node voltages: V1, V2 * The current on voltage sources: iVs * The measurement values: Vo ```python unknowns = [V1,V2,iVs,Vo] ``` We can see the equations and unknows before solving the circuit. To ease reusing the code, we will define a **showCircuit** function that shows equations and unknowns ```python # Define the function def showCircuit(): print('Equations') for eq in equations: print(' ',eq) print() print('Unknowns:',unknowns) print() # Use the function showCircuit() ``` Equations iVs - (V1 - V2)/R1 Is - V2/R2 - (-V1 + V2)/R1 Eq(Vs, V1) Eq(Vo, V2) Unknowns: [V1, V2, iVs, Vo] Now, we can solve the circuit. The sympy **solve** function gets a list of equations and unknowns and return a **dictionary** with solved unknowns The following code solves the circuit and list the solutions ```python # Solve the circuit solution = sympy.solve(equations,unknowns) # List the solutions print('Solutions') for sol in solution: print(' ',sol,'=',solution[sol]) ``` Solutions V1 = Vs V2 = R2*(Is*R1 + Vs)/(R1 + R2) iVs = (-Is*R2 + Vs)/(R1 + R2) Vo = R2*(Is*R1 + Vs)/(R1 + R2) Note that, in this case, the equation that includes **iVs** is only needed to obtain this unknown, so we can eliminate its equation and the **iVs** unknown if we don't need the **iVs** solution. Note also that we can easily identify **V1** as **Vs**, so we can also eliminate the **Vs** equation if we use **Vs** as the voltage on node **V1** Finally note that we can also identify **V2** as **Vo** so we can also eliminate the **Vo** equation. The following code solves the circuit using only one equations ```python solution = sympy.solve(Is-(Vo-Vs)/R1-Vo/R2,Vo) print('Vo =',solution[0]) ``` Vo = R2*(Is*R1 + Vs)/(R1 + R2) ## Solve using the loop current method Instead of using the **nodal** method, we could also use the complementary **loop current** method In this method we assign a current to each loop in the circuit We will first generate a set of sympy symbols. There will be: * One symbol for each component: Vs, R1, R2, Is * One voltage symbol for each current sypply: Vo * One symbol for each measurement we want to obtain: Vo * One symbol for each loop current: I1, I2 Note that, in this circuit, **Vo** appears two times, as the voltage on the **Is** source and as the value to measure. Logically we only define one **Vo** symbol. ```python # Create the circuit symbols Vs,R1,R2,Is,Vo,I1,I2 = sympy.symbols('Vs,R1,R2,Is,Vo,I1,I2') ``` Then we create a list of equations and add one equation for each loop that adds all voltages on the loop ```python # New list of equations equations = [] # Loop current equations equations.append(Vs-R1*I1-R2*(I1-I2)) # Loop current 1 equations.append(-R2*(I2-I1)-Vo) # Loop current 2 ``` Then we create one equation for each current supply that relates it to the loop currents ```python # Current source equations equations.append(sympy.Eq(Is,-I2)) # Current source Is ``` Now we can define the unknows for the circuit. The number of unknowns shall be equal to the number of equations. The list includes: * The loop currents: I1, I2 * The voltage on current sources: Vo * The measurement values: Vo ```python # Unknowns list unknowns = [I1,I2,Vo] ``` We can see the equations and unknows before solving the circuit ```python showCircuit() ``` Equations -I1*R1 - R2*(I1 - I2) + Vs -R2*(-I1 + I2) - Vo Eq(Is, -I2) Unknowns: [I1, I2, Vo] Now we can obtain the solution ```python # Obtain solution solution = sympy.solve(equations,unknowns) print('Vo =',solution[Vo]) ``` Vo = R2*(Is*R1 + Vs)/(R1 + R2) As in the **nodal** case, you could have used less equations. For instance, you could have used the **Is** current for the second loop. ```python # Create the circuit symbols Vs,R1,R2,Is,Vo,I1 = sympy.symbols('Vs,R1,R2,Is,Vo,I1') # New list of equations equations = [] # Loop current equations equations.append(Vs-R1*I1-R2*(I1+Is)) # Loop current 1 equations.append(R2*(Is+I1)-Vo) # Loop current 2 # Unknowns list unknowns = [I1,Vo] # Show equations and unknowns showCircuit() # Obtain solution solution = sympy.solve(equations,unknowns) print('Vo =',solution[Vo]) ``` Equations -I1*R1 - R2*(I1 + Is) + Vs R2*(I1 + Is) - Vo Unknowns: [I1, Vo] Vo = R2*(Is*R1 + Vs)/(R1 + R2) ## Circuit with current measurements The following example is special because the circuit has current measurements **I1** and **I2** that we want to obtain The circuit can be solved using four different methods ### Method #1 : Use nodal method and get currents from resistors In this method we will just use the normal nodal methods and we will compute the currents using Ohm's law Note that we don't need the current on **Vs** so there is no point in obtaining the equation on node 1 ```python # Symbols for the circuit Vs,R1,R2,R3,V2,I1,I2 = sympy.symbols('Vs,R1,R2,R3,V2,I1,I2') # Nodal equation only on node 2 equations = [] equations.append(-(V2-Vs)/R1-V2/R2-V2/R3) # Equations for the currents using Ohm's law equations.append(sympy.Eq(I1,V2/R2)) equations.append(sympy.Eq(I2,V2/R3)) # Unknowns unknowns = [V2,I1,I2] # Show equations and unknowns showCircuit() # Solve the circuit solution = sympy.solve(equations,unknowns) print('I1 =',solution[I1]) print('I2 =',solution[I2]) ``` Equations -V2/R3 - V2/R2 + (-V2 + Vs)/R1 Eq(I1, V2/R2) Eq(I2, V2/R3) Unknowns: [V2, I1, I2] I1 = R3*Vs/(R1*R2 + R1*R3 + R2*R3) I2 = R2*Vs/(R1*R2 + R1*R3 + R2*R3) ### Method #2 : Use four nodes plus ground We can split the node 2 in three nodes: 2, 3 and 4 That way we can use the current equations to obtain I1 and I2 As all three nodes have the same voltage, we can set them equal using two equations As in the previous case, we don't need the equation in node 1 ```python # Symbols for the circuit Vs,R1,R2,R3,V2,V3,V4,I1,I2 = sympy.symbols('Vs,R1,R2,R3,V2,V3,V4,I1,I2') # Node equations equations = [] equations.append(-(V2-Vs)/R1-I1-I2) # Node 2 equations.append(I1-V3/R2) # Node 3 equations.append(I2-V4/R3) # Node 4 # In fact, nodes 2, 3 and 4 are the same equations.append(sympy.Eq(V2,V3)) equations.append(sympy.Eq(V2,V4)) # Unknowns unknowns = [V2,V3,V4,I1,I2] # Show equations and unknowns showCircuit() # Solve the circuit solution = sympy.solve(equations,unknowns) print('I1 =',solution[I1]) print('I2 =',solution[I2]) ``` Equations -I1 - I2 + (-V2 + Vs)/R1 I1 - V3/R2 I2 - V4/R3 Eq(V2, V3) Eq(V2, V4) Unknowns: [V2, V3, V4, I1, I2] I1 = R3*Vs/(R1*R2 + R1*R3 + R2*R3) I2 = R2*Vs/(R1*R2 + R1*R3 + R2*R3) ### Method #3 : Use the loop current method In this case we will define two loop currents * Ia goes on the first loop: Vs -> R1 -> R2 * I2 goes on the second loop: R2 -> R3 ```python # Symbols for the circuit Vs,R1,R2,R3,Ia,I1,I2 = sympy.symbols('Vs,R1,R2,R3,Ia,I1,I2') # Loop equations equations = [] equations.append(Vs-R1*Ia-R2*(Ia-I2)) # Loop Ia equations.append(-R2*(I2-Ia)-R3*I2) # Loop I2 # Define I1 from loop currents equations.append(sympy.Eq(I1,Ia-I2)) # Unknowns unknowns = [Ia,I1,I2] # Show equations and unknowns showCircuit() # Solve the circuit solution = sympy.solve(equations,unknowns) print('I1 =',solution[I1]) print('I2 =',solution[I2]) ``` Equations -Ia*R1 - R2*(-I2 + Ia) + Vs -I2*R3 - R2*(I2 - Ia) Eq(I1, -I2 + Ia) Unknowns: [Ia, I1, I2] I1 = R3*Vs/(R1*R2 + R1*R3 + R2*R3) I2 = R2*Vs/(R1*R2 + R1*R3 + R2*R3) ### Method #4 : Use a modified loop current method In this method we will use **I1** and **I2** as loop currents * I1 goes Vs -> R1 -> R2 * I2 goes Vs -> R1 -> R3 ```python # Symbols for the circuit Vs,R1,R2,R3,I1,I2 = sympy.symbols('Vs,R1,R2,R3,I1,I2') # Loop equations equations = [] equations.append(Vs-R1*(I1+I2)-R2*I1) # Loop I1 equations.append(Vs-R1*(I1+I2)-R3*I2) # Loop I2 # Unknowns unknowns = [I1,I2] # Show equations and unknowns showCircuit() # Solve the circuit solution = sympy.solve(equations,unknowns) print('I1 =',solution[I1]) print('I2 =',solution[I2]) ``` Equations -I1*R2 - R1*(I1 + I2) + Vs -I2*R3 - R1*(I1 + I2) + Vs Unknowns: [I1, I2] I1 = R3*Vs/(R1*R2 + R1*R3 + R2*R3) I2 = R2*Vs/(R1*R2 + R1*R3 + R2*R3) ## Controlled voltage source The following circuit includes voltage controlled source In this case we will treat the controlled voltage source as an independent voltage source, but, we will use $k \cdot V_m$ as its value. That means that we will need to add an equation to add $V_m$ to the set of symbols The following code defines and solves the circuit using the loop current method. ```python # Symbols for the circuit Vs,R1,R2,k,R3,I1,I2,Vm = sympy.symbols('Vs,R1,R2,k,R3,I1,I2,Vm') # Loop equations equations = [] equations.append(Vs-I1*R1-I1*R2) # Loop I1 equations.append(k*Vm-I2*R3) # Loop I2 # Equations for Vm and Vo equations.append(sympy.Eq(Vm,I1*R2)) equations.append(sympy.Eq(Vo,I2*R3)) # Unknowns unknowns = [I1,I2,Vm,Vo] # Show equations and unknowns showCircuit() # Solve the circuit solution = sympy.solve(equations,unknowns) print('Vo =',solution[Vo]) ``` Equations -I1*R1 - I1*R2 + Vs -I2*R3 + Vm*k Eq(Vm, I1*R2) Eq(Vo, I2*R3) Unknowns: [I1, I2, Vm, Vo] Vo = R2*Vs*k/(R1 + R2) The circuit could also be solved using the nodal method. Remember that we don't need the nodal equations for nodes on grounded supplies if we don't need the supply current ```python # Symbols for the circuit Vs,Vm,Vo,R1,R2,k = sympy.symbols('Vs,Vm,Vo,R1,R2,k') # Node equation equations = [] equations.append(-(Vm-Vs)/R1-Vm/R2) # Equation for Vo equations.append(sympy.Eq(Vo,k*Vm)) # Unknowns unknowns = [Vm,Vo] # Show equations and unknowns showCircuit() # Solve the circuit solution = sympy.solve(equations,unknowns) print('Vo =',solution[Vo]) ``` Equations -Vm/R2 + (-Vm + Vs)/R1 Eq(Vo, Vm*k) Unknowns: [Vm, Vo] Vo = R2*Vs*k/(R1 + R2) ## RC Circuit Now we can also solve circuits with capacitor or inductors You just need to define the **capacitors** currents and voltages as function of the **s** variable: $\qquad i_C = V_C \cdot C \cdot s \qquad v_C = \frac{i_C}{C \cdot s}$ Also, for **inductors**: $\qquad i_L = \frac{V_L}{L \cdot s} \qquad v_L = i_L \cdot L \cdot s$ We will use the following circuit as an example The following code describes and solves the circuit using the current loop method ```python # Symbols for the circuit Vs,R1,R3,C1,C2,Vo,I1,I2,s = sympy.symbols('Vs,R1,R3,C1,C2,Vo,I1,I2,s') # Loop equations equations = [] equations.append(Vs-R1*I1-(I1-I2)/(C1*s)) equations.append(-(I2-I1)/(C1*s)-R3*I2-I2/(C2*s)) # Equation for Vo equations.append(sympy.Eq(Vo,I2/(C2*s))) # Unknowns unknowns = [I1,I2,Vo] # Show equations and unknowns showCircuit() # Solve the circuit solution = sympy.solve(equations,unknowns) Vo_s = solution[Vo] print('Solution') print(' Vo =',Vo_s) ``` Equations -I1*R1 + Vs - (I1 - I2)/(C1*s) -I2*R3 - I2/(C2*s) + (I1 - I2)/(C1*s) Eq(Vo, I2/(C2*s)) Unknowns: [I1, I2, Vo] Solution Vo = -C1*Vs/(C2 - (C1*R1*s + 1)*(C1*C2*R3*s + C1 + C2)) We can obtain a better solution equation using **simplify**, **expand** and **collect** from the sympy module ```python # Use simplify, expand and collect to give a prettier equation Vo_s = Vo_s.simplify().expand() # Eliminate quotients of quotients Vo_s = sympy.collect(Vo_s,s).simplify() # Group s symbols and simplify print('Prettier solution') print(' Vo =',Vo_s) ``` Prettier solution Vo = Vs/(C1*C2*R1*R3*s**2 + s*(C1*R1 + C2*R1 + C2*R3) + 1) We can obtian a particular solution using numbers to substitute the literals To substitute one symbol you can use: >`expr.subs(oldSymbol,newSymbol)` But, in order to substitute several symbols at once you can use a substitution dictionary: >`expr.subs({old1:new1,old2:new2,....})` Substituting in our example we get a **particular** solution ```python H_s = Vo_s.subs({Vs:1,R1:1000,R3:100,C1:1e-6,C2:100e-9}) H_s = H_s.simplify() print('Particular solution') print(' H(s) = Vo(s)/Vs(s) =',H_s) ``` Particular solution H(s) = Vo(s)/Vs(s) = 1/(1.0e-8*s**2 + 0.00111*s + 1) We can also get the **poles**, the **zeros** and the **DC gain** ```python numer,denom =H_s.as_numer_denom() print('Num =',numer) print('Den =',denom) print() zeros = sympy.roots(numer,s) poles = sympy.roots(denom,s) print('Zeros =',zeros) print('Poles =',poles) print() print('DC gain =',H_s.subs(s,0).evalf()) ``` Num = 1 Den = 1.0e-8*s**2 + 0.00111*s + 1 Zeros = {} Poles = {-110091.666030631: 1, -908.333969368548: 1} DC gain = 1.00000000000000 ## Opamp circuit We can also solve operational amplifier circuits The easiest solution is obtained if we can guarantee that the **virtual shortcircuit** holds In this case, the opamp output is an unknown and the two input voltages are equal: $\qquad V_{(+)}=V_{(-)}$ We will use the nodal method. Remember that we don't need the node equations in nodes 1 and 3 because we don't need the source currents ```python # Symbols for the circuit Vs,Ri,Rf,Vo,V2 = sympy.symbols('Vs,Ri,Rf,Vo,V2') # Node equation equations = [] equations.append(-(V2-Vs)/Ri-(V2-Vo)/Rf) # Virtual shortcircuit equations.append(V2) # V2 = V(+) = 0 # Unknowns unknowns = [V2,Vo] # Show equations and unknowns showCircuit() # Solve the circuit solution = sympy.solve(equations,unknowns) print('Vo =',solution[Vo]) ``` Equations (-V2 + Vs)/Ri - (V2 - Vo)/Rf V2 Unknowns: [V2, Vo] Vo = -Rf*Vs/Ri ### Finite gain solution If we don't want to use the **virtual short circuit** we can solve the opamp as a voltage controlled voltage source In this case the opamp can be defined with two equations: $\qquad V_d = V_{(+)}-V_{(-)}$ $\qquad V_O = A \cdot V_d $ Then, the ideal case will be given when $A \rightarrow \infty$ ```python # Symbols for the circuit Vs,Ri,Rf,Vo,V2,Vd,A = sympy.symbols('Vs,Ri,Rf,Vo,V2,Vd,A') # Node equation equations = [] equations.append(-(V2-Vs)/Ri-(V2-Vo)/Rf) # Opamp equations equations.append(sympy.Eq(Vd,0-V2)) equations.append(sympy.Eq(Vo,A*Vd)) # Unknowns unknowns = [V2,Vo,Vd] # Show equations and unknowns showCircuit() # Solve the circuit solution = sympy.solve(equations,unknowns) print('Solution as function of A') print() print(' Vo =',solution[Vo]) print() print('Solution for A -> oo') print() print(' Vo =',sympy.limit(solution[Vo],A,sympy.oo)) ``` Equations (-V2 + Vs)/Ri - (V2 - Vo)/Rf Eq(Vd, -V2) Eq(Vo, A*Vd) Unknowns: [V2, Vo, Vd] Solution as function of A Vo = -A*Rf*Vs/(A*Ri + Rf + Ri) Solution for A -> oo Vo = -Rf*Vs/Ri ### Dominant pole solution Having a solution as function of **A** enables us to obtain the response of the circuit using a dominant pole model for the operational amplifier. Just susbtitute, in the solution **A** for the one pole model of the opamp $\qquad A = \frac{Ao \cdot p1}{s+p1}$ ```python # New A, p1 and s symbols Ao,p1,s = sympy.symbols('Ao,p1,s') Vo_s = solution[Vo].subs(A,Ao*p1/(s+p1)) # Use simplify, expand and collect to give a prettier equation Vo_s = Vo_s.simplify().expand() # Eliminate quotients of quotients Vo_s = sympy.collect(Vo_s,s) # Group s symbols Vo_s = sympy.collect(Vo_s,Ri) # Group Ri symbols print('Vo(s) =',Vo_s) ``` Vo(s) = -Ao*Rf*Vs*p1/(Rf*p1 + Ri*(Ao*p1 + p1) + s*(Rf + Ri)) We can obtian, as in a previous example, a particular solution using numbers to substitute the literals In our opamp circuit solution we substitute: * Circuit resistors: R1, R2 * Opamp model: Ao, p1 We also substitute Vs for 1 to obtain the transfer function $H(s)$ $\qquad H(s)=\frac{V_O(s)}{V_s(s)}$ ```python H_s = Vo_s.subs({Vs:1,Ao:100000,Rf:100000,Ri:10000,p1:16}) print('H(s) =',H_s) ``` H(s) = -160000000000/(110000*s + 16001760000) Now you can also obtain the **poles** and **zeros** of $H(s)$ Also we can get the DC gain We will use the **evalf()** method that evaluates a **sympy** expression to a floating point number ```python numer,denom =H_s.as_numer_denom() print('Num =',numer) print('Den =',denom) print() zeros = sympy.roots(numer,s) poles = sympy.roots(denom,s) print('Zeros =',zeros) print('Poles =',poles) print() print('DC gain =',H_s.subs(s,0).evalf()) ``` Num = -160000000000 Den = 110000*s + 16001760000 Zeros = {} Poles = {-1600176/11: 1} DC gain = -9.99890012098669 <BR><BR><BR><BR><BR><BR> ## Document information Copyright © Vicente Jiménez (2018) Last update: 26/3/2018 This work is licensed under a [Creative Common Attribution-ShareAlike 4.0 International license](http://creativecommons.org/licenses/by-sa/4.0/). You can find the module [here](https://github.com/R6500/Python-bits/tree/master/Modules) See my blogs [AIM65](http://aim65.blogspot.com.es/) (in spanish) and [R6500](http://r6500.blogspot.com.es/) (in english) ```python ```
(* Properties of to_N and to_C. Ideally we wnat (to_N (to_C G)) = G, but that is not the case; the actual theorems are slightly different (G_subset_toN_toC_G and toN_toC_G_subset_G). *) From mathcomp Require Import all_ssreflect. Require Import Coq.Strings.String Coq.Bool.Bool Coq.Lists.List. Import ListNotations. From Coq.Arith Require Import Arith EqNat. Open Scope string_scope. Open Scope list_scope. From Taxiway Require Import To_complete To_naive Types. From Hammer Require Import Hammer. Set Hammer ReconstrLimit 20. Require Import Coq.Program.Equality. Require Import Arith. Require Import Setoid. Require Import Relations. Require Import Compare_dec. Require Import ArithRing. Require Import Omega. Require Import Coq.Program.Tactics. (* ============= partial identity ================*) (* outputs in (previous_edges ne bg) are in bg *) Lemma prev_edge_in_bi_G: forall G ne prev_ne, In ne G -> In prev_ne (previous_edges ne (undirect_to_bidirect G)) -> In prev_ne (undirect_to_bidirect G). Proof. intros. unfold previous_edges in H0. remember (undirect_to_bidirect G) as bg. apply filter_In in H0. destruct H0. assumption. Qed. Lemma prev_edge_prop: forall prev_ne ne G, In ne G -> In prev_ne (previous_edges ne (undirect_to_bidirect G)) -> prev_ne.1.1 =v= ne.1.2 /\ prev_ne.1.2 >v< ne.1.1. Proof. intros. unfold previous_edges in H0. apply filter_In in H0. destruct H0. apply andb_true_iff in H1. easy. Qed. (* undirect_to_bidirect preserve original edges *) Lemma undirect_edge_in_bi_G: forall G undir_e, In undir_e G -> undir_e.1.1 >v< input -> In undir_e (undirect_to_bidirect G). Proof. intros. unfold undirect_to_bidirect. apply filter_In. split. - apply in_flat_map. exists undir_e. split. intuition. intuition. - intuition. Qed. Definition no_self_loop (G: N_Graph_type) : Prop := (forall ne, In ne G -> ne.1.1 <> ne.1.2). (* A spec on graph, ensuring that no self-looping *) Lemma no_self_loop_in_bg: forall G, no_self_loop G -> no_self_loop (undirect_to_bidirect G). Proof. intros G H. unfold no_self_loop. intros. unfold undirect_to_bidirect in *. apply filter_In in H0. destruct H0. apply in_flat_map in H0. destruct H0 as [e hyp]; destruct hyp. unfold no_self_loop in H. simpl in H2. destruct H2. - hammer. - hammer. Qed. (* Check if there's "input" vertex *) Definition no_input_vertex (G: N_Graph_type) : Prop := (forall ne, In ne G -> (ne.1.1 >v< input) /\ (ne.1.2 >v< input)). (* a lemma to ensure there's no input vertices left *) Lemma no_input_vertex_in_bg: forall G, no_input_vertex G -> no_input_vertex (undirect_to_bidirect G). Proof. intros. unfold no_input_vertex. intros. unfold undirect_to_bidirect in H0. apply filter_In in H0. destruct H0. apply in_flat_map in H0. destruct H0 as [e hyp]; destruct hyp. unfold no_self_loop in H. simpl in H2. destruct H2. - hammer. - hammer. Qed. (* vertices in the naive graph, ARB *) Example AA3 : Vertex := index 1. Example AB := index 2. Example AC := index 3. Example AA1 := index 4. Example Ch := index 5. Example BC := index 6. Example A3r := index 7. Example A2r := index 8. Example A1r := index 9. (* taxiway name *) Example A : Taxiway_type := "A". Example B := "B". Example C := "C". Example A1 := "A1". Example A2 := "A2". Example A3 := "A3". (* input edges have taxiway name "" *) Example naive_ann_arbor : N_Graph_type :=[ ((Ch, input), ""); ((A1r, input), ""); ((A2r, input), ""); ((A3r, input), ""); ((BC, input), ""); ((Ch, BC), C); ((BC, AB), B); ((AB, AA3), A); ((AA3, A3r), A3); ((AB, A2r), A2); ((BC, AC), C); ((AB, AC), A); ((AC, AA1), A); ((AA1, A1r), A1) ]. (* Example G1 : N_Graph_type := [ ((AA1, AC), A); ((AA1, A1r), A) ]. Theorem toC_toN_id : forall (ne: Edge_type) , no_self_loop G1 -> (* no self loop *) In ne G1 -> (exists prev_ne, In prev_ne (previous_edges ne (undirect_to_bidirect G1))) -> (* ne has a previous edge in the bidirect graph *) (forall ne, In ne G1 -> (ne.1.1 >v< input) /\ (ne.1.2 >v< input)) -> (* input vertex should not appear in any naive graph *) In ne (to_N (to_C G1)) \/ In (Edge_inv ne) (to_N (to_C G1)). Proof. intros. simpl in H0. destruct H0. hammer. hammer. Qed. *) (* TODO o put it in types.v *) Lemma negb_eqv_refl: forall v1 v2, v1 >v< v2 <-> v2 >v< v1. Proof. intros. split. - hammer. - hammer. Qed. Lemma negb_eqv_false_equiv: forall v1 v2, (v1 =v= v2) = false -> (v2 =v= v1) = false. Proof. intros. apply eqv_rewrite_2. apply negb_eqv_refl. hammer. Qed. Lemma bidirected_graph_no_edge_end_with_input: forall ne G, In ne (undirect_to_bidirect G) -> ne.1.1 >v< input. Proof. intros. unfold undirect_to_bidirect in H. apply filter_In in H. destruct H. assumption. Qed. (* Here we prove "most" of the edges in G are in (to_N (to_C G)). Specifically, an edge ne in undirected graph G is also in (to_N (to_C G)) if: 1. there's no self-loop in G 2. ne is not an input edge 3. there exists a previous edge of ne in the bidirected graph. Because our undirect graph uses an ordered pair [A,B] (a directed edge) to represent {[A,B],[B,A]}, this is equivalent to say that there is an edge e in the undirect graph, s.t. e or reverse_e is ne's previous edge, under condition 2 *) Theorem G_subset_toN_toC_G : forall (ne: Edge_type) (G: N_Graph_type), no_self_loop G -> (* no self loop *) In ne G -> (exists prev_ne, (* ne has a previous edge in the bidirect graph *) (In prev_ne (previous_edges ne (undirect_to_bidirect G))) ) -> (ne.1.2 >v< input /\ ne.1.1 >v< input) -> (* ne is not an input edge *) In ne (to_N (to_C G)). Proof. intros ne G Hno_self_loop Hne_in_G Hexist_prev H_ne_not_input. destruct H_ne_not_input as [H_ne_not_input1 H_ne_not_input2]. unfold to_C. remember (undirect_to_bidirect G) as bg. unfold generate_edges. destruct Hexist_prev as [prev_ne Hprev_ne]. remember (to_N (to_C [ne; prev_ne] )) as G''. destruct ne as [neEndStart neTaxi] eqn:Hne1. destruct neEndStart as [neEnd neStart] eqn:Hne2. simpl in H_ne_not_input1, H_ne_not_input2. assert (Hne3: neStart >v< neEnd). { apply Hno_self_loop in Hne_in_G; simpl in Hne_in_G. apply eqv_inv. hammer. } assert(Hne4: (neEnd >v< neStart)). { apply negb_eqv_refl. assumption. } assert(Hne5: (neEnd =v= neStart) = false). { hammer. } assert(Hne5_2: (neStart =v= neEnd) = false). { apply negb_eqv_false_equiv. assumption. } (* properties about ne and prev_ne *) assert(Hprev_ne_in_bg: In prev_ne bg). { rewrite -> Heqbg. apply prev_edge_in_bi_G with (ne:= ne). hammer. hammer. } assert (Hprev_ne1: (prev_ne.1.1 >v< input) ) by hammer. assert (Hprev_ne3: prev_ne.1.1 =v= ne.1.2 /\ prev_ne.1.2 >v< ne.1.1). { apply prev_edge_prop with (G:=G). hammer. hammer. } rewrite -> Hne1 in Hprev_ne3; simpl in Hprev_ne3. destruct Hprev_ne3 as [Hprev_ne3 Hprev_ne4]. assert (Hprev_ne5: (prev_ne.1.1 >v< prev_ne.1.2)). { rewrite -> Heqbg in Hprev_ne_in_bg. apply no_self_loop_in_bg in Hprev_ne_in_bg. apply eqv_inv. assumption. assumption. } assert (Hprev_ne6: (prev_ne.1.2 =v= neStart) = false). { apply eqv_eq in Hprev_ne3. rewrite Hprev_ne3 in Hprev_ne5. clear - Hprev_ne5. apply eqv_rewrite_2 in Hprev_ne5. destruct (prev_ne.1.2 =v= neStart) eqn: Htemp. - apply eqv_eq in Htemp. symmetry in Htemp. apply eqv_eq in Htemp. rewrite Hprev_ne5 in Htemp. intuition. - intuition. } assert (lemma: In ne G'' ). { (* 4 situations, whether ne_start/end ?= Types.input *) rewrite -> HeqG''. rewrite <- Hne1. unfold to_C. remember (undirect_to_bidirect [ne; prev_ne ]) as b_G' eqn: Hbg_ne. (* bidirected graph from [ne] *) rewrite -> Hne1 in Hbg_ne. (* eval bg_ne *) unfold undirect_to_bidirect in Hbg_ne. simpl in Hbg_ne. rewrite -> H_ne_not_input1 in Hbg_ne; rewrite -> H_ne_not_input2 in Hbg_ne. rewrite -> Hprev_ne1 in Hbg_ne. destruct (prev_ne.1.2 >v< input) eqn: Hprev_ne2. - simpl in Hbg_ne. unfold Edge_inv in Hbg_ne; simpl in Hbg_ne. (* eval (generate_edges bg_ne) *) unfold generate_edges, previous_edges. rewrite -> Hbg_ne. simpl. Ltac choose_branch term hyp := assert (hyp: term) by hammer; rewrite hyp; simpl. choose_branch ((neEnd =v= neStart) && (neStart >v< neEnd) = false) branch1. choose_branch ((neStart =v= neStart) && (neEnd >v< neEnd) = false) branch2. choose_branch ((prev_ne.1.1 =v= neStart) && (prev_ne.1.2 >v< neEnd) = true) branch3. left. unfold c_to_n; simpl. easy. - rewrite Hbg_ne. simpl. unfold Edge_inv, generate_edges. simpl. choose_branch ((neEnd =v= neStart) && (neStart >v< neEnd) = false) branch1. choose_branch ((neStart =v= neStart) && (neEnd >v< neEnd) = false) branch2. choose_branch ((prev_ne.1.1 =v= neStart) && (prev_ne.1.2 >v< neEnd) = true) branch3. left. unfold c_to_n; simpl. easy. } assert(Hne8: (neStart =v= neStart)) by hammer. assert(Hne9: (neEnd =v= neEnd)) by hammer. assert (Hprev_ne7: (prev_ne.1.1 =v= neEnd) = false). { apply eqv_rewrite_2. apply eqv_inv. apply eqv_eq in Hprev_ne3. rewrite Hprev_ne3. apply eqv_inv. assumption. } (* eval G''*) unfold In, to_N, to_C, undirect_to_bidirect, generate_edges, previous_edges in HeqG''; simpl in HeqG''. Ltac unfold_undir_to_bidir Hprev_ne1 Hne7 H := unfold undirect_to_bidirect in H; simpl in H; rewrite -> Hprev_ne1, Hne7 in H; simpl. Ltac choose_branch_2 term hyp H:= assert (hyp: term) by first [apply negb_eqv_false_equiv; easy | hammer]; rewrite -> hyp in H; simpl in H. unfold Edge_inv in HeqG''. simpl in HeqG''. apply eqv_rewrite_2 in Hprev_ne4. apply eqv_rewrite_2 in Hne3. apply eqv_rewrite_2 in Hprev_ne1. apply eqv_rewrite_2 in Hprev_ne5. destruct (prev_ne.1.2 >v< input) eqn:Hprev_ne_not_input. - repeat ( try rewrite -> Hne3 in HeqG''; try rewrite -> Hne4 in HeqG''; try rewrite -> Hne5 in HeqG''; try rewrite -> Hne5_2 in HeqG''; try rewrite -> Hne8 in HeqG''; try rewrite -> Hne9 in HeqG''; try rewrite -> H_ne_not_input1 in HeqG''; try rewrite -> H_ne_not_input2 in HeqG''; try rewrite -> Hprev_ne_in_bg in HeqG''; try rewrite -> Hprev_ne1 in HeqG''; try rewrite -> Hprev_ne3 in HeqG''; try rewrite -> Hprev_ne4 in HeqG''; try rewrite -> Hprev_ne5 in HeqG''; try rewrite -> Hprev_ne6 in HeqG''; try rewrite -> Hprev_ne7 in HeqG''; try rewrite -> Hne1 in HeqG''; try unfold Edge_inv in HeqG''; try simpl in HeqG''; try unfold c_to_n in HeqG'' ). choose_branch_2 ((neEnd =v= prev_ne.1.2) = false) hyp1 HeqG''. choose_branch_2 ((neStart =v= prev_ne.1.2) = false) hyp2 HeqG''. choose_branch_2 ((prev_ne.1.2 =v= prev_ne.1.2)) hyp3 HeqG''. choose_branch_2 ((prev_ne.1.1 =v= prev_ne.1.1)) hyp4 HeqG''. choose_branch_2 ((neEnd =v= prev_ne.1.1) = false) hyp5 HeqG''. choose_branch_2 (((neStart =v= prev_ne.1.1))) hyp6 HeqG''. choose_branch_2 ((prev_ne.1.2 =v= prev_ne.1.1) = false) hyp7 HeqG''. assert(lemma2: In ne (to_N (to_C G))). { (* destruct Hprev_ne0 as [L Hprev_ne0]. rewrite <- Hprev_ne0. *) unfold to_C. rewrite <- Heqbg. simpl. (* evaluate the first generate_edges *) Ltac temp Hne1 Hne3 Hne4 Hne5 Hne5_2 Hne6 Hne7 Hne8 Hne9 Hprev_ne1 Hprev_ne2 Hprev_ne3 Hprev_ne4 Hprev_ne5 Hprev_ne6 Hprev_ne7 Hprev_ne hyp1 hyp2 hyp3 hyp4 hyp5 hyp6 hyp7 hyp8 hyp9:= unfold generate_edges at 1; simpl; repeat ( try rewrite -> Hne1; try rewrite -> Hne3; try rewrite -> Hne4; try rewrite -> Hne5; try rewrite -> Hne5_2; try rewrite -> Hne6; try rewrite -> Hne7; try rewrite -> Hne8; try rewrite -> Hne9; try rewrite -> Hprev_ne1; try rewrite -> Hprev_ne2; try rewrite -> Hprev_ne3; try rewrite -> Hprev_ne4; try rewrite -> Hprev_ne5; try rewrite -> Hprev_ne6; try rewrite -> Hprev_ne7; try rewrite -> hyp1; try rewrite -> hyp2; try rewrite -> hyp3; try rewrite -> hyp4; try rewrite -> hyp5; try rewrite -> hyp6; try rewrite -> hyp7; try rewrite -> hyp8; try rewrite -> hyp9; try unfold Edge_inv; try simpl ); unfold c_to_n; simpl. temp Hne1 Hne3 Hne4 Hne5 Hne5_2 Hne6 Hne7 Hne8 Hne9 Hprev_ne1 Hprev_ne2 Hprev_ne3 Hprev_ne4 Hprev_ne5 Hprev_ne6 Hprev_ne7 Hprev_ne hyp1 hyp2 hyp3 hyp4 hyp5 hyp6 hyp7 hyp8 hyp9. unfold to_N. apply in_map_iff. exists (prev_ne.1, (neEnd, neStart), neTaxi). split. - easy. - apply in_flat_map. exists ne. split. + rewrite Heqbg. apply undirect_edge_in_bi_G. * hammer. * hammer. + apply in_map_iff. exists prev_ne. split. hammer. hammer. } hammer. (* the proof for this case is kind of redundant with the previous one *) - repeat ( try rewrite -> Hne3 in HeqG''; try rewrite -> Hne4 in HeqG''; try rewrite -> Hne5 in HeqG''; try rewrite -> Hne5_2 in HeqG''; try rewrite -> Hne8 in HeqG''; try rewrite -> Hne9 in HeqG''; try rewrite -> H_ne_not_input1 in HeqG''; try rewrite -> H_ne_not_input2 in HeqG''; try rewrite -> Hprev_ne_in_bg in HeqG''; try rewrite -> Hprev_ne1 in HeqG''; try rewrite -> Hprev_ne3 in HeqG''; try rewrite -> Hprev_ne4 in HeqG''; try rewrite -> Hprev_ne5 in HeqG''; try rewrite -> Hprev_ne6 in HeqG''; try rewrite -> Hprev_ne7 in HeqG''; try rewrite -> Hne1 in HeqG''; try unfold Edge_inv in HeqG''; try simpl in HeqG''; try unfold c_to_n in HeqG'' ). choose_branch_2 ((neEnd =v= prev_ne.1.2) = false) hyp1 HeqG''. choose_branch_2 ((neStart =v= prev_ne.1.2) = false) hyp2 HeqG''. assert(lemma2: In ne (to_N (to_C G))). { unfold to_C. rewrite <- Heqbg. simpl. unfold c_to_n; simpl. temp Hne1 Hne3 Hne4 Hne5 Hne5_2 Hne6 Hne7 Hne8 Hne9 Hprev_ne1 Hprev_ne2 Hprev_ne3 Hprev_ne4 Hprev_ne5 Hprev_ne6 Hprev_ne7 Hprev_ne hyp1 hyp2 hyp3 hyp4 hyp5 hyp6 hyp7 hyp8 hyp9. unfold to_N. apply in_map_iff. exists (prev_ne.1, (neEnd, neStart), neTaxi). split. - easy. - apply in_flat_map. exists ne. split. + rewrite Heqbg. apply undirect_edge_in_bi_G. * hammer. * hammer. + apply in_map_iff. exists prev_ne. split. hammer. hammer. } hammer. Qed. (* (to_N (to_C G)) \subset (undirect_to_bidirect G) *) Theorem toN_toC_G_subset_G : forall (G: N_Graph_type), incl (to_N (to_C G)) (undirect_to_bidirect G). Proof. intros. unfold incl. intro ne. intros. unfold to_N, to_C in H. remember (undirect_to_bidirect G) as bg. apply in_map_iff in H. destruct H as [A H]. destruct H. apply in_flat_map in H0. destruct H0 as [e H1]. destruct H1 as [H1 H2]. unfold generate_edges in H2. apply in_map_iff in H2. destruct H2 as [V H2]. destruct H2 as [H2 H3]. assert (e = ne) by hammer. rewrite <- H0. assumption. Qed.
#include "network/acceptor.h" #include "share/log.h" #include "share/atomic.h" #include <boost/bind.hpp> #include <fcntl.h> using namespace yohub; Acceptor::Acceptor(EventPool* event_pool) : bind_(0), event_pool_(event_pool), accept_socket_(Socket::CreateNonblockingSocket()), accept_channel_(event_pool, accept_socket_.fd()), idle_fd_(::open("/dev/null", O_RDONLY | O_CLOEXEC)) { accept_channel_.SetReadCallback(boost::bind(&Acceptor::OnAccept, this)); } Acceptor::~Acceptor() { accept_channel_.Unregister(); } void Acceptor::SetAndBind(const InetAddress& bindaddr) { AtomicSetValue(bind_, 1); accept_socket_.SetReuseAddr(true); accept_socket_.SetTcpNoDelay(true); accept_socket_.Bind(bindaddr); } void Acceptor::Listen() { assert(AtomicGetValue(bind_)); accept_socket_.Listen(); accept_channel_.Register(); } void Acceptor::OnAccept() { InetAddress peeraddr(0); int newfd = accept_socket_.Accept(&peeraddr); if (newfd >= 0) { LOG_TRACE("new connection, fd=%d", newfd); if (on_new_connection_cb_) { on_new_connection_cb_(newfd, peeraddr); } else { ::close(newfd); LOG_WARN("the new connection callback should set"); } } else { LOG_WARN("OnAccept failed, fd=%d", accept_socket_.fd()); if (errno == EMFILE) { ::close(idle_fd_); idle_fd_ = ::accept(accept_socket_.fd(), NULL, NULL); ::close(idle_fd_); idle_fd_ = ::open("/dev/null", O_RDONLY | O_CLOEXEC); LOG_WARN("reached max file descriptor"); } } }
%!TEX root = /home/renaud/Documents/EPL/tfe/latex/tfe.tex \section{Discrete-time compartment model} \label{sec:dtcm(chapcomp)} It is also possible to build a discrete-time compartment model, and this could even be more relevant than a continuous-time one in the context of numerical implementation. Consider equation~\eqref{eq:compartmentmatrix}. For a given time step $\Delta t > 0$, we would like to build a similar expression that would link $\b c(t+\Delta t)$ to $\b c(t)$. From the theory of ordinary differential equations~\cite{EDO}, we know that the general solution to that equation is \begin{equation} \label{eq:generalODEsol} \b c(t) = \Exp^{\bs \Omega^{-1}\b A(t-t_0)} \b c(t_0) + \int_{t_0}^t \Exp^{\bs \Omega^{-1}\b A(t-s)} \b q(s) \rm ds. \end{equation} For a general source term $\b q$, it is not possible to write a matrix expression of the form $\b c(t+\Delta t) = \b A_{\Delta t} \b c(t) + \b B_{\Delta t} \b q(t)$, but it is possible under certain conditions on $\b q$. In this work, we won't need such conditions because we make the assumption that there is no source/sink term, i.e. we assume that $\b q = 0$. Let $t_0 < t_1 < t_2 < \dots$ be such that $t_{k+1} = t_k + \Delta t$. If $\b c(t_k)$ is known, $\b c(t_{k+1})$ can be computed using~\eqref{eq:generalODEsol} with $\b q = 0$: \begin{equation} \b c(t_{k+1}) = \Exp^{\bs \Omega^{-1}\b A\Delta t} \b c(t_k). \end{equation} Doing this, we have found a matrix relation that links $\b c(t+\Delta t)$ to $\b c(t)$: \begin{equation} \label{eq:generaldiscretecompartment} \b c(t + \Delta t) = \b A_{\Delta t} \b c(t), \end{equation} where $\b A_{\Delta t} = \Exp^{\bs \Omega^{-1}\b A\Delta t}$ is the \textit{discrete interaction matrix}. Notice that the discrete interaction matrix is closely related to the transition probability matrix introduced in chapter~\ref{chap:clustering}. Indeed, developing~\eqref{eq:generaldiscretecompartment} for $C_i(t)$ yields \begin{equation} \label{eq:crapaud} C_i(t+\Delta t) = [\b A_{\Delta t}]_{i,1} C_{1}(t) + [\b A_{\Delta t}]_{i,2} C_{2}(t) + \ldots + [\b A_{\Delta t}]_{i,N} C_{N}(t). \end{equation} Let $P_i(t)$ denote the number of tracer's particles in compartment $i$ at time $t$, and let $P$ be the mass of one tracer's particle. Notice that \begin{equation} C_i(t) = \frac{P_i(t) P}{|\Omega_i|}. \end{equation} Multiplying equation~\eqref{eq:crapaud} by $|\Omega_i|/P$ yields after some manipulations \begin{equation} P_i(t) = [\b A_{\Delta t}]_{i,1} \frac{|\Omega_i|}{|\Omega_1|} P_{1}(t) + [\b A_{\Delta t}]_{i,2}\frac{|\Omega_i|}{|\Omega_2|} P_{2}(t) + \ldots + [\b A_{\Delta t}]_{i,N}\frac{|\Omega_i|}{|\Omega_N|} P_{N}(t). \end{equation} Hence, the factor $\frac{|\Omega_i|}{|\Omega_j|}[\b A_{\Delta t}]_{i,j}$ can be interpreted as the probability \label{page:probability_interpretation} for a tracer's particle to end up in compartment $i$ after a period $\Delta t$ if it was initially in compartment $j$. This consideration suggests that the entries of $\b A_{\Delta t}$ should be nonnegative: this is indeed an important property of the discrete interaction matrix that shall be proven shortly. \begin{property} \label{prop1_discr_comp} The entries of the discrete interaction matrix are nonnegative: \begin{equation} [\b A_{\Delta t}]_{ij} \ge 0 \mbox{ for every } i,j = 1,\dots,N. \end{equation} \end{property} \begin{proof} Let $C_0 > 0$ be a positive constant, and fix $j \in \{1,\dots,N\}$. Suppose that \begin{equation} \b c(t) = \begin{pmatrix} c_1(t) \\ \vdots \\ c_{j-1}(t) \\ c_j(t) \\ c_{j+1}(t) \\ \vdots \\ c_N(t) \end{pmatrix} = \begin{pmatrix} 0 \\ \vdots \\ 0 \\ C_0 \\ 0 \\ \vdots \\ 0 \end{pmatrix}. \end{equation} By equation~\eqref{eq:generaldiscretecompartment}, \begin{equation} \b c(t+\Delta t) = \b A_{\Delta t} \b c(t) = \begin{pmatrix} [\b A_{\Delta t}]_{1,j} C_0 \\ \vdots \\ [\b A_{\Delta t}]_{N,j} C_0 \end{pmatrix}. \end{equation} Since $\b c$ is a concentration, we must have that $\b c(t) \ge \b 0$ at any time $t$. Therefore, since $C_0 > 0$ we must have that \begin{equation} [\b A_{\Delta t}]_{i,j} \ge 0 \mbox{ for every } i = 1,\dots,N. \end{equation} Finally, as we have made no assumption on $j$, this must be true for any $j \in \{1,\dots,N\}$, which concludes the proof. \end{proof} The interpretation of $\frac{|\Omega_i|}{|\Omega_j|}[\b A_{\Delta t}]_{i,j}$ in terms of a transition probability of the tracer's particles between compartments suggests another important property of the discrete interaction matrix. Indeed, the tracer's particles can neither disappear nor be created, hence the sum of the probabilities over all possible destinations (i.e. over all compartments since we consider an isolated domain) must be equal to one: \begin{equation} \sum_{i=1}^N \frac{|\Omega_i|}{|\Omega_j|}[\b A_{\Delta t}]_{i,j} = 1 \quad \mbox{for every } j=1,\dots,N. \end{equation} This property can be deduced from property~\ref{prop1_comp}: \begin{property} \label{prop1ter_comp} \label{prop2_discr_comp} The columns of the discrete interaction matrix satisfy the following relation: \begin{equation} \sum_{i=1}^N |\Omega_i| [\b A_{\Delta t}]_{ij} = |\Omega_j| \quad \mbox{for every } j=1,\dots,N. \end{equation} In matrix form: \begin{equation} \bs \omega^\t \b A_{\Delta t} = \bs \omega^\t . \end{equation} \end{property} \begin{proof} The expression of the mean concentration over $\Omega$ is the same as in the continuous case: \begin{equation} \bar C = \frac{1}{|\Omega|} \b 1^\t \bs \Omega \b c. \end{equation} Since $\bar C$ is constant, we must have that \begin{equation} |\Omega| \bar C(t+\Delta t) = |\Omega| \bar C(t) = \b1^\t \bs \Omega \b c(t) = \bs \omega^\t \b c(t), \end{equation} but by equation~\eqref{eq:generaldiscretecompartment} we also have that \begin{equation} |\Omega| \bar C(t+\Delta t) = \b1^\t \bs \Omega \b c(t+\Delta t) = \b1^\t \bs \Omega \b A_{\Delta t} \b c(t) = \bs \omega^\t \b A_{\Delta t} \b c(t). \end{equation} Hence, $\bs \omega^\t \b c(t) = \bs \omega^\t \b A_{\Delta t} \b c(t)$, and since this must be true for every possible value of $\b c(t)$, we must have that \begin{equation} \label{eq:prop1ter_comp} \bs \omega^\t = \bs \omega^\t \b A_{\Delta t}, \end{equation} the desired result. \end{proof} \begin{corollary}{prop1ter_comp} \label{corollary2} If the compartments all have the same size, the discrete interaction matrix is left stochastic: \begin{equation} \b 1^\t \b A_{\Delta t} = \b 1^\t. \end{equation} \end{corollary} \begin{proof} Let $|\Omega_0|$ be the size of the compartments. Then, $\bs \omega = |\Omega_0| \b 1$ and equation~\eqref{eq:prop1ter_comp} reduces to \begin{equation} |\Omega_0| \b 1^\t = |\Omega_0| \b 1^\t \b A_{\Delta t}. \end{equation} \end{proof} Property~\ref{prop2_comp} also has an interpretation in terms of the discrete interaction matrix: \begin{property} \label{prop2ter_comp} \label{prop3_discr_comp} The discrete interaction matrix is right stochastic: \begin{equation} \b A_{\Delta t} \b 1 = \b 1. \end{equation} \end{property} \begin{proof} Let $C_0 > 0$ be a constant and $\b c(t) = C_0 \b 1$. Introducing the latter in~\eqref{eq:generaldiscretecompartment} yields \begin{equation} C_0 \b 1 = \b A_{\Delta t} C_0 \b 1 = C_0 \b A_{\Delta t} \b 1. \end{equation} \end{proof} Two last properties allow to bound the entries of the discrete interaction matrix: \begin{property} \label{prop4_discr_comp} The entries of the discrete interaction matrix are smaller than one: \begin{equation} [\b A_{\Delta t}]_{i,j} \le 1 \mbox{ for every } i,j = 1,\dots,N. \end{equation} \end{property} \begin{proof} We proceed by contradiction. Suppose there exists $i,j \in \{1,\dots,N\}$ such that $[\b A_{\Delta t}]_{i,j} > 1$. By property~\ref{prop1_discr_comp}, all the entries of $\b A_{\Delta t}$ are nonnegative so that \begin{equation} \sum_{k = 1}^N [\b A_{\Delta t}]_{i,k} > 1, \end{equation} in contradiction with property~\ref{prop2ter_comp}. \end{proof} \begin{property} \label{prop5_discr_comp} The entries of the discrete interaction matrix satisfy \begin{equation} \frac{|\Omega_i|}{|\Omega_j|} [\b A_{\Delta t}]_{i,j} \le 1 \mbox{ for every } i,j = 1,\dots,N. \end{equation} \end{property} \begin{proof} We proceed again by contradiction. Suppose there exist $i,j \in \{1,\dots,N\}$ such that $\frac{|\Omega_i|}{|\Omega_j|} [\b A_{\Delta t}]_{i,j} > 1$. By property~\ref{prop1_discr_comp}, all the entries of $\b A_{\Delta t}$ are nonnegative so that \begin{equation} \sum_{k = 1}^N \frac{|\Omega_k|}{|\Omega_j|}[\b A_{\Delta t}]_{k,j} > 1, \end{equation} in contradiction with property~\ref{prop1ter_comp}. \end{proof} This last property is in agreement with the interpretation of the factors $\frac{|\Omega_i|}{|\Omega_j|} [\b A_{\Delta t}]_{i,j}$ as probabilities of transition between the compartments.
\subsection{Brownian motion} brownian motion in stats. given we start at a, what is chance be end up at b? normal. do 1d then multi d
Dental health is so important to every single individual. You will note that engaging the services of a dentist like Velosia will often be of great value. They are often able to perform a good number of procedures. These procedures will time and again include implant dentistry. These implants have gained so much popularity particularly in the recent past. You will however realize that we have a number of trends in implant dentistry that you will need to be familiarized with. It is through this that you will be assured of a more reliable decision at the end of the day. Such trends will often include the following. You will note that there has been an increase in the need for full-arch restorations. This has been appreciated as a game-changer by a good number of dental patients. You will learn that implant surfaces that are more likely to speed up healing times to be embraced. This is due to the fact that they will assure you of better tooth replacement solutions much faster. As such, the dental patient will not be subjected to too much disruption of their daily lives. You will also note that there has been a decrease in the use of cement. Cement-free restorations are worth going for by many dentists. Such restorations will often assure you of safety and even simplicity. You need to keep in mind that data is often a perfect differentiator. There is often a need for you to aim at getting an implant that is scientifically as well as clinically-backed. Approved connections will often assure you of better results in the long run. You will also note that immediate satisfaction is being widely embraced. As such, you will barely have to wait for so long before you get an implant. The implant placement will come immediately after loading. It is necessary to point out that advanced aesthetics will be relied on. New concepts and tools are being relied on. They have become quite reliable in offering full-contour solutions. It is necessary to point out that there is an influx of cheaper CAD as well as CAM abutments. These low cost abutments will time and again compromise the integrity of the implant. This implies that it will be prudent for you to go for a qualified dentist. It is through them that you will get quality abutments. It is important to mention that virtual reality has been embraced in dental surgery. It is through this that it has become easier for clinicians to follow up on the patients later on. It is through this that the patients will be able to realize better implant care after the surgery.
= Elephanta Caves =
Require Export Coq.Lists.List. Require Import Coq.omega.Omega. Require Export Coq.Sorting.Permutation. Require Import Coq.Logic.FunctionalExtensionality. Require Import RamifyCoq.lib.Coqlib. Require Import RamifyCoq.lib.EquivDec_ext. Lemma In_tail: forall A (a : A) L, In a (tl L) -> In a L. Proof. induction L; simpl; auto. Qed. Definition eq_as_set {A} (L1 L2 : list A) : Prop := incl L1 L2 /\ incl L2 L1. Notation "a '~=' b" := (eq_as_set a b) (at level 1). Lemma eq_as_set_refl: forall A (L : list A), L ~= L. Proof. intros; split; apply incl_refl. Qed. Lemma eq_as_set_sym: forall A (L1 L2 : list A), L1 ~= L2 -> L2 ~= L1. Proof. intros; hnf in *; firstorder. Qed. Lemma eq_as_set_trans: forall A (L1 L2 L3 : list A), L1 ~= L2 -> L2 ~= L3 -> L1 ~= L3. Proof. intros; hnf in *; intuition; apply incl_tran with L2; trivial. Qed. Add Parametric Relation {A} : (list A) eq_as_set reflexivity proved by (eq_as_set_refl A) symmetry proved by (eq_as_set_sym A) transitivity proved by (eq_as_set_trans A) as eq_as_set_rel. Lemma eq_as_set_app: forall A (L1 L2 L3 L4: list A), L1 ~= L2 -> L3 ~= L4 -> (L1 ++ L3) ~= (L2 ++ L4). Proof. intros; hnf in *; intuition. Qed. Lemma eq_as_set_nil: forall {A} (l : list A), nil ~= l -> l = nil. Proof. intros; destruct l; auto. destruct H. assert (In a (a :: l)) by apply in_eq. specialize (H0 a H1). inversion H0. Qed. Lemma Forall_tl: forall {A : Type} (P : A -> Prop) (x : A) (l : list A), Forall P (x :: l) -> Forall P l. Proof. intros; rewrite Forall_forall in *; intros. apply H, in_cons; auto. Qed. Lemma Forall_app: forall {A : Type} (P : A -> Prop) (l1 l2 : list A), Forall P l1 -> Forall P l2 -> Forall P (l1 ++ l2). Proof. induction l1; intros. rewrite app_nil_l; auto. generalize (Forall_inv H); intros. rewrite <- app_comm_cons. apply Forall_cons; auto. apply IHl1; auto. apply Forall_tl with a; auto. Qed. Lemma Forall_app_iff: forall {A : Type} (P : A -> Prop) (l1 l2 : list A), Forall P (l1 ++ l2) <-> Forall P l1 /\ Forall P l2. Proof. intros; induction l1; intros. + simpl. assert (Forall P nil) by constructor; tauto. + simpl; split; intros. - inversion H; subst; split; try tauto. constructor; auto; tauto. - destruct H. inversion H; subst. constructor; auto; tauto. Qed. Lemma Forall_incl: forall {A : Type} (P : A -> Prop) (l1 l2 : list A), incl l1 l2 -> Forall P l2 -> Forall P l1. Proof. intros; hnf in *. rewrite Forall_forall in *; intro y; intros. apply H0, H; auto. Qed. Lemma map_incl: forall {A B : Type} (f : A -> B) (l1 l2 : list A), incl l1 l2 -> incl (map f l1) (map f l2). Proof. intros; hnf in *; intros. rewrite in_map_iff in *. destruct H0 as [y [? ?]]. exists y; split; auto. Qed. Lemma NoDup_cons_1 : forall (A : Type) (x : A) (l : list A), NoDup (x :: l) -> NoDup l. Proof. intros. rewrite NoDup_cons_iff in H. destruct H; auto. Qed. Lemma NoDup_cons_2 : forall (A : Type) (x : A) (l : list A), NoDup (x :: l) -> ~ In x l. Proof. intros. rewrite NoDup_cons_iff in H. destruct H; auto. Qed. Lemma NoDup_app_r: forall (A : Type) (l1 l2 : list A), NoDup (l1 ++ l2) -> NoDup l2. Proof. induction l1; simpl; intros; auto. apply NoDup_cons_1 in H. apply IHl1. auto. Qed. Lemma NoDup_app_l: forall (A : Type) (l1 l2 : list A), NoDup (l1 ++ l2) -> NoDup l1. Proof. intros A l1 l2. revert l1. induction l2; intros. rewrite app_nil_r in H. apply H. apply NoDup_remove_1 in H. apply IHl2. apply H. Qed. Lemma NoDup_app_not_in: forall (A : Type) (l1 l2 : list A), NoDup (l1 ++ l2) -> forall y, In y l1 -> ~ In y l2. Proof. induction l1; intros. inversion H0. rewrite <- app_comm_cons in H. apply in_inv in H0. destruct H0. subst. apply NoDup_cons_2 in H. intro. apply H. apply in_or_app. right. apply H0. apply NoDup_cons_1 in H. apply IHl1; auto. Qed. Lemma NoDup_app_inv: forall (A : Type) (l1 l2 : list A), NoDup l1 -> NoDup l2 -> (forall x, In x l1 -> ~ In x l2) -> NoDup (l1 ++ l2). Proof. induction l1; intros. rewrite app_nil_l. auto. rewrite <- app_comm_cons. apply NoDup_cons. intro. apply in_app_or in H2. destruct H2. apply NoDup_cons_2 in H. auto. apply (H1 a). apply in_eq. auto. apply IHl1. apply NoDup_cons_1 in H. auto. auto. intro y; intros. apply H1. apply in_cons. auto. Qed. Lemma NoDup_app_iff: forall (A : Type) (l1 l2 : list A), NoDup (l1 ++ l2) <-> NoDup l1 /\ NoDup l2 /\ (forall x, In x l1 -> ~ In x l2). Proof. intros. split; intros. split. apply NoDup_app_l with l2. auto. split. apply NoDup_app_r with l1; auto. apply NoDup_app_not_in; auto. destruct H as [? [? ?]]. apply NoDup_app_inv; auto. Qed. Lemma In_remove_length: forall {A: Type} (eq_dec : forall x y : A, {x = y} + {x <> y}) (l: list A) x, In x l -> length (remove eq_dec x l) < length l. Proof. intros ? ? l x. apply (@proj1 _ (length (remove eq_dec x l) <= length l)). induction l. + split; [intro H; inversion H | reflexivity]. + simpl. destruct (eq_dec x a). - split; [intros; omega | omega]. - split. * intros. simpl. destruct IHl. destruct H; [congruence | apply H0 in H]. omega. * simpl; omega. Qed. Lemma not_in_app: forall {A} (eq_dec : forall x y : A, {x = y} + {x <> y}) x a (l : list A), (~ In x (a :: l)) -> x <> a /\ ~ In x l. Proof. intros; split. destruct (eq_dec x a); auto. subst; intro; apply H. apply in_eq. intro. apply H; apply in_cons; auto. Qed. Lemma remove_In_iff: forall (A : Type) (eq_dec : forall x y : A, {x = y} + {x <> y}) (l : list A) (x y : A), In x (remove eq_dec y l) <-> In x l /\ x <> y. Proof. intros. induction l; simpl. 1: tauto. destruct (eq_dec y a); [subst | simpl ]; rewrite IHl; intuition. apply n. subst; auto. Qed. Lemma remove_incl: forall (A : Type) (eq_dec : forall x y : A, {x = y} + {x <> y}) (l : list A) (x : A), incl (remove eq_dec x l) l. Proof. intros. hnf. intros. rewrite remove_In_iff in H. destruct H; auto. Qed. Lemma remove_in_2: forall (A : Type) (eq_dec : forall x y : A, {x = y} + {x <> y}) (l : list A) (x y : A), In x l -> x = y \/ In x (remove eq_dec y l). Proof. intros. destruct (eq_dec x y). - left; auto. - right. rewrite remove_In_iff. split; auto. Qed. Lemma remove_len_le: forall (A : Type) (eq_dec : forall x y : A, {x = y} + {x <> y}) (l : list A) (x : A), length (remove eq_dec x l) <= length l. Proof. induction l; intros; simpl in *. auto. destruct (eq_dec x a). intuition. simpl. intuition. Qed. Fixpoint intersect {A: Type} (eq_dec : forall x y : A, {x = y} + {x <> y}) (l1 l2 : list A) : list A := match l1 with | nil => nil | e :: l => if (in_dec eq_dec e l2) then e :: intersect eq_dec l l2 else intersect eq_dec l l2 end. Lemma intersect_property {A: Type} (eq_dec : forall x y : A, {x = y} + {x <> y}): forall l1 l2 x, (In x l1 /\ In x l2) <-> In x (intersect eq_dec l1 l2). Proof. induction l1; intros; simpl. intuition. destruct (in_dec eq_dec a l2). split; intros. destruct H as [[? | ?] ?]. subst. apply in_eq. apply in_cons. rewrite <- IHl1. split; auto. split. apply in_inv in H. destruct H; [left | right]; auto. rewrite <- IHl1 in H. destruct H; auto. apply in_inv in H; destruct H. subst; auto. rewrite <- IHl1 in H; destruct H; auto. rewrite <- IHl1. intuition. subst; intuition. Qed. Lemma intersect_nodup {A: Type} (eq_dec : forall x y : A, {x = y} + {x <> y}): forall (l1 l2 : list A), NoDup l1 -> NoDup (intersect eq_dec l1 l2). Proof. induction l1; intros; simpl; auto. destruct (in_dec eq_dec a l2). apply NoDup_cons. apply NoDup_cons_2 in H. intro; apply H. rewrite <- intersect_property in H0. destruct H0; auto. apply IHl1. apply NoDup_cons_1 in H; auto. apply IHl1. apply NoDup_cons_1 in H. auto. Qed. Fixpoint subtract {A: Type} (eq_dec : forall x y : A, {x = y} + {x <> y}) (l1 l2 : list A) : list A := match l2 with | nil => l1 | e :: l => subtract eq_dec (remove eq_dec e l1) l end. Lemma remove_app {A: Type} (eq_dec : forall x y : A, {x = y} + {x <> y}): forall l1 l2 a, remove eq_dec a (l1 ++ l2) = remove eq_dec a l1 ++ remove eq_dec a l2. Proof. induction l1; intros; simpl; auto. destruct (eq_dec a0 a). subst. apply IHl1. rewrite <- app_comm_cons. f_equal. apply IHl1. Qed. Lemma remove_not_in {A: Type} (eq_dec : forall x y : A, {x = y} + {x <> y}): forall l x, ~ In x l -> remove eq_dec x l = l. Proof. induction l; intros; simpl; auto. destruct (eq_dec x a). subst. exfalso; apply H, in_eq. f_equal. apply IHl. intro; apply H. apply in_cons. auto. Qed. Lemma remove_middle {A: Type} (eq_dec : forall x y : A, {x = y} + {x <> y}): forall l1 l2 a, NoDup (l1 ++ a :: l2) -> remove eq_dec a (l1 ++ a :: l2) = l1 ++ l2. Proof. intros. rewrite (remove_app eq_dec). f_equal. apply NoDup_remove_2 in H. apply remove_not_in. intro; apply H, in_or_app; left. auto. simpl. destruct (eq_dec a a). apply remove_not_in. apply NoDup_remove_2 in H. intro; apply H, in_or_app; right; auto. exfalso; apply n; auto. Qed. Lemma subtract_permutation {A: Type} (eq_dec : forall x y : A, {x = y} + {x <> y}): forall (l1 l2 : list A), NoDup l1 -> NoDup l2 -> incl l2 l1 -> Permutation l1 (subtract eq_dec l1 l2 ++ l2). Proof. intros l1 l2; revert l1; induction l2; intros; simpl. rewrite app_nil_r. apply Permutation_refl. assert (In a (a :: l2)) by apply in_eq. generalize (H1 a H2); intros. apply in_split in H3. destruct H3 as [ll1 [ll2 ?]]. subst. assert (incl l2 (ll1 ++ ll2)). intro y; intros. apply in_or_app. assert (In y (a :: l2)) by (apply in_cons; auto). specialize (H1 y H4). apply in_app_or in H1. destruct H1; [left | right]; auto. apply in_inv in H1. destruct H1. subst. apply NoDup_cons_2 in H0. intuition. auto. apply Permutation_trans with (a :: ll1 ++ ll2). apply Permutation_sym. apply Permutation_middle. apply Permutation_cons_app. rewrite (remove_middle eq_dec); auto. apply IHl2. apply NoDup_remove_1 in H. auto. apply NoDup_remove_1 in H. apply NoDup_cons_1 in H0. auto. auto. Qed. Lemma subtract_nodup {A: Type} (eq_dec : forall x y : A, {x = y} + {x <> y}): forall (l1 l2 : list A), NoDup l1 -> NoDup (subtract eq_dec l1 l2). Proof. intros l1 l2; revert l1; induction l2; intros; simpl; auto. apply IHl2. destruct (in_dec eq_dec a l1). apply in_split in i. destruct i as [ll1 [ll2 ?]]. subst. rewrite remove_app. assert (~ In a ll1 /\ ~ In a ll2). apply NoDup_remove_2 in H. split; intro; apply H, in_or_app; [left | right] ; auto. destruct H0. rewrite (remove_not_in eq_dec _ _ H0). simpl. destruct (eq_dec a a). rewrite (remove_not_in eq_dec _ _ H1). apply NoDup_remove_1 in H. auto. exfalso; intuition. rewrite (remove_not_in eq_dec _ _ n). auto. Qed. Lemma subtract_property {A: Type} (eq_dec : forall x y : A, {x = y} + {x <> y}): forall l1 l2 x, (In x l1 /\ ~ In x l2) <-> In x (subtract eq_dec l1 l2). Proof. intros l1 l2; revert l1; induction l2; intros. simpl; auto; intuition. split; intros. destruct H. apply (not_in_app eq_dec) in H0. destruct H0. simpl. rewrite <- IHl2. split; auto. apply (remove_in_2 _ eq_dec _ _ a) in H. destruct H; intuition. simpl in H. rewrite <- IHl2 in H. destruct H. split. rewrite remove_In_iff in H. destruct H; auto. intro. apply in_inv in H1. destruct H1. subst. apply remove_In in H. auto. apply H0; auto. Qed. Lemma tri_list_split {A : Type} (eq_dec : forall x y : A, {x = y} + {x <> y}): forall (l l1 l2 : list A), NoDup l -> NoDup l1 -> NoDup l2 -> l ~= (l1 ++ l2) -> exists i1 i2 i3, Permutation l1 (i1 ++ i2) /\ Permutation l2 (i2 ++ i3) /\ Permutation l (i1 ++ i2 ++ i3). Proof. intros. remember (intersect eq_dec l1 l2) as j2. remember (subtract eq_dec l1 j2) as j1. remember (subtract eq_dec l2 j2) as j3. exists j1, j2, j3. assert (Permutation l1 (j1 ++ j2)). rewrite Heqj1. apply subtract_permutation. auto. rewrite Heqj2. apply intersect_nodup. auto. intro y; intros. rewrite Heqj2 in H3. rewrite <- intersect_property in H3. intuition. split. auto. assert (Permutation l2 (j2 ++ j3)). rewrite Heqj3. apply Permutation_trans with (subtract eq_dec l2 j2 ++ j2). apply subtract_permutation. auto. rewrite Heqj2. apply intersect_nodup. auto. intro y; intros. rewrite Heqj2 in H4. rewrite <- intersect_property in H4. intuition. apply Permutation_app_comm. split; auto. remember (subtract eq_dec l l2) as j4. apply Permutation_trans with (j4 ++ l2). rewrite Heqj4. apply subtract_permutation; auto. destruct H2. repeat intro. apply (H5 a). apply in_or_app; right; auto. apply Permutation_app. apply NoDup_Permutation. rewrite Heqj4. apply subtract_nodup; auto. rewrite Heqj1. apply subtract_nodup; auto. rewrite Heqj1, Heqj4. destruct H2. hnf in H2, H5. intro x; split; intros; rewrite <- subtract_property in H6; destruct H6; rewrite <- subtract_property; split. apply H2 in H6. apply in_app_or in H6. destruct H6; intuition. rewrite Heqj2. intro; apply H7. rewrite <- intersect_property in H8. destruct H8; auto. apply H5. apply in_or_app; left; auto. intro; apply H7. rewrite Heqj2. rewrite <- intersect_property. split; auto. auto. Qed. Arguments tri_list_split [A] _ [l] [l1] [l2] _ _ _ _. Lemma double_list_split {A : Type} (eq_dec : forall x y : A, {x = y} + {x <> y}): forall (l1 l2 : list A), NoDup l1 -> NoDup l2 -> exists i1 i2 i3, Permutation l1 (i1 ++ i2) /\ Permutation l2 (i2 ++ i3) /\ NoDup (i1 ++ i2 ++ i3). Proof. intros. remember (intersect eq_dec l1 l2) as j2. remember (subtract eq_dec l1 j2) as j1. remember (subtract eq_dec l2 j2) as j3. exists j1, j2, j3. assert (Permutation l1 (j1 ++ j2)). rewrite Heqj1. apply subtract_permutation. auto. rewrite Heqj2. apply intersect_nodup. auto. intro y; intros. rewrite Heqj2 in H1. rewrite <- intersect_property in H1. intuition. split. auto. assert (Permutation l2 (j2 ++ j3)). rewrite Heqj3. apply Permutation_trans with (subtract eq_dec l2 j2 ++ j2). apply subtract_permutation. auto. rewrite Heqj2. apply intersect_nodup. auto. intro y; intros. rewrite Heqj2 in H2. rewrite <- intersect_property in H2. intuition. apply Permutation_app_comm. split; auto. apply NoDup_app_inv. rewrite Heqj1. apply subtract_nodup; auto. apply NoDup_app_inv. rewrite Heqj2. apply intersect_nodup; auto. rewrite Heqj3. apply subtract_nodup; auto. intros. rewrite Heqj3. intro. rewrite <- subtract_property in H4. destruct H4. auto. intros. rewrite Heqj1 in H3. rewrite <- subtract_property in H3. destruct H3. intro. apply in_app_or in H5. destruct H5. auto. apply H4; clear H4. rewrite Heqj3 in H5. rewrite <- subtract_property in H5. destruct H5 as [? _]. assert (In x l1 /\ In x l2) by intuition. rewrite intersect_property in H5. rewrite Heqj2. apply H5. Qed. Arguments double_list_split [A] _ [l1] [l2] _ _. Lemma eq_as_set_spec: forall {A} (l1 l2: list A), (forall x, In x l1 <-> In x l2) -> l1 ~= l2. Proof. intros. split; intro x; intros; specialize (H x); tauto. Qed. Notation "a '+::' b" := (a ++ (b :: nil)) (at level 19). Lemma app_cons_assoc: forall {A} (l1 l2 : list A) x, l1 ++ x :: l2 = l1 +:: x ++ l2. Proof. intros. induction l1. simpl. auto. rewrite <- app_comm_cons. rewrite IHl1. do 2 rewrite <- app_comm_cons. auto. Qed. Definition Dup {A} (L : list A) : Prop := ~ NoDup L. Lemma Dup_unfold {A} {EA : EqDec A eq}: forall (a : A) (L : list A), Dup (a :: L) -> In a L \/ Dup L. Proof. intros; destruct (in_dec equiv_dec a L); [left; trivial | right; intro; apply H; constructor; auto]. Qed. Lemma Dup_cyclic {A} {EA : EqDec A eq} : forall (L : list A), Dup L -> exists a L1 L2 L3, L = L1 ++ (a :: L2) ++ (a :: L3). Proof. induction L. destruct 1. constructor. intros. apply Dup_unfold in H. destruct H. apply in_split in H. destruct H as [L1 [L2 ?]]. exists a. exists nil. exists L1. exists L2. rewrite H. simpl. trivial. destruct (IHL H) as [a' [L1 [L2 [L3 ?]]]]. rewrite H0. exists a'. exists (a :: L1). exists L2. exists L3. trivial. Qed. Fixpoint foot {A} (L : list A) : option A := match L with | nil => None | a :: nil => Some a | a :: L' => foot L' end. Lemma foot_simpl: forall A (a1 a2 : A) (L : list A), foot (a1 :: a2 :: L) = foot (a2 :: L). Proof. intros. simpl. destruct L; auto. Qed. Lemma foot_last: forall A (L : list A) (a : A), foot (L +:: a) = Some a. Proof. induction L; auto; intros; destruct L; auto; rewrite <- (IHL a0); simpl; destruct (L +:: a0); simpl; auto. Qed. Lemma foot_app: forall A (L1 L2 : list A), L2 <> nil -> foot (L1 ++ L2) = foot L2. Proof. induction L1. auto. intros. rewrite <- app_comm_cons. simpl. case_eq (L1 ++ L2). intro. apply app_eq_nil in H0. destruct H0. contradiction. intros. rewrite <- H0. apply IHL1. trivial. Qed. Lemma foot_explicit {A}: forall L (a : A), foot L = Some a -> exists L', L = L' +:: a. Proof. induction L. inversion 1. intros. simpl in H. icase L. inv H. exists nil. trivial. specialize (IHL a0 H). destruct IHL. exists (a :: x). rewrite <- app_comm_cons. congr. Qed. Lemma foot_in {A}: forall (a : A) L, foot L = Some a -> In a L. Proof. induction L. inversion 1. icase L. simpl. inversion 1. auto. rewrite foot_simpl. right. auto. Qed. Lemma foot_none_nil {A}: forall (l : list A), foot l = None -> l = nil. Proof. induction l; intros; auto. simpl in H. destruct l. inversion H. specialize (IHl H). inversion IHl. Qed. Lemma cons_tail_dec {A}: forall (l: list A), (l = nil) + {l0: list A & {a: A | l = l0 +:: a}}. Proof. intros. destruct l. 1: left; auto. right. revert a; induction l; intros. + exists nil, a; auto. + destruct (IHl a) as [? [? ?]]. exists (a0 :: x), x0. rewrite e. simpl; auto. Qed. Lemma filter_incl: forall A f (l: list A), incl (filter f l) l. Proof. intros. hnf. intros. rewrite filter_In in H. destruct H; auto. Qed. Lemma NoDup_filter: forall A f (l: list A), NoDup l -> NoDup (filter f l). Proof. intros. induction l. - simpl; constructor. - inversion H; subst. simpl; destruct (f a) eqn:?; [constructor |]; auto. rewrite filter_In. tauto. Qed. Lemma exists_list_dec: forall A (l: list A) P, (forall x, {P x} + {~ P x}) -> ({exists x, In x l /\ P x} + {~ exists x, In x l /\ P x}). Proof. intros. induction l. + right; intros [x [? ?]]. inversion H. + destruct (X a); [| destruct IHl]; [left | left | right]. - exists a; split; auto. left; auto. - destruct e as [? [? ?]]. exists x; split; auto. right; auto. - intros [? [? ?]]. destruct H; [subst; tauto |]. apply n0; exists x. tauto. Qed. Lemma exists_list_weak_dec: forall A (l: list A) P (X: forall x, (P x) \/ (~ P x)), (exists x, In x l /\ P x) \/ (~ exists x, In x l /\ P x). Proof. intros. induction l. + right; intros [x [? ?]]. inversion H. + destruct (X a); [| destruct IHl]; [left | left | right]. - exists a; split; auto. left; auto. - destruct H0 as [? [? ?]]. exists x; split; auto. right; auto. - intros [? [? ?]]. destruct H1; [subst; tauto |]. apply H0; exists x. tauto. Qed. (* TODO: As this lemma is proved. many other lemmas about remove can be replaced by similar existential lemmas. *) Lemma In_Permutation_cons: forall {A : Type} (l : list A) (x : A), In x l -> exists l', Permutation l (x :: l'). Proof. intros. induction l. + inversion H. + destruct H. - exists l; subst; reflexivity. - destruct (IHl H) as [l' ?]. exists (a :: l'). rewrite H0. constructor. Qed. Lemma incl_Permutation {A: Type}: forall (l1 l2: list A), NoDup l2 -> incl l2 l1 -> exists l', Permutation l1 (l2 ++ l'). Proof. intros l1 l2. revert l1. induction l2; intros. - exists l1. simpl. auto. - rewrite NoDup_cons_iff in H. destruct H. hnf in H0. assert (In a l1) by (apply H0; simpl; auto). assert (incl l2 l1) by (hnf; intros; apply H0; simpl; auto). specialize (IHl2 l1 H1 H3). destruct IHl2 as [l3 ?]. assert (In a l3) by (rewrite H4 in H2; apply in_app_or in H2; destruct H2; [exfalso|]; auto). apply In_Permutation_cons in H5. destruct H5 as [l4 ?]. rewrite H5 in H4. exists l4. rewrite H4. rewrite <- app_comm_cons. symmetry. apply Permutation_middle. Qed. Lemma perm_spec_minus_1: forall {A : Type} (l : list A) (P: A -> Prop) (x : A), P x -> (forall y : A, In y l <-> P y) /\ NoDup l -> (exists l', Permutation l (x :: l') /\ (forall y : A, In y l' <-> P y /\ x <> y) /\ NoDup l'). Proof. intros. destruct H0. rewrite <- H0 in H. destruct (In_Permutation_cons _ _ H) as [l' ?]. exists l'. split; auto. eapply Permutation_NoDup in H1; eauto. pose proof NoDup_cons_1 _ _ _ H1. pose proof NoDup_cons_2 _ _ _ H1. split; [| auto]. intro y; rewrite <- H0. assert (x = y -> ~ In y l') by (intro; subst; auto). pose proof @Permutation_in _ _ _ y H2. pose proof @Permutation_in _ _ _ y (Permutation_sym H2). simpl in H6, H7. tauto. Qed. Lemma Permutation_spec_Prop_join: forall {A : Type} (l : list A) (P Pf: A -> Prop) (x : A), Prop_join (eq x) Pf P -> (forall y : A, In y l <-> P y) /\ NoDup l -> (exists l', Permutation l (x :: l') /\ (forall y : A, In y l' <-> Pf y) /\ NoDup l'). Proof. intros. destruct H, H0. assert (In x l) by (rewrite H0, H; auto). destruct (In_Permutation_cons _ _ H3) as [l' ?]. exists l'. split; auto. pose proof Permutation_NoDup H4 H2. pose proof NoDup_cons_1 _ _ _ H5. pose proof NoDup_cons_2 _ _ _ H5. split; auto. intros. pose proof @Permutation_in _ _ _ y H4. pose proof @Permutation_in _ _ _ y (Permutation_sym H4). simpl in H8, H9. clear H6 H2 H3 H4 H5. specialize (H y). specialize (H0 y). specialize (H1 y). assert (x = y -> ~ In y l') by (intros; subst; auto). tauto. Qed. Lemma nodup_remove_perm: forall {A : Type} (eq_dec : forall x y : A, {x = y} + {x <> y}) (l : list A) (x : A), NoDup l -> In x l -> Permutation l (x :: remove eq_dec x l). Proof. intros. apply in_split in H0. destruct H0 as [l1 [l2 ?]]. subst. rewrite (remove_middle eq_dec _ _ _ H). rewrite app_cons_assoc. apply (@Permutation_app_tail _ _ (x :: l1) l2), Permutation_sym, Permutation_cons_append. Qed. Lemma filter_perm: forall {A: Type} (f g: A -> bool) l, (forall x, In x l -> f x = negb (g x)) -> Permutation l (filter f l ++ filter g l). Proof. intros. induction l. + reflexivity. + simpl. pose proof (H a (or_introl eq_refl)). spec IHl; [intros; apply H; simpl; auto |]. destruct (g a) eqn:?H; simpl in H0; rewrite H0. - apply Permutation_cons_app; auto. - apply Permutation_cons; auto. Qed. Existing Instance Permutation_app'. Ltac split5 := split; [| split; [| split; [| split]]]. Lemma spec_or_list_split: forall {A} (l: list A) P Q, NoDup l -> (forall x, In x l <-> P x \/ Q x) -> exists lp lq, NoDup lp /\ NoDup lq /\ (forall x, In x lp -> P x) /\ (forall x, In x lq -> Q x) /\ (forall x, In x l <-> In x lp \/ In x lq). Proof. intros. pose proof (fun x => proj1 (H0 x)). clear H0. induction l. + exists nil, nil. split5; [constructor | constructor |..]; intro x; simpl; tauto. + spec IHl; [inversion H; auto |]. spec IHl; [intros; apply H1; simpl; auto |]. destruct IHl as [lp [lq [? [? [? [? ?]]]]]]. destruct (H1 a (or_introl eq_refl)); [exists (a :: lp), lq | exists lp, (a :: lq)]; split5; intros; auto. - constructor; auto. inversion H; subst. firstorder. - destruct H7; [subst |]; auto. - simpl; specialize (H5 x); tauto. - constructor; auto. inversion H; subst. firstorder. - destruct H7; [subst |]; auto. - simpl; specialize (H5 x); tauto. Qed. Lemma spec_list_split: forall {A} (l: list A) P Q R, NoDup l -> (forall x, In x l <-> R x) -> Prop_join P Q R -> exists lp lq, NoDup lp /\ NoDup lq /\ (forall x, In x lp <-> P x) /\ (forall x, In x lq <-> Q x) /\ Permutation l (lp ++ lq). Proof. intros A l P Q R ? EQUIV [? ?]. assert (forall a, In a l <-> P a \/ Q a) by firstorder. clear EQUIV H0 R; rename H2 into H0. pose proof (spec_or_list_split l P Q H H0). destruct H2 as [lp [lq [? [? [? [? ?]]]]]]. exists lp, lq. split5; auto. + firstorder. + firstorder. + apply NoDup_Permutation; auto. - apply NoDup_app_inv; auto. firstorder. - intro; rewrite in_app_iff. firstorder. Qed. Fixpoint select {A: Type} {P: A -> Prop} (dec_p: forall x, Decidable (P x)) (l: list A) : list A := match l with | nil => nil | x :: lx => if dec_p x then x :: select dec_p lx else select dec_p lx end. Lemma select_In {A: Type} {P: A -> Prop} (dec_p: forall x, Decidable (P x)): forall x l, In x (select dec_p l) <-> In x l /\ P x. Proof. intros; induction l; simpl; [intuition | destruct (dec_p a)]; split; intro. + simpl in H. destruct H; [subst|]; intuition. + destruct H. simpl. destruct H; [left | right]; intuition. + rewrite IHl in H. intuition. + rewrite IHl. destruct H. split; auto. destruct H; [subst; exfalso|]; intuition. Qed. Lemma NoDup_select {A: Type} {P: A -> Prop} (dec_p: forall x, Decidable (P x)): forall l, NoDup l -> NoDup (select dec_p l). Proof. intro. induction l; intros; simpl; auto. specialize (IHl (NoDup_cons_1 _ _ _ H)). apply NoDup_cons_2 in H. destruct (dec_p a); auto. constructor; auto. intro. apply H. rewrite select_In in H0. intuition. Qed. Lemma or_dec_prop_list_split: forall {A} (l: list A) P Q, NoDup l -> (forall x, Decidable (P x)) -> (forall x, Decidable (Q x)) -> (forall x, In x l <-> P x \/ Q x) -> exists lp lq, NoDup lp /\ NoDup lq /\ (forall x, In x lp <-> P x) /\ (forall x, In x lq <-> Q x) /\ (forall x, In x l <-> In x lp \/ In x lq). Proof. intros. exists (select X l), (select X0 l). split5; intros. + apply NoDup_select; auto. + apply NoDup_select; auto. + rewrite select_In. firstorder. + rewrite select_In. firstorder. + do 2 rewrite select_In. firstorder. Qed. Fixpoint prefixes {A: Type} (l: list A): list (list A) := match l with | nil => nil | a :: l0 => nil :: map (cons a) (prefixes l0) end. Definition cprefix {A: Type} (l: list A) := combine (prefixes l) l. Lemma map_id: forall {A: Type} (l: list A), map id l = l. Proof. intros. induction l; auto. simpl. rewrite IHl; auto. Qed. Lemma length_prefixes: forall {A: Type} (l: list A), length (prefixes l) = length l. Proof. intros. induction l; auto. simpl. f_equal. rewrite map_length. auto. Qed. Lemma prefixes_app_1: forall {A: Type} (l: list A) (a: A), prefixes (l +:: a) = prefixes l +:: l. Proof. intros. induction l; auto. simpl. rewrite IHl. rewrite map_app. auto. Qed. Lemma combine_app: forall {A B: Type} (la1 la2: list A) (lb1 lb2: list B), length la1 = length lb1 -> combine (la1 ++ la2) (lb1 ++ lb2) = combine la1 lb1 ++ combine la2 lb2. Proof. intros. revert lb1 H; induction la1; intros; destruct lb1; try now inversion H. inv H. simpl. f_equal. apply IHla1; auto. Qed. Lemma combine_prefixes_app_1: forall {A: Type} (l: list A) (a: A), cprefix (l +:: a) = cprefix l +:: (l, a). Proof. intros. unfold cprefix. rewrite prefixes_app_1. rewrite combine_app by (apply length_prefixes). auto. Qed. Lemma map_fst_combine: forall {A B: Type} (a: list A) (b: list B), length a = length b -> map fst (combine a b) = a. Proof. intros. revert b H; induction a; intros; destruct b; try solve [inversion H]. + reflexivity. + simpl. f_equal. apply IHa. inv H. auto. Qed. Lemma map_snd_combine: forall {A B: Type} (a: list A) (b: list B), length a = length b -> map snd (combine a b) = b. Proof. intros. revert b H; induction a; intros; destruct b; try solve [inversion H]. + reflexivity. + simpl. f_equal. apply IHa. inv H. auto. Qed. Lemma map_snd_cprefix: forall {A: Type} (l: list A), map snd (cprefix l) = l. Proof. intros. apply map_snd_combine. apply length_prefixes. Qed. Lemma map_snd_cprefix': forall {A B: Type} (l: list A) (f: A -> B), map f l = map (fun p => f (snd p)) (cprefix l). Proof. intros. unfold cprefix. rewrite <- (map_map snd f). rewrite map_snd_combine; auto. apply length_prefixes. Qed. Ltac rev_induction l := revert dependent l; refine (rev_ind _ _ _); intros. Lemma in_cprefix: forall {A: Type} (xs: list A) xs0 x0, In (xs0, x0) (cprefix xs) -> In x0 xs. Proof. intros. rev_induction xs. + inversion H. + rewrite combine_prefixes_app_1 in H0. rewrite in_app_iff in H0 |- *. destruct H0. - auto. - destruct H0 as [| []]. inversion H0; subst. simpl; auto. Qed. Lemma in_cprefix': forall {A: Type} (xs: list A) xs_done x0, In (xs_done, x0) (cprefix xs) -> exists xs_later, xs = xs_done ++ x0 :: xs_later. Proof. intros. rev_induction xs. + inversion H. + rewrite combine_prefixes_app_1 in H0. rewrite in_app_iff in H0. destruct H0. - destruct (H H0) as [xs_later ?]. exists (xs_later +:: x). change (x0 :: xs_later +:: x) with ((x0 :: xs_later) +:: x). rewrite app_assoc. f_equal; auto. - destruct H0 as [| []]. inversion H0; subst. exists nil; auto. Qed. Lemma in_cprefix_cprefix: forall {A: Type} (xs: list A) xs0 xss0, In (xss0, xs0) (cprefix (cprefix xs)) -> xss0 = cprefix (fst xs0). Proof. intros. rev_induction xs. + inversion H. + rewrite !combine_prefixes_app_1 in H0. rewrite in_app_iff in H0. destruct H0; [auto |]. destruct H0 as [| []]. inversion H0; subst. reflexivity. Qed. Lemma in_cprefix_cprefix': forall {A: Type} (xs: list A) xs0 xss0, In (xss0, xs0) (cprefix (cprefix xs)) -> map snd xss0 = fst xs0. Proof. intros. rev_induction xs. + inversion H. + rewrite !combine_prefixes_app_1 in H0. rewrite in_app_iff in H0. destruct H0; [auto |]. destruct H0 as [| []]. inversion H0; subst. rewrite map_snd_cprefix. reflexivity. Qed. Lemma nodup_remove_nodup: forall {A : Type} (eq_dec : forall x y : A, {x = y} + {x <> y}) (l : list A) (x : A), NoDup l -> NoDup (remove eq_dec x l). Proof. intros. destruct (in_dec eq_dec x l). 2: rewrite remove_not_in; auto. pose proof (nodup_remove_perm eq_dec _ _ H i). apply (Permutation_NoDup H0) in H. apply NoDup_cons_1 in H; auto. Qed. Lemma filter_cons: forall {A: Type} (f: A -> bool) l x xl, filter f l = x :: xl -> exists l1 l2, l = l1 ++ x :: l2 /\ filter f l1 = nil /\ filter f l2 = xl /\ f x = true. Proof. intros. induction l. 1: simpl in H; inversion H. simpl in H. destruct (f a) eqn:? . + inversion H. subst a. exists nil, l. split; [|split; [|split]]; auto. + specialize (IHl H). destruct IHl as [l1 [l2 [? [? [? ?]]]]]. exists (a :: l1), l2. split; [|split; [|split]]; auto. - rewrite <- app_comm_cons. subst l. auto. - simpl. destruct (f a) eqn:? . inversion Heqb. auto. Qed. Lemma filter_2_cons: forall {A: Type} (f: A -> bool) l x1 x2 xl, filter f l = x1 :: x2 :: xl -> exists l1 l2 l3, l = l1 ++ x1 :: l2 ++ x2 :: l3 /\ filter f l1 = nil /\ filter f l2 = nil /\ filter f l3 = xl /\ f x1 = true /\ f x2 = true. Proof. intros. apply filter_cons in H. destruct H as [l1 [l4 [? [? [? ?]]]]]. apply filter_cons in H1. destruct H1 as [l2 [l3 [? [? [? ?]]]]]. subst l4. exists l1, l2, l3. split; auto. Qed. Lemma map_mid: forall {A B: Type} (f: A -> B) l x xl1 xl2, map f l = xl1 ++ x :: xl2 -> exists y yl1 yl2, l = yl1 ++ y :: yl2 /\ f y = x /\ map f yl1 = xl1 /\ map f yl2 = xl2. Proof. intros. revert xl1 H. induction l; intros. 1: simpl in H; destruct xl1; inversion H. destruct xl1. + clear IHl. simpl in H. exists a, nil, l. inversion H. split; auto. + simpl in H. inversion H. specialize (IHl _ H2). destruct IHl as [y [yl1 [yl2 [? [? [? ?]]]]]]. exists y, (a :: yl1), yl2. simpl. subst l. rewrite H4. split; auto. Qed. Lemma map_2_mid: forall {A B: Type} (f: A -> B) l x1 x2 l1 l2 l3, map f l = l1 ++ x1 :: l2 ++ x2 :: l3 -> exists y1 y2 m1 m2 m3, l = m1 ++ y1 :: m2 ++ y2 :: m3 /\ map f m1 = l1 /\ map f m2 = l2 /\ map f m3 = l3 /\ f y1 = x1 /\ f y2 = x2. Proof. intros. apply map_mid in H. destruct H as [y1 [m1 [m4 [? [? [? ?]]]]]]. apply map_mid in H2. destruct H2 as [y2 [m2 [m3 [? [? [? ?]]]]]]. subst m4. exists y1, y2, m1, m2, m3. split; auto. Qed. Lemma nth_error_None_iff: forall {A} (l: list A) n, nth_error l n = None <-> n >= length l. Proof. intros. revert n; induction l; intros; destruct n; simpl. + split; [intros _; omega | auto]. + split; [intros _; omega | auto]. + split; [intros; inversion H | omega]. + rewrite IHl. omega. Qed. (* TODO: These three lemmas are copied from VST.veric.assert_lemmas and VST.veric.initial_world *) Lemma nth_error_in_bounds: forall {A} (l: list A) i, (O <= i < length l)%nat -> exists x, nth_error l i = value x. Proof. intros until i; intros H. revert i l H. induction i; destruct l; intros; simpl in *; try solve [eauto | omega]. apply IHi; omega. Qed. Lemma nth_error_app: forall {T} (al bl : list T) (j: nat), nth_error (al++bl) (length al + j) = nth_error bl j. Proof. intros. induction al; simpl; auto. Qed. Lemma nth_error_app1: forall {T} (al bl : list T) (j: nat), (j < length al)%nat -> nth_error (al++bl) j = nth_error al j. Proof. intros. revert al H; induction j; destruct al; simpl; intros; auto; try omega. apply IHj. omega. Qed. Lemma in_split_not_in_first: forall {A} (eq_dec: forall x y : A, {x = y} + {x <> y}) (x: A) (l: list A), In x l -> exists l1 l2, l = l1 ++ x :: l2 /\ ~ In x l1. Proof. intros ? ? ?. induction l; intros. - inversion H. - simpl in H. destruct (eq_dec a x). + exists nil, l. rewrite app_nil_l. subst a. split; auto. + destruct H. 1: exfalso; auto. specialize (IHl H). destruct IHl as [l1 [l2 [? ?]]]. exists (a :: l1), l2. simpl. rewrite H0. split; auto. intro. destruct H2; auto. Qed. Lemma in_split_not_in_last: forall {A} (eq_dec: forall x y : A, {x = y} + {x <> y}) (x: A) (l: list A), In x l -> exists l1 l2, l = l1 ++ x :: l2 /\ ~ In x l2. Proof. intros ? ? ? ?. rev_induction l. 1: inversion H. destruct (eq_dec x0 x). - exists l, nil. subst x0. split; auto. - rewrite in_app_iff in H0. destruct H0. + specialize (H H0). destruct H as [l1 [l2 [? ?]]]. exists l1, (l2 +:: x0). rewrite H. rewrite <- app_assoc. simpl. split; auto. intro. rewrite in_app_iff in H2. destruct H2; auto. simpl in H2. destruct H2; auto. + simpl in H0. destruct H0; exfalso; auto. Qed. Fixpoint filter_sum_left {A B} (l: list (A + B)) : list A := match l with | nil => nil | inl x :: l' => x :: filter_sum_left l' | inr _ :: l' => filter_sum_left l' end. Fixpoint filter_sum_right {A B} (l: list (A + B)) : list B := match l with | nil => nil | inl _ :: l' => filter_sum_right l' | inr x :: l' => x :: filter_sum_right l' end. Fixpoint filter_option {A} (l: list (option A)) : list A := match l with | nil => nil | Some x :: l' => x :: filter_option l' | None :: l' => filter_option l' end. Lemma filter_sum_right_In_iff {A B}: forall e (l: list (A + B)), In (inr e) l <-> In e (filter_sum_right l). Proof. intros. induction l; simpl; intuition. - inversion H2. - inversion H2. simpl. left; reflexivity. - simpl in H1. destruct H1. + subst b. left; reflexivity. + right. apply H0. assumption. Qed. Lemma filter_sum_left_In_iff {A B}: forall e (l: list (A + B)), In (inl e) l <-> In e (filter_sum_left l). Proof. intros. induction l; simpl; intuition. - inversion H2. simpl. left; reflexivity. - simpl in H1. destruct H1. + subst a0. left; reflexivity. + right. apply H0. assumption. - inversion H2. Qed. Lemma filter_option_In_iff {A}: forall e (l: list (option A)), In (Some e) l <-> In e (filter_option l). Proof. intros. induction l; simpl; try reflexivity. destruct a; intuition. - inversion H2. simpl. left; reflexivity. - simpl in H1. destruct H1. + subst a. left; reflexivity. + right. apply H0. assumption. - inversion H2. Qed. Lemma combine_nth_lt {A B}: forall (l1: list A) (l2: list B) n x y, n < length l1 -> n < length l2 -> nth n (combine l1 l2) (x, y) = (nth n l1 x, nth n l2 y). Proof. induction l1; intros. - simpl in *. exfalso. omega. - destruct l2. + simpl in H0. exfalso. omega. + simpl. destruct n; [|simpl in *; rewrite IHl1 by omega]; reflexivity. Qed. Lemma map_tl {A B: Type}: forall (f: A -> B) (l: list A), map f (tl l) = tl (map f l). Proof. intros; destruct l; simpl; reflexivity. Qed. Lemma fold_left_comm: forall {A B} (f: A -> B -> A) l1 l2 init, (forall a b1 b2, f (f a b1) b2 = f (f a b2) b1) -> Permutation l1 l2 -> fold_left f l1 init = fold_left f l2 init. Proof. intros. remember (length l1). assert (length l1 <= n) by omega. clear Heqn. revert init l1 l2 H1 H0. induction n; intros; destruct l1. - apply Permutation_nil in H0. subst l2. simpl. reflexivity. - simpl in H1; exfalso; omega. - apply Permutation_nil in H0. subst l2. simpl. reflexivity. - simpl in H1. assert (length l1 <= n) by omega. clear H1. assert (In b l2) by (apply Permutation_in with (x := b) in H0; [assumption | left; reflexivity]). apply in_split in H1. destruct H1 as [l3 [l4 ?]]. subst l2. apply Permutation_cons_app_inv in H0. simpl. rewrite IHn with (l2 := l3 ++ l4) by assumption. rewrite !fold_left_app. simpl. f_equal. clear -H. revert b init. rev_induction l3; simpl. 1: reflexivity. rewrite !fold_left_app. simpl. rewrite H. f_equal. apply H0. Qed. Local Open Scope Z_scope. Lemma fold_left_Z_mono_strict: forall {A} (f: Z -> A -> Z) (l1 l2 l3: list A) s, (forall a b, a < f a b) -> (forall a b1 b2, f (f a b1) b2 = f (f a b2) b1) -> l2 <> nil -> Permutation (l1 ++ l2) l3 -> fold_left f l1 s < fold_left f l3 s. Proof. intros. rewrite <- (fold_left_comm _ _ _ _ H0 H2). rewrite fold_left_app. remember (fold_left f l1 s). clear -H H1. rev_induction l2. 1: contradiction. rewrite fold_left_app. simpl. destruct l. 1: simpl; apply H. transitivity (fold_left f (a :: l) z); [apply H0; intro; inversion H2 | apply H]. Qed. Lemma fold_left_Z_mono: forall {A} (f: Z -> A -> Z) (l1 l2 l3: list A) s, (forall a b, a <= f a b) -> (forall a b1 b2, f (f a b1) b2 = f (f a b2) b1) -> Permutation (l1 ++ l2) l3 -> fold_left f l1 s <= fold_left f l3 s. Proof. intros. rewrite <- (fold_left_comm _ _ _ _ H0 H1). rewrite fold_left_app. remember (fold_left f l1 s). clear -H. rev_induction l2. 1: simpl; intuition. rewrite fold_left_app. simpl. transitivity (fold_left f l z); [apply H0 | apply H]. Qed. Lemma fold_left_mono_filter: forall {A} (f: Z -> A -> Z) (l: list A) (h: A -> bool) s, (forall a b, a <= f a b) -> (forall a b1 b2, f (f a b1) b2 = f (f a b2) b1) -> fold_left f (filter h l) s <= fold_left f l s. Proof. intros. remember (fun x: A => negb (h x)) as g. assert (Permutation (filter h l ++ filter g l) l) by (symmetry; apply filter_perm; intros; subst; apply Bool.negb_involutive_reverse). apply (fold_left_Z_mono f _ _ _ s H H0 H1). Qed. Lemma fold_left_ext: forall {A B} (f g: A -> B -> A) l init, (forall x y, In y l -> f x y = g x y) -> fold_left f l init = fold_left g l init. Proof. intros. revert init. rev_induction l; intros; simpl. 1: reflexivity. rewrite !fold_left_app. simpl. rewrite H; intros; apply H0; rewrite in_app_iff; intuition. Qed. Lemma NoDup_combine_r: forall {A B} (l1: list A) (l2: list B), NoDup l2 -> NoDup (combine l1 l2). Proof. intros. revert l2 H. induction l1; intros; simpl. 1: constructor. destruct l2; constructor. - intro. apply in_combine_r in H0. apply NoDup_cons_2 in H. contradiction. - apply IHl1. apply NoDup_cons_1 in H. assumption. Qed. Lemma filter_ext: forall {A} (f g: A -> bool) l, (forall i, In i l -> f i = g i) -> filter f l = filter g l. Proof. intros. induction l; simpl. 1: reflexivity. assert (f a = g a) by (apply H; left; reflexivity). assert (forall i : A, In i l -> f i = g i) by (intros; apply H; right; assumption). destruct (f a), (g a); [|inversion H0.. |]; rewrite IHl by assumption; reflexivity. Qed. Lemma filter_singular_perm: forall {A} (f g: A -> bool) l x, (forall i, In i l -> i <> x -> f i = g i) -> In x l -> g x = false -> f x = true -> NoDup l -> Permutation (filter f l) (x :: filter g l). Proof. intros. induction l. 1: inversion H0. simpl. simpl in H0. destruct H0. - subst a. rewrite H1. rewrite H2. constructor. cut (filter f l = filter g l). + intros. rewrite H0. reflexivity. + apply filter_ext. intros. apply H. * simpl; right; assumption. * apply NoDup_cons_2 in H3. intro. subst i. contradiction. - assert (a <> x) by (apply NoDup_cons_2 in H3; intro; subst a; contradiction). assert (f a = g a) by (apply H; [left; reflexivity | assumption]). assert (Permutation (filter f l) (x :: filter g l)). { apply IHl; [intros; apply H; [right|] | |apply NoDup_cons_1 in H3]; assumption. } destruct (f a); destruct (g a); try discriminate; clear H5; [transitivity (a :: x :: filter g l); constructor|]; assumption. Qed. Lemma app_not_nil: forall {A} (l: list A) (a: A), l ++ (a :: nil) <> nil. Proof. intros. destruct l; intro; simpl in H; inversion H. Qed. Lemma combine_repeat_eq_map: forall {A B} (a: A) (l: list B), combine (repeat a (length l)) l = map (fun b : B => (a, b)) l. Proof. intros. induction l; simpl; auto. rewrite IHl. reflexivity. Qed. Lemma combine_map_join: forall {A B C} (f: A -> B) (g: A -> C) (l: list A), combine (map f l) (map g l) = map (fun x => (f x, g x)) l. Proof. intros. induction l; simpl; auto. rewrite IHl. reflexivity. Qed. Lemma map_fst_split: forall {A B} (l: list (A * B)), map fst l = fst (split l). Proof. intros. pose proof (split_length_l l). pose proof (split_length_r l). pose proof (split_combine l). destruct (split l). simpl in *. rewrite <- H0 in H. now rewrite <- H1, map_fst_combine. Qed. Lemma map_snd_split: forall {A B} (l: list (A * B)), map snd l = snd (split l). Proof. intros. pose proof (split_length_l l). pose proof (split_length_r l). pose proof (split_combine l). destruct (split l). simpl in *. rewrite <- H0 in H. now rewrite <- H1, map_snd_combine. Qed. Lemma In_map_fst_iff: forall {A B} a (l: list (A * B)), In a (map fst l) <-> exists b : B, In (a, b) l. Proof. intros. induction l; simpl. 1: intuition; now destruct H. destruct a0 as [a0 b0]. simpl in *. split; intros. - destruct H. 1: subst; exists b0; now left. rewrite IHl in H. destruct H as [b ?]. exists b. now right. - destruct H as [b ?]. destruct H. 1: inversion H; now left. rewrite IHl. right. now exists b. Qed. Lemma In_map_snd_iff: forall {A B} b (l: list (A * B)), In b (map snd l) <-> exists a : A, In (a, b) l. Proof. intros. induction l; simpl. 1: intuition; now destruct H. destruct a as [a0 b0]. simpl in *. split; intros. - destruct H. 1: subst; exists a0; now left. rewrite IHl in H. destruct H as [a ?]. exists a. now right. - destruct H as [a ?]. destruct H. 1: inversion H; now left. rewrite IHl. right. now exists a. Qed. Lemma In_map_fst: forall {A B} a b (l: list (A * B)), In (a, b) l -> In a (map fst l). Proof. intros. assert (exists y, In (a, y) l) by (now exists b). now rewrite <- In_map_fst_iff in H0. Qed. Lemma In_map_snd: forall {A B} a b (l: list (A * B)), In (a, b) l -> In b (map snd l). Proof. intros. assert (exists x, In (x, b) l) by (now exists a). now rewrite <- In_map_snd_iff in H0. Qed. Section LIST_DERIVED_BIJECTION. Context {A: Type}. Context {AE: EqDec A eq}. Fixpoint bi_look_up (l: list (A * A)) (key: A): option A := match l with | nil => None | (k, v) :: l' => if equiv_dec k key then Some v else if equiv_dec v key then Some k else bi_look_up l' key end. Definition list_bi_map (l: list (A * A)) (r: A): A := match (bi_look_up l r) with | Some v => v | None => r end. Definition DoubleNoDup (l: list (A * A)): Prop := let (left_l, right_l) := split l in NoDup (left_l ++ right_l). Lemma DoubleNoDup_cons_tl: forall x l, DoubleNoDup (x :: l) -> DoubleNoDup l. Proof. intros. destruct x as [x y]. unfold DoubleNoDup in *. simpl in H. destruct (split l) as [l1 l2]. simpl in H. apply NoDup_cons_1, NoDup_remove_1 in H. assumption. Qed. Lemma DoubleNoDup_cons_hd: forall k v l, DoubleNoDup ((k, v) :: l) -> k <> v. Proof. intros. unfold DoubleNoDup in H. simpl in H. destruct (split l) as [l1 l2]. simpl in H. apply NoDup_cons_2 in H. intro. subst. apply H. rewrite in_app_iff. right. left. reflexivity. Qed. Definition InEither (v: A) (l: list (A * A)): Prop := let (left_l, right_l) := split l in In v (left_l ++ right_l). Definition IsEither (v: A) (a: A * A): Prop := v = fst a \/ v = snd a. Lemma InEither_cons_iff: forall v a l, InEither v (a :: l) <-> IsEither v a \/ InEither v l. Proof. do 3 intro. revert v a. induction l; intros. - destruct a. unfold InEither at 1. simpl. unfold IsEither. simpl. intuition. - rewrite IHl. unfold InEither. simpl. destruct (split l) as [l1 l2]. destruct a. destruct a0. unfold IsEither. simpl. rewrite !in_app_iff. simpl. clear. firstorder. Qed. Lemma InEither_dec: forall v l, {InEither v l} + {~ InEither v l}. Proof. intros. induction l. 1: right; intro; inversion H. destruct a as [v1 v2]. destruct (equiv_dec v v1); unfold equiv in *. - left. rewrite InEither_cons_iff. left. red. simpl. left. assumption. - destruct (equiv_dec v v2); unfold equiv in *. + left. rewrite InEither_cons_iff. left. red. simpl. right. assumption. + destruct IHl; [left | right]. * rewrite InEither_cons_iff. right. assumption. * intro. apply n. clear n. rewrite InEither_cons_iff in H. destruct H; auto. red in H. simpl in H. exfalso. unfold complement in *. destruct H; auto. Defined. Lemma list_bi_map_cons_1: forall a l x, ~ IsEither x a -> list_bi_map (a :: l) x = list_bi_map l x. Proof. intros. unfold list_bi_map. simpl. destruct a. unfold IsEither in H. simpl in H. apply Decidable.not_or in H. destruct H. destruct (equiv_dec a x). 1: exfalso; intuition. destruct (equiv_dec a0 x). 1: exfalso; intuition. reflexivity. Qed. Lemma list_bi_map_not_In: forall l x, ~ InEither x l -> list_bi_map l x = x. Proof. induction l; intros. 1: unfold list_bi_map; simpl; reflexivity. rewrite InEither_cons_iff in H. apply Decidable.not_or in H. destruct H. rewrite list_bi_map_cons_1; auto. Qed. Lemma IsEither_dec: forall v a, {IsEither v a} + {~ IsEither v a}. Proof. intros. destruct a. destruct (equiv_dec v a). - left. red. left. simpl. assumption. - destruct (equiv_dec v a0). + left. red. right; simpl; assumption. + right. unfold IsEither. simpl. unfold equiv, complement in *. intuition. Defined. Lemma list_bi_map_In: forall l x, InEither x l -> exists k v, In (k, v) l /\ ((x = k /\ list_bi_map l x = v) \/ (x = v /\ list_bi_map l x = k)). Proof. induction l; intros. 1: inversion H. destruct (IsEither_dec x a). - destruct a. exists a, a0. simpl. split. 1: left; reflexivity. red in i. simpl in i. destruct i; subst; [left | right]; split; try reflexivity; unfold list_bi_map; simpl. + destruct (equiv_dec a a); [| exfalso; apply c]; reflexivity. + destruct (equiv_dec a a0). 1: intuition. destruct (equiv_dec a0 a0); [| exfalso; apply c0]; reflexivity. - rewrite InEither_cons_iff in H. destruct H. 1: contradiction. specialize (IHl _ H). destruct IHl as [k [v [? ?]]]. exists k, v. split. + simpl. right; assumption. + destruct a. unfold IsEither in n. simpl in n. apply Decidable.not_or in n. destruct n. unfold list_bi_map in *. simpl. destruct (equiv_dec a x); unfold equiv in *. 1: exfalso; intuition. destruct (equiv_dec a0 x); unfold equiv in *. 1: exfalso; intuition. assumption. Qed. Lemma DoubleNoDup_cons_neq: forall v1 v2 l, DoubleNoDup ((v1, v2) :: l) -> ~ InEither v1 l /\ ~ InEither v2 l. Proof. do 3 intro. revert v1 v2. induction l; intros. 1: intuition. destruct a. specialize (IHl _ _ (DoubleNoDup_cons_tl _ _ H)). destruct IHl. unfold DoubleNoDup in H. simpl in H. unfold InEither in *. simpl. destruct (split l) as [l1 l2]. split. - simpl in H. apply NoDup_cons_2 in H. simpl in *. intro. apply H. destruct H2; auto. right. rewrite in_app_iff in H2 |-* . destruct H2; intuition. - apply NoDup_remove_2 in H. intro. apply H. rewrite in_app_iff in H2 |-* . destruct H2; auto. left. right. assumption. Qed. Lemma In_InEither: forall v1 v2 l, In (v1, v2) l -> InEither v1 l /\ InEither v2 l. Proof. do 3 intro. revert v1 v2. induction l; intros. 1: inversion H. simpl in H. destruct H. - subst. rewrite !InEither_cons_iff. unfold IsEither. simpl. intuition. - apply IHl in H. destruct H. rewrite !InEither_cons_iff. intuition. Qed. Lemma DoubleNoDup_In_fst_eq: forall l k v1 v2, DoubleNoDup l -> In (k, v1) l -> In (k, v2) l -> v1 = v2. Proof. induction l; intros. 1: inversion H0. simpl in H0, H1. destruct H0, H1. - rewrite H0 in H1. inversion H1. reflexivity. - apply In_InEither in H1. destruct H1. subst a. apply DoubleNoDup_cons_neq in H. destruct H. contradiction. - apply In_InEither in H0. destruct H0. subst a. apply DoubleNoDup_cons_neq in H. destruct H. contradiction. - eapply IHl; eauto. eapply DoubleNoDup_cons_tl; eauto. Qed. Lemma DoubleNoDup_In_snd_eq: forall l k1 k2 v, DoubleNoDup l -> In (k1, v) l -> In (k2, v) l -> k1 = k2. Proof. induction l; intros. 1: inversion H0. simpl in H0, H1. destruct H0, H1. - rewrite H0 in H1. inversion H1. reflexivity. - apply In_InEither in H1. destruct H1. subst a. apply DoubleNoDup_cons_neq in H. destruct H. contradiction. - apply In_InEither in H0. destruct H0. subst a. apply DoubleNoDup_cons_neq in H. destruct H. contradiction. - eapply IHl; eauto. eapply DoubleNoDup_cons_tl; eauto. Qed. Lemma DoubleNoDup_In_fst_snd_impsb: forall l v1 v2 v, DoubleNoDup l -> In (v1, v) l -> In (v, v2) l -> False. Proof. induction l; intros. 1: inversion H0. simpl in H0, H1. destruct H0, H1. - rewrite H0 in H1. inversion H1. subst. apply DoubleNoDup_cons_hd in H. contradiction. - apply In_InEither in H1. destruct H1. subst a. apply DoubleNoDup_cons_neq in H. destruct H. contradiction. - apply In_InEither in H0. destruct H0. subst a. apply DoubleNoDup_cons_neq in H. destruct H. contradiction. - apply (IHl v1 v2 v); auto. eapply DoubleNoDup_cons_tl; eauto. Qed. Lemma DoubleNoDup_bi_look_up: forall k v l, DoubleNoDup l -> In (k, v) l -> bi_look_up l k = Some v /\ bi_look_up l v = Some k. Proof. do 3 intro. induction l; intros. 1: inversion H0. assert (a = (k, v) \/ a <> (k, v)). { destruct a; destruct (equiv_dec a k); destruct (equiv_dec a0 v); unfold equiv in *; unfold complement in *; simpl in *; subst; [left; reflexivity | right; intro; apply c; inversion H1; reflexivity..]. } destruct H1. - subst. simpl. apply DoubleNoDup_cons_hd in H. destruct (equiv_dec k k); intuition. destruct (equiv_dec k v); intuition. destruct (equiv_dec v v); intuition. - destruct a. simpl. destruct (equiv_dec a k); unfold equiv in *. + exfalso. subst a. apply H1. f_equal. eapply DoubleNoDup_In_fst_eq; eauto. simpl. left; reflexivity. + destruct (equiv_dec a0 k); unfold equiv in *. * exfalso. subst a0. eapply (DoubleNoDup_In_fst_snd_impsb _ a); eauto. simpl. left; reflexivity. * destruct (equiv_dec a v); unfold equiv in *. -- exfalso. subst a. eapply (DoubleNoDup_In_fst_snd_impsb _ k a0 v); eauto. simpl. left; reflexivity. -- destruct (equiv_dec a0 v); unfold equiv in *. ++ exfalso. subst. apply H1. f_equal. eapply DoubleNoDup_In_snd_eq; eauto. simpl. left; reflexivity. ++ apply IHl. 1: eapply DoubleNoDup_cons_tl; eauto. simpl in H0. destruct H0; auto. contradiction. Qed. Lemma bijective_list_bi_map: forall l, DoubleNoDup l -> bijective (list_bi_map l) (list_bi_map l). Proof. intros. constructor; intros. - destruct (InEither_dec x l). + apply list_bi_map_In in i. destruct i as [kx [vx [? ?]]]. destruct (InEither_dec y l). * apply list_bi_map_In in i. destruct i as [ky [vy [? ?]]]. destruct H2 as [[? ?] | [? ?]]; destruct H4 as [[? ?] | [? ?]]; rewrite H5, H6 in H0; subst. -- eapply DoubleNoDup_In_snd_eq; eauto. -- exfalso; eapply (DoubleNoDup_In_fst_snd_impsb _ kx); eauto. -- exfalso; eapply (DoubleNoDup_In_fst_snd_impsb _ ky); eauto. -- eapply DoubleNoDup_In_fst_eq; eauto. * pose proof n. apply list_bi_map_not_In in n. rewrite <- H0 in n. destruct H2 as [[? ?] | [? ?]]; rewrite H4 in n; rewrite n in H1; exfalso; apply H3; apply In_InEither in H1; destruct H1; assumption. + pose proof n. apply list_bi_map_not_In in n. rewrite H0 in n. destruct (InEither_dec y l). * apply list_bi_map_In in i. destruct i as [ky [vy [? ?]]]. destruct H3 as [[? ?] | [? ?]]; rewrite H4 in n; rewrite n in H2; exfalso; apply H1; apply In_InEither in H2; destruct H2; assumption. * apply list_bi_map_not_In in H1. apply list_bi_map_not_In in n0. rewrite H1, n0 in H0. assumption. - destruct (InEither_dec x l). + apply list_bi_map_In in i. destruct i as [k [v [? ?]]]. destruct (DoubleNoDup_bi_look_up _ _ _ H H0). destruct H1 as [[? ?] | [? ?]]; subst x; rewrite H4; unfold list_bi_map. * rewrite H3. reflexivity. * rewrite H2. reflexivity. + apply list_bi_map_not_In in n. rewrite n. assumption. Qed. Lemma DoubleNoDup_cons_iff: forall a b l, DoubleNoDup ((a, b) :: l) <-> DoubleNoDup l /\ a <> b /\ ~ InEither a l /\ ~ InEither b l. Proof. intros. unfold DoubleNoDup, InEither. simpl. destruct (split l) as [l1 l2]. rewrite !NoDup_app_iff, !NoDup_cons_iff, !in_app_iff. simpl. split; intros. - destruct H as [[? ?] [[? ?] ?]]. intuition. + apply (H3 x); right; assumption. + apply (H3 b); left; auto. + apply (H3 a); [left | right]; auto. + apply (H3 b); [right | left]; auto. - destruct H as [[? [? ?]] [? [? ?]]]. apply Decidable.not_or in H3. apply Decidable.not_or in H4. destruct H3, H4. intuition; [subst; contradiction..| apply (H1 x); assumption]. Qed. Lemma InEither_app_iff: forall a l1 l2, InEither a (l1 ++ l2) <-> InEither a l1 \/ InEither a l2. Proof. intros a l1. revert a. induction l1; simpl; intros. 1: intuition. rewrite !InEither_cons_iff, IHl1. intuition. Qed. Lemma DoubleNoDup_app_iff: forall l1 l2, DoubleNoDup (l1 ++ l2) <-> DoubleNoDup l1 /\ DoubleNoDup l2 /\ (forall x, InEither x l1 -> ~ InEither x l2). Proof. induction l1; simpl; intros. 1: intuition; constructor. destruct a as [a b]. rewrite !DoubleNoDup_cons_iff, !InEither_app_iff, IHl1. clear IHl1. intuition. - apply (H4 x); auto. rewrite InEither_cons_iff in H5. destruct H5; auto. unfold IsEither in H5. simpl in H5. exfalso. destruct H5; subst; contradiction. - apply (H3 x); auto. rewrite InEither_cons_iff. right; assumption. - apply (H3 a); auto. rewrite InEither_cons_iff. left. left. simpl; reflexivity. - apply (H3 b); auto. rewrite InEither_cons_iff. left. right. simpl; reflexivity. Qed. Lemma DoubleNoDup_list_bi_map: forall k v l, DoubleNoDup l -> In (k, v) l -> list_bi_map l k = v /\ list_bi_map l v = k. Proof. intros. destruct (DoubleNoDup_bi_look_up _ _ _ H H0). unfold list_bi_map. rewrite H1, H2. split; reflexivity. Qed. Lemma DoubleNoDup_cons_InEither: forall l a b, DoubleNoDup (a :: l) -> InEither b l -> ~ IsEither b a. Proof. intros. destruct a as [x y]. rewrite DoubleNoDup_cons_iff in H. destruct H as [? [? [? ?]]]. intro. red in H4. simpl in H4. destruct H4; now subst. Qed. Lemma list_bi_map_nil: list_bi_map nil = id. Proof. extensionality x. unfold list_bi_map. now simpl. Qed. Lemma DoubleNoDup_fst: forall l, DoubleNoDup l -> NoDup (map fst l). Proof. intros. red in H. destruct (split l) eqn:? . rewrite map_fst_split, Heqp. simpl. now apply NoDup_app_l in H. Qed. Lemma DoubleNoDup_snd: forall l, DoubleNoDup l -> NoDup (map snd l). Proof. intros. red in H. destruct (split l) eqn:? . rewrite map_snd_split, Heqp. simpl. now apply NoDup_app_r in H. Qed. End LIST_DERIVED_BIJECTION. Section LIST_DERIVED_MAPPING. Context {A: Type}. Context {AE: EqDec A eq}. Fixpoint look_up (l: list (A * A)) (key: A): option A := match l with | nil => None | (k, v) :: l' => if equiv_dec k key then Some v else look_up l' key end. Definition list_map (l: list (A * A)) (r: A): A := match (look_up l r) with | Some v => v | None => r end. Lemma list_map_cons_1: forall a l x, x <> fst a -> list_map (a :: l) x = list_map l x. Proof. intros. unfold list_map. simpl. destruct a. simpl in *. destruct (equiv_dec a x). 1: unfold equiv in e; exfalso; apply H; subst; easy. reflexivity. Qed. Lemma list_map_not_In: forall l x, ~ In x (map fst l) -> list_map l x = x. Proof. induction l; intros. 1: unfold list_map; simpl; reflexivity. simpl in H. apply Decidable.not_or in H. destruct H. rewrite list_map_cons_1. 2: intuition. now apply IHl. Qed. Lemma NoDup_look_up: forall k v l, NoDup (map fst l) -> In (k, v) l -> look_up l k = Some v. Proof. do 3 intro. induction l; intros. 1: inversion H0. simpl in *. destruct a as [k0 v0]. destruct H0. - inversion H0. subst. destruct (equiv_dec k k). reflexivity. exfalso. intuition. - simpl in H. destruct (equiv_dec k0 k); unfold equiv in *. + apply NoDup_cons_2 in H. exfalso. apply H. subst. now apply (in_map fst) in H0. + apply NoDup_cons_1 in H. now apply IHl. Qed. Lemma list_map_In: forall l k v, NoDup (map fst l) -> In (k, v) l -> list_map l k = v. Proof. intros. unfold list_map. now rewrite (NoDup_look_up k v). Qed. Lemma list_map_NoDup_app_eq: forall l1 l2 v, NoDup (map fst (l2 ++ l1)) -> (~ In v (map fst l1) -> In (v, v) l2) -> list_map l1 v = list_map (l2 ++ l1) v. Proof. intros. destruct (in_dec equiv_dec v (map fst (l2 ++ l1))). - destruct (in_dec equiv_dec v (map fst l1)). + rewrite In_map_fst_iff in i0. destruct i0 as [b ?]. erewrite !list_map_In; eauto. 1: rewrite in_app_iff; now right. rewrite map_app in H. now apply NoDup_app_r in H. + rewrite list_map_not_In; auto. apply H0 in n. erewrite list_map_In; eauto. rewrite in_app_iff. now left. - rewrite !list_map_not_In; auto. intro. apply n. rewrite map_app, in_app_iff. now right. Qed. Lemma list_map_DoubleNoDup_incl_eq: forall l1 l2 v, DoubleNoDup (l2 ++ l1) -> (In v (map fst (l2 ++ l1)) -> In v (map fst l1)) -> list_map l1 v = list_map (l2 ++ l1) v. Proof. intros. destruct (in_dec equiv_dec v (map fst (l2 ++ l1))). - destruct (in_dec equiv_dec v (map fst l1)). 2: now apply H0 in i. rewrite In_map_fst_iff in i0. destruct i0 as [b ?]. rewrite !(list_map_In _ _ b); auto. + now apply DoubleNoDup_fst in H. + rewrite in_app_iff. now right. + rewrite DoubleNoDup_app_iff in H. destruct H as [? [? ?]]. now apply DoubleNoDup_fst in H2. - rewrite !list_map_not_In; auto. intro. apply n. rewrite map_app, in_app_iff. now right. Qed. Lemma look_up_not_In: forall l v, ~ In v (map fst l) <-> look_up l v = None. Proof. induction l; intros; simpl. 1: intuition. destruct a as [k v']. simpl. split; intros. - apply Decidable.not_or in H. destruct H. destruct (equiv_dec k v); unfold equiv in *; [contradiction | now apply IHl]. - destruct (equiv_dec k v). 1: inversion H. rewrite <- IHl in H. intro. unfold equiv, complement in c. destruct H0; contradiction. Qed. Lemma In_look_up: forall l v a, look_up l v = Some a -> In v (map fst l) /\ In a (map snd l). Proof. induction l; intros; simpl in *. 1: inversion H. destruct a as [k v']. simpl. destruct (equiv_dec k v); unfold equiv in *. - inversion H. subst. intuition. - apply IHl in H. destruct H. split; now right. Qed. Lemma InEither_map_iff: forall v (l: list (A * A)), InEither v l <-> In v (map fst l) \/ In v (map snd l). Proof. intros. unfold InEither. destruct (split l) eqn:? . rewrite in_app_iff, map_fst_split, map_snd_split, Heqp. now simpl. Qed. Lemma In_look_up': forall l k v, look_up l k = Some v -> In (k, v) l. Proof. induction l; intros; simpl in *. 1: inversion H. destruct a as [k' v']. destruct (equiv_dec k' k); unfold equiv in *. - inversion H. subst. now left. - apply IHl in H. now right. Qed. Lemma list_map_idempotent: forall l, DoubleNoDup l -> idempotent (list_map l). Proof. destruct l; intros; red; intros. - unfold list_map. now simpl. - destruct p as [k v]. rewrite DoubleNoDup_cons_iff in H. destruct H as [? [? [? ?]]]. unfold list_map. simpl. destruct (equiv_dec k x); unfold equiv in *. + subst x. destruct (equiv_dec k v); auto. destruct (look_up l v) eqn:? ; auto. apply In_look_up in Heqo. exfalso. apply H2. rewrite InEither_map_iff. now left. + unfold complement in c. destruct (look_up l x) eqn:? . * apply In_look_up in Heqo. destruct Heqo. destruct (equiv_dec k a); unfold equiv in *. -- subst a. exfalso. apply H1. rewrite InEither_map_iff. now right. -- destruct (look_up l a) eqn:? ; auto. apply In_look_up in Heqo. destruct Heqo as [? _]. red in H. destruct (split l) eqn:? . rewrite map_fst_split, Heqp in H5. rewrite map_snd_split, Heqp in H4. simpl in H4, H5. rewrite NoDup_app_iff in H. destruct H as [_ [_ ?]]. exfalso. now apply (H a). * destruct (equiv_dec k x); unfold equiv in *; [easy | now rewrite Heqo]. Qed. Lemma list_map_bi_map: forall l x, ~ In x (map snd l) -> list_map l x = list_bi_map l x. Proof. induction l; intros; unfold list_map, list_bi_map; simpl; auto. destruct a as [k v]. simpl in *. apply Decidable.not_or in H. destruct H. destruct (equiv_dec k x); auto. destruct (equiv_dec v x); unfold equiv in *. 1: easy. fold (list_map l x) (list_bi_map l x). now apply IHl. Qed. End LIST_DERIVED_MAPPING.
#!/usr/bin/env python3 import sys import time # numpy and scipy import numpy as np from edgetpu.detection.engine import DetectionEngine from imutils.video import VideoStream from PIL import Image import argparse import imutils import time import cv2 # Ros import rospy from sensor_msgs.msg import CompressedImage import rospkg from std_msgs.msg import Int16MultiArray class FaceDetectorEdgeTPU: def __init__(self): # Read input parameters self.input_image_compressed = rospy.get_param('~input_image_compressed', "usb_cam/image_raw/compressed") self.output_image_compressed = rospy.get_param('~output_image', "face_image/compressed") self.model_path = rospy.get_param('~model_path', "model.tflite") self.threshold = rospy.get_param('~threshold', 0.8) self.rotation_angle = rospy.get_param('~rotation_angle', 0.0) self.labels_file = rospy.get_param('~labels_file', "") self.tracked_object = rospy.get_param('~tracked_object', "person") self.enable_labeling = False self.labels = {} # fix path if required if len(self.model_path) > 0: if "pkg://" in self.model_path: rp = rospkg.RosPack() path = rp.get_path('braccio_camai') self.model_path = self.model_path.replace("pkg://braccio_camai", path) else: rospy.loginfo("Invalid model path") return if len(self.labels_file) > 0: if "pkg://" in self.labels_file: rp = rospkg.RosPack() path = rp.get_path('braccio_camai') self.labels_file = self.labels_file.replace("pkg://braccio_camai", path) # loop over the class labels file for row in open(self.labels_file): # unpack the row and update the labels dictionary (classID, label) = row.strip().split(maxsplit=1) self.labels[int(classID)] = label.strip() self.enable_labeling = True # print input parameters rospy.loginfo("input_image_compressed: " + self.input_image_compressed) rospy.loginfo("output_image_compressed: " + self.output_image_compressed) rospy.loginfo("model_path: " + self.model_path) rospy.loginfo("threshold: " + str(self.threshold)) rospy.loginfo("rotation_angle: " + str(self.rotation_angle)) rospy.loginfo("labels_file: " + str(self.labels_file)) rospy.loginfo("tracked_object: " + str(self.tracked_object)) self.current_image = CompressedImage() rospy.loginfo("Loading Tensorflow model") self.model = DetectionEngine(self.model_path) self.pub_image = rospy.Publisher(self.output_image_compressed, CompressedImage, queue_size=1) self.pub_box = rospy.Publisher("bounding_box", Int16MultiArray, queue_size=1) self.subscriber = rospy.Subscriber(self.input_image_compressed, CompressedImage, self.callback, queue_size=1) rospy.loginfo("detection started") while not rospy.is_shutdown(): self.process_current_image() #rospy.spin() def process_current_image(self): # No image data received if len(self.current_image.data) == 0: return # skip is no subscribers request for detections if self.pub_box.get_num_connections() == 0 and self.pub_image.get_num_connections() == 0: return np_arr = np.fromstring(self.current_image.data, np.uint8) frame_ori = cv2.imdecode(np_arr, cv2.IMREAD_COLOR) frame = self.rotate_image(frame_ori, self.rotation_angle) orig = frame.copy() frame = Image.fromarray(frame) # make predictions on the input frame results = self.model.DetectWithImage(frame, threshold=self.threshold, keep_aspect_ratio=True, relative_coord=False) # loop over the results for r in results: # extract the bounding box box = r.bounding_box.flatten().astype("int") (startX, startY, endX, endY) = box if self.enable_labeling: label = self.labels[r.label_id] if label != self.tracked_object: continue # skip current object y = startY - 15 if startY - 15 > 15 else startY + 15 text = "{}: {:.2f}%".format(label, r.score * 100) cv2.putText(orig, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) # draw the bounding box and label on the image cv2.rectangle(orig, (startX, startY), (endX, endY), (0, 255, 0), 2) box_msg = Int16MultiArray() box_msg.data = [r.label_id, startX, startY, endX, endY] self.pub_box.publish(box_msg) break # skip if no subscribers are registered if self.pub_image.get_num_connections() == 0: return #### Create CompressedIamge #### msg = CompressedImage() msg.header.stamp = rospy.Time.now() msg.format = "jpeg" msg.data = np.array(cv2.imencode('.jpg', orig)[1]).tostring() # Publish image with face detections self.pub_image.publish(msg) def callback(self, ros_data): self.current_image = ros_data def rotate_image(self, image, angle): image_center = tuple(np.array(image.shape[1::-1]) / 2) rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0) result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR) return result def main(args): rospy.init_node('FaceDetectorEdgeTPU') FaceDetectorEdgeTPU() cv2.destroyAllWindows() if __name__ == '__main__': main(sys.argv)
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.finset.fold import data.finset.option import data.finset.prod import data.multiset.lattice import order.complete_lattice /-! # Lattice operations on finsets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ variables {α β γ ι : Type*} namespace finset open multiset order_dual /-! ### sup -/ section sup -- TODO: define with just `[has_bot α]` where some lemmas hold without requiring `[order_bot α]` variables [semilattice_sup α] [order_bot α] /-- Supremum of a finite set: `sup {a, b, c} f = f a ⊔ f b ⊔ f c` -/ def sup (s : finset β) (f : β → α) : α := s.fold (⊔) ⊥ f variables {s s₁ s₂ : finset β} {f g : β → α} {a : α} lemma sup_def : s.sup f = (s.1.map f).sup := rfl @[simp] lemma sup_empty : (∅ : finset β).sup f = ⊥ := fold_empty @[simp] lemma sup_cons {b : β} (h : b ∉ s) : (cons b s h).sup f = f b ⊔ s.sup f := fold_cons h @[simp] lemma sup_insert [decidable_eq β] {b : β} : (insert b s : finset β).sup f = f b ⊔ s.sup f := fold_insert_idem lemma sup_image [decidable_eq β] (s : finset γ) (f : γ → β) (g : β → α) : (s.image f).sup g = s.sup (g ∘ f) := fold_image_idem @[simp] lemma sup_map (s : finset γ) (f : γ ↪ β) (g : β → α) : (s.map f).sup g = s.sup (g ∘ f) := fold_map @[simp] lemma sup_singleton {b : β} : ({b} : finset β).sup f = f b := sup_singleton lemma sup_union [decidable_eq β] : (s₁ ∪ s₂).sup f = s₁.sup f ⊔ s₂.sup f := finset.induction_on s₁ (by rw [empty_union, sup_empty, bot_sup_eq]) $ λ a s has ih, by rw [insert_union, sup_insert, sup_insert, ih, sup_assoc] lemma sup_sup : s.sup (f ⊔ g) = s.sup f ⊔ s.sup g := begin refine finset.cons_induction_on s _ (λ b t _ h, _), { rw [sup_empty, sup_empty, sup_empty, bot_sup_eq] }, { rw [sup_cons, sup_cons, sup_cons, h], exact sup_sup_sup_comm _ _ _ _ } end theorem sup_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀ a ∈ s₂, f a = g a) : s₁.sup f = s₂.sup g := by subst hs; exact finset.fold_congr hfg @[simp] protected lemma sup_le_iff {a : α} : s.sup f ≤ a ↔ (∀ b ∈ s, f b ≤ a) := begin apply iff.trans multiset.sup_le, simp only [multiset.mem_map, and_imp, exists_imp_distrib], exact ⟨λ k b hb, k _ _ hb rfl, λ k a' b hb h, h ▸ k _ hb⟩, end alias finset.sup_le_iff ↔ _ sup_le attribute [protected] sup_le lemma sup_const_le : s.sup (λ _, a) ≤ a := finset.sup_le $ λ _ _, le_rfl lemma le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f := finset.sup_le_iff.1 le_rfl _ hb @[simp] lemma sup_bUnion [decidable_eq β] (s : finset γ) (t : γ → finset β) : (s.bUnion t).sup f = s.sup (λ x, (t x).sup f) := eq_of_forall_ge_iff $ λ c, by simp [@forall_swap _ β] lemma sup_const {s : finset β} (h : s.nonempty) (c : α) : s.sup (λ _, c) = c := eq_of_forall_ge_iff $ λ b, finset.sup_le_iff.trans h.forall_const @[simp] lemma sup_bot (s : finset β) : s.sup (λ _, ⊥) = (⊥ : α) := begin obtain rfl | hs := s.eq_empty_or_nonempty, { exact sup_empty }, { exact sup_const hs _ } end lemma sup_ite (p : β → Prop) [decidable_pred p] : s.sup (λ i, ite (p i) (f i) (g i)) = (s.filter p).sup f ⊔ (s.filter (λ i, ¬ p i)).sup g := fold_ite _ lemma sup_mono_fun {g : β → α} (h : ∀ b ∈ s, f b ≤ g b) : s.sup f ≤ s.sup g := finset.sup_le (λ b hb, le_trans (h b hb) (le_sup hb)) lemma sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f := finset.sup_le $ λ b hb, le_sup $ h hb protected lemma sup_comm (s : finset β) (t : finset γ) (f : β → γ → α) : s.sup (λ b, t.sup (f b)) = t.sup (λ c, s.sup (λ b, f b c)) := begin refine eq_of_forall_ge_iff (λ a, _), simp_rw finset.sup_le_iff, exact ⟨λ h c hc b hb, h b hb c hc, λ h b hb c hc, h c hc b hb⟩, end @[simp] lemma sup_attach (s : finset β) (f : β → α) : s.attach.sup (λ x, f x) = s.sup f := (s.attach.sup_map (function.embedding.subtype _) f).symm.trans $ congr_arg _ attach_map_val /-- See also `finset.product_bUnion`. -/ lemma sup_product_left (s : finset β) (t : finset γ) (f : β × γ → α) : (s ×ˢ t).sup f = s.sup (λ i, t.sup $ λ i', f ⟨i, i'⟩) := begin simp only [le_antisymm_iff, finset.sup_le_iff, mem_product, and_imp, prod.forall], exact ⟨λ b c hb hc, (le_sup hb).trans' $ le_sup hc, λ b hb c hc, le_sup $ mem_product.2 ⟨hb, hc⟩⟩, end lemma sup_product_right (s : finset β) (t : finset γ) (f : β × γ → α) : (s ×ˢ t).sup f = t.sup (λ i', s.sup $ λ i, f ⟨i, i'⟩) := by rw [sup_product_left, finset.sup_comm] @[simp] lemma sup_erase_bot [decidable_eq α] (s : finset α) : (s.erase ⊥).sup id = s.sup id := begin refine (sup_mono (s.erase_subset _)).antisymm (finset.sup_le_iff.2 $ λ a ha, _), obtain rfl | ha' := eq_or_ne a ⊥, { exact bot_le }, { exact le_sup (mem_erase.2 ⟨ha', ha⟩) } end lemma sup_sdiff_right {α β : Type*} [generalized_boolean_algebra α] (s : finset β) (f : β → α) (a : α) : s.sup (λ b, f b \ a) = s.sup f \ a := begin refine finset.cons_induction_on s _ (λ b t _ h, _), { rw [sup_empty, sup_empty, bot_sdiff] }, { rw [sup_cons, sup_cons, h, sup_sdiff] } end lemma comp_sup_eq_sup_comp [semilattice_sup γ] [order_bot γ] {s : finset β} {f : β → α} (g : α → γ) (g_sup : ∀ x y, g (x ⊔ y) = g x ⊔ g y) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := finset.cons_induction_on s bot (λ c t hc ih, by rw [sup_cons, sup_cons, g_sup, ih]) /-- Computing `sup` in a subtype (closed under `sup`) is the same as computing it in `α`. -/ lemma sup_coe {P : α → Prop} {Pbot : P ⊥} {Psup : ∀ {{x y}}, P x → P y → P (x ⊔ y)} (t : finset β) (f : β → {x : α // P x}) : (@sup _ _ (subtype.semilattice_sup Psup) (subtype.order_bot Pbot) t f : α) = t.sup (λ x, f x) := by { rw [comp_sup_eq_sup_comp coe]; intros; refl } @[simp] lemma sup_to_finset {α β} [decidable_eq β] (s : finset α) (f : α → multiset β) : (s.sup f).to_finset = s.sup (λ x, (f x).to_finset) := comp_sup_eq_sup_comp multiset.to_finset to_finset_union rfl lemma _root_.list.foldr_sup_eq_sup_to_finset [decidable_eq α] (l : list α) : l.foldr (⊔) ⊥ = l.to_finset.sup id := begin rw [←coe_fold_r, ←multiset.fold_dedup_idem, sup_def, ←list.to_finset_coe, to_finset_val, multiset.map_id], refl end theorem subset_range_sup_succ (s : finset ℕ) : s ⊆ range (s.sup id).succ := λ n hn, mem_range.2 $ nat.lt_succ_of_le $ le_sup hn theorem exists_nat_subset_range (s : finset ℕ) : ∃n : ℕ, s ⊆ range n := ⟨_, s.subset_range_sup_succ⟩ lemma sup_induction {p : α → Prop} (hb : p ⊥) (hp : ∀ a₁, p a₁ → ∀ a₂, p a₂ → p (a₁ ⊔ a₂)) (hs : ∀ b ∈ s, p (f b)) : p (s.sup f) := begin induction s using finset.cons_induction with c s hc ih, { exact hb, }, { rw sup_cons, apply hp, { exact hs c (mem_cons.2 (or.inl rfl)), }, { exact ih (λ b h, hs b (mem_cons.2 (or.inr h))), }, }, end lemma sup_le_of_le_directed {α : Type*} [semilattice_sup α] [order_bot α] (s : set α) (hs : s.nonempty) (hdir : directed_on (≤) s) (t : finset α) : (∀ x ∈ t, ∃ y ∈ s, x ≤ y) → ∃ x, x ∈ s ∧ t.sup id ≤ x := begin classical, apply finset.induction_on t, { simpa only [forall_prop_of_true, and_true, forall_prop_of_false, bot_le, not_false_iff, sup_empty, forall_true_iff, not_mem_empty], }, { intros a r har ih h, have incs : ↑r ⊆ ↑(insert a r), by { rw finset.coe_subset, apply finset.subset_insert, }, -- x ∈ s is above the sup of r obtain ⟨x, ⟨hxs, hsx_sup⟩⟩ := ih (λ x hx, h x $ incs hx), -- y ∈ s is above a obtain ⟨y, hys, hay⟩ := h a (finset.mem_insert_self a r), -- z ∈ s is above x and y obtain ⟨z, hzs, ⟨hxz, hyz⟩⟩ := hdir x hxs y hys, use [z, hzs], rw [sup_insert, id.def, sup_le_iff], exact ⟨le_trans hay hyz, le_trans hsx_sup hxz⟩, }, end -- If we acquire sublattices -- the hypotheses should be reformulated as `s : subsemilattice_sup_bot` lemma sup_mem (s : set α) (w₁ : ⊥ ∈ s) (w₂ : ∀ x y ∈ s, x ⊔ y ∈ s) {ι : Type*} (t : finset ι) (p : ι → α) (h : ∀ i ∈ t, p i ∈ s) : t.sup p ∈ s := @sup_induction _ _ _ _ _ _ (∈ s) w₁ w₂ h @[simp] lemma sup_eq_bot_iff (f : β → α) (S : finset β) : S.sup f = ⊥ ↔ ∀ s ∈ S, f s = ⊥ := begin classical, induction S using finset.induction with a S haS hi; simp [*], end end sup lemma sup_eq_supr [complete_lattice β] (s : finset α) (f : α → β) : s.sup f = (⨆ a ∈ s, f a) := le_antisymm (finset.sup_le $ assume a ha, le_supr_of_le a $ le_supr _ ha) (supr_le $ assume a, supr_le $ assume ha, le_sup ha) lemma sup_id_eq_Sup [complete_lattice α] (s : finset α) : s.sup id = Sup s := by simp [Sup_eq_supr, sup_eq_supr] lemma sup_id_set_eq_sUnion (s : finset (set α)) : s.sup id = ⋃₀(↑s) := sup_id_eq_Sup _ @[simp] lemma sup_set_eq_bUnion (s : finset α) (f : α → set β) : s.sup f = ⋃ x ∈ s, f x := sup_eq_supr _ _ lemma sup_eq_Sup_image [complete_lattice β] (s : finset α) (f : α → β) : s.sup f = Sup (f '' s) := begin classical, rw [←finset.coe_image, ←sup_id_eq_Sup, sup_image, function.comp.left_id], end /-! ### inf -/ section inf -- TODO: define with just `[has_top α]` where some lemmas hold without requiring `[order_top α]` variables [semilattice_inf α] [order_top α] /-- Infimum of a finite set: `inf {a, b, c} f = f a ⊓ f b ⊓ f c` -/ def inf (s : finset β) (f : β → α) : α := s.fold (⊓) ⊤ f variables {s s₁ s₂ : finset β} {f g : β → α} {a : α} lemma inf_def : s.inf f = (s.1.map f).inf := rfl @[simp] lemma inf_empty : (∅ : finset β).inf f = ⊤ := fold_empty @[simp] lemma inf_cons {b : β} (h : b ∉ s) : (cons b s h).inf f = f b ⊓ s.inf f := @sup_cons αᵒᵈ _ _ _ _ _ _ h @[simp] lemma inf_insert [decidable_eq β] {b : β} : (insert b s : finset β).inf f = f b ⊓ s.inf f := fold_insert_idem lemma inf_image [decidable_eq β] (s : finset γ) (f : γ → β) (g : β → α) : (s.image f).inf g = s.inf (g ∘ f) := fold_image_idem @[simp] lemma inf_map (s : finset γ) (f : γ ↪ β) (g : β → α) : (s.map f).inf g = s.inf (g ∘ f) := fold_map @[simp] lemma inf_singleton {b : β} : ({b} : finset β).inf f = f b := inf_singleton lemma inf_union [decidable_eq β] : (s₁ ∪ s₂).inf f = s₁.inf f ⊓ s₂.inf f := @sup_union αᵒᵈ _ _ _ _ _ _ _ lemma inf_inf : s.inf (f ⊓ g) = s.inf f ⊓ s.inf g := @sup_sup αᵒᵈ _ _ _ _ _ _ theorem inf_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀ a ∈ s₂, f a = g a) : s₁.inf f = s₂.inf g := by subst hs; exact finset.fold_congr hfg @[simp] lemma inf_bUnion [decidable_eq β] (s : finset γ) (t : γ → finset β) : (s.bUnion t).inf f = s.inf (λ x, (t x).inf f) := @sup_bUnion αᵒᵈ _ _ _ _ _ _ _ _ lemma inf_const {s : finset β} (h : s.nonempty) (c : α) : s.inf (λ _, c) = c := @sup_const αᵒᵈ _ _ _ _ h _ @[simp] lemma inf_top (s : finset β) : s.inf (λ _, ⊤) = (⊤ : α) := @sup_bot αᵒᵈ _ _ _ _ protected lemma le_inf_iff {a : α} : a ≤ s.inf f ↔ ∀ b ∈ s, a ≤ f b := @finset.sup_le_iff αᵒᵈ _ _ _ _ _ _ alias finset.le_inf_iff ↔ _ le_inf attribute [protected] le_inf lemma le_inf_const_le : a ≤ s.inf (λ _, a) := finset.le_inf $ λ _ _, le_rfl lemma inf_le {b : β} (hb : b ∈ s) : s.inf f ≤ f b := finset.le_inf_iff.1 le_rfl _ hb lemma inf_mono_fun {g : β → α} (h : ∀ b ∈ s, f b ≤ g b) : s.inf f ≤ s.inf g := finset.le_inf (λ b hb, le_trans (inf_le hb) (h b hb)) lemma inf_mono (h : s₁ ⊆ s₂) : s₂.inf f ≤ s₁.inf f := finset.le_inf $ λ b hb, inf_le $h hb lemma inf_attach (s : finset β) (f : β → α) : s.attach.inf (λ x, f x) = s.inf f := @sup_attach αᵒᵈ _ _ _ _ _ protected lemma inf_comm (s : finset β) (t : finset γ) (f : β → γ → α) : s.inf (λ b, t.inf (f b)) = t.inf (λ c, s.inf (λ b, f b c)) := @finset.sup_comm αᵒᵈ _ _ _ _ _ _ _ lemma inf_product_left (s : finset β) (t : finset γ) (f : β × γ → α) : (s ×ˢ t).inf f = s.inf (λ i, t.inf $ λ i', f ⟨i, i'⟩) := @sup_product_left αᵒᵈ _ _ _ _ _ _ _ lemma inf_product_right (s : finset β) (t : finset γ) (f : β × γ → α) : (s ×ˢ t).inf f = t.inf (λ i', s.inf $ λ i, f ⟨i, i'⟩) := @sup_product_right αᵒᵈ _ _ _ _ _ _ _ @[simp] lemma inf_erase_top [decidable_eq α] (s : finset α) : (s.erase ⊤).inf id = s.inf id := @sup_erase_bot αᵒᵈ _ _ _ _ lemma sup_sdiff_left {α β : Type*} [boolean_algebra α] (s : finset β) (f : β → α) (a : α) : s.sup (λ b, a \ f b) = a \ s.inf f := begin refine finset.cons_induction_on s _ (λ b t _ h, _), { rw [sup_empty, inf_empty, sdiff_top] }, { rw [sup_cons, inf_cons, h, sdiff_inf] } end lemma inf_sdiff_left {α β : Type*} [boolean_algebra α] {s : finset β} (hs : s.nonempty) (f : β → α) (a : α) : s.inf (λ b, a \ f b) = a \ s.sup f := begin induction hs using finset.nonempty.cons_induction with b b t _ _ h, { rw [sup_singleton, inf_singleton] }, { rw [sup_cons, inf_cons, h, sdiff_sup] } end lemma inf_sdiff_right {α β : Type*} [boolean_algebra α] {s : finset β} (hs : s.nonempty) (f : β → α) (a : α) : s.inf (λ b, f b \ a) = s.inf f \ a := begin induction hs using finset.nonempty.cons_induction with b b t _ _ h, { rw [inf_singleton, inf_singleton] }, { rw [inf_cons, inf_cons, h, inf_sdiff] } end lemma comp_inf_eq_inf_comp [semilattice_inf γ] [order_top γ] {s : finset β} {f : β → α} (g : α → γ) (g_inf : ∀ x y, g (x ⊓ y) = g x ⊓ g y) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := @comp_sup_eq_sup_comp αᵒᵈ _ γᵒᵈ _ _ _ _ _ _ _ g_inf top /-- Computing `inf` in a subtype (closed under `inf`) is the same as computing it in `α`. -/ lemma inf_coe {P : α → Prop} {Ptop : P ⊤} {Pinf : ∀ {{x y}}, P x → P y → P (x ⊓ y)} (t : finset β) (f : β → {x : α // P x}) : (@inf _ _ (subtype.semilattice_inf Pinf) (subtype.order_top Ptop) t f : α) = t.inf (λ x, f x) := @sup_coe αᵒᵈ _ _ _ _ Ptop Pinf t f lemma _root_.list.foldr_inf_eq_inf_to_finset [decidable_eq α] (l : list α) : l.foldr (⊓) ⊤ = l.to_finset.inf id := begin rw [←coe_fold_r, ←multiset.fold_dedup_idem, inf_def, ←list.to_finset_coe, to_finset_val, multiset.map_id], refl end lemma inf_induction {p : α → Prop} (ht : p ⊤) (hp : ∀ a₁, p a₁ → ∀ a₂, p a₂ → p (a₁ ⊓ a₂)) (hs : ∀ b ∈ s, p (f b)) : p (s.inf f) := @sup_induction αᵒᵈ _ _ _ _ _ _ ht hp hs lemma inf_mem (s : set α) (w₁ : ⊤ ∈ s) (w₂ : ∀ x y ∈ s, x ⊓ y ∈ s) {ι : Type*} (t : finset ι) (p : ι → α) (h : ∀ i ∈ t, p i ∈ s) : t.inf p ∈ s := @inf_induction _ _ _ _ _ _ (∈ s) w₁ w₂ h @[simp] lemma inf_eq_top_iff (f : β → α) (S : finset β) : S.inf f = ⊤ ↔ ∀ s ∈ S, f s = ⊤ := @finset.sup_eq_bot_iff αᵒᵈ _ _ _ _ _ end inf @[simp] lemma to_dual_sup [semilattice_sup α] [order_bot α] (s : finset β) (f : β → α) : to_dual (s.sup f) = s.inf (to_dual ∘ f) := rfl @[simp] lemma to_dual_inf [semilattice_inf α] [order_top α] (s : finset β) (f : β → α) : to_dual (s.inf f) = s.sup (to_dual ∘ f) := rfl @[simp] lemma of_dual_sup [semilattice_inf α] [order_top α] (s : finset β) (f : β → αᵒᵈ) : of_dual (s.sup f) = s.inf (of_dual ∘ f) := rfl @[simp] lemma of_dual_inf [semilattice_sup α] [order_bot α] (s : finset β) (f : β → αᵒᵈ) : of_dual (s.inf f) = s.sup (of_dual ∘ f) := rfl section distrib_lattice variables [distrib_lattice α] section order_bot variables [order_bot α] {s : finset β} {f : β → α} {a : α} lemma sup_inf_distrib_left (s : finset ι) (f : ι → α) (a : α) : a ⊓ s.sup f = s.sup (λ i, a ⊓ f i) := begin induction s using finset.cons_induction with i s hi h, { simp_rw [finset.sup_empty, inf_bot_eq] }, { rw [sup_cons, sup_cons, inf_sup_left, h] } end lemma sup_inf_distrib_right (s : finset ι) (f : ι → α) (a : α) : s.sup f ⊓ a = s.sup (λ i, f i ⊓ a) := by { rw [_root_.inf_comm, s.sup_inf_distrib_left], simp_rw _root_.inf_comm } protected lemma disjoint_sup_right : disjoint a (s.sup f) ↔ ∀ i ∈ s, disjoint a (f i) := by simp only [disjoint_iff, sup_inf_distrib_left, sup_eq_bot_iff] protected lemma disjoint_sup_left : disjoint (s.sup f) a ↔ ∀ i ∈ s, disjoint (f i) a := by simp only [disjoint_iff, sup_inf_distrib_right, sup_eq_bot_iff] end order_bot section order_top variables [order_top α] lemma inf_sup_distrib_left (s : finset ι) (f : ι → α) (a : α) : a ⊔ s.inf f = s.inf (λ i, a ⊔ f i) := @sup_inf_distrib_left αᵒᵈ _ _ _ _ _ _ lemma inf_sup_distrib_right (s : finset ι) (f : ι → α) (a : α) : s.inf f ⊔ a = s.inf (λ i, f i ⊔ a) := @sup_inf_distrib_right αᵒᵈ _ _ _ _ _ _ end order_top end distrib_lattice section linear_order variables [linear_order α] section order_bot variables [order_bot α] {s : finset ι} {f : ι → α} {a : α} lemma comp_sup_eq_sup_comp_of_is_total [semilattice_sup β] [order_bot β] (g : α → β) (mono_g : monotone g) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := comp_sup_eq_sup_comp g mono_g.map_sup bot @[simp] protected lemma le_sup_iff (ha : ⊥ < a) : a ≤ s.sup f ↔ ∃ b ∈ s, a ≤ f b := ⟨finset.cons_induction_on s (λ h, absurd h (not_le_of_lt ha)) (λ c t hc ih, by simpa using @or.rec _ _ (∃ b, (b = c ∨ b ∈ t) ∧ a ≤ f b) (λ h, ⟨c, or.inl rfl, h⟩) (λ h, let ⟨b, hb, hle⟩ := ih h in ⟨b, or.inr hb, hle⟩)), (λ ⟨b, hb, hle⟩, trans hle (le_sup hb))⟩ @[simp] protected lemma lt_sup_iff : a < s.sup f ↔ ∃ b ∈ s, a < f b := ⟨finset.cons_induction_on s (λ h, absurd h not_lt_bot) (λ c t hc ih, by simpa using @or.rec _ _ (∃ b, (b = c ∨ b ∈ t) ∧ a < f b) (λ h, ⟨c, or.inl rfl, h⟩) (λ h, let ⟨b, hb, hlt⟩ := ih h in ⟨b, or.inr hb, hlt⟩)), (λ ⟨b, hb, hlt⟩, lt_of_lt_of_le hlt (le_sup hb))⟩ @[simp] protected lemma sup_lt_iff (ha : ⊥ < a) : s.sup f < a ↔ ∀ b ∈ s, f b < a := ⟨(λ hs b hb, lt_of_le_of_lt (le_sup hb) hs), finset.cons_induction_on s (λ _, ha) (λ c t hc, by simpa only [sup_cons, sup_lt_iff, mem_cons, forall_eq_or_imp] using and.imp_right)⟩ end order_bot section order_top variables [order_top α] {s : finset ι} {f : ι → α} {a : α} lemma comp_inf_eq_inf_comp_of_is_total [semilattice_inf β] [order_top β] (g : α → β) (mono_g : monotone g) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := comp_inf_eq_inf_comp g mono_g.map_inf top @[simp] protected lemma inf_le_iff (ha : a < ⊤) : s.inf f ≤ a ↔ ∃ b ∈ s, f b ≤ a := @finset.le_sup_iff αᵒᵈ _ _ _ _ _ _ ha @[simp] protected lemma inf_lt_iff : s.inf f < a ↔ ∃ b ∈ s, f b < a := @finset.lt_sup_iff αᵒᵈ _ _ _ _ _ _ @[simp] protected lemma lt_inf_iff (ha : a < ⊤) : a < s.inf f ↔ ∀ b ∈ s, a < f b := @finset.sup_lt_iff αᵒᵈ _ _ _ _ _ _ ha end order_top end linear_order lemma inf_eq_infi [complete_lattice β] (s : finset α) (f : α → β) : s.inf f = ⨅ a ∈ s, f a := @sup_eq_supr _ βᵒᵈ _ _ _ lemma inf_id_eq_Inf [complete_lattice α] (s : finset α) : s.inf id = Inf s := @sup_id_eq_Sup αᵒᵈ _ _ lemma inf_id_set_eq_sInter (s : finset (set α)) : s.inf id = ⋂₀ ↑s := inf_id_eq_Inf _ @[simp] lemma inf_set_eq_bInter (s : finset α) (f : α → set β) : s.inf f = ⋂ x ∈ s, f x := inf_eq_infi _ _ lemma inf_eq_Inf_image [complete_lattice β] (s : finset α) (f : α → β) : s.inf f = Inf (f '' s) := @sup_eq_Sup_image _ βᵒᵈ _ _ _ section sup' variables [semilattice_sup α] lemma sup_of_mem {s : finset β} (f : β → α) {b : β} (h : b ∈ s) : ∃ (a : α), s.sup (coe ∘ f : β → with_bot α) = ↑a := Exists.imp (λ a, Exists.fst) (@le_sup (with_bot α) _ _ _ _ _ _ h (f b) rfl) /-- Given nonempty finset `s` then `s.sup' H f` is the supremum of its image under `f` in (possibly unbounded) join-semilattice `α`, where `H` is a proof of nonemptiness. If `α` has a bottom element you may instead use `finset.sup` which does not require `s` nonempty. -/ def sup' (s : finset β) (H : s.nonempty) (f : β → α) : α := with_bot.unbot (s.sup (coe ∘ f)) (by simpa using H) variables {s : finset β} (H : s.nonempty) (f : β → α) @[simp] lemma coe_sup' : ((s.sup' H f : α) : with_bot α) = s.sup (coe ∘ f) := by rw [sup', with_bot.coe_unbot] @[simp] lemma sup'_cons {b : β} {hb : b ∉ s} {h : (cons b s hb).nonempty} : (cons b s hb).sup' h f = f b ⊔ s.sup' H f := by { rw ←with_bot.coe_eq_coe, simp only [coe_sup', sup_cons, with_bot.coe_sup], } @[simp] lemma sup'_insert [decidable_eq β] {b : β} {h : (insert b s).nonempty} : (insert b s).sup' h f = f b ⊔ s.sup' H f := by { rw ←with_bot.coe_eq_coe, simp only [coe_sup', sup_insert, with_bot.coe_sup], } @[simp] lemma sup'_singleton {b : β} {h : ({b} : finset β).nonempty} : ({b} : finset β).sup' h f = f b := rfl lemma sup'_le {a : α} (hs : ∀ b ∈ s, f b ≤ a) : s.sup' H f ≤ a := by { rw [←with_bot.coe_le_coe, coe_sup'], exact finset.sup_le (λ b h, with_bot.coe_le_coe.2 $ hs b h) } lemma le_sup' {b : β} (h : b ∈ s) : f b ≤ s.sup' ⟨b, h⟩ f := by { rw [←with_bot.coe_le_coe, coe_sup'], exact le_sup h, } @[simp] lemma sup'_const (a : α) : s.sup' H (λ b, a) = a := begin apply le_antisymm, { apply sup'_le, intros, exact le_rfl, }, { apply le_sup' (λ b, a) H.some_spec, } end @[simp] lemma sup'_le_iff {a : α} : s.sup' H f ≤ a ↔ ∀ b ∈ s, f b ≤ a := iff.intro (λ h b hb, trans (le_sup' f hb) h) (sup'_le H f) lemma sup'_bUnion [decidable_eq β] {s : finset γ} (Hs : s.nonempty) {t : γ → finset β} (Ht : ∀ b, (t b).nonempty) : (s.bUnion t).sup' (Hs.bUnion (λ b _, Ht b)) f = s.sup' Hs (λ b, (t b).sup' (Ht b) f) := eq_of_forall_ge_iff $ λ c, by simp [@forall_swap _ β] lemma comp_sup'_eq_sup'_comp [semilattice_sup γ] {s : finset β} (H : s.nonempty) {f : β → α} (g : α → γ) (g_sup : ∀ x y, g (x ⊔ y) = g x ⊔ g y) : g (s.sup' H f) = s.sup' H (g ∘ f) := begin rw [←with_bot.coe_eq_coe, coe_sup'], let g' := with_bot.map g, show g' ↑(s.sup' H f) = s.sup (λ a, g' ↑(f a)), rw coe_sup', refine comp_sup_eq_sup_comp g' _ rfl, intros f₁ f₂, induction f₁ using with_bot.rec_bot_coe, { rw [bot_sup_eq], exact bot_sup_eq.symm, }, { induction f₂ using with_bot.rec_bot_coe, { refl }, { exact congr_arg coe (g_sup f₁ f₂) } } end lemma sup'_induction {p : α → Prop} (hp : ∀ a₁, p a₁ → ∀ a₂, p a₂ → p (a₁ ⊔ a₂)) (hs : ∀ b ∈ s, p (f b)) : p (s.sup' H f) := begin show @with_bot.rec_bot_coe α (λ _, Prop) true p ↑(s.sup' H f), rw coe_sup', refine sup_induction trivial _ hs, rintro (_|a₁) h₁ a₂ h₂, { rw [with_bot.none_eq_bot, bot_sup_eq], exact h₂ }, cases a₂, exacts [h₁, hp a₁ h₁ a₂ h₂] end lemma sup'_mem (s : set α) (w : ∀ x y ∈ s, x ⊔ y ∈ s) {ι : Type*} (t : finset ι) (H : t.nonempty) (p : ι → α) (h : ∀ i ∈ t, p i ∈ s) : t.sup' H p ∈ s := sup'_induction H p w h @[congr] lemma sup'_congr {t : finset β} {f g : β → α} (h₁ : s = t) (h₂ : ∀ x ∈ s, f x = g x) : s.sup' H f = t.sup' (h₁ ▸ H) g := begin subst s, refine eq_of_forall_ge_iff (λ c, _), simp only [sup'_le_iff, h₂] { contextual := tt } end @[simp] lemma sup'_map {s : finset γ} {f : γ ↪ β} (g : β → α) (hs : (s.map f).nonempty) (hs': s.nonempty := finset.map_nonempty.mp hs) : (s.map f).sup' hs g = s.sup' hs' (g ∘ f) := by rw [←with_bot.coe_eq_coe, coe_sup', sup_map, coe_sup'] end sup' section inf' variables [semilattice_inf α] lemma inf_of_mem {s : finset β} (f : β → α) {b : β} (h : b ∈ s) : ∃ (a : α), s.inf (coe ∘ f : β → with_top α) = ↑a := @sup_of_mem αᵒᵈ _ _ _ f _ h /-- Given nonempty finset `s` then `s.inf' H f` is the infimum of its image under `f` in (possibly unbounded) meet-semilattice `α`, where `H` is a proof of nonemptiness. If `α` has a top element you may instead use `finset.inf` which does not require `s` nonempty. -/ def inf' (s : finset β) (H : s.nonempty) (f : β → α) : α := with_top.untop (s.inf (coe ∘ f)) (by simpa using H) variables {s : finset β} (H : s.nonempty) (f : β → α) {a : α} {b : β} @[simp] lemma coe_inf' : ((s.inf' H f : α) : with_top α) = s.inf (coe ∘ f) := @coe_sup' αᵒᵈ _ _ _ H f @[simp] lemma inf'_cons {b : β} {hb : b ∉ s} {h : (cons b s hb).nonempty} : (cons b s hb).inf' h f = f b ⊓ s.inf' H f := @sup'_cons αᵒᵈ _ _ _ H f _ _ h @[simp] lemma inf'_insert [decidable_eq β] {b : β} {h : (insert b s).nonempty} : (insert b s).inf' h f = f b ⊓ s.inf' H f := @sup'_insert αᵒᵈ _ _ _ H f _ _ h @[simp] lemma inf'_singleton {b : β} {h : ({b} : finset β).nonempty} : ({b} : finset β).inf' h f = f b := rfl lemma le_inf' (hs : ∀ b ∈ s, a ≤ f b) : a ≤ s.inf' H f := @sup'_le αᵒᵈ _ _ _ H f _ hs lemma inf'_le (h : b ∈ s) : s.inf' ⟨b, h⟩ f ≤ f b := @le_sup' αᵒᵈ _ _ _ f _ h @[simp] lemma inf'_const (a : α) : s.inf' H (λ b, a) = a := @sup'_const αᵒᵈ _ _ _ H _ @[simp] lemma le_inf'_iff : a ≤ s.inf' H f ↔ ∀ b ∈ s, a ≤ f b := @sup'_le_iff αᵒᵈ _ _ _ H f _ lemma inf'_bUnion [decidable_eq β] {s : finset γ} (Hs : s.nonempty) {t : γ → finset β} (Ht : ∀ b, (t b).nonempty) : (s.bUnion t).inf' (Hs.bUnion (λ b _, Ht b)) f = s.inf' Hs (λ b, (t b).inf' (Ht b) f) := @sup'_bUnion αᵒᵈ _ _ _ _ _ _ Hs _ Ht lemma comp_inf'_eq_inf'_comp [semilattice_inf γ] {s : finset β} (H : s.nonempty) {f : β → α} (g : α → γ) (g_inf : ∀ x y, g (x ⊓ y) = g x ⊓ g y) : g (s.inf' H f) = s.inf' H (g ∘ f) := @comp_sup'_eq_sup'_comp αᵒᵈ _ γᵒᵈ _ _ _ H f g g_inf lemma inf'_induction {p : α → Prop} (hp : ∀ a₁, p a₁ → ∀ a₂, p a₂ → p (a₁ ⊓ a₂)) (hs : ∀ b ∈ s, p (f b)) : p (s.inf' H f) := @sup'_induction αᵒᵈ _ _ _ H f _ hp hs lemma inf'_mem (s : set α) (w : ∀ x y ∈ s, x ⊓ y ∈ s) {ι : Type*} (t : finset ι) (H : t.nonempty) (p : ι → α) (h : ∀ i ∈ t, p i ∈ s) : t.inf' H p ∈ s := inf'_induction H p w h @[congr] lemma inf'_congr {t : finset β} {f g : β → α} (h₁ : s = t) (h₂ : ∀ x ∈ s, f x = g x) : s.inf' H f = t.inf' (h₁ ▸ H) g := @sup'_congr αᵒᵈ _ _ _ H _ _ _ h₁ h₂ @[simp] lemma inf'_map {s : finset γ} {f : γ ↪ β} (g : β → α) (hs : (s.map f).nonempty) (hs': s.nonempty := finset.map_nonempty.mp hs) : (s.map f).inf' hs g = s.inf' hs' (g ∘ f) := @sup'_map αᵒᵈ _ _ _ _ _ _ hs hs' end inf' section sup variables [semilattice_sup α] [order_bot α] lemma sup'_eq_sup {s : finset β} (H : s.nonempty) (f : β → α) : s.sup' H f = s.sup f := le_antisymm (sup'_le H f (λ b, le_sup)) (finset.sup_le (λ b, le_sup' f)) lemma sup_closed_of_sup_closed {s : set α} (t : finset α) (htne : t.nonempty) (h_subset : ↑t ⊆ s) (h : ∀ a b ∈ s, a ⊔ b ∈ s) : t.sup id ∈ s := sup'_eq_sup htne id ▸ sup'_induction _ _ h h_subset lemma coe_sup_of_nonempty {s : finset β} (h : s.nonempty) (f : β → α) : (↑(s.sup f) : with_bot α) = s.sup (coe ∘ f) := by simp only [←sup'_eq_sup h, coe_sup' h] end sup section inf variables [semilattice_inf α] [order_top α] lemma inf'_eq_inf {s : finset β} (H : s.nonempty) (f : β → α) : s.inf' H f = s.inf f := @sup'_eq_sup αᵒᵈ _ _ _ _ H f lemma inf_closed_of_inf_closed {s : set α} (t : finset α) (htne : t.nonempty) (h_subset : ↑t ⊆ s) (h : ∀ a b ∈ s, a ⊓ b ∈ s) : t.inf id ∈ s := @sup_closed_of_sup_closed αᵒᵈ _ _ _ t htne h_subset h lemma coe_inf_of_nonempty {s : finset β} (h : s.nonempty) (f : β → α): (↑(s.inf f) : with_top α) = s.inf (λ i, f i) := @coe_sup_of_nonempty αᵒᵈ _ _ _ _ h f end inf section sup variables {C : β → Type*} [Π (b : β), semilattice_sup (C b)] [Π (b : β), order_bot (C b)] @[simp] protected lemma sup_apply (s : finset α) (f : α → Π (b : β), C b) (b : β) : s.sup f b = s.sup (λ a, f a b) := comp_sup_eq_sup_comp (λ x : Π b : β, C b, x b) (λ i j, rfl) rfl end sup section inf variables {C : β → Type*} [Π (b : β), semilattice_inf (C b)] [Π (b : β), order_top (C b)] @[simp] protected lemma inf_apply (s : finset α) (f : α → Π (b : β), C b) (b : β) : s.inf f b = s.inf (λ a, f a b) := @finset.sup_apply _ _ (λ b, (C b)ᵒᵈ) _ _ s f b end inf section sup' variables {C : β → Type*} [Π (b : β), semilattice_sup (C b)] @[simp] protected lemma sup'_apply {s : finset α} (H : s.nonempty) (f : α → Π (b : β), C b) (b : β) : s.sup' H f b = s.sup' H (λ a, f a b) := comp_sup'_eq_sup'_comp H (λ x : Π b : β, C b, x b) (λ i j, rfl) end sup' section inf' variables {C : β → Type*} [Π (b : β), semilattice_inf (C b)] @[simp] protected lemma inf'_apply {s : finset α} (H : s.nonempty) (f : α → Π (b : β), C b) (b : β) : s.inf' H f b = s.inf' H (λ a, f a b) := @finset.sup'_apply _ _ (λ b, (C b)ᵒᵈ) _ _ H f b end inf' @[simp] lemma to_dual_sup' [semilattice_sup α] {s : finset ι} (hs : s.nonempty) (f : ι → α) : to_dual (s.sup' hs f) = s.inf' hs (to_dual ∘ f) := rfl @[simp] lemma to_dual_inf' [semilattice_inf α] {s : finset ι} (hs : s.nonempty) (f : ι → α) : to_dual (s.inf' hs f) = s.sup' hs (to_dual ∘ f) := rfl @[simp] lemma of_dual_sup' [semilattice_inf α] {s : finset ι} (hs : s.nonempty) (f : ι → αᵒᵈ) : of_dual (s.sup' hs f) = s.inf' hs (of_dual ∘ f) := rfl @[simp] lemma of_dual_inf' [semilattice_sup α] {s : finset ι} (hs : s.nonempty) (f : ι → αᵒᵈ) : of_dual (s.inf' hs f) = s.sup' hs (of_dual ∘ f) := rfl section linear_order variables [linear_order α] {s : finset ι} (H : s.nonempty) {f : ι → α} {a : α} @[simp] lemma le_sup'_iff : a ≤ s.sup' H f ↔ ∃ b ∈ s, a ≤ f b := begin rw [←with_bot.coe_le_coe, coe_sup', finset.le_sup_iff (with_bot.bot_lt_coe a)], exact bex_congr (λ b hb, with_bot.coe_le_coe), end @[simp] lemma lt_sup'_iff : a < s.sup' H f ↔ ∃ b ∈ s, a < f b := begin rw [←with_bot.coe_lt_coe, coe_sup', finset.lt_sup_iff], exact bex_congr (λ b hb, with_bot.coe_lt_coe), end @[simp] lemma sup'_lt_iff : s.sup' H f < a ↔ ∀ i ∈ s, f i < a := begin rw [←with_bot.coe_lt_coe, coe_sup', finset.sup_lt_iff (with_bot.bot_lt_coe a)], exact ball_congr (λ b hb, with_bot.coe_lt_coe), end @[simp] lemma inf'_le_iff : s.inf' H f ≤ a ↔ ∃ i ∈ s, f i ≤ a := @le_sup'_iff αᵒᵈ _ _ _ H f _ @[simp] lemma inf'_lt_iff : s.inf' H f < a ↔ ∃ i ∈ s, f i < a := @lt_sup'_iff αᵒᵈ _ _ _ H f _ @[simp] lemma lt_inf'_iff : a < s.inf' H f ↔ ∀ i ∈ s, a < f i := @sup'_lt_iff αᵒᵈ _ _ _ H f _ lemma exists_mem_eq_sup' (f : ι → α) : ∃ i, i ∈ s ∧ s.sup' H f = f i := begin refine H.cons_induction (λ c, _) (λ c s hc hs ih, _), { exact ⟨c, mem_singleton_self c, rfl⟩, }, { rcases ih with ⟨b, hb, h'⟩, rw [sup'_cons hs, h'], cases total_of (≤) (f b) (f c) with h h, { exact ⟨c, mem_cons.2 (or.inl rfl), sup_eq_left.2 h⟩, }, { exact ⟨b, mem_cons.2 (or.inr hb), sup_eq_right.2 h⟩, }, }, end lemma exists_mem_eq_inf' (f : ι → α) : ∃ i, i ∈ s ∧ s.inf' H f = f i := @exists_mem_eq_sup' αᵒᵈ _ _ _ H f lemma exists_mem_eq_sup [order_bot α] (s : finset ι) (h : s.nonempty) (f : ι → α) : ∃ i, i ∈ s ∧ s.sup f = f i := sup'_eq_sup h f ▸ exists_mem_eq_sup' h f lemma exists_mem_eq_inf [order_top α] (s : finset ι) (h : s.nonempty) (f : ι → α) : ∃ i, i ∈ s ∧ s.inf f = f i := @exists_mem_eq_sup αᵒᵈ _ _ _ _ h f end linear_order /-! ### max and min of finite sets -/ section max_min variables [linear_order α] /-- Let `s` be a finset in a linear order. Then `s.max` is the maximum of `s` if `s` is not empty, and `⊥` otherwise. It belongs to `with_bot α`. If you want to get an element of `α`, see `s.max'`. -/ protected def max (s : finset α) : with_bot α := sup s coe lemma max_eq_sup_coe {s : finset α} : s.max = s.sup coe := rfl theorem max_eq_sup_with_bot (s : finset α) : s.max = sup s coe := rfl @[simp] theorem max_empty : (∅ : finset α).max = ⊥ := rfl @[simp] theorem max_insert {a : α} {s : finset α} : (insert a s).max = max a s.max := fold_insert_idem @[simp] theorem max_singleton {a : α} : finset.max {a} = (a : with_bot α) := by { rw [← insert_emptyc_eq], exact max_insert } theorem max_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ (b : α), s.max = b := (@le_sup (with_bot α) _ _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem max_of_nonempty {s : finset α} (h : s.nonempty) : ∃ (a : α), s.max = a := let ⟨a, ha⟩ := h in max_of_mem ha theorem max_eq_bot {s : finset α} : s.max = ⊥ ↔ s = ∅ := ⟨λ h, s.eq_empty_or_nonempty.elim id (λ H, let ⟨a, ha⟩ := max_of_nonempty H in by rw h at ha; cases ha), λ h, h.symm ▸ max_empty⟩ theorem mem_of_max {s : finset α} : ∀ {a : α}, s.max = a → a ∈ s := finset.induction_on s (λ _ H, by cases H) (λ b s _ (ih : ∀ {a : α}, s.max = a → a ∈ s) a (h : (insert b s).max = a), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases max_choice ↑b s.max with q q; rw [max_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end) lemma le_max {a : α} {s : finset α} (as : a ∈ s) : ↑a ≤ s.max := le_sup as lemma not_mem_of_max_lt_coe {a : α} {s : finset α} (h : s.max < a) : a ∉ s := mt le_max h.not_le theorem le_max_of_eq {s : finset α} {a b : α} (h₁ : a ∈ s) (h₂ : s.max = b) : a ≤ b := with_bot.coe_le_coe.mp $ (le_max h₁).trans h₂.le theorem not_mem_of_max_lt {s : finset α} {a b : α} (h₁ : b < a) (h₂ : s.max = ↑b) : a ∉ s := finset.not_mem_of_max_lt_coe $ h₂.trans_lt $ with_bot.coe_lt_coe.mpr h₁ lemma max_mono {s t : finset α} (st : s ⊆ t) : s.max ≤ t.max := sup_mono st protected lemma max_le {M : with_bot α} {s : finset α} (st : ∀ a ∈ s, (a : with_bot α) ≤ M) : s.max ≤ M := finset.sup_le st /-- Let `s` be a finset in a linear order. Then `s.min` is the minimum of `s` if `s` is not empty, and `⊤` otherwise. It belongs to `with_top α`. If you want to get an element of `α`, see `s.min'`. -/ protected def min (s : finset α) : with_top α := inf s coe theorem min_eq_inf_with_top (s : finset α) : s.min = inf s coe := rfl @[simp] theorem min_empty : (∅ : finset α).min = ⊤ := rfl @[simp] theorem min_insert {a : α} {s : finset α} : (insert a s).min = min ↑a s.min := fold_insert_idem @[simp] theorem min_singleton {a : α} : finset.min {a} = (a : with_top α) := by { rw ← insert_emptyc_eq, exact min_insert } theorem min_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b : α, s.min = b := (@inf_le (with_top α) _ _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem min_of_nonempty {s : finset α} (h : s.nonempty) : ∃ a : α, s.min = a := let ⟨a, ha⟩ := h in min_of_mem ha theorem min_eq_top {s : finset α} : s.min = ⊤ ↔ s = ∅ := ⟨λ h, s.eq_empty_or_nonempty.elim id (λ H, let ⟨a, ha⟩ := min_of_nonempty H in by rw h at ha; cases ha), λ h, h.symm ▸ min_empty⟩ theorem mem_of_min {s : finset α} : ∀ {a : α}, s.min = a → a ∈ s := @mem_of_max αᵒᵈ _ s lemma min_le {a : α} {s : finset α} (as : a ∈ s) : s.min ≤ a := inf_le as lemma not_mem_of_coe_lt_min {a : α} {s : finset α} (h : ↑a < s.min) : a ∉ s := mt min_le h.not_le theorem min_le_of_eq {s : finset α} {a b : α} (h₁ : b ∈ s) (h₂ : s.min = a) : a ≤ b := with_top.coe_le_coe.mp $ h₂.ge.trans (min_le h₁) theorem not_mem_of_lt_min {s : finset α} {a b : α} (h₁ : a < b) (h₂ : s.min = ↑b) : a ∉ s := finset.not_mem_of_coe_lt_min $ (with_top.coe_lt_coe.mpr h₁).trans_eq h₂.symm lemma min_mono {s t : finset α} (st : s ⊆ t) : t.min ≤ s.min := inf_mono st protected lemma le_min {m : with_top α} {s : finset α} (st : ∀ a : α, a ∈ s → m ≤ a) : m ≤ s.min := finset.le_inf st /-- Given a nonempty finset `s` in a linear order `α`, then `s.min' h` is its minimum, as an element of `α`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.min`, taking values in `with_top α`. -/ def min' (s : finset α) (H : s.nonempty) : α := inf' s H id /-- Given a nonempty finset `s` in a linear order `α`, then `s.max' h` is its maximum, as an element of `α`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.max`, taking values in `with_bot α`. -/ def max' (s : finset α) (H : s.nonempty) : α := sup' s H id variables (s : finset α) (H : s.nonempty) {x : α} theorem min'_mem : s.min' H ∈ s := mem_of_min $ by simp [min', finset.min] theorem min'_le (x) (H2 : x ∈ s) : s.min' ⟨x, H2⟩ ≤ x := min_le_of_eq H2 (with_top.coe_untop _ _).symm theorem le_min' (x) (H2 : ∀ y ∈ s, x ≤ y) : x ≤ s.min' H := H2 _ $ min'_mem _ _ theorem is_least_min' : is_least ↑s (s.min' H) := ⟨min'_mem _ _, min'_le _⟩ @[simp] lemma le_min'_iff {x} : x ≤ s.min' H ↔ ∀ y ∈ s, x ≤ y := le_is_glb_iff (is_least_min' s H).is_glb /-- `{a}.min' _` is `a`. -/ @[simp] lemma min'_singleton (a : α) : ({a} : finset α).min' (singleton_nonempty _) = a := by simp [min'] theorem max'_mem : s.max' H ∈ s := mem_of_max $ by simp [max', finset.max] theorem le_max' (x) (H2 : x ∈ s) : x ≤ s.max' ⟨x, H2⟩ := le_max_of_eq H2 (with_bot.coe_unbot _ _).symm theorem max'_le (x) (H2 : ∀ y ∈ s, y ≤ x) : s.max' H ≤ x := H2 _ $ max'_mem _ _ theorem is_greatest_max' : is_greatest ↑s (s.max' H) := ⟨max'_mem _ _, le_max' _⟩ @[simp] lemma max'_le_iff {x} : s.max' H ≤ x ↔ ∀ y ∈ s, y ≤ x := is_lub_le_iff (is_greatest_max' s H).is_lub @[simp] lemma max'_lt_iff {x} : s.max' H < x ↔ ∀ y ∈ s, y < x := ⟨λ Hlt y hy, (s.le_max' y hy).trans_lt Hlt, λ H, H _ $ s.max'_mem _⟩ @[simp] lemma lt_min'_iff : x < s.min' H ↔ ∀ y ∈ s, x < y := @max'_lt_iff αᵒᵈ _ _ H _ lemma max'_eq_sup' : s.max' H = s.sup' H id := eq_of_forall_ge_iff $ λ a, (max'_le_iff _ _).trans (sup'_le_iff _ _).symm lemma min'_eq_inf' : s.min' H = s.inf' H id := @max'_eq_sup' αᵒᵈ _ s H /-- `{a}.max' _` is `a`. -/ @[simp] lemma max'_singleton (a : α) : ({a} : finset α).max' (singleton_nonempty _) = a := by simp [max'] theorem min'_lt_max' {i j} (H1 : i ∈ s) (H2 : j ∈ s) (H3 : i ≠ j) : s.min' ⟨i, H1⟩ < s.max' ⟨i, H1⟩ := is_glb_lt_is_lub_of_ne (s.is_least_min' _).is_glb (s.is_greatest_max' _).is_lub H1 H2 H3 /-- If there's more than 1 element, the min' is less than the max'. An alternate version of `min'_lt_max'` which is sometimes more convenient. -/ lemma min'_lt_max'_of_card (h₂ : 1 < card s) : s.min' (finset.card_pos.mp $ lt_trans zero_lt_one h₂) < s.max' (finset.card_pos.mp $ lt_trans zero_lt_one h₂) := begin rcases one_lt_card.1 h₂ with ⟨a, ha, b, hb, hab⟩, exact s.min'_lt_max' ha hb hab end lemma map_of_dual_min (s : finset αᵒᵈ) : s.min.map of_dual = (s.image of_dual).max := by { rw [max_eq_sup_with_bot, sup_image], exact congr_fun option.map_id _ } lemma map_of_dual_max (s : finset αᵒᵈ) : s.max.map of_dual = (s.image of_dual).min := by { rw [min_eq_inf_with_top, inf_image], exact congr_fun option.map_id _ } lemma map_to_dual_min (s : finset α) : s.min.map to_dual = (s.image to_dual).max := by { rw [max_eq_sup_with_bot, sup_image], exact congr_fun option.map_id _ } lemma map_to_dual_max (s : finset α) : s.max.map to_dual = (s.image to_dual).min := by { rw [min_eq_inf_with_top, inf_image], exact congr_fun option.map_id _ } lemma of_dual_min' {s : finset αᵒᵈ} (hs : s.nonempty) : of_dual (min' s hs) = max' (s.image of_dual) (hs.image _) := by { convert rfl, exact image_id } lemma of_dual_max' {s : finset αᵒᵈ} (hs : s.nonempty) : of_dual (max' s hs) = min' (s.image of_dual) (hs.image _) := by { convert rfl, exact image_id } lemma to_dual_min' {s : finset α} (hs : s.nonempty) : to_dual (min' s hs) = max' (s.image to_dual) (hs.image _) := by { convert rfl, exact image_id } lemma to_dual_max' {s : finset α} (hs : s.nonempty) : to_dual (max' s hs) = min' (s.image to_dual) (hs.image _) := by { convert rfl, exact image_id } lemma max'_subset {s t : finset α} (H : s.nonempty) (hst : s ⊆ t) : s.max' H ≤ t.max' (H.mono hst) := le_max' _ _ (hst (s.max'_mem H)) lemma min'_subset {s t : finset α} (H : s.nonempty) (hst : s ⊆ t) : t.min' (H.mono hst) ≤ s.min' H := min'_le _ _ (hst (s.min'_mem H)) lemma max'_insert (a : α) (s : finset α) (H : s.nonempty) : (insert a s).max' (s.insert_nonempty a) = max (s.max' H) a := (is_greatest_max' _ _).unique $ by { rw [coe_insert, max_comm], exact (is_greatest_max' _ _).insert _ } lemma min'_insert (a : α) (s : finset α) (H : s.nonempty) : (insert a s).min' (s.insert_nonempty a) = min (s.min' H) a := (is_least_min' _ _).unique $ by { rw [coe_insert, min_comm], exact (is_least_min' _ _).insert _ } lemma lt_max'_of_mem_erase_max' [decidable_eq α] {a : α} (ha : a ∈ s.erase (s.max' H)) : a < s.max' H := lt_of_le_of_ne (le_max' _ _ (mem_of_mem_erase ha)) $ ne_of_mem_of_not_mem ha $ not_mem_erase _ _ lemma min'_lt_of_mem_erase_min' [decidable_eq α] {a : α} (ha : a ∈ s.erase (s.min' H)) : s.min' H < a := @lt_max'_of_mem_erase_max' αᵒᵈ _ s H _ a ha @[simp] lemma max'_image [linear_order β] {f : α → β} (hf : monotone f) (s : finset α) (h : (s.image f).nonempty) : (s.image f).max' h = f (s.max' ((nonempty.image_iff f).mp h)) := begin refine le_antisymm (max'_le _ _ _ (λ y hy, _)) (le_max' _ _ (mem_image.mpr ⟨_, max'_mem _ _, rfl⟩)), obtain ⟨x, hx, rfl⟩ := mem_image.mp hy, exact hf (le_max' _ _ hx) end @[simp] lemma min'_image [linear_order β] {f : α → β} (hf : monotone f) (s : finset α) (h : (s.image f).nonempty) : (s.image f).min' h = f (s.min' ((nonempty.image_iff f).mp h)) := begin convert @max'_image αᵒᵈ βᵒᵈ _ _ (λ a : αᵒᵈ, to_dual (f (of_dual a))) (by simpa) _ _; convert h, rw nonempty.image_iff, end lemma coe_max' {s : finset α} (hs : s.nonempty) : ↑(s.max' hs) = s.max := coe_sup' hs id lemma coe_min' {s : finset α} (hs : s.nonempty) : ↑(s.min' hs) = s.min := coe_inf' hs id lemma max_mem_image_coe {s : finset α} (hs : s.nonempty) : s.max ∈ (s.image coe : finset (with_bot α)) := mem_image.2 ⟨max' s hs, max'_mem _ _, coe_max' hs⟩ lemma min_mem_image_coe {s : finset α} (hs : s.nonempty) : s.min ∈ (s.image coe : finset (with_top α)) := mem_image.2 ⟨min' s hs, min'_mem _ _, coe_min' hs⟩ lemma max_mem_insert_bot_image_coe (s : finset α) : s.max ∈ (insert ⊥ (s.image coe) : finset (with_bot α)) := mem_insert.2 $ s.eq_empty_or_nonempty.imp max_eq_bot.2 max_mem_image_coe lemma min_mem_insert_top_image_coe (s : finset α) : s.min ∈ (insert ⊤ (s.image coe) : finset (with_top α)) := mem_insert.2 $ s.eq_empty_or_nonempty.imp min_eq_top.2 min_mem_image_coe lemma max'_erase_ne_self {s : finset α} (s0 : (s.erase x).nonempty) : (s.erase x).max' s0 ≠ x := ne_of_mem_erase (max'_mem _ s0) lemma min'_erase_ne_self {s : finset α} (s0 : (s.erase x).nonempty) : (s.erase x).min' s0 ≠ x := ne_of_mem_erase (min'_mem _ s0) lemma max_erase_ne_self {s : finset α} : (s.erase x).max ≠ x := begin by_cases s0 : (s.erase x).nonempty, { refine ne_of_eq_of_ne (coe_max' s0).symm _, exact with_bot.coe_eq_coe.not.mpr (max'_erase_ne_self _) }, { rw [not_nonempty_iff_eq_empty.mp s0, max_empty], exact with_bot.bot_ne_coe } end lemma min_erase_ne_self {s : finset α} : (s.erase x).min ≠ x := by convert @max_erase_ne_self αᵒᵈ _ _ _ lemma exists_next_right {x : α} {s : finset α} (h : ∃ y ∈ s, x < y) : ∃ y ∈ s, x < y ∧ ∀ z ∈ s, x < z → y ≤ z := have Hne : (s.filter ((<) x)).nonempty := h.imp $ λ y hy, mem_filter.2 ⟨hy.fst, hy.snd⟩, ⟨min' _ Hne, (mem_filter.1 (min'_mem _ Hne)).1, (mem_filter.1 (min'_mem _ Hne)).2, λ z hzs hz, min'_le _ _ $ mem_filter.2 ⟨hzs, hz⟩⟩ lemma exists_next_left {x : α} {s : finset α} (h : ∃ y ∈ s, y < x) : ∃ y ∈ s, y < x ∧ ∀ z ∈ s, z < x → z ≤ y := @exists_next_right αᵒᵈ _ x s h /-- If finsets `s` and `t` are interleaved, then `finset.card s ≤ finset.card t + 1`. -/ lemma card_le_of_interleaved {s t : finset α} (h : ∀ x y ∈ s, x < y → (∀ z ∈ s, z ∉ set.Ioo x y) → ∃ z ∈ t, x < z ∧ z < y) : s.card ≤ t.card + 1 := begin replace h : ∀ x y ∈ s, x < y → ∃ z ∈ t, x < z ∧ z < y, { intros x hx y hy hxy, rcases exists_next_right ⟨y, hy, hxy⟩ with ⟨a, has, hxa, ha⟩, rcases h x hx a has hxa (λ z hzs hz, hz.2.not_le $ ha _ hzs hz.1) with ⟨b, hbt, hxb, hba⟩, exact ⟨b, hbt, hxb, hba.trans_le $ ha _ hy hxy⟩ }, set f : α → with_top α := λ x, (t.filter (λ y, x < y)).min, have f_mono : strict_mono_on f s, { intros x hx y hy hxy, rcases h x hx y hy hxy with ⟨a, hat, hxa, hay⟩, calc f x ≤ a : min_le (mem_filter.2 ⟨hat, hxa⟩) ... < f y : (finset.lt_inf_iff $ with_top.coe_lt_top a).2 $ λ b hb, with_top.coe_lt_coe.2 $ hay.trans (mem_filter.1 hb).2 }, calc s.card = (s.image f).card : (card_image_of_inj_on f_mono.inj_on).symm ... ≤ (insert ⊤ (t.image coe) : finset (with_top α)).card : card_mono $ image_subset_iff.2 $ λ x hx, insert_subset_insert _ (image_subset_image $ filter_subset _ _) (min_mem_insert_top_image_coe _) ... ≤ t.card + 1 : (card_insert_le _ _).trans (add_le_add_right card_image_le _) end /-- If finsets `s` and `t` are interleaved, then `finset.card s ≤ finset.card (t \ s) + 1`. -/ lemma card_le_diff_of_interleaved {s t : finset α} (h : ∀ x y ∈ s, x < y → (∀ z ∈ s, z ∉ set.Ioo x y) → ∃ z ∈ t, x < z ∧ z < y) : s.card ≤ (t \ s).card + 1 := card_le_of_interleaved $ λ x hx y hy hxy hs, let ⟨z, hzt, hxz, hzy⟩ := h x hx y hy hxy hs in ⟨z, mem_sdiff.2 ⟨hzt, λ hzs, hs z hzs ⟨hxz, hzy⟩⟩, hxz, hzy⟩ /-- Induction principle for `finset`s in a linearly ordered type: a predicate is true on all `s : finset α` provided that: * it is true on the empty `finset`, * for every `s : finset α` and an element `a` strictly greater than all elements of `s`, `p s` implies `p (insert a s)`. -/ @[elab_as_eliminator] lemma induction_on_max [decidable_eq α] {p : finset α → Prop} (s : finset α) (h0 : p ∅) (step : ∀ a s, (∀ x ∈ s, x < a) → p s → p (insert a s)) : p s := begin induction s using finset.strong_induction_on with s ihs, rcases s.eq_empty_or_nonempty with rfl|hne, { exact h0 }, { have H : s.max' hne ∈ s, from max'_mem s hne, rw ← insert_erase H, exact step _ _ (λ x, s.lt_max'_of_mem_erase_max' hne) (ihs _ $ erase_ssubset H) } end /-- Induction principle for `finset`s in a linearly ordered type: a predicate is true on all `s : finset α` provided that: * it is true on the empty `finset`, * for every `s : finset α` and an element `a` strictly less than all elements of `s`, `p s` implies `p (insert a s)`. -/ @[elab_as_eliminator] lemma induction_on_min [decidable_eq α] {p : finset α → Prop} (s : finset α) (h0 : p ∅) (step : ∀ a s, (∀ x ∈ s, a < x) → p s → p (insert a s)) : p s := @induction_on_max αᵒᵈ _ _ _ s h0 step end max_min section max_min_induction_value variables [linear_order α] [linear_order β] /-- Induction principle for `finset`s in any type from which a given function `f` maps to a linearly ordered type : a predicate is true on all `s : finset α` provided that: * it is true on the empty `finset`, * for every `s : finset α` and an element `a` such that for elements of `s` denoted by `x` we have `f x ≤ f a`, `p s` implies `p (insert a s)`. -/ @[elab_as_eliminator] lemma induction_on_max_value [decidable_eq ι] (f : ι → α) {p : finset ι → Prop} (s : finset ι) (h0 : p ∅) (step : ∀ a s, a ∉ s → (∀ x ∈ s, f x ≤ f a) → p s → p (insert a s)) : p s := begin induction s using finset.strong_induction_on with s ihs, rcases (s.image f).eq_empty_or_nonempty with hne|hne, { simp only [image_eq_empty] at hne, simp only [hne, h0] }, { have H : (s.image f).max' hne ∈ (s.image f), from max'_mem (s.image f) hne, simp only [mem_image, exists_prop] at H, rcases H with ⟨a, has, hfa⟩, rw ← insert_erase has, refine step _ _ (not_mem_erase a s) (λ x hx, _) (ihs _ $ erase_ssubset has), rw hfa, exact le_max' _ _ (mem_image_of_mem _ $ mem_of_mem_erase hx) } end /-- Induction principle for `finset`s in any type from which a given function `f` maps to a linearly ordered type : a predicate is true on all `s : finset α` provided that: * it is true on the empty `finset`, * for every `s : finset α` and an element `a` such that for elements of `s` denoted by `x` we have `f a ≤ f x`, `p s` implies `p (insert a s)`. -/ @[elab_as_eliminator] lemma induction_on_min_value [decidable_eq ι] (f : ι → α) {p : finset ι → Prop} (s : finset ι) (h0 : p ∅) (step : ∀ a s, a ∉ s → (∀ x ∈ s, f a ≤ f x) → p s → p (insert a s)) : p s := @induction_on_max_value αᵒᵈ ι _ _ _ _ s h0 step end max_min_induction_value section exists_max_min variables [linear_order α] lemma exists_max_image (s : finset β) (f : β → α) (h : s.nonempty) : ∃ x ∈ s, ∀ x' ∈ s, f x' ≤ f x := begin cases max_of_nonempty (h.image f) with y hy, rcases mem_image.mp (mem_of_max hy) with ⟨x, hx, rfl⟩, exact ⟨x, hx, λ x' hx', le_max_of_eq (mem_image_of_mem f hx') hy⟩, end lemma exists_min_image (s : finset β) (f : β → α) (h : s.nonempty) : ∃ x ∈ s, ∀ x' ∈ s, f x ≤ f x' := @exists_max_image αᵒᵈ β _ s f h end exists_max_min lemma is_glb_iff_is_least [linear_order α] (i : α) (s : finset α) (hs : s.nonempty) : is_glb (s : set α) i ↔ is_least ↑s i := begin refine ⟨λ his, _, is_least.is_glb⟩, suffices : i = min' s hs, { rw this, exact is_least_min' s hs, }, rw [is_glb, is_greatest, mem_lower_bounds, mem_upper_bounds] at his, exact le_antisymm (his.1 (finset.min' s hs) (finset.min'_mem s hs)) (his.2 _ (finset.min'_le s)), end lemma is_glb_mem [linear_order α] {i : α} (s : finset α) (his : is_glb (s : set α) i) (hs : s.nonempty) : i ∈ s := by { rw ← mem_coe, exact ((is_glb_iff_is_least i s hs).mp his).1, } lemma is_lub_mem [linear_order α] {i : α} (s : finset α) (his : is_lub (s : set α) i) (hs : s.nonempty) : i ∈ s := @is_glb_mem αᵒᵈ _ i s his hs end finset namespace multiset lemma map_finset_sup [decidable_eq α] [decidable_eq β] (s : finset γ) (f : γ → multiset β) (g : β → α) (hg : function.injective g) : map g (s.sup f) = s.sup (map g ∘ f) := finset.comp_sup_eq_sup_comp _ (λ _ _, map_union hg) (map_zero _) lemma count_finset_sup [decidable_eq β] (s : finset α) (f : α → multiset β) (b : β) : count b (s.sup f) = s.sup (λa, count b (f a)) := begin letI := classical.dec_eq α, refine s.induction _ _, { exact count_zero _ }, { assume i s his ih, rw [finset.sup_insert, sup_eq_union, count_union, finset.sup_insert, ih], refl } end lemma mem_sup {α β} [decidable_eq β] {s : finset α} {f : α → multiset β} {x : β} : x ∈ s.sup f ↔ ∃ v ∈ s, x ∈ f v := begin classical, apply s.induction_on, { simp }, { intros a s has hxs, rw [finset.sup_insert, multiset.sup_eq_union, multiset.mem_union], split, { intro hxi, cases hxi with hf hf, { refine ⟨a, _, hf⟩, simp only [true_or, eq_self_iff_true, finset.mem_insert] }, { rcases hxs.mp hf with ⟨v, hv, hfv⟩, refine ⟨v, _, hfv⟩, simp only [hv, or_true, finset.mem_insert] } }, { rintros ⟨v, hv, hfv⟩, rw [finset.mem_insert] at hv, rcases hv with rfl | hv, { exact or.inl hfv }, { refine or.inr (hxs.mpr ⟨v, hv, hfv⟩) } } }, end end multiset namespace finset lemma mem_sup {α β} [decidable_eq β] {s : finset α} {f : α → finset β} {x : β} : x ∈ s.sup f ↔ ∃ v ∈ s, x ∈ f v := begin change _ ↔ ∃ v ∈ s, x ∈ (f v).val, rw [←multiset.mem_sup, ←multiset.mem_to_finset, sup_to_finset], simp_rw [val_to_finset], end lemma sup_eq_bUnion {α β} [decidable_eq β] (s : finset α) (t : α → finset β) : s.sup t = s.bUnion t := by { ext, rw [mem_sup, mem_bUnion], } @[simp] lemma sup_singleton'' [decidable_eq α] (s : finset β) (f : β → α) : s.sup (λ b, {f b}) = s.image f := by { ext a, rw [mem_sup, mem_image], simp only [mem_singleton, eq_comm] } @[simp] lemma sup_singleton' [decidable_eq α] (s : finset α) : s.sup singleton = s := (s.sup_singleton'' _).trans image_id end finset section lattice variables {ι' : Sort*} [complete_lattice α] /-- Supremum of `s i`, `i : ι`, is equal to the supremum over `t : finset ι` of suprema `⨆ i ∈ t, s i`. This version assumes `ι` is a `Type*`. See `supr_eq_supr_finset'` for a version that works for `ι : Sort*`. -/ lemma supr_eq_supr_finset (s : ι → α) : (⨆ i, s i) = (⨆ t : finset ι, ⨆ i ∈ t, s i) := begin classical, exact le_antisymm (supr_le $ assume b, le_supr_of_le {b} $ le_supr_of_le b $ le_supr_of_le (by simp) $ le_rfl) (supr_le $ assume t, supr_le $ assume b, supr_le $ assume hb, le_supr _ _) end /-- Supremum of `s i`, `i : ι`, is equal to the supremum over `t : finset ι` of suprema `⨆ i ∈ t, s i`. This version works for `ι : Sort*`. See `supr_eq_supr_finset` for a version that assumes `ι : Type*` but has no `plift`s. -/ lemma supr_eq_supr_finset' (s : ι' → α) : (⨆ i, s i) = (⨆ t : finset (plift ι'), ⨆ i ∈ t, s (plift.down i)) := by rw [← supr_eq_supr_finset, ← equiv.plift.surjective.supr_comp]; refl /-- Infimum of `s i`, `i : ι`, is equal to the infimum over `t : finset ι` of infima `⨅ i ∈ t, s i`. This version assumes `ι` is a `Type*`. See `infi_eq_infi_finset'` for a version that works for `ι : Sort*`. -/ lemma infi_eq_infi_finset (s : ι → α) : (⨅ i, s i) = ⨅ (t : finset ι) (i ∈ t), s i := @supr_eq_supr_finset αᵒᵈ _ _ _ /-- Infimum of `s i`, `i : ι`, is equal to the infimum over `t : finset ι` of infima `⨅ i ∈ t, s i`. This version works for `ι : Sort*`. See `infi_eq_infi_finset` for a version that assumes `ι : Type*` but has no `plift`s. -/ lemma infi_eq_infi_finset' (s : ι' → α) : (⨅ i, s i) = (⨅ t : finset (plift ι'), ⨅ i ∈ t, s (plift.down i)) := @supr_eq_supr_finset' αᵒᵈ _ _ _ end lattice namespace set variables {ι' : Sort*} /-- Union of an indexed family of sets `s : ι → set α` is equal to the union of the unions of finite subfamilies. This version assumes `ι : Type*`. See also `Union_eq_Union_finset'` for a version that works for `ι : Sort*`. -/ lemma Union_eq_Union_finset (s : ι → set α) : (⋃ i, s i) = (⋃ t : finset ι, ⋃ i ∈ t, s i) := supr_eq_supr_finset s /-- Union of an indexed family of sets `s : ι → set α` is equal to the union of the unions of finite subfamilies. This version works for `ι : Sort*`. See also `Union_eq_Union_finset` for a version that assumes `ι : Type*` but avoids `plift`s in the right hand side. -/ lemma Union_eq_Union_finset' (s : ι' → set α) : (⋃ i, s i) = (⋃ t : finset (plift ι'), ⋃ i ∈ t, s (plift.down i)) := supr_eq_supr_finset' s /-- Intersection of an indexed family of sets `s : ι → set α` is equal to the intersection of the intersections of finite subfamilies. This version assumes `ι : Type*`. See also `Inter_eq_Inter_finset'` for a version that works for `ι : Sort*`. -/ lemma Inter_eq_Inter_finset (s : ι → set α) : (⋂ i, s i) = (⋂ t : finset ι, ⋂ i ∈ t, s i) := infi_eq_infi_finset s /-- Intersection of an indexed family of sets `s : ι → set α` is equal to the intersection of the intersections of finite subfamilies. This version works for `ι : Sort*`. See also `Inter_eq_Inter_finset` for a version that assumes `ι : Type*` but avoids `plift`s in the right hand side. -/ lemma Inter_eq_Inter_finset' (s : ι' → set α) : (⋂ i, s i) = (⋂ t : finset (plift ι'), ⋂ i ∈ t, s (plift.down i)) := infi_eq_infi_finset' s end set namespace finset /-! ### Interaction with ordered algebra structures -/ lemma sup_mul_le_mul_sup_of_nonneg [linear_ordered_semiring α] [order_bot α] {a b : ι → α} (s : finset ι) (ha : ∀ i ∈ s, 0 ≤ a i) (hb : ∀ i ∈ s, 0 ≤ b i) : s.sup (a * b) ≤ s.sup a * s.sup b := finset.sup_le $ λ i hi, mul_le_mul (le_sup hi) (le_sup hi) (hb _ hi) ((ha _ hi).trans $ le_sup hi) lemma mul_inf_le_inf_mul_of_nonneg [linear_ordered_semiring α] [order_top α] {a b : ι → α} (s : finset ι) (ha : ∀ i ∈ s, 0 ≤ a i) (hb : ∀ i ∈ s, 0 ≤ b i) : s.inf a * s.inf b ≤ s.inf (a * b) := finset.le_inf $ λ i hi, mul_le_mul (inf_le hi) (inf_le hi) (finset.le_inf hb) (ha i hi) lemma sup'_mul_le_mul_sup'_of_nonneg [linear_ordered_semiring α] {a b : ι → α} (s : finset ι) (H : s.nonempty) (ha : ∀ i ∈ s, 0 ≤ a i) (hb : ∀ i ∈ s, 0 ≤ b i) : s.sup' H (a * b) ≤ s.sup' H a * s.sup' H b := sup'_le _ _ $ λ i hi, mul_le_mul (le_sup' _ hi) (le_sup' _ hi) (hb _ hi) ((ha _ hi).trans $ le_sup' _ hi) lemma inf'_mul_le_mul_inf'_of_nonneg [linear_ordered_semiring α] {a b : ι → α} (s : finset ι) (H : s.nonempty) (ha : ∀ i ∈ s, 0 ≤ a i) (hb : ∀ i ∈ s, 0 ≤ b i) : s.inf' H a * s.inf' H b ≤ s.inf' H (a * b) := le_inf' _ _ $ λ i hi, mul_le_mul (inf'_le _ hi) (inf'_le _ hi) (le_inf' _ _ hb) (ha _ hi) open function /-! ### Interaction with big lattice/set operations -/ section lattice lemma supr_coe [has_Sup β] (f : α → β) (s : finset α) : (⨆ x ∈ (↑s : set α), f x) = ⨆ x ∈ s, f x := rfl lemma infi_coe [has_Inf β] (f : α → β) (s : finset α) : (⨅ x ∈ (↑s : set α), f x) = ⨅ x ∈ s, f x := rfl variables [complete_lattice β] theorem supr_singleton (a : α) (s : α → β) : (⨆ x ∈ ({a} : finset α), s x) = s a := by simp theorem infi_singleton (a : α) (s : α → β) : (⨅ x ∈ ({a} : finset α), s x) = s a := by simp lemma supr_option_to_finset (o : option α) (f : α → β) : (⨆ x ∈ o.to_finset, f x) = ⨆ x ∈ o, f x := by simp lemma infi_option_to_finset (o : option α) (f : α → β) : (⨅ x ∈ o.to_finset, f x) = ⨅ x ∈ o, f x := @supr_option_to_finset _ βᵒᵈ _ _ _ variables [decidable_eq α] theorem supr_union {f : α → β} {s t : finset α} : (⨆ x ∈ s ∪ t, f x) = (⨆ x ∈ s, f x) ⊔ (⨆ x ∈ t, f x) := by simp [supr_or, supr_sup_eq] theorem infi_union {f : α → β} {s t : finset α} : (⨅ x ∈ s ∪ t, f x) = (⨅ x ∈ s, f x) ⊓ (⨅ x ∈ t, f x) := @supr_union α βᵒᵈ _ _ _ _ _ lemma supr_insert (a : α) (s : finset α) (t : α → β) : (⨆ x ∈ insert a s, t x) = t a ⊔ (⨆ x ∈ s, t x) := by { rw insert_eq, simp only [supr_union, finset.supr_singleton] } lemma infi_insert (a : α) (s : finset α) (t : α → β) : (⨅ x ∈ insert a s, t x) = t a ⊓ (⨅ x ∈ s, t x) := @supr_insert α βᵒᵈ _ _ _ _ _ lemma supr_finset_image {f : γ → α} {g : α → β} {s : finset γ} : (⨆ x ∈ s.image f, g x) = (⨆ y ∈ s, g (f y)) := by rw [← supr_coe, coe_image, supr_image, supr_coe] lemma sup_finset_image {β γ : Type*} [semilattice_sup β] [order_bot β] (f : γ → α) (g : α → β) (s : finset γ) : (s.image f).sup g = s.sup (g ∘ f) := begin classical, induction s using finset.induction_on with a s' ha ih; simp * end lemma infi_finset_image {f : γ → α} {g : α → β} {s : finset γ} : (⨅ x ∈ s.image f, g x) = (⨅ y ∈ s, g (f y)) := by rw [← infi_coe, coe_image, infi_image, infi_coe] lemma supr_insert_update {x : α} {t : finset α} (f : α → β) {s : β} (hx : x ∉ t) : (⨆ (i ∈ insert x t), function.update f x s i) = (s ⊔ ⨆ (i ∈ t), f i) := begin simp only [finset.supr_insert, update_same], rcongr i hi, apply update_noteq, rintro rfl, exact hx hi end lemma infi_insert_update {x : α} {t : finset α} (f : α → β) {s : β} (hx : x ∉ t) : (⨅ (i ∈ insert x t), update f x s i) = (s ⊓ ⨅ (i ∈ t), f i) := @supr_insert_update α βᵒᵈ _ _ _ _ f _ hx lemma supr_bUnion (s : finset γ) (t : γ → finset α) (f : α → β) : (⨆ y ∈ s.bUnion t, f y) = ⨆ (x ∈ s) (y ∈ t x), f y := by simp [@supr_comm _ α, supr_and] lemma infi_bUnion (s : finset γ) (t : γ → finset α) (f : α → β) : (⨅ y ∈ s.bUnion t, f y) = ⨅ (x ∈ s) (y ∈ t x), f y := @supr_bUnion _ βᵒᵈ _ _ _ _ _ _ end lattice theorem set_bUnion_coe (s : finset α) (t : α → set β) : (⋃ x ∈ (↑s : set α), t x) = ⋃ x ∈ s, t x := rfl theorem set_bInter_coe (s : finset α) (t : α → set β) : (⋂ x ∈ (↑s : set α), t x) = ⋂ x ∈ s, t x := rfl theorem set_bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : finset α), s x) = s a := supr_singleton a s theorem set_bInter_singleton (a : α) (s : α → set β) : (⋂ x ∈ ({a} : finset α), s x) = s a := infi_singleton a s @[simp] lemma set_bUnion_preimage_singleton (f : α → β) (s : finset β) : (⋃ y ∈ s, f ⁻¹' {y}) = f ⁻¹' s := set.bUnion_preimage_singleton f s lemma set_bUnion_option_to_finset (o : option α) (f : α → set β) : (⋃ x ∈ o.to_finset, f x) = ⋃ x ∈ o, f x := supr_option_to_finset o f lemma set_bInter_option_to_finset (o : option α) (f : α → set β) : (⋂ x ∈ o.to_finset, f x) = ⋂ x ∈ o, f x := infi_option_to_finset o f lemma subset_set_bUnion_of_mem {s : finset α} {f : α → set β} {x : α} (h : x ∈ s) : f x ⊆ ⋃ (y ∈ s), f y := show f x ≤ (⨆ y ∈ s, f y), from le_supr_of_le x $ le_supr _ h variables [decidable_eq α] lemma set_bUnion_union (s t : finset α) (u : α → set β) : (⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) := supr_union lemma set_bInter_inter (s t : finset α) (u : α → set β) : (⋂ x ∈ s ∪ t, u x) = (⋂ x ∈ s, u x) ∩ (⋂ x ∈ t, u x) := infi_union lemma set_bUnion_insert (a : α) (s : finset α) (t : α → set β) : (⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) := supr_insert a s t lemma set_bInter_insert (a : α) (s : finset α) (t : α → set β) : (⋂ x ∈ insert a s, t x) = t a ∩ (⋂ x ∈ s, t x) := infi_insert a s t lemma set_bUnion_finset_image {f : γ → α} {g : α → set β} {s : finset γ} : (⋃ x ∈ s.image f, g x) = (⋃ y ∈ s, g (f y)) := supr_finset_image lemma set_bInter_finset_image {f : γ → α} {g : α → set β} {s : finset γ} : (⋂ x ∈ s.image f, g x) = (⋂ y ∈ s, g (f y)) := infi_finset_image lemma set_bUnion_insert_update {x : α} {t : finset α} (f : α → set β) {s : set β} (hx : x ∉ t) : (⋃ (i ∈ insert x t), @update _ _ _ f x s i) = (s ∪ ⋃ (i ∈ t), f i) := supr_insert_update f hx lemma set_bInter_insert_update {x : α} {t : finset α} (f : α → set β) {s : set β} (hx : x ∉ t) : (⋂ (i ∈ insert x t), @update _ _ _ f x s i) = (s ∩ ⋂ (i ∈ t), f i) := infi_insert_update f hx lemma set_bUnion_bUnion (s : finset γ) (t : γ → finset α) (f : α → set β) : (⋃ y ∈ s.bUnion t, f y) = ⋃ (x ∈ s) (y ∈ t x), f y := supr_bUnion s t f lemma set_bInter_bUnion (s : finset γ) (t : γ → finset α) (f : α → set β) : (⋂ y ∈ s.bUnion t, f y) = ⋂ (x ∈ s) (y ∈ t x), f y := infi_bUnion s t f end finset
module Test.Optics import UnitTest import Data.Optics import Control.Category PLZ : Type PLZ = Integer mutual record Person where constructor MkPerson name : String address : Address second : Maybe Address record Address where constructor MkAddress street: String plz : PLZ city : String instance Eq Person where (==) (MkPerson name address second) (MkPerson x y z) = (name == x) && (address == y) && (second == z) instance Eq Address where (==) (MkAddress street plz city) (MkAddress x y z) = (street == x) && (plz == y) && (city == z) instance Show Person where show p = "Person(" ++ name p ++ ")" instance Show Address where show a = "Address(" ++ street a ++ ")" hamburg: Address hamburg = MkAddress "Elbchaussee" 2000 "Hamburg" p: Person p = MkPerson "Holmes" hamburg (Just hamburg) _name : Lens Person String _name = MkLens (\p => name p) (\p,n => record { name = n} p) _address : Lens Person Address _address = MkLens (\p => address p) (\p, a => record { address = a} p) _secondary_address : Optional Person Address _secondary_address = MkOptional (\p => second p) (\p, a => record { second = Just a} p ) _street : Lens Address String _street = MkLens (\a => street a) (\a, s => record { street = s} a) _person_street : Lens Person String _person_street = _address >>> _street _secondary_street : Optional Person String _secondary_street = _secondary_address +:? lensAsOptional _street testPersonNameGet : IO () testPersonNameGet = assertEq "the _name lens can get the name of a person" (get _name p) ("Holmes") testPersonNameSet : IO () testPersonNameSet = assertEq "the _name lens can set the name of a person" (set _name p "Watson") ( record { name = "Watson"} p) testPersonAddressStreetGet : IO () testPersonAddressStreetGet = assertEq "the composed _person_street lens can get the name of the street" (get _person_street p) ("Elbchaussee") testModifyF : IO () testModifyF = assertEq "modifyF can modify a value using a functor"(modifyF (\n => Just n) _name p) (Just p) runall : IO() runall = do testPersonNameGet testPersonNameSet testPersonAddressStreetGet testModifyF
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import algebra.big_operators.ring import number_theory.divisors import data.nat.squarefree import algebra.invertible import data.nat.factorization.basic /-! # Arithmetic Functions and Dirichlet Convolution This file defines arithmetic functions, which are functions from `ℕ` to a specified type that map 0 to 0. In the literature, they are often instead defined as functions from `ℕ+`. These arithmetic functions are endowed with a multiplication, given by Dirichlet convolution, and pointwise addition, to form the Dirichlet ring. ## Main Definitions * `arithmetic_function R` consists of functions `f : ℕ → R` such that `f 0 = 0`. * An arithmetic function `f` `is_multiplicative` when `x.coprime y → f (x * y) = f x * f y`. * The pointwise operations `pmul` and `ppow` differ from the multiplication and power instances on `arithmetic_function R`, which use Dirichlet multiplication. * `ζ` is the arithmetic function such that `ζ x = 1` for `0 < x`. * `σ k` is the arithmetic function such that `σ k x = ∑ y in divisors x, y ^ k` for `0 < x`. * `pow k` is the arithmetic function such that `pow k x = x ^ k` for `0 < x`. * `id` is the identity arithmetic function on `ℕ`. * `ω n` is the number of distinct prime factors of `n`. * `Ω n` is the number of prime factors of `n` counted with multiplicity. * `μ` is the Möbius function (spelled `moebius` in code). ## Main Results * Several forms of Möbius inversion: * `sum_eq_iff_sum_mul_moebius_eq` for functions to a `comm_ring` * `sum_eq_iff_sum_smul_moebius_eq` for functions to an `add_comm_group` * `prod_eq_iff_prod_pow_moebius_eq` for functions to a `comm_group` * `prod_eq_iff_prod_pow_moebius_eq_of_nonzero` for functions to a `comm_group_with_zero` ## Notation The arithmetic functions `ζ` and `σ` have Greek letter names, which are localized notation in the namespace `arithmetic_function`. ## Tags arithmetic functions, dirichlet convolution, divisors -/ open finset open_locale big_operators namespace nat variable (R : Type*) /-- An arithmetic function is a function from `ℕ` that maps 0 to 0. In the literature, they are often instead defined as functions from `ℕ+`. Multiplication on `arithmetic_functions` is by Dirichlet convolution. -/ @[derive [has_zero, inhabited]] def arithmetic_function [has_zero R] := zero_hom ℕ R variable {R} namespace arithmetic_function section has_zero variable [has_zero R] instance : has_coe_to_fun (arithmetic_function R) (λ _, ℕ → R) := zero_hom.has_coe_to_fun @[simp] lemma to_fun_eq (f : arithmetic_function R) : f.to_fun = f := rfl @[simp] lemma map_zero {f : arithmetic_function R} : f 0 = 0 := zero_hom.map_zero' f theorem coe_inj {f g : arithmetic_function R} : (f : ℕ → R) = g ↔ f = g := ⟨λ h, zero_hom.coe_inj h, λ h, h ▸ rfl⟩ @[simp] lemma zero_apply {x : ℕ} : (0 : arithmetic_function R) x = 0 := zero_hom.zero_apply x @[ext] theorem ext ⦃f g : arithmetic_function R⦄ (h : ∀ x, f x = g x) : f = g := zero_hom.ext h theorem ext_iff {f g : arithmetic_function R} : f = g ↔ ∀ x, f x = g x := zero_hom.ext_iff section has_one variable [has_one R] instance : has_one (arithmetic_function R) := ⟨⟨λ x, ite (x = 1) 1 0, rfl⟩⟩ lemma one_apply {x : ℕ} : (1 : arithmetic_function R) x = ite (x = 1) 1 0 := rfl @[simp] lemma one_one : (1 : arithmetic_function R) 1 = 1 := rfl @[simp] lemma one_apply_ne {x : ℕ} (h : x ≠ 1) : (1 : arithmetic_function R) x = 0 := if_neg h end has_one end has_zero instance nat_coe [add_monoid_with_one R] : has_coe (arithmetic_function ℕ) (arithmetic_function R) := ⟨λ f, ⟨↑(f : ℕ → ℕ), by { transitivity ↑(f 0), refl, simp }⟩⟩ @[simp] lemma nat_coe_nat (f : arithmetic_function ℕ) : (↑f : arithmetic_function ℕ) = f := ext $ λ _, cast_id _ @[simp] lemma nat_coe_apply [add_monoid_with_one R] {f : arithmetic_function ℕ} {x : ℕ} : (f : arithmetic_function R) x = f x := rfl instance int_coe [add_group_with_one R] : has_coe (arithmetic_function ℤ) (arithmetic_function R) := ⟨λ f, ⟨↑(f : ℕ → ℤ), by { transitivity ↑(f 0), refl, simp }⟩⟩ @[simp] lemma int_coe_int (f : arithmetic_function ℤ) : (↑f : arithmetic_function ℤ) = f := ext $ λ _, int.cast_id _ @[simp] lemma int_coe_apply [add_group_with_one R] {f : arithmetic_function ℤ} {x : ℕ} : (f : arithmetic_function R) x = f x := rfl @[simp] lemma coe_coe [add_group_with_one R] {f : arithmetic_function ℕ} : ((f : arithmetic_function ℤ) : arithmetic_function R) = f := by { ext, simp, } @[simp] lemma nat_coe_one [add_monoid_with_one R] : ((1 : arithmetic_function ℕ) : arithmetic_function R) = 1 := by { ext n, simp [one_apply] } @[simp] lemma int_coe_one [add_group_with_one R] : ((1 : arithmetic_function ℤ) : arithmetic_function R) = 1 := by { ext n, simp [one_apply] } section add_monoid variable [add_monoid R] instance : has_add (arithmetic_function R) := ⟨λ f g, ⟨λ n, f n + g n, by simp⟩⟩ @[simp] lemma add_apply {f g : arithmetic_function R} {n : ℕ} : (f + g) n = f n + g n := rfl instance : add_monoid (arithmetic_function R) := { add_assoc := λ _ _ _, ext (λ _, add_assoc _ _ _), zero_add := λ _, ext (λ _, zero_add _), add_zero := λ _, ext (λ _, add_zero _), .. arithmetic_function.has_zero R, .. arithmetic_function.has_add } end add_monoid instance [add_monoid_with_one R] : add_monoid_with_one (arithmetic_function R) := { nat_cast := λ n, ⟨λ x, if x = 1 then (n : R) else 0, by simp⟩, nat_cast_zero := by ext; simp [nat.cast], nat_cast_succ := λ _, by ext; by_cases x = 1; simp [nat.cast, *], .. arithmetic_function.add_monoid, .. arithmetic_function.has_one } instance [add_comm_monoid R] : add_comm_monoid (arithmetic_function R) := { add_comm := λ _ _, ext (λ _, add_comm _ _), .. arithmetic_function.add_monoid } instance [add_group R] : add_group (arithmetic_function R) := { neg := λ f, ⟨λ n, - f n, by simp⟩, add_left_neg := λ _, ext (λ _, add_left_neg _), .. arithmetic_function.add_monoid } instance [add_comm_group R] : add_comm_group (arithmetic_function R) := { .. arithmetic_function.add_comm_monoid, .. arithmetic_function.add_group } section has_scalar variables {M : Type*} [has_zero R] [add_comm_monoid M] [has_scalar R M] /-- The Dirichlet convolution of two arithmetic functions `f` and `g` is another arithmetic function such that `(f * g) n` is the sum of `f x * g y` over all `(x,y)` such that `x * y = n`. -/ instance : has_scalar (arithmetic_function R) (arithmetic_function M) := ⟨λ f g, ⟨λ n, ∑ x in divisors_antidiagonal n, f x.fst • g x.snd, by simp⟩⟩ @[simp] lemma smul_apply {f : arithmetic_function R} {g : arithmetic_function M} {n : ℕ} : (f • g) n = ∑ x in divisors_antidiagonal n, f x.fst • g x.snd := rfl end has_scalar /-- The Dirichlet convolution of two arithmetic functions `f` and `g` is another arithmetic function such that `(f * g) n` is the sum of `f x * g y` over all `(x,y)` such that `x * y = n`. -/ instance [semiring R] : has_mul (arithmetic_function R) := ⟨(•)⟩ @[simp] lemma mul_apply [semiring R] {f g : arithmetic_function R} {n : ℕ} : (f * g) n = ∑ x in divisors_antidiagonal n, f x.fst * g x.snd := rfl lemma mul_apply_one [semiring R] {f g : arithmetic_function R} : (f * g) 1 = f 1 * g 1 := by simp @[simp, norm_cast] lemma nat_coe_mul [semiring R] {f g : arithmetic_function ℕ} : (↑(f * g) : arithmetic_function R) = f * g := by { ext n, simp } @[simp, norm_cast] lemma int_coe_mul [ring R] {f g : arithmetic_function ℤ} : (↑(f * g) : arithmetic_function R) = f * g := by { ext n, simp } section module variables {M : Type*} [semiring R] [add_comm_monoid M] [module R M] lemma mul_smul' (f g : arithmetic_function R) (h : arithmetic_function M) : (f * g) • h = f • g • h := begin ext n, simp only [mul_apply, smul_apply, sum_smul, mul_smul, smul_sum, finset.sum_sigma'], apply finset.sum_bij, swap 5, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, exact ⟨(k, l*j), (l, j)⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [finset.mem_sigma, mem_divisors_antidiagonal] at H ⊢, rcases H with ⟨⟨rfl, n0⟩, rfl, i0⟩, refine ⟨⟨(mul_assoc _ _ _).symm, n0⟩, rfl, _⟩, rw mul_ne_zero_iff at *, exact ⟨i0.2, n0.2⟩, }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [mul_assoc] }, { rintros ⟨⟨a,b⟩, ⟨c,d⟩⟩ ⟨⟨i,j⟩, ⟨k,l⟩⟩ H₁ H₂, simp only [finset.mem_sigma, mem_divisors_antidiagonal, and_imp, prod.mk.inj_iff, add_comm, heq_iff_eq] at H₁ H₂ ⊢, rintros rfl h2 rfl rfl, exact ⟨⟨eq.trans H₁.2.1.symm H₂.2.1, rfl⟩, rfl, rfl⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, refine ⟨⟨(i*k, l), (i, k)⟩, _, _⟩, { simp only [finset.mem_sigma, mem_divisors_antidiagonal] at H ⊢, rcases H with ⟨⟨rfl, n0⟩, rfl, j0⟩, refine ⟨⟨mul_assoc _ _ _, n0⟩, rfl, _⟩, rw mul_ne_zero_iff at *, exact ⟨n0.1, j0.1⟩ }, { simp only [true_and, mem_divisors_antidiagonal, and_true, prod.mk.inj_iff, eq_self_iff_true, ne.def, mem_sigma, heq_iff_eq] at H ⊢, rw H.2.1 } } end lemma one_smul' (b : arithmetic_function M) : (1 : arithmetic_function R) • b = b := begin ext, rw smul_apply, by_cases x0 : x = 0, {simp [x0]}, have h : {(1,x)} ⊆ divisors_antidiagonal x := by simp [x0], rw ← sum_subset h, {simp}, intros y ymem ynmem, have y1ne : y.fst ≠ 1, { intro con, simp only [con, mem_divisors_antidiagonal, one_mul, ne.def] at ymem, simp only [mem_singleton, prod.ext_iff] at ynmem, tauto }, simp [y1ne], end end module section semiring variable [semiring R] instance : monoid (arithmetic_function R) := { one_mul := one_smul', mul_one := λ f, begin ext, rw mul_apply, by_cases x0 : x = 0, {simp [x0]}, have h : {(x,1)} ⊆ divisors_antidiagonal x := by simp [x0], rw ← sum_subset h, {simp}, intros y ymem ynmem, have y2ne : y.snd ≠ 1, { intro con, simp only [con, mem_divisors_antidiagonal, mul_one, ne.def] at ymem, simp only [mem_singleton, prod.ext_iff] at ynmem, tauto }, simp [y2ne], end, mul_assoc := mul_smul', .. arithmetic_function.has_one, .. arithmetic_function.has_mul } instance : semiring (arithmetic_function R) := { zero_mul := λ f, by { ext, simp only [mul_apply, zero_mul, sum_const_zero, zero_apply] }, mul_zero := λ f, by { ext, simp only [mul_apply, sum_const_zero, mul_zero, zero_apply] }, left_distrib := λ a b c, by { ext, simp only [←sum_add_distrib, mul_add, mul_apply, add_apply] }, right_distrib := λ a b c, by { ext, simp only [←sum_add_distrib, add_mul, mul_apply, add_apply] }, .. arithmetic_function.has_zero R, .. arithmetic_function.has_mul, .. arithmetic_function.has_add, .. arithmetic_function.add_comm_monoid, .. arithmetic_function.add_monoid_with_one, .. arithmetic_function.monoid } end semiring instance [comm_semiring R] : comm_semiring (arithmetic_function R) := { mul_comm := λ f g, by { ext, rw [mul_apply, ← map_swap_divisors_antidiagonal, sum_map], simp [mul_comm] }, .. arithmetic_function.semiring } instance [comm_ring R] : comm_ring (arithmetic_function R) := { .. arithmetic_function.add_comm_group, .. arithmetic_function.comm_semiring } instance {M : Type*} [semiring R] [add_comm_monoid M] [module R M] : module (arithmetic_function R) (arithmetic_function M) := { one_smul := one_smul', mul_smul := mul_smul', smul_add := λ r x y, by { ext, simp only [sum_add_distrib, smul_add, smul_apply, add_apply] }, smul_zero := λ r, by { ext, simp only [smul_apply, sum_const_zero, smul_zero, zero_apply] }, add_smul := λ r s x, by { ext, simp only [add_smul, sum_add_distrib, smul_apply, add_apply] }, zero_smul := λ r, by { ext, simp only [smul_apply, sum_const_zero, zero_smul, zero_apply] }, } section zeta /-- `ζ 0 = 0`, otherwise `ζ x = 1`. The Dirichlet Series is the Riemann ζ. -/ def zeta : arithmetic_function ℕ := ⟨λ x, ite (x = 0) 0 1, rfl⟩ localized "notation `ζ` := nat.arithmetic_function.zeta" in arithmetic_function @[simp] lemma zeta_apply {x : ℕ} : ζ x = if (x = 0) then 0 else 1 := rfl lemma zeta_apply_ne {x : ℕ} (h : x ≠ 0) : ζ x = 1 := if_neg h @[simp] theorem coe_zeta_mul_apply [semiring R] {f : arithmetic_function R} {x : ℕ} : (↑ζ * f) x = ∑ i in divisors x, f i := begin rw mul_apply, transitivity ∑ i in divisors_antidiagonal x, f i.snd, { apply sum_congr rfl, intros i hi, rcases mem_divisors_antidiagonal.1 hi with ⟨rfl, h⟩, rw [nat_coe_apply, zeta_apply_ne (left_ne_zero_of_mul h), cast_one, one_mul] }, { apply sum_bij (λ i h, prod.snd i), { rintros ⟨a, b⟩ h, simp [snd_mem_divisors_of_mem_antidiagonal h] }, { rintros ⟨a, b⟩ h, refl }, { rintros ⟨a1, b1⟩ ⟨a2, b2⟩ h1 h2 h, dsimp at h, rw h at *, rw mem_divisors_antidiagonal at *, ext, swap, {refl}, simp only [prod.fst, prod.snd] at *, apply nat.eq_of_mul_eq_mul_right _ (eq.trans h1.1 h2.1.symm), rcases h1 with ⟨rfl, h⟩, apply nat.pos_of_ne_zero (right_ne_zero_of_mul h) }, { intros a ha, rcases mem_divisors.1 ha with ⟨⟨b, rfl⟩, ne0⟩, use (b, a), simp [ne0, mul_comm] } } end theorem coe_zeta_smul_apply {M : Type*} [comm_ring R] [add_comm_group M] [module R M] {f : arithmetic_function M} {x : ℕ} : ((↑ζ : arithmetic_function R) • f) x = ∑ i in divisors x, f i := begin rw smul_apply, transitivity ∑ i in divisors_antidiagonal x, f i.snd, { apply sum_congr rfl, intros i hi, rcases mem_divisors_antidiagonal.1 hi with ⟨rfl, h⟩, rw [nat_coe_apply, zeta_apply_ne (left_ne_zero_of_mul h), cast_one, one_smul] }, { apply sum_bij (λ i h, prod.snd i), { rintros ⟨a, b⟩ h, simp [snd_mem_divisors_of_mem_antidiagonal h] }, { rintros ⟨a, b⟩ h, refl }, { rintros ⟨a1, b1⟩ ⟨a2, b2⟩ h1 h2 h, dsimp at h, rw h at *, rw mem_divisors_antidiagonal at *, ext, swap, {refl}, simp only [prod.fst, prod.snd] at *, apply nat.eq_of_mul_eq_mul_right _ (eq.trans h1.1 h2.1.symm), rcases h1 with ⟨rfl, h⟩, apply nat.pos_of_ne_zero (right_ne_zero_of_mul h) }, { intros a ha, rcases mem_divisors.1 ha with ⟨⟨b, rfl⟩, ne0⟩, use (b, a), simp [ne0, mul_comm] } } end @[simp] theorem coe_mul_zeta_apply [semiring R] {f : arithmetic_function R} {x : ℕ} : (f * ζ) x = ∑ i in divisors x, f i := begin apply mul_opposite.op_injective, rw [op_sum], convert @coe_zeta_mul_apply Rᵐᵒᵖ _ { to_fun := mul_opposite.op ∘ f, map_zero' := by simp} x, rw [mul_apply, mul_apply, op_sum], conv_lhs { rw ← map_swap_divisors_antidiagonal, }, rw sum_map, apply sum_congr rfl, intros y hy, by_cases h1 : y.fst = 0, { simp [function.comp_apply, h1] }, { simp only [h1, mul_one, one_mul, prod.fst_swap, function.embedding.coe_fn_mk, prod.snd_swap, if_false, zeta_apply, zero_hom.coe_mk, nat_coe_apply, cast_one] } end theorem zeta_mul_apply {f : arithmetic_function ℕ} {x : ℕ} : (ζ * f) x = ∑ i in divisors x, f i := by rw [← nat_coe_nat ζ, coe_zeta_mul_apply] theorem mul_zeta_apply {f : arithmetic_function ℕ} {x : ℕ} : (f * ζ) x = ∑ i in divisors x, f i := by rw [← nat_coe_nat ζ, coe_mul_zeta_apply] end zeta open_locale arithmetic_function section pmul /-- This is the pointwise product of `arithmetic_function`s. -/ def pmul [mul_zero_class R] (f g : arithmetic_function R) : arithmetic_function R := ⟨λ x, f x * g x, by simp⟩ @[simp] lemma pmul_apply [mul_zero_class R] {f g : arithmetic_function R} {x : ℕ} : f.pmul g x = f x * g x := rfl lemma pmul_comm [comm_monoid_with_zero R] (f g : arithmetic_function R) : f.pmul g = g.pmul f := by { ext, simp [mul_comm] } section non_assoc_semiring variable [non_assoc_semiring R] @[simp] lemma pmul_zeta (f : arithmetic_function R) : f.pmul ↑ζ = f := begin ext x, cases x; simp [nat.succ_ne_zero], end @[simp] lemma zeta_pmul (f : arithmetic_function R) : (ζ : arithmetic_function R).pmul f = f := begin ext x, cases x; simp [nat.succ_ne_zero], end end non_assoc_semiring variables [semiring R] /-- This is the pointwise power of `arithmetic_function`s. -/ def ppow (f : arithmetic_function R) (k : ℕ) : arithmetic_function R := if h0 : k = 0 then ζ else ⟨λ x, (f x) ^ k, by { rw [map_zero], exact zero_pow (nat.pos_of_ne_zero h0) }⟩ @[simp] lemma ppow_zero {f : arithmetic_function R} : f.ppow 0 = ζ := by rw [ppow, dif_pos rfl] @[simp] lemma ppow_apply {f : arithmetic_function R} {k x : ℕ} (kpos : 0 < k) : f.ppow k x = (f x) ^ k := by { rw [ppow, dif_neg (ne_of_gt kpos)], refl } lemma ppow_succ {f : arithmetic_function R} {k : ℕ} : f.ppow (k + 1) = f.pmul (f.ppow k) := begin ext x, rw [ppow_apply (nat.succ_pos k), pow_succ], induction k; simp, end lemma ppow_succ' {f : arithmetic_function R} {k : ℕ} {kpos : 0 < k} : f.ppow (k + 1) = (f.ppow k).pmul f := begin ext x, rw [ppow_apply (nat.succ_pos k), pow_succ'], induction k; simp, end end pmul /-- Multiplicative functions -/ def is_multiplicative [monoid_with_zero R] (f : arithmetic_function R) : Prop := f 1 = 1 ∧ (∀ {m n : ℕ}, m.coprime n → f (m * n) = f m * f n) namespace is_multiplicative section monoid_with_zero variable [monoid_with_zero R] @[simp] lemma map_one {f : arithmetic_function R} (h : f.is_multiplicative) : f 1 = 1 := h.1 @[simp] lemma map_mul_of_coprime {f : arithmetic_function R} (hf : f.is_multiplicative) {m n : ℕ} (h : m.coprime n) : f (m * n) = f m * f n := hf.2 h end monoid_with_zero lemma map_prod {ι : Type*} [comm_monoid_with_zero R] (g : ι → ℕ) {f : nat.arithmetic_function R} (hf : f.is_multiplicative) (s : finset ι) (hs : (s : set ι).pairwise (coprime on g)): f (∏ i in s, g i) = ∏ i in s, f (g i) := begin classical, induction s using finset.induction_on with a s has ih hs, { simp [hf] }, rw [coe_insert, set.pairwise_insert_of_symmetric (coprime.symmetric.comap g)] at hs, rw [prod_insert has, prod_insert has, hf.map_mul_of_coprime, ih hs.1], exact nat.coprime_prod_right (λ i hi, hs.2 _ hi (hi.ne_of_not_mem has).symm), end lemma nat_cast {f : arithmetic_function ℕ} [semiring R] (h : f.is_multiplicative) : is_multiplicative (f : arithmetic_function R) := ⟨by simp [h], λ m n cop, by simp [cop, h]⟩ lemma int_cast {f : arithmetic_function ℤ} [ring R] (h : f.is_multiplicative) : is_multiplicative (f : arithmetic_function R) := ⟨by simp [h], λ m n cop, by simp [cop, h]⟩ lemma mul [comm_semiring R] {f g : arithmetic_function R} (hf : f.is_multiplicative) (hg : g.is_multiplicative) : is_multiplicative (f * g) := ⟨by { simp [hf, hg], }, begin simp only [mul_apply], intros m n cop, rw sum_mul_sum, symmetry, apply sum_bij (λ (x : (ℕ × ℕ) × ℕ × ℕ) h, (x.1.1 * x.2.1, x.1.2 * x.2.2)), { rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h, rcases h with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩, simp only [mem_divisors_antidiagonal, nat.mul_eq_zero, ne.def], split, {ring}, rw nat.mul_eq_zero at *, apply not_or ha hb }, { rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h, rcases h with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩, dsimp only, rw [hf.map_mul_of_coprime cop.coprime_mul_right.coprime_mul_right_right, hg.map_mul_of_coprime cop.coprime_mul_left.coprime_mul_left_right], ring, }, { rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ ⟨⟨c1, c2⟩, ⟨d1, d2⟩⟩ hab hcd h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at hab, rcases hab with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at hcd, simp only [prod.mk.inj_iff] at h, ext; dsimp only, { transitivity nat.gcd (a1 * a2) (a1 * b1), { rw [nat.gcd_mul_left, cop.coprime_mul_left.coprime_mul_right_right.gcd_eq_one, mul_one] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.1.1, h.1, nat.gcd_mul_left, cop.coprime_mul_left.coprime_mul_right_right.gcd_eq_one, mul_one] } }, { transitivity nat.gcd (a1 * a2) (a2 * b2), { rw [mul_comm, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.gcd_eq_one, mul_one] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.1.1, h.2, mul_comm, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.gcd_eq_one, mul_one] } }, { transitivity nat.gcd (b1 * b2) (a1 * b1), { rw [mul_comm, nat.gcd_mul_right, cop.coprime_mul_right.coprime_mul_left_right.symm.gcd_eq_one, one_mul] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.2.1, h.1, mul_comm c1 d1, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.symm.gcd_eq_one, mul_one] } }, { transitivity nat.gcd (b1 * b2) (a2 * b2), { rw [nat.gcd_mul_right, cop.coprime_mul_left.coprime_mul_right_right.symm.gcd_eq_one, one_mul] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.2.1, h.2, nat.gcd_mul_right, cop.coprime_mul_left.coprime_mul_right_right.symm.gcd_eq_one, one_mul] } } }, { rintros ⟨b1, b2⟩ h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h, use ((b1.gcd m, b2.gcd m), (b1.gcd n, b2.gcd n)), simp only [exists_prop, prod.mk.inj_iff, ne.def, mem_product, mem_divisors_antidiagonal], rw [← cop.gcd_mul _, ← cop.gcd_mul _, ← h.1, nat.gcd_mul_gcd_of_coprime_of_mul_eq_mul cop h.1, nat.gcd_mul_gcd_of_coprime_of_mul_eq_mul cop.symm _], { rw [nat.mul_eq_zero, decidable.not_or_iff_and_not] at h, simp [h.2.1, h.2.2] }, rw [mul_comm n m, h.1] } end⟩ lemma pmul [comm_semiring R] {f g : arithmetic_function R} (hf : f.is_multiplicative) (hg : g.is_multiplicative) : is_multiplicative (f.pmul g) := ⟨by { simp [hf, hg], }, λ m n cop, begin simp only [pmul_apply, hf.map_mul_of_coprime cop, hg.map_mul_of_coprime cop], ring, end⟩ /-- For any multiplicative function `f` and any `n > 0`, we can evaluate `f n` by evaluating `f` at `p ^ k` over the factorization of `n` -/ lemma multiplicative_factorization [comm_monoid_with_zero R] (f : arithmetic_function R) (hf : f.is_multiplicative) : ∀ {n : ℕ}, n ≠ 0 → f n = n.factorization.prod (λ p k, f (p ^ k)) := λ n hn, multiplicative_factorization f hf.2 hf.1 hn /-- A recapitulation of the definition of multiplicative that is simpler for proofs -/ lemma iff_ne_zero [monoid_with_zero R] {f : arithmetic_function R} : is_multiplicative f ↔ f 1 = 1 ∧ (∀ {m n : ℕ}, m ≠ 0 → n ≠ 0 → m.coprime n → f (m * n) = f m * f n) := begin refine and_congr_right' (forall₂_congr (λ m n, ⟨λ h _ _, h, λ h hmn, _⟩)), rcases eq_or_ne m 0 with rfl | hm, { simp }, rcases eq_or_ne n 0 with rfl | hn, { simp }, exact h hm hn hmn, end /-- Two multiplicative functions `f` and `g` are equal if and only if they agree on prime powers -/ lemma eq_iff_eq_on_prime_powers [comm_monoid_with_zero R] (f : arithmetic_function R) (hf : f.is_multiplicative) (g : arithmetic_function R) (hg : g.is_multiplicative) : f = g ↔ ∀ (p i : ℕ), nat.prime p → f (p ^ i) = g (p ^ i) := begin split, { intros h p i _, rw [h] }, intros h, ext n, by_cases hn : n = 0, { rw [hn, arithmetic_function.map_zero, arithmetic_function.map_zero] }, rw [multiplicative_factorization f hf hn, multiplicative_factorization g hg hn], refine finset.prod_congr rfl _, simp only [support_factorization, list.mem_to_finset], intros p hp, exact h p _ (nat.prime_of_mem_factors hp), end end is_multiplicative section special_functions /-- The identity on `ℕ` as an `arithmetic_function`. -/ def id : arithmetic_function ℕ := ⟨id, rfl⟩ @[simp] lemma id_apply {x : ℕ} : id x = x := rfl /-- `pow k n = n ^ k`, except `pow 0 0 = 0`. -/ def pow (k : ℕ) : arithmetic_function ℕ := id.ppow k @[simp] lemma pow_apply {k n : ℕ} : pow k n = if (k = 0 ∧ n = 0) then 0 else n ^ k := begin cases k, { simp [pow] }, simp [pow, (ne_of_lt (nat.succ_pos k)).symm], end lemma pow_zero_eq_zeta : pow 0 = ζ := by { ext n, simp } /-- `σ k n` is the sum of the `k`th powers of the divisors of `n` -/ def sigma (k : ℕ) : arithmetic_function ℕ := ⟨λ n, ∑ d in divisors n, d ^ k, by simp⟩ localized "notation `σ` := nat.arithmetic_function.sigma" in arithmetic_function lemma sigma_apply {k n : ℕ} : σ k n = ∑ d in divisors n, d ^ k := rfl lemma sigma_one_apply (n : ℕ) : σ 1 n = ∑ d in divisors n, d := by simp [sigma_apply] lemma sigma_zero_apply (n : ℕ) : σ 0 n = (divisors n).card := by simp [sigma_apply] lemma sigma_zero_apply_prime_pow {p i : ℕ} (hp : p.prime) : σ 0 (p ^ i) = i + 1 := by rw [sigma_zero_apply, divisors_prime_pow hp, card_map, card_range] lemma zeta_mul_pow_eq_sigma {k : ℕ} : ζ * pow k = σ k := begin ext, rw [sigma, zeta_mul_apply], apply sum_congr rfl, intros x hx, rw [pow_apply, if_neg (not_and_of_not_right _ _)], contrapose! hx, simp [hx], end lemma is_multiplicative_one [monoid_with_zero R] : is_multiplicative (1 : arithmetic_function R) := is_multiplicative.iff_ne_zero.2 ⟨by simp, begin intros m n hm hn hmn, rcases eq_or_ne m 1 with rfl | hm', { simp }, rw [one_apply_ne, one_apply_ne hm', zero_mul], rw [ne.def, nat.mul_eq_one_iff, not_and_distrib], exact or.inl hm' end⟩ lemma is_multiplicative_zeta : is_multiplicative ζ := is_multiplicative.iff_ne_zero.2 ⟨by simp, by simp {contextual := tt}⟩ lemma is_multiplicative_id : is_multiplicative arithmetic_function.id := ⟨rfl, λ _ _ _, rfl⟩ lemma is_multiplicative.ppow [comm_semiring R] {f : arithmetic_function R} (hf : f.is_multiplicative) {k : ℕ} : is_multiplicative (f.ppow k) := begin induction k with k hi, { exact is_multiplicative_zeta.nat_cast }, { rw ppow_succ, apply hf.pmul hi }, end lemma is_multiplicative_pow {k : ℕ} : is_multiplicative (pow k) := is_multiplicative_id.ppow lemma is_multiplicative_sigma {k : ℕ} : is_multiplicative (σ k) := begin rw [← zeta_mul_pow_eq_sigma], apply ((is_multiplicative_zeta).mul is_multiplicative_pow) end /-- `Ω n` is the number of prime factors of `n`. -/ def card_factors : arithmetic_function ℕ := ⟨λ n, n.factors.length, by simp⟩ localized "notation `Ω` := nat.arithmetic_function.card_factors" in arithmetic_function lemma card_factors_apply {n : ℕ} : Ω n = n.factors.length := rfl @[simp] lemma card_factors_one : Ω 1 = 0 := by simp [card_factors] lemma card_factors_eq_one_iff_prime {n : ℕ} : Ω n = 1 ↔ n.prime := begin refine ⟨λ h, _, λ h, list.length_eq_one.2 ⟨n, factors_prime h⟩⟩, cases n, { contrapose! h, simp }, rcases list.length_eq_one.1 h with ⟨x, hx⟩, rw [← prod_factors n.succ_ne_zero, hx, list.prod_singleton], apply prime_of_mem_factors, rw [hx, list.mem_singleton] end lemma card_factors_mul {m n : ℕ} (m0 : m ≠ 0) (n0 : n ≠ 0) : Ω (m * n) = Ω m + Ω n := by rw [card_factors_apply, card_factors_apply, card_factors_apply, ← multiset.coe_card, ← factors_eq, unique_factorization_monoid.normalized_factors_mul m0 n0, factors_eq, factors_eq, multiset.card_add, multiset.coe_card, multiset.coe_card] lemma card_factors_multiset_prod {s : multiset ℕ} (h0 : s.prod ≠ 0) : Ω s.prod = (multiset.map Ω s).sum := begin revert h0, apply s.induction_on, by simp, intros a t h h0, rw [multiset.prod_cons, mul_ne_zero_iff] at h0, simp [h0, card_factors_mul, h], end @[simp] lemma card_factors_apply_prime {p : ℕ} (hp : p.prime) : Ω p = 1 := card_factors_eq_one_iff_prime.2 hp @[simp] lemma card_factors_apply_prime_pow {p k : ℕ} (hp : p.prime) : Ω (p ^ k) = k := by rw [card_factors_apply, hp.factors_pow, list.length_repeat] /-- `ω n` is the number of distinct prime factors of `n`. -/ def card_distinct_factors : arithmetic_function ℕ := ⟨λ n, n.factors.dedup.length, by simp⟩ localized "notation `ω` := nat.arithmetic_function.card_distinct_factors" in arithmetic_function lemma card_distinct_factors_zero : ω 0 = 0 := by simp @[simp] lemma card_distinct_factors_one : ω 1 = 0 := by simp [card_distinct_factors] lemma card_distinct_factors_apply {n : ℕ} : ω n = n.factors.dedup.length := rfl lemma card_distinct_factors_eq_card_factors_iff_squarefree {n : ℕ} (h0 : n ≠ 0) : ω n = Ω n ↔ squarefree n := begin rw [squarefree_iff_nodup_factors h0, card_distinct_factors_apply], split; intro h, { rw ← list.eq_of_sublist_of_length_eq n.factors.dedup_sublist h, apply list.nodup_dedup }, { rw h.dedup, refl } end @[simp] lemma card_distinct_factors_apply_prime_pow {p k : ℕ} (hp : p.prime) (hk : k ≠ 0) : ω (p ^ k) = 1 := by rw [card_distinct_factors_apply, hp.factors_pow, list.repeat_dedup hk, list.length_singleton] @[simp] lemma card_distinct_factors_apply_prime {p : ℕ} (hp : p.prime) : ω p = 1 := by rw [←pow_one p, card_distinct_factors_apply_prime_pow hp one_ne_zero] /-- `μ` is the Möbius function. If `n` is squarefree with an even number of distinct prime factors, `μ n = 1`. If `n` is squarefree with an odd number of distinct prime factors, `μ n = -1`. If `n` is not squarefree, `μ n = 0`. -/ def moebius : arithmetic_function ℤ := ⟨λ n, if squarefree n then (-1) ^ (card_factors n) else 0, by simp⟩ localized "notation `μ` := nat.arithmetic_function.moebius" in arithmetic_function @[simp] lemma moebius_apply_of_squarefree {n : ℕ} (h : squarefree n) : μ n = (-1) ^ card_factors n := if_pos h @[simp] lemma moebius_eq_zero_of_not_squarefree {n : ℕ} (h : ¬ squarefree n) : μ n = 0 := if_neg h lemma moebius_apply_one : μ 1 = 1 := by simp lemma moebius_ne_zero_iff_squarefree {n : ℕ} : μ n ≠ 0 ↔ squarefree n := begin split; intro h, { contrapose! h, simp [h] }, { simp [h, pow_ne_zero] } end lemma moebius_ne_zero_iff_eq_or {n : ℕ} : μ n ≠ 0 ↔ μ n = 1 ∨ μ n = -1 := begin split; intro h, { rw moebius_ne_zero_iff_squarefree at h, rw moebius_apply_of_squarefree h, apply neg_one_pow_eq_or }, { rcases h with h | h; simp [h] } end lemma moebius_apply_prime {p : ℕ} (hp : p.prime) : μ p = -1 := by rw [moebius_apply_of_squarefree hp.squarefree, card_factors_apply_prime hp, pow_one] lemma moebius_apply_prime_pow {p k : ℕ} (hp : p.prime) (hk : k ≠ 0) : μ (p ^ k) = if k = 1 then -1 else 0 := begin split_ifs, { rw [h, pow_one, moebius_apply_prime hp] }, rw [moebius_eq_zero_of_not_squarefree], rw [squarefree_pow_iff hp.ne_one hk, not_and_distrib], exact or.inr h, end lemma moebius_apply_is_prime_pow_not_prime {n : ℕ} (hn : is_prime_pow n) (hn' : ¬ n.prime) : μ n = 0 := begin obtain ⟨p, k, hp, hk, rfl⟩ := (is_prime_pow_nat_iff _).1 hn, rw [moebius_apply_prime_pow hp hk.ne', if_neg], rintro rfl, exact hn' (by simpa), end lemma is_multiplicative_moebius : is_multiplicative μ := begin rw is_multiplicative.iff_ne_zero, refine ⟨by simp, λ n m hn hm hnm, _⟩, simp only [moebius, zero_hom.coe_mk, squarefree_mul hnm, ite_and, card_factors_mul hn hm], rw [pow_add, mul_comm, ite_mul_zero_left, ite_mul_zero_right, mul_comm], end open unique_factorization_monoid @[simp] @[simp] lemma coe_zeta_mul_moebius : (ζ * μ : arithmetic_function ℤ) = 1 := by rw [mul_comm, moebius_mul_coe_zeta] @[simp] lemma coe_moebius_mul_coe_zeta [ring R] : (μ * ζ : arithmetic_function R) = 1 := by rw [←coe_coe, ←int_coe_mul, moebius_mul_coe_zeta, int_coe_one] @[simp] lemma coe_zeta_mul_coe_moebius [ring R] : (ζ * μ : arithmetic_function R) = 1 := by rw [←coe_coe, ←int_coe_mul, coe_zeta_mul_moebius, int_coe_one] section comm_ring variable [comm_ring R] instance : invertible (ζ : arithmetic_function R) := { inv_of := μ, inv_of_mul_self := coe_moebius_mul_coe_zeta, mul_inv_of_self := coe_zeta_mul_coe_moebius} /-- A unit in `arithmetic_function R` that evaluates to `ζ`, with inverse `μ`. -/ def zeta_unit : (arithmetic_function R)ˣ := ⟨ζ, μ, coe_zeta_mul_coe_moebius, coe_moebius_mul_coe_zeta⟩ @[simp] lemma coe_zeta_unit : ((zeta_unit : (arithmetic_function R)ˣ) : arithmetic_function R) = ζ := rfl @[simp] lemma inv_zeta_unit : ((zeta_unit⁻¹ : (arithmetic_function R)ˣ) : arithmetic_function R) = μ := rfl end comm_ring /-- Möbius inversion for functions to an `add_comm_group`. -/ theorem sum_eq_iff_sum_smul_moebius_eq [add_comm_group R] {f g : ℕ → R} : (∀ (n : ℕ), 0 < n → ∑ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∑ (x : ℕ × ℕ) in n.divisors_antidiagonal, μ x.fst • g x.snd = f n := begin let f' : arithmetic_function R := ⟨λ x, if x = 0 then 0 else f x, if_pos rfl⟩, let g' : arithmetic_function R := ⟨λ x, if x = 0 then 0 else g x, if_pos rfl⟩, transitivity (ζ : arithmetic_function ℤ) • f' = g', { rw ext_iff, apply forall_congr, intro n, cases n, { simp }, rw coe_zeta_smul_apply, simp only [n.succ_ne_zero, forall_prop_of_true, succ_pos', if_false, zero_hom.coe_mk], rw sum_congr rfl (λ x hx, _), rw (if_neg (ne_of_gt (nat.pos_of_mem_divisors hx))) }, transitivity μ • g' = f', { split; intro h, { rw [← h, ← mul_smul, moebius_mul_coe_zeta, one_smul] }, { rw [← h, ← mul_smul, coe_zeta_mul_moebius, one_smul] } }, { rw ext_iff, apply forall_congr, intro n, cases n, { simp }, simp only [n.succ_ne_zero, forall_prop_of_true, succ_pos', smul_apply, if_false, zero_hom.coe_mk], rw sum_congr rfl (λ x hx, _), rw (if_neg (ne_of_gt (nat.pos_of_mem_divisors (snd_mem_divisors_of_mem_antidiagonal hx)))) }, end /-- Möbius inversion for functions to a `ring`. -/ theorem sum_eq_iff_sum_mul_moebius_eq [ring R] {f g : ℕ → R} : (∀ (n : ℕ), 0 < n → ∑ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∑ (x : ℕ × ℕ) in n.divisors_antidiagonal, (μ x.fst : R) * g x.snd = f n := begin rw sum_eq_iff_sum_smul_moebius_eq, apply forall_congr, refine λ a, imp_congr_right (λ _, (sum_congr rfl $ λ x hx, _).congr_left), rw [zsmul_eq_mul], end /-- Möbius inversion for functions to a `comm_group`. -/ theorem prod_eq_iff_prod_pow_moebius_eq [comm_group R] {f g : ℕ → R} : (∀ (n : ℕ), 0 < n → ∏ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∏ (x : ℕ × ℕ) in n.divisors_antidiagonal, g x.snd ^ (μ x.fst) = f n := @sum_eq_iff_sum_smul_moebius_eq (additive R) _ _ _ /-- Möbius inversion for functions to a `comm_group_with_zero`. -/ theorem prod_eq_iff_prod_pow_moebius_eq_of_nonzero [comm_group_with_zero R] {f g : ℕ → R} (hf : ∀ (n : ℕ), 0 < n → f n ≠ 0) (hg : ∀ (n : ℕ), 0 < n → g n ≠ 0) : (∀ (n : ℕ), 0 < n → ∏ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∏ (x : ℕ × ℕ) in n.divisors_antidiagonal, g x.snd ^ (μ x.fst) = f n := begin refine iff.trans (iff.trans (forall_congr (λ n, _)) (@prod_eq_iff_prod_pow_moebius_eq Rˣ _ (λ n, if h : 0 < n then units.mk0 (f n) (hf n h) else 1) (λ n, if h : 0 < n then units.mk0 (g n) (hg n h) else 1))) (forall_congr (λ n, _)); refine imp_congr_right (λ hn, _), { dsimp, rw [dif_pos hn, ← units.eq_iff, ← units.coe_hom_apply, monoid_hom.map_prod, units.coe_mk0, prod_congr rfl _], intros x hx, rw [dif_pos (nat.pos_of_mem_divisors hx), units.coe_hom_apply, units.coe_mk0] }, { dsimp, rw [dif_pos hn, ← units.eq_iff, ← units.coe_hom_apply, monoid_hom.map_prod, units.coe_mk0, prod_congr rfl _], intros x hx, rw [dif_pos (nat.pos_of_mem_divisors (nat.snd_mem_divisors_of_mem_antidiagonal hx)), units.coe_hom_apply, units.coe_zpow, units.coe_mk0] } end end special_functions end arithmetic_function end nat
State Before: a b : ℝ n : ℕ ⊢ (∫ (x : ℝ) in a..b, 1 / (1 + x ^ 2)) = arctan b - arctan a State After: no goals Tactic: simp only [one_div, integral_inv_one_add_sq]
// ----------------------------------------------------------------------------- // Fern © Geoneric // // This file is part of Geoneric Fern which is available under the terms of // the GNU General Public License (GPL), version 2. If you do not want to // be bound by the terms of the GPL, you may purchase a proprietary license // from Geoneric (http://www.geoneric.eu/contact). // ----------------------------------------------------------------------------- #define BOOST_TEST_MODULE fern io netcdf core attribute #include <boost/test/unit_test.hpp> #include "fern/io/core/file.h" #include "fern/io/netcdf/core/attribute.h" #include "fern/io/netcdf/core/dataset.h" namespace fi = fern::io; namespace fin = fern::io::netcdf; BOOST_AUTO_TEST_CASE(has_attribute) { std::string dataset_pathname = "earth.nc"; BOOST_REQUIRE(fi::file_exists(dataset_pathname)); fin::DatasetHandle dataset = fin::open_dataset(dataset_pathname); BOOST_CHECK(!fin::has_attribute(dataset, "does_not_exist")); BOOST_CHECK( fin::has_attribute(dataset, "Conventions")); }
-- WIP Trying to proove addBoth.sub, addBoth.sup -- Is it really necessary to import BEq and have beq_eq_eq? -- Tested with: -- leanprover/lean4:nightly unchanged - Lean (version 4.0.0-nightly-2023-01-28, commit e37f209c1a2a, Release) import Std.Data.AssocList import Std.Data.List.Lemmas import Std.Classes.BEq namespace MWE8 theorem cond_eq_ite (c : Bool) (a b : α) : cond c a b = if c then a else b := by cases c <;> rfl theorem cond_decide {α} (p : Prop) [Decidable p] (t e : α) : cond (decide p) t e = if p then t else e := by by_cases p <;> simp [*] -- https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/Problems.20simplifying.20.20conditions.20with.20hypotheses/near/324212540 @[simp] theorem beq_eq_eq [DecidableEq α] (x y : α) : (x == y) = decide (x = y) := rfl abbrev Strings := List String instance : Repr (Std.AssocList String Strings) where reprPrec s n := s.toList.repr n def addDecl (s: Std.AssocList String Strings) (d: String) : Std.AssocList String Strings := match s.contains d with | true => s | false => .cons d [] s theorem addDecl.added (s: Std.AssocList String Strings) (d: String): (addDecl s d).contains d := by simp [addDecl] split <;> simp next x heq => simp_all theorem addDecl.cons (s: Std.AssocList String Strings) (d: String): (addDecl s d).isEmpty = false := by simp [addDecl] split <;> simp [List.isEmpty] . case h_1 x heq => split <;> simp_all theorem addDecl.after (s: Std.AssocList String Strings) (x y: String): s.contains x → (addDecl s y).contains x := by intro h simp [Std.AssocList.contains, addDecl] at h ⊢ apply Exists.elim h split <;> simp_all done def addSubSup: String → String → Std.AssocList String Strings → Std.AssocList String Strings | sub, sup, .nil => .cons sub [sup] .nil | sub, sup, .cons a as tail => bif a = sub then .cons sub (as.insert sup) tail else .cons a as (addSubSup sub sup tail) theorem addSubSup.sub (sub sup: String) (ss: Std.AssocList String Strings): (addSubSup sub sup ss).contains sub := by induction ss <;> simp_all . case cons key value tail tail_ih => simp [addSubSup, cond_eq_ite] by_cases key = sub . case pos h => simp [h] . case neg h => simp [h] apply tail_ih def addBoth (sub sup: String) (ss: Std.AssocList String Strings) : Std.AssocList String Strings := let ss' := addDecl ss sup addSubSup sub sup ss' theorem addBoth.sub_eq (sub sup: String) (ss: Std.AssocList String Strings) : (addBoth sub sup ss).contains sub := by induction ss <;> simp_all . case nil => simp [addBoth, addDecl, addSubSup, cond_eq_ite] split <;> simp_all . case cons key value tail tail_ih => simp [addBoth, addDecl] by_cases key = sup <;> simp [*] . case pos => simp [addSubSup, cond_eq_ite] by_cases sup = sub <;> simp [*] . case neg h => simp [addBoth, addDecl] at tail_ih split at tail_ih . case h_1 => by_cases key = sub <;> simp [*] . case h_2 x heq => by_cases key = sub <;> simp_all simp [addSubSup, cond_eq_ite, h] at tail_ih apply tail_ih . case neg h => split <;> simp_all . case h_1 x heq => -- Given the tactic state: -- subsupkey: String -- value: Strings -- tail: Std.AssocList String Strings -- x: Bool -- tail_ih: ∃ x, x ∈ Std.AssocList.toList (addBoth sub sup tail) ∧ x.fst = sub -- h: ¬key = sup -- heq: ∃ x, x ∈ Std.AssocList.toList tail ∧ x.fst = sup -- How to prove? -- ⊢ ∃ x, x ∈ Std.AssocList.toList (addSubSup sub sup (Std.AssocList.cons key value tail)) ∧ x.fst = sub sorry . case h_2 x heq => -- Given the tactic state: -- subsupkey: String -- value: Strings -- tail: Std.AssocList String Strings -- x: Bool -- tail_ih: ∃ x, x ∈ Std.AssocList.toList (addBoth sub sup tail) ∧ x.fst = sub -- h: ¬key = sup -- heq: (List.any (Std.AssocList.toList tail) fun x => decide (x.fst = sup)) = false -- How to prove? -- ⊢ ∃ x, -- x ∈ Std.AssocList.toList (addSubSup sub sup (Std.AssocList.cons sup [] (Std.AssocList.cons key value tail))) ∧ -- x.fst = sub sorry theorem addBoth.sub_beq (sub sup: String) (ss: Std.AssocList String Strings) : (addBoth sub sup ss).contains sub := by induction ss <;> simp_all . case nil => simp [addBoth, addDecl, addSubSup, cond_eq_ite] split <;> simp_all . case cons key value tail tail_ih => simp [addBoth, addDecl] by_cases key == sup <;> simp_all . case pos => simp [addSubSup, cond_eq_ite] by_cases sup == sub <;> simp [*] . case pos => simp_all . case neg h => simp [addBoth, addDecl] at tail_ih split at tail_ih . case h_1 => by_cases key == sub <;> simp_all . case h_2 x heq => by_cases key == sub <;> simp_all simp [addSubSup, cond_eq_ite, h] at tail_ih apply tail_ih . case neg h => split <;> simp_all . case h_1 x heq => -- Given the tactic state: (same as addBoth.sub_eq: path cons/neg/h_1) -- subsupkey: String -- value: Strings -- tail: Std.AssocList String Strings -- x: Bool -- tail_ih: ∃ x, x ∈ Std.AssocList.toList (addBoth sub sup tail) ∧ x.fst = sub -- h: ¬key = sup -- heq: ∃ x, x ∈ Std.AssocList.toList tail ∧ x.fst = sup -- How to prove? -- ⊢ ∃ x, x ∈ Std.AssocList.toList (addSubSup sub sup (Std.AssocList.cons key value tail)) ∧ x.fst = sub sorry . case h_2 x heq => -- Given the tactic state: (same as addBoth.sub_eq: path cons/neg/h_2) -- subsupkey: String -- value: Strings -- tail: Std.AssocList String Strings -- x: Bool -- tail_ih: ∃ x, x ∈ Std.AssocList.toList (addBoth sub sup tail) ∧ x.fst = sub -- h: ¬key = sup -- heq: (List.any (Std.AssocList.toList tail) fun x => decide (x.fst = sup)) = false -- How to prove? -- ⊢ ∃ x, -- x ∈ Std.AssocList.toList (addSubSup sub sup (Std.AssocList.cons sup [] (Std.AssocList.cons key value tail))) ∧ -- x.fst = sub sorry theorem addBoth.sup_eq (sub sup: String) (ss: Std.AssocList String Strings) : (addBoth sub sup ss).contains sup := by simp [addBoth] simp [addDecl] induction ss <;> simp [*] . case nil => simp [addSubSup, cond_eq_ite] by_cases sup = sub <;> simp [*] . case cons key value tail tail_ih => simp [addDecl, cond_eq_ite] by_cases key = sup <;> simp [*] . case pos h1 => simp [addSubSup, cond_eq_ite] at tail_ih ⊢ by_cases sup = sub <;> simp [*] . case neg h1 => let ⟨ x, hx, he ⟩ := tail_ih split <;> simp_all . case h_1 y heq => -- Given the tactic state: -- subsupkey: String -- value: Strings -- tail: Std.AssocList String Strings -- x: String × Strings -- y: Bool -- tail_ih: ∃ x, x ∈ Std.AssocList.toList (addSubSup sub sup tail) ∧ x.fst = sup -- h1: ¬key = sup -- hx: x ∈ Std.AssocList.toList (addSubSup sub sup tail) -- he: x.fst = sup -- heq: ∃ x, x ∈ Std.AssocList.toList tail ∧ x.fst = sup -- How to prove? -- ⊢ ∃ x, x ∈ Std.AssocList.toList (addSubSup sub sup (Std.AssocList.cons key value tail)) ∧ x.fst = sup sorry . case h_2 y heq => -- Given the tactic state: -- subsupkey: String -- value: Strings -- tail: Std.AssocList String Strings -- x: String × Strings -- y: Bool -- tail_ih: ∃ x, x ∈ Std.AssocList.toList (addSubSup sub sup (Std.AssocList.cons sup [] tail)) ∧ x.fst = sup -- h1: ¬key = sup -- hx: x ∈ Std.AssocList.toList (addSubSup sub sup (Std.AssocList.cons sup [] tail)) -- he: x.fst = sup -- heq: (List.any (Std.AssocList.toList tail) fun x => decide (x.fst = sup)) = false -- How to prove? -- ⊢ ∃ x, -- x ∈ Std.AssocList.toList (addSubSup sub sup (Std.AssocList.cons sup [] (Std.AssocList.cons key value tail))) ∧ -- x.fst = sup sorry theorem addBoth.sup_beq (sub sup: String) (ss: Std.AssocList String Strings) : (addBoth sub sup ss).contains sup := by simp [addBoth] simp [addDecl] induction ss <;> simp_all . case nil => simp [addSubSup, cond_eq_ite] by_cases sup == sub <;> simp_all . case cons key value tail tail_ih => simp [addDecl, cond_eq_ite] by_cases key == sup <;> simp_all . case pos h1 => simp [addSubSup, cond_eq_ite] by_cases sup == sub <;> simp_all . case neg h1 => let ⟨ x, hx, he ⟩ := tail_ih split <;> simp_all . case h_1 y heq => -- Given the tactic state (same as addBoth.sup_eq: path cons/neg/h1) -- subsupkey: String -- value: Strings -- tail: Std.AssocList String Strings -- x: String × Strings -- y: Bool -- tail_ih: ∃ x, x ∈ Std.AssocList.toList (addSubSup sub sup tail) ∧ x.fst = sup -- h1: ¬key = sup -- hx: x ∈ Std.AssocList.toList (addSubSup sub sup tail) -- he: x.fst = sup -- heq: ∃ x, x ∈ Std.AssocList.toList tail ∧ x.fst = sup -- How to prove? -- ⊢ ∃ x, x ∈ Std.AssocList.toList (addSubSup sub sup (Std.AssocList.cons key value tail)) ∧ x.fst = sup sorry . case h_2 y heq => -- Given the tactic state: (same as addBoth.sup_eq: path cons/neg/h2) -- subsupkey: String -- value: Strings -- tail: Std.AssocList String Strings -- x: String × Strings -- y: Bool -- tail_ih: ∃ x, x ∈ Std.AssocList.toList (addSubSup sub sup (Std.AssocList.cons sup [] tail)) ∧ x.fst = sup -- h1: ¬key = sup -- hx: x ∈ Std.AssocList.toList (addSubSup sub sup (Std.AssocList.cons sup [] tail)) -- he: x.fst = sup -- heq: (List.any (Std.AssocList.toList tail) fun x => decide (x.fst = sup)) = false -- How to prove? -- ⊢ ∃ x, -- x ∈ Std.AssocList.toList (addSubSup sub sup (Std.AssocList.cons sup [] (Std.AssocList.cons key value tail))) ∧ -- x.fst = sup sorry end MWE8
library(plm) options(scipen=999) Panel <- read.csv("C:/data/car/h1_variables.txt") fixed <- plm(car_val ~ score + filelate + car_e_val + lnAsset + modified + gc + factor(year) , data=Panel, index=c("X10", "year") , effect = "twoway" , model="within") summary(fixed)
```python import sys import numpy as np ``` ```python sys.path.insert(0, '../') sys.path.insert(0, '../detmodel/') ``` ```python import elements ``` ```python import si_mu_late ``` ```python det = si_mu_late.setup_detector('../cards/atlas_mm.yml') ``` ```python det ``` <detector.Detector at 0x7fa757624c88> ```python class conf(): def __init__(self, nevs,ismu,muxmin,muxmax,muymin,muymax,muamin,muamax,bkgr): self.nevs=nevs self.ismu=ismu self.muxmin=muxmin self.muxmax=muxmax self.muymin=muymin self.muymax=muymax self.muamin=muamin self.muamax=muamax self.bkgr=bkgr ``` ```python myconf = conf(1,1,0,0,0,0,0,0,100000) ``` ```python signals = si_mu_late.event(det,myconf) ``` 1 1 1 1 1 1 1 1 ```python signals ``` ```python import sympy ``` ```python l1 = sympy.Line3D( sympy.Point3D(-1/2, 0, 1), sympy.Point3D(-1/2, 5, 1) ) l2 = sympy.Line3D(sympy.Point3D(5, -5, 1), sympy.Point3D(5, 5, 1)) ``` ```python l1.intersection(l2) ``` ```python det.get_signals() ``` ```python det.planes[1].z ``` ```python mu = elements.Muon(0,0,0,0) ``` ```python det.planes[3].pass_muon(mu) ``` ```python ``` ```python ``` ```python ``` ```python ```