Datasets:
AI4M
/

text
stringlengths
0
3.34M
-- --------------------------------------------------------------- [ Utils.idr ] -- -- Utilities -- -- --------------------------------------------------------------------- [ EOH ] module RFC.Utils import System %access public ||| Representation of String literals that are to be sent. Literal : String -> Type Literal str = (str' : String ** str' = str) -- ----------------------------------------------------------------- [ DayTime ] ||| Simple Record for DayTime record DayTime : Type where MkDaytime : (y : Int) -> (m : Int) -> (d : Int) -> (hh : Int) -> (mm : Int) -> (ss : Int) -> DayTime instance Show DayTime where show date = unwords [show (y date), "-", show (m date), "-", show (d date), " ", show (hh date), ":", show (mm date), ":", show (ss date) ] -- --------------------------------------------------------------------- [ EOF ]
import Pkg Pkg.activate("emergency_services") # load all necessary packages and functions include("functions/start_load_packages.jl") # state the parts of the framework that should be executed # stage 1: only the optimisation will be executed # stage 2: only the simulation will be executed (requires at least one run of stage 1) # both: both stages will be executed framework = "both"::String # state the name of the problem instance that should be solved, possible examples # are "0510","1008","1508","2040" where the name corresponds to the number of BAs problem = "2040"::String # state the name of the subproblem that should be solved, for example "one_location", # "basic", "two_locations", eg. subproblem = "nine_locations"::String # state the strength of the compactness and contiguity constraints # C0 = no contiguity constraints (no compactness) # C1 = solely contiguity constrains (no compactness) # C2 = contiguity and normal ompactness constraints # C3 = contiguity and strong compactness constraints # For more details take a look at the article this program is based on compactness = "C2"::String # state the number of simulations that should be executed due to the variability of the driving time sim_number = 100::Int64 # state the main input parameters for the optimisation (framework stage 1) number_districts = 9::Int64 # number of districts that should be opened max_drive = 30.0::Float64 # maximum driving distance (minutes) to district border nearby_districts = 2::Int64 # minimal number of districts within nearby radius nearby_radius = 30.0::Float64 # maximal driving time to nearby district center fixed_locations = 0::Int64 # number of current locations that should not be moved plot_district = true::Bool # state whether the resulting district should be plotted # state the optimisation options solver = "gurobi" const GRB_ENV = Gurobi.Env() const optcr = 0.000::Float64 # allowed gap const reslim = 21600::Int64 # maximal duration of optimisation in seconds const cores = 8::Int64 # number of CPU cores const nodlim = 1000000::Int64 # maximal number of nodes const iterlim = 100000000::Int64 # maximal number of iterations const silent = false::Bool # state whether to surpress the optimisation log # state the weight of each priority for the driving time # important: the weight has to equal the number of priorities # in the incident data stage prio_weight = [1, 1, 1, 1, 1] # state the main parameters for the simulation (framework stage 2) const min_capacity = 2::Int64 # minimal capacity for each district during each weekhour const exchange_prio = 5::Int64 # till which priority can cars be exchanged to foreign districts const patrol_prio = 5::Int64 # till which priority can patrol cars be dispatched as backup const patrol_ratio = 0.00::Float64 # which proportion of the ressources is assigned to be on patrol const patrol_time = 5.00::Float64 # maximal driving time for a patrol car dispatch as help const patrol_area = 5::Int64 # time spent patrolling per basic area const backlog_max = 60::Int64 # maximal average backlog (minutes) per car in district for exchange const max_queue = 80::Int64 # maximal length of the queue of incidents per district and priority const real_capacity = false::Bool # state whether a predefined capacity plan should be loaded const drop_incident = 360::Int64 # total number of minutes after which an incident # will leave the queue even if it's not fully fulfilled # state the main parameters for the capacity estimation if no capacity plan is given const total_capacity = 50.0::Float64 # average capacity per hour in the area over the incident timeframe const capacity_service = 0.90::Float64 # alpha service level for weekhour workload estimation # state how many cars should be reserved for the own district per incident priority # during exchanges to other districts this threshold will not be crossed # important: the exchange_reserve has to equal the number of priorities exchange_reserve = [0,0,0,0,0] # state whether to save the plotted results const save_plots = true::Bool # save the plots # lock to avoid racing conditions during the simulation ren_lock = ReentrantLock() # load the input data include("2_define_data.jl") print("\n Input data sucessfully loaded.") # prepare the input data for stage 1 (also neccessary for stage 2!) # append the weekhour to the incident dataset incidents.weekhour = epoch_weekhour.(incidents.epoch) # prepare the workload for each BA if allocated to a potential center if isfile("data/$problem/workload_$problem.csv") workload = readdlm("data/$problem/workload_$problem.csv", Float64) we = readdlm("data/$problem/weight_$problem.csv", Float64)[:,1] print("\n Workload and weight recovered from saved file.") else dur = @elapsed workload, we = workload_calculation(incidents::DataFrame, prio_weight::Vector{Int64}, drivingtime::Array{Float64,2}, traffic::Array{Float64,2}, size(airdist,1)::Int64) workload = round.(workload, digits = 3) writedlm("data/$problem/workload_$problem.csv", workload) writedlm("data/$problem/weight_$problem.csv", we) print("\n Finished workload and weight calculation after ",dur," seconds.") end # prepare the sets for the contiguity and compactness constraints dur = @elapsed N, M, card_n, card_m = sets_m_n(airdist::Array{Float64,2}, size(airdist,1)::Int64) print("\n Finished set calculation after ", dur," seconds.") print("\n Input sucessfully prepared for both stages.") # state which problem and constraints will be the aim of the framework print("\n Framework will be applied to the problem ",subproblem," with the constraint set ", compactness,".") # district optimisation (framework stage 1) if framework != "stage 2" print("\n Starting optimisation.") # Create a Dataframe to save the main results opt_out = DataFrame(prbl = String[], cmpct = String[], objv = Float64[], gp = Float64[], time = Float64[]) # Start the optimisation model X, gap, objval, scnds = model_and_optimise(solver, number_districts, drivingtime, we, workload, adjacent, N, M, card_n, card_m, max_drive, compactness, potential_locations, nearby_radius, nearby_districts, current_locations, fixed_locations) districts = create_frame(X, size(airdist,1)) print("\n Duration of the optimisation: ", scnds, " seconds") # Save the optimisation results and district layouts CSV.write("results_stage1/$problem/district_layout_$(problem)_$(subproblem)_$(compactness).csv", districts) push!(opt_out, (prbl = problem, cmpct = compactness, objv = objval, gp = gap, time = scnds)) CSV.write("results_stage1/$problem/optimisation_$(problem)_$(subproblem)_$(compactness).csv", opt_out) print("\n Results from stage 1 written to file.") # Plot the resulting district layout if plot_district && hexshape !== nothing district_plot = plot_generation(districts, hexshape) display(district_plot) if save_plots == 1 savefig("graphs/$problem/district_layout_$(problem)_$(subproblem)_$(compactness).pdf") end end # End stage 1 of the framework end # emergency service simulation (framework stage 2) if framework != "stage 1" # prepare the input data for the simulation # load the district layout in case solely stage 2 is executed if isfile("results_stage1/$problem/district_layout_$(problem)_$(subproblem)_$(compactness).csv") districts = CSV.read("results_stage1/$problem/district_layout_$(problem)_$(subproblem)_$(compactness).csv", DataFrame) districts[!,:index] = convert.(Int64,districts[!,:index]) districts[!,:location] = convert.(Int64,districts[!,:location]) print("\n Districts loaded from file.") else error("Perform stage 1 first, to determine the district layouts.") end # prepare the input data for stage 2 sim_data = prepare_simulation_data(incidents, districts) ## simulation_capacity: apply a heuristic to derive the capacity of each location in each weekhour simulation_capacity, capacity_plot = capacity_heuristic(incidents,sim_data,total_capacity,min_capacity) ## ressource_flow: fill the intial ressource flow matrix of the simulation ressource_flow = ressource_flow_matrix(sim_data, incidents, simulation_capacity) print("\n Input sucessfully prepared for simulation.") print("\n Ressource matrix build.","\n") # pepare the execution of multiple simulation runs weekly_location = DataFrame() weekly_priority = DataFrame() capacity_status = DataFrame() main_results = DataFrame() # start the simulation print("\n Starting ", sim_number," emergency service simulations.") Threads.@threads for sim_run = 1:sim_number rfw = copy(ressource_flow) smd = copy(sim_data) scnds = @elapsed smd,rfw = part2_simulation!(districts::DataFrame, incidents::DataFrame, smd::DataFrame, rfw::Array{Int64,3}, drivingtime::Array{Float64,2}, traffic::Array{Float64,2}, max_drive::Float64, drop_incident::Int64, exchange_reserve::Vector{Int64}) main_results_local, weekly_location_local, weekly_priority_local, capacity_status_local = evaluate_results(incidents, smd, rfw, simulation_capacity) # save the results for later evaluation weekly_location_local[:,:simulation_run] .= sim_run weekly_priority_local[:,:simulation_run] .= sim_run capacity_status_local[:,:simulation_run] .= sim_run main_results_local[:,:simulation_run] .= sim_run Threads.lock(ren_lock) do append!(weekly_location, weekly_location_local) append!(weekly_priority, weekly_priority_local) append!(capacity_status, capacity_status_local) append!(main_results, main_results_local) end print("\n Simulation ",nrow(main_results)," of ", sim_number," completed after ", scnds, " seconds on thread ",Threads.threadid()) end # Aggregate the results of all simulations weekly_location = groupby(weekly_location,[:location_responsible, :weekhour]) weekly_location = combine(weekly_location, [n => mean => n for n in names(weekly_location) if n != "simulation_run"]) weekly_location = round.(weekly_location, digits = 5) weekly_priority = groupby(weekly_priority,[:weekhour,:priority]) weekly_priority = combine(weekly_priority, [n => mean => n for n in names(weekly_priority) if n != "simulation_run"]) weekly_priority = round.(weekly_priority, digits = 5) capacity_status = groupby(capacity_status,[:weekhour,:variable]) capacity_status = combine(capacity_status, :value => mean => :value) main_results = combine(main_results, [n => mean => n for n in names(main_results) if n != "simulation_run"]) main_results = round.(main_results, digits = 5) main_priority = groupby(weekly_priority, :priority) main_priority = combine(main_priority, [n => mean => n for n in names(main_priority) if n != "weekhour"]) main_priority = round.(main_priority, digits = 5) print("\n\n Main results of simulation:") print("\n Average dispatch time first car: ", main_results[1,:dispatch_time_first]) for prio = 1:nrow(main_priority) print("\n Average dispatch time priority ", prio,": ", main_priority[prio,:dispatch_time_first]) end print("\n Average dispatch time all cars: ", main_results[1,:dispatch_time_all]) print("\n Average response time first car: ", main_results[1,:response_time_first]) for prio = 1:nrow(main_priority) print("\n Average response time priority ", prio,": ", main_priority[prio,:response_time_first]) end print("\n Average response time all cars: ", main_results[1,:response_time_all]) print("\n Average exchange ratio: ", main_results[1,:exchange_ratio]) print("\n Average ratio undispatched cars: ", main_results[1,:ratio_cars_undispatched]) print("\n Unfullfilled calls for service: ", main_results[1,:incidents_unfulfilled]) # Plot the aggregated results plot_simulation_results(weekly_location, weekly_priority, capacity_status, capacity_plot, subproblem, compactness) # Save the main results of the simulation CSV.write("results_stage2/$problem/simulation_$(problem)_$(subproblem)_$(compactness).csv", main_results) print("\n Results from stage 2 written to file. Framework ended.") print("\n") end print("\n")
%!TEX root = ../main.tex \subsection{Properties of Lines} \objective{Classify linear and linear-like functions, and explain relationships of slopes.} All non-vertical lines have slope, which is defined as rise over run, $\frac{\Delta x}{\Delta y}$ or $m$. The initial value of a linear equation might not be zero, but an ordered pair of the form $(0,b)$. The variable $b$ is called the $y-$intercept. All together, this is the famous $y=mx+b$ form of lines. \marginfig[-0.1in]{\chapdir/pics/ceiling_function}{The ceiling function.} However, that formula only makes sense when the origin is within view and we might become concerned with the output-value when the input is 0. In calculus and other areas of mathematics, we are more often simply interested in the slope and some arbitrary point, $(x_1,y_1)$. Hence we find a majority of time from here on out, the point-slope form of \index{linear!point-slope form} linear equation is most helpful, $y-y_1=m(x-x_1)$, a form which allows us to see the slope, and a (random?) point on the line very easily. This form is nearly as easy to put in your TI-8* as your old friend slope-intercept: simply add $y_1$ to the other side, and you have a $y=$ form ready to be entered in your grapher. \subsection{Parallel vs. Perpendicular} If a line has slope expressed via the fraction in lowest terms $\frac{a}{b}$, then any other fraction that reduces to the same ratio will produce a line parallel to the first. Consider the sketch of how to make a line rotated $90^\circ$ clockwise or counterclockwise to the first. They will have slopes of $\frac{-b}{a}$ or $\frac{b}{-a}$, which are the same things. In short, perpendicular lines have opposite reciprocal slope.\index{linear!parallel} \index{linear!perpendicular} \subsection{Linear-like} Several functions are linear in pieces, and are used in computer programming and other systems of functions \subsubsection{Ceiling, Floor, and Round} Various forms of rounding are present in computer systems and your TI-8*. Rounding down in all cases, rounding up in call cases, and the familiar rounding to the closest. \marginfig[-1.0in]{\chapdir/pics/floor_function}{The floor function} \subsubsection{Modulus} The most used function in this respect, and the foundation of an entire species of mathematics (called Modular Arithmetic) is the modulus function. It can be thought of as taking two arguments, one is what to divide by, and the other is what to divide. The function returns the remainder. For example, 10 mod 3 is 1, and 49 mod 7 is 0. Consider the graph of y=x mod 5. \subsubsection{Rates of Change} A constant function is one that never changes (by definition). \index{constant!derivative} Algebraically, that means it is of the form $y=c$, where $c$ is some numbers. The slope is always zero and the graph is always a horizontal line. A vertical line is not a function and its slope is undefined. Every other line has a constant rate of change, it's slope. In calculus terminology, it's derivative is a constant.
Formal statement is: lemma bounded_connected_Compl_real: fixes S :: "real set" assumes "bounded S" and conn: "connected(- S)" shows "S = {}" Informal statement is: If $S$ is a bounded set and $-S$ is connected, then $S$ is empty.
function [X12,x1,x2] = DigitalOscillator(f1,f2,Fs,t1) % Function to simulate Digital Sinusodial Oscillator % Input Variables % f1 = first input analog frequency Suggested Range(697-1477) % f2 = second input analog frequency Suggested Range(697-1477 % Fs = Sampling Frequency Default = 8000 cycles/sec % t1 = Tone Length Default = .1 sec % % Output Variables % Y = Sine Signal for two given frequencies % x1 = Sine Signal for first frequency % x2 = Sine Signal for second frequency % % Rajiv Singla DSP Final Project Fall 2005 %===================================================================== % Checking for minimum number of arguments if nargin < 2 error('Not enough input arguments'); end % Setting Default values if nargin == 2 Fs = 8000; t1 = 0.1; end Ts=1/Fs; %Sampling Time samples=t1/Ts; %Number of samples in the tone %% Generating first Signal w0=2*3.1416*f1/Fs; A=1; a1=-2*cos(w0); Y1=0; Y2=-A*sin(w0); for n=1:samples x1(n)=-a1*Y1-Y2; Y2=Y1; Y1=x1(n); end x1=[0 x1]; %appending zero in the beginning %% Generating second Signal w1=2*3.1416*f2/Fs; A=1; a2=-2*cos(w1); P1=0; P2=-A*sin(w1); for n=1:samples x2(n)=-a2*P1-P2; P2=P1; P1=x2(n); end x2=[0 x2]; %appending zero in the beginning %% Combining both signal X12 = .5*(x1 + x2);
-- exercises in "Type-Driven Development with Idris" -- chapter 6 -- check that all functions are total %default total data Format = Number Format | Doubble Format | Str Format | Chhar Format | Lit String Format | End %name Format fmt, fmt1, fmt2, fmt3 PrintfType : Format -> Type PrintfType (Number fmt) = (i : Int) -> PrintfType fmt PrintfType (Doubble fmt) = (d : Double) -> PrintfType fmt PrintfType (Str fmt) = (str : String) -> PrintfType fmt PrintfType (Chhar fmt) = (car : Char) -> PrintfType fmt PrintfType (Lit str fmt) = PrintfType fmt PrintfType End = String printFmt : (fmt : Format) -> (acc : String) -> PrintfType fmt printFmt (Number fmt) acc = \i => printFmt fmt (acc ++ show i) printFmt (Doubble fmt) acc = \d => printFmt fmt (acc ++ show d) printFmt (Str fmt) acc = \str => printFmt fmt (acc ++ str) printFmt (Chhar fmt) acc = \char => printFmt fmt (acc ++ show char) printFmt (Lit str fmt) acc = printFmt fmt (acc ++ str) printFmt End acc = acc toFormat : (xs : List Char) -> Format toFormat [] = End toFormat ('%' :: 'd' :: chars) = Number (toFormat chars) toFormat ('%' :: 'f' :: chars) = Doubble (toFormat chars) toFormat ('%' :: 's' :: chars) = Str (toFormat chars) toFormat ('%' :: 'c' :: chars) = Chhar (toFormat chars) toFormat ('%' :: chars) = Lit "%" (toFormat chars) toFormat (c :: chars) = case toFormat chars of Lit str chars' => Lit (strCons c str) chars' fmt => Lit (strCons c "") fmt printf : (fmt : String) -> PrintfType (toFormat (unpack fmt)) printf fmt = printFmt _ "" -- > :t printf "%s = %d" -- printf "%s = %d" : String -> Int -> String -- > :t printf "%c %f" -- printf "%c %f" : Char -> Double -> String -- > printf "%c %f" 'X' 24 -- "'X' 24.0" : String
If $d \leq e$, then the closed ball of radius $d$ centered at $x$ is contained in the closed ball of radius $e$ centered at $x$.
theory Strict_Omega_Category imports Globular_Set begin section \<open>Strict $\omega$-categories\<close> text \<open> First, we define a locale \<open>pre_strict_omega_category\<close> that holds the data of a strict $\omega$-category without the associativity, unity and exchange axioms \cite[Def 1.4.8 (a) - (b)]{Leinster2004}. We do this in order to set up convenient notation before we state the remaining axioms. \<close> locale pre_strict_omega_category = globular_set + fixes comp :: "nat \<Rightarrow> nat \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> 'a" and i :: "nat \<Rightarrow> 'a \<Rightarrow> 'a" assumes comp_fun: "is_composable_pair m n x' x \<Longrightarrow> comp m n x' x \<in> X m" and i_fun: "i n \<in> X n \<rightarrow> X (Suc n)" and s_comp_Suc: "is_composable_pair (Suc m) m x' x \<Longrightarrow> s m (comp (Suc m) m x' x) = s m x" and t_comp_Suc: "is_composable_pair (Suc m) m x' x \<Longrightarrow> t m (comp (Suc m) m x' x) = t m x'" and s_comp: "\<lbrakk>is_composable_pair (Suc m) n x' x; n < m\<rbrakk> \<Longrightarrow> s m (comp (Suc m) n x' x) = comp m n (s m x') (s m x)" and t_comp: "\<lbrakk>is_composable_pair (Suc m) n x' x; n < m\<rbrakk> \<Longrightarrow> t m (comp (Suc m) n x' x) = comp m n (t m x') (s m x)" and s_i: "x \<in> X n \<Longrightarrow> s n (i n x) = x" and t_i: "x \<in> X n \<Longrightarrow> t n (i n x) = x" begin text \<open>Similar to the generalised source and target maps in \<open>globular_set\<close>, we defined a generalised identity map. The first argument gives the dimension of the resulting identity cell, while the second gives the dimension of the input cell.\<close> fun i' :: "nat \<Rightarrow> nat \<Rightarrow> 'a \<Rightarrow> 'a" where "i' 0 0 = id" | "i' 0 (Suc n) = undefined" | "i' (Suc m) n = (if Suc m < n then undefined else if Suc m = n then id else i m \<circ> i' m n)" lemma i'_n_n [simp]: "i' n n = id" by (metis i'.elims i'.simps(1) less_irrefl_nat) lemma i'_Suc_n_n [simp]: "i' (Suc n) n = i n" by simp lemma i'_Suc [simp]: "n \<le> m \<Longrightarrow> i' (Suc m) n = i m \<circ> i' m n" by fastforce lemma i'_Suc': "n < m \<Longrightarrow> i' m n = i' m (Suc n) \<circ> i n" proof (induction m arbitrary: n) case 0 then show ?case by blast next case (Suc m) then show ?case by force qed lemma i'_fun: "n \<le> m \<Longrightarrow> i' m n \<in> X n \<rightarrow> X m" proof (induction m arbitrary: n) case 0 then show ?case by fastforce next case (Suc m) thus ?case proof (cases "n = Suc m") case True then show ?thesis by auto next case False hence "n \<le> m" using `n \<le> Suc m` by force thus ?thesis using Suc.IH i_fun by auto qed qed end text \<open>Now we may define a strict $\omega$-category including the composition, unity and exchange axioms \cite[Def 1.4.8 (c) - (f)]{Leinster2004}.\<close> locale strict_omega_category = pre_strict_omega_category + assumes comp_assoc: "\<lbrakk>is_composable_pair m n x' x; is_composable_pair m n x'' x'\<rbrakk> \<Longrightarrow> comp m n (comp m n x'' x') x = comp m n x'' (comp m n x' x)" and i_comp: "\<lbrakk>n < m; x \<in> X m\<rbrakk> \<Longrightarrow> comp m n (i' m n (t' m n x)) x = x" and comp_i: "\<lbrakk>n < m; x \<in> X m\<rbrakk> \<Longrightarrow> comp m n x (i' m n (s' m n x)) = x" and bin_interchange: "\<lbrakk>q < p; p < m; is_composable_pair m p y' y; is_composable_pair m p x' x; is_composable_pair m q y' x'; is_composable_pair m q y x\<rbrakk> \<Longrightarrow> comp m q (comp m p y' y) (comp m p x' x) = comp m p (comp m q y' x') (comp m q y x)" and null_interchange: "\<lbrakk>q < p; is_composable_pair p q x' x\<rbrakk> \<Longrightarrow> comp (Suc p) q (i p x') (i p x) = i p (comp p q x' x)" locale strict_omega_functor = globular_map + source: strict_omega_category X s\<^sub>X t\<^sub>X comp\<^sub>X i\<^sub>X + target: strict_omega_category Y s\<^sub>Y t\<^sub>Y comp\<^sub>Y i\<^sub>Y for comp\<^sub>X i\<^sub>X comp\<^sub>Y i\<^sub>Y + assumes commute_with_comp: "is_composable_pair m n x' x \<Longrightarrow> \<phi> m (comp\<^sub>X m n x' x) = comp\<^sub>Y m n (\<phi> m x') (\<phi> m x)" and commute_with_id: "x \<in> X n \<Longrightarrow> \<phi> (Suc n) (i\<^sub>X n x) = i\<^sub>Y n (\<phi> n x)" end
function [y,n] = ADEM_plaid(x,n) % creates a Gaussian modulated n x n visual plaid stimulus % FORMAT [y,n] = ADEM_plaid(x,[n]) % x(1) - horizontal displacement % x(2) - vertical displacement %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Karl Friston % $Id: ADEM_plaid.m 3655 2009-12-23 20:15:34Z karl $ % default stimulus %-------------------------------------------------------------------------- try n; catch n = 4; end % stimulus %-------------------------------------------------------------------------- sx = [1:n]'; sx = sx - n/2 - n*x(1)/8; sy = [1:n] ; sy = sy - n/2 - n*x(2)/8; sx = exp(-sx.^2/(2*(n/6)^2)).*cos(2*pi*sx*2/n); sy = exp(-sy.^2/(2*(n/6)^2)).*cos(2*pi*sy*2/n); % vectorise under defaults %-------------------------------------------------------------------------- if nargin > 1 y = sx*sy; else y = spm_vec(sx*sy); end
Load LFindLoad. From lfind Require Import LFind. From QuickChick Require Import QuickChick. From adtind Require Import goal33. Derive Show for natural. Derive Arbitrary for natural. Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed. Lemma conj5synthconj5 : forall (lv0 : natural), (@eq natural (lv0) (plus lv0 Zero)). Admitted. QuickChick conj5synthconj5.
@testset "montecarlo" begin end
(* Title: HOL/Library/Product_Lexorder.thy Author: Norbert Voelker *) section \<open>Lexicographic order on product types\<close> theory Product_Lexorder imports MainRLT begin instantiation prod :: (ord, ord) ord begin definition "x \<le> y \<longleftrightarrow> fst x < fst y \<or> fst x \<le> fst y \<and> snd x \<le> snd y" definition "x < y \<longleftrightarrow> fst x < fst y \<or> fst x \<le> fst y \<and> snd x < snd y" instance .. end lemma less_eq_prod_simp [simp, code]: "(x1, y1) \<le> (x2, y2) \<longleftrightarrow> x1 < x2 \<or> x1 \<le> x2 \<and> y1 \<le> y2" by (simp add: less_eq_prod_def) lemma less_prod_simp [simp, code]: "(x1, y1) < (x2, y2) \<longleftrightarrow> x1 < x2 \<or> x1 \<le> x2 \<and> y1 < y2" by (simp add: less_prod_def) text \<open>A stronger version for partial orders.\<close> lemma less_prod_def': fixes x y :: "'a::order \<times> 'b::ord" shows "x < y \<longleftrightarrow> fst x < fst y \<or> fst x = fst y \<and> snd x < snd y" by (auto simp add: less_prod_def le_less) instance prod :: (preorder, preorder) preorder by standard (auto simp: less_eq_prod_def less_prod_def less_le_not_le intro: order_trans) instance prod :: (order, order) order by standard (auto simp add: less_eq_prod_def) instance prod :: (linorder, linorder) linorder by standard (auto simp: less_eq_prod_def) instantiation prod :: (linorder, linorder) distrib_lattice begin definition "(inf :: 'a \<times> 'b \<Rightarrow> _ \<Rightarrow> _) = min" definition "(sup :: 'a \<times> 'b \<Rightarrow> _ \<Rightarrow> _) = max" instance by standard (auto simp add: inf_prod_def sup_prod_def max_min_distrib2) end instantiation prod :: (bot, bot) bot begin definition "bot = (bot, bot)" instance .. end instance prod :: (order_bot, order_bot) order_bot by standard (auto simp add: bot_prod_def) instantiation prod :: (top, top) top begin definition "top = (top, top)" instance .. end instance prod :: (order_top, order_top) order_top by standard (auto simp add: top_prod_def) instance prod :: (wellorder, wellorder) wellorder proof fix P :: "'a \<times> 'b \<Rightarrow> bool" and z :: "'a \<times> 'b" assume P: "\<And>x. (\<And>y. y < x \<Longrightarrow> P y) \<Longrightarrow> P x" show "P z" proof (induct z) case (Pair a b) show "P (a, b)" proof (induct a arbitrary: b rule: less_induct) case (less a\<^sub>1) note a\<^sub>1 = this show "P (a\<^sub>1, b)" proof (induct b rule: less_induct) case (less b\<^sub>1) note b\<^sub>1 = this show "P (a\<^sub>1, b\<^sub>1)" proof (rule P) fix p assume p: "p < (a\<^sub>1, b\<^sub>1)" show "P p" proof (cases "fst p < a\<^sub>1") case True then have "P (fst p, snd p)" by (rule a\<^sub>1) then show ?thesis by simp next case False with p have 1: "a\<^sub>1 = fst p" and 2: "snd p < b\<^sub>1" by (simp_all add: less_prod_def') from 2 have "P (a\<^sub>1, snd p)" by (rule b\<^sub>1) with 1 show ?thesis by simp qed qed qed qed qed qed text \<open>Legacy lemma bindings\<close> lemmas prod_le_def = less_eq_prod_def lemmas prod_less_def = less_prod_def lemmas prod_less_eq = less_prod_def' end
cc ------------ dpmjet3.4 - authors: S.Roesler, R.Engel, J.Ranft ------- cc -------- phojet1.12-40 - authors: S.Roesler, R.Engel, J.Ranft ------- cc - oct'13 ------- cc ----------- pythia-6.4 - authors: Torbjorn Sjostrand, Lund'10 ------- cc --------------------------------------------------------------------- cc converted for use with FLUKA ------- cc - oct'13 ------- C...PYONOF C...Switches on and off decay channel by search for match. SUBROUTINE PYONOF(CHIN) C...Double precision and integer declarations. IMPLICIT DOUBLE PRECISION(A-H, O-Z) IMPLICIT INTEGER(I-N) INTEGER PYCOMP C...Commonblocks. include 'inc/pydat1' include 'inc/pydat3' C...Local arrays and character variables. INTEGER KFCMP(10),KFTMP(10) CHARACTER CHIN*(*),CHTMP*104,CHFIX*104,CHMODE*10,CHCODE*8, &CHALP(2)*26 DATA CHALP/'abcdefghijklmnopqrstuvwxyz', &'ABCDEFGHIJKLMNOPQRSTUVWXYZ'/ C...Determine length of character variable. CHTMP=CHIN//' ' LBEG=0 100 LBEG=LBEG+1 IF(CHTMP(LBEG:LBEG).EQ.' ') GOTO 100 LEND=LBEG-1 105 LEND=LEND+1 IF(LEND.LE.100.AND.CHTMP(LEND:LEND).NE.'!') GOTO 105 110 LEND=LEND-1 IF(CHTMP(LEND:LEND).EQ.' ') GOTO 110 LEN=1+LEND-LBEG CHFIX(1:LEN)=CHTMP(LBEG:LEND) C...Find colon separator and particle code. LCOLON=0 120 LCOLON=LCOLON+1 IF(CHFIX(LCOLON:LCOLON).NE.':') GOTO 120 CHCODE=' ' CHCODE(10-LCOLON:8)=CHFIX(1:LCOLON-1) READ(CHCODE,'(I8)',ERR=300) KF KC=PYCOMP(KF) C...Done if unknown code or no decay channels. IF(KC.EQ.0) THEN CALL PYERRM(18,'(PYONOF:) unrecognized particle '//CHCODE) RETURN ENDIF IDCBEG=MDCY(KC,2) IDCLEN=MDCY(KC,3) IF(IDCBEG.EQ.0.OR.IDCLEN.EQ.0) THEN CALL PYERRM(18,'(PYONOF:) no decay channels for '//CHCODE) RETURN ENDIF C...Find command name up to blank or equal sign. LSEP=LCOLON 130 LSEP=LSEP+1 IF(LSEP.LE.LEN.AND.CHFIX(LSEP:LSEP).NE.' '.AND. &CHFIX(LSEP:LSEP).NE.'=') GOTO 130 CHMODE=' ' LMODE=LSEP-LCOLON-1 CHMODE(1:LMODE)=CHFIX(LCOLON+1:LSEP-1) C...Convert to uppercase. DO 150 LCOM=1,LMODE DO 140 LALP=1,26 IF(CHMODE(LCOM:LCOM).EQ.CHALP(1)(LALP:LALP)) & CHMODE(LCOM:LCOM)=CHALP(2)(LALP:LALP) 140 CONTINUE 150 CONTINUE C...Identify command. Failed if not identified. MODE=0 IF(CHMODE.EQ.'ALLOFF') MODE=1 IF(CHMODE.EQ.'ALLON') MODE=2 IF(CHMODE.EQ.'OFFIFANY') MODE=3 IF(CHMODE.EQ.'ONIFANY') MODE=4 IF(CHMODE.EQ.'OFFIFALL') MODE=5 IF(CHMODE.EQ.'ONIFALL') MODE=6 IF(CHMODE.EQ.'OFFIFMATCH') MODE=7 IF(CHMODE.EQ.'ONIFMATCH') MODE=8 IF(MODE.EQ.0) THEN CALL PYERRM(18,'(PYONOF:) unknown command '//CHMODE) RETURN ENDIF C...Simple cases when all on or all off. IF(MODE.EQ.1.OR.MODE.EQ.2) THEN WRITE(MSTU(11),1000) KF,CHMODE DO 160 IDC=IDCBEG,IDCBEG+IDCLEN-1 IF(MDME(IDC,1).LT.0) GOTO 160 MDME(IDC,1)=MODE-1 160 CONTINUE RETURN ENDIF C...Identify matching list. NCMP=0 LBEG=LSEP 170 LBEG=LBEG+1 IF(LBEG.GT.LEN) GOTO 190 IF(LBEG.LT.LEN.AND.(CHFIX(LBEG:LBEG).EQ.' '.OR. &CHFIX(LBEG:LBEG).EQ.'='.OR.CHFIX(LBEG:LBEG).EQ.',')) GOTO 170 LEND=LBEG-1 180 LEND=LEND+1 IF(LEND.LT.LEN.AND.CHFIX(LEND:LEND).NE.' '.AND. &CHFIX(LEND:LEND).NE.'='.AND.CHFIX(LEND:LEND).NE.',') GOTO 180 IF(LEND.LT.LEN) LEND=LEND-1 CHCODE=' ' CHCODE(8-LEND+LBEG:8)=CHFIX(LBEG:LEND) READ(CHCODE,'(I8)',ERR=300) KFREAD NCMP=NCMP+1 KFCMP(NCMP)=ABS(KFREAD) LBEG=LEND IF(NCMP.LT.10) GOTO 170 190 CONTINUE WRITE(MSTU(11),1100) KF,CHMODE,(KFCMP(ICMP),ICMP=1,NCMP) C...Only one matching required. IF(MODE.EQ.3.OR.MODE.EQ.4) THEN DO 220 IDC=IDCBEG,IDCBEG+IDCLEN-1 IF(MDME(IDC,1).LT.0) GOTO 220 DO 210 IKF=1,5 KFNOW=ABS(KFDP(IDC,IKF)) IF(KFNOW.EQ.0) GOTO 210 DO 200 ICMP=1,NCMP IF(KFCMP(ICMP).EQ.KFNOW) THEN MDME(IDC,1)=MODE-3 GOTO 220 ENDIF 200 CONTINUE 210 CONTINUE 220 CONTINUE RETURN ENDIF C...Multiple matchings required. DO 260 IDC=IDCBEG,IDCBEG+IDCLEN-1 IF(MDME(IDC,1).LT.0) GOTO 260 NTMP=NCMP DO 230 ITMP=1,NTMP KFTMP(ITMP)=KFCMP(ITMP) 230 CONTINUE NFIN=0 DO 250 IKF=1,5 KFNOW=ABS(KFDP(IDC,IKF)) IF(KFNOW.EQ.0) GOTO 250 NFIN=NFIN+1 DO 240 ITMP=1,NTMP IF(KFTMP(ITMP).EQ.KFNOW) THEN KFTMP(ITMP)=KFTMP(NTMP) NTMP=NTMP-1 GOTO 250 ENDIF 240 CONTINUE 250 CONTINUE IF(NTMP.EQ.0.AND.MODE.LE.6) MDME(IDC,1)=MODE-5 IF(NTMP.EQ.0.AND.NFIN.EQ.NCMP.AND.MODE.GE.7) & MDME(IDC,1)=MODE-7 260 CONTINUE RETURN C...Error exit for impossible read of particle code. 300 CALL PYERRM(18,'(PYONOF:) could not interpret particle code ' &//CHCODE) C...Formats for output. 1000 FORMAT(' Decays for',I8,' set ',A10) 1100 FORMAT(' Decays for',I8,' set ',A10,' if match',10I8) RETURN END
import System.Random main : IO () main = do value <- randomRIO (the Double 10, the Double 30.5) printLn $ value > 10
proposition\<^marker>\<open>tag unimportant\<close> Cauchy_theorem_triangle_cofinite: assumes "continuous_on (convex hull {a,b,c}) f" and "finite S" and "(\<And>x. x \<in> interior(convex hull {a,b,c}) - S \<Longrightarrow> f field_differentiable (at x))" shows "(f has_contour_integral 0) (linepath a b +++ linepath b c +++ linepath c a)"
Formal statement is: lemma continuous_on_iff: "continuous_on s f \<longleftrightarrow> (\<forall>x\<in>s. \<forall>e>0. \<exists>d>0. \<forall>x'\<in>s. dist x' x < d \<longrightarrow> dist (f x') (f x) < e)" Informal statement is: A function $f$ is continuous on a set $S$ if and only if for every $x \in S$ and every $\epsilon > 0$, there exists a $\delta > 0$ such that for every $x' \in S$, if $|x' - x| < \delta$, then $|f(x') - f(x)| < \epsilon$.
/** * Copyright (C) 2014 yvt <[email protected]>. * * 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. */ #pragma once #include <boost/asio.hpp> #include <string> namespace mcore { std::pair<boost::asio::ip::address, int> parseEndpoint(const std::string&); boost::asio::ip::tcp::endpoint parseTcpEndpoint(const std::string&); template <class T> void serializeDictionary(std::vector<char> &output, const T& dic) { for (const auto& ent: dic) { }; } template <class T> std::vector<char> serializeDictionary(const T& dic) { std::vector<char> buffer; buffer.reserve(512); serializeDictionary(buffer, dic); return buffer; } class CountingCombiner { public: using result_type = std::size_t; template <class Iterator> result_type operator()(Iterator first, Iterator last) const { std::size_t count = 0; while (first != last) { try { *first; } catch(const boost::signals2::expired_slot &) {} ++first; ++count; } return count; } }; }
Formal statement is: lemma setdist_neq_0_sing_1: "\<lbrakk>setdist {x} S = a; a \<noteq> 0\<rbrakk> \<Longrightarrow> S \<noteq> {} \<and> x \<notin> closure S" Informal statement is: If the distance between a point $x$ and a set $S$ is nonzero, then $S$ is nonempty and $x$ is not in the closure of $S$.
Require Import Nat List Bool PeanoNat Orders. Require Import Coq.Structures.OrdersFacts. Require Import Coq.Relations.Relation_Definitions. Require Import Coq.Sorting.Sorted. Require Import Coq.Sorting.Permutation. Require Import Sorticoq.SortedList. Require Import Sorticoq.BinaryTree. Import ListNotations. Module TreeSort (Import O: UsualOrderedTypeFull'). (* Module Bdefs := UsualOrderedTypeFull'_to_BinaryTree O. Import Bdefs. *) Include (BinaryTree_over_OrderedType O). Fixpoint makeBST (l: list A) : BinaryTree := match l with | nil => BT_nil | h::t => BST_Insert (makeBST t) h end. Lemma makeBST_ok: forall x (l: list A), In_tree x (makeBST l) <-> In x l. Proof. split; intros; induction l; simpl in *; [inversion H | idtac | inversion H | idtac ]. - apply In_tree_insert in H; intuition. - apply In_insert_cond; intuition. Qed. Definition Treesort (l: list A) : list A := BT_get_list (makeBST l). Lemma Treesort_is_LocallySorted: forall l, LocallySorted lte (Treesort l). Proof. intros. apply BST_is_LocallySorted. induction l; simpl; auto. apply Insert_not_change_BSTSP. assumption. Qed. Lemma Treesort_Permutation: forall l, Permutation l (Treesort l). Proof. induction l; simpl; auto. unfold Treesort in *. simpl. remember (BST_Insert _ a) as Tr. symmetry in HeqTr. apply BST_Insert_emplace in HeqTr. destruct HeqTr as [e1 [e2 [H' H'']]]. rewrite <- H'. rewrite <- H'' in IHl. simpl. apply Permutation_cons_app. auto. Qed. Theorem Treesort_is_sorting_algo: is_sorting_algo lte Treesort. Proof. unfold is_sorting_algo. split. - apply Treesort_Permutation. - apply Sorted_LocallySorted_iff. apply Treesort_is_LocallySorted. Qed. End TreeSort.
lemma is_unit_monom_0: fixes a :: "'a::field" assumes "a \<noteq> 0" shows "is_unit (monom a 0)"
import Control.Monad.State data Tree a = Empty | Node (Tree a) a (Tree a) testTree : Tree String testTree = Node (Node (Node Empty "Jim" Empty) "Fred" (Node Empty "Sheila" Empty)) "Alice" (Node Empty "Bob" (Node Empty "Eve" Empty)) testStream : Stream Int testStream = [1..] flatten : Tree a -> List a flatten Empty = [] flatten (Node left val right) = flatten left ++ (val :: flatten right) labelTreeWith : Stream label -> Tree elem -> (Stream label, Tree (label, elem)) labelTreeWith lbls Empty = (lbls, Empty) labelTreeWith lbls (Node l e r) = let (forThis :: forRight, lbldLeft) = labelTreeWith lbls l (forNext, lbldRight) = labelTreeWith forRight r in (forNext, Node lbldLeft (forThis, e) lbldRight) labelTreeWith2 : Tree a -> State (Stream label) (Tree (label, a)) labelTreeWith2 Empty = pure Empty labelTreeWith2 (Node left elem right) = do lbldLeft <- labelTreeWith2 left (this :: rest) <- get put rest lbldRight <- labelTreeWith2 right pure (Node lbldLeft (this, elem) lbldRight) deepFirst : Tree elem -> Tree (Int, elem) deepFirst tree = snd (labelTreeWith testStream tree) deepFirst2 : Tree elem -> Tree (Int, elem) deepFirst2 tree = evalState (labelTreeWith2 tree) [1..] countEmpty : Tree elem -> State Nat () countEmpty Empty = do curr <- get put (S curr) countEmpty (Node left _ right) = do countEmpty left countEmpty right countEmptyNode : Tree elem -> State (Nat, Nat) () countEmptyNode Empty = do (currEmpties, currFull) <- get put (S currEmpties, currFull) countEmptyNode (Node left _ right) = do countEmptyNode left countEmptyNode right (currEmpties, currFull) <- get put (currEmpties, S currFull)
/* * Copyright (c) 2016-2021 lymastee, All rights reserved. * Contact: [email protected] * * This file is part of the gslib project. * * 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. */ #pragma once #ifndef utilities_9904f6c1_3075_4335_b065_c7099f52e80b_h #define utilities_9904f6c1_3075_4335_b065_c7099f52e80b_h #include <ariel/type.h> #include <gslib/std.h> #include <gslib/string.h> #include <gslib/file.h> __ariel_begin__ /* * Text format elements: * [section] { ... } * [section]:[notation] { ... } * * where sections could be nested */ extern bool io_bad_eof(const string& src, int32 curr); extern int32 io_skip_blank_charactors(const string& src, int32 start); extern int32 io_read_section_name(const string& src, string& name, int32 start); extern int32 io_read_notation(const string& src, string& notation, int32 start); extern int32 io_skip_section(const string& src, int32 start); extern int32 io_enter_section(const string& src, int32 start, gchar st = _t('{')); extern int32 io_read_line_of_section(const string& src, string& line, int32 start); /* * Binary format elements: * #[uint32][string]@[uint32] section about length(in bytes) * $[uint32][string] notation string(ASCII only) */ using gs::file; class __gs_novtable io_binary_stream abstract { public: typedef vector<int32> section_stack; enum control_type { ctl_unknown, ctl_section, ctl_notation, ctl_counter, ctl_byte_stream_field, ctl_word_stream_field, ctl_dword_stream_field, ctl_qword_stream_field, }; public: io_binary_stream(int32 size); virtual ~io_binary_stream() {} control_type read_control_type(); bool next_byte_valid() const { return next_n_bytes_valid(1); } bool next_word_valid() const { return next_n_bytes_valid(2); } bool next_dword_valid() const { return next_n_bytes_valid(4); } bool next_qword_valid() const { return next_n_bytes_valid(8); } bool next_n_bytes_valid(int32 bytes) const; void seek_to(int32 bytes); void seek_by(int32 bytes); float read_float(); double read_double(); int32 read_nstring(string& str); int32 read_string(string& str, const string& stopch); void enter_section(int32 size) { _section_stack.push_back(size); } bool exit_section(); bool skip_current_section(); bool skip_next_section(); protected: int32 _size; int32 _current; section_stack _section_stack; public: virtual byte read_byte() = 0; virtual word read_word() = 0; virtual dword read_dword() = 0; virtual qword read_qword() = 0; virtual bool read_field_to_buf(void* ptr, int32 bytes) = 0; virtual void rewind_to(int32 bytes) = 0; virtual int32 current_dev_pos() const = 0; protected: void rewind_by(int32 bytes); void take_next_n_bytes(int32 n); bool section_stack_valid(int32 bytes) const; }; class io_binary_memory: public io_binary_stream { public: io_binary_memory(const void* ptr, int32 size); virtual byte read_byte() override; virtual word read_word() override; virtual dword read_dword() override; virtual qword read_qword() override; virtual bool read_field_to_buf(void* ptr, int32 bytes) override; virtual void rewind_to(int32 bytes) override {} virtual int32 current_dev_pos() const override { return _current; } protected: const byte* _mem; }; class io_binary_file: public io_binary_stream { public: io_binary_file(file& pf); virtual byte read_byte() override; virtual word read_word() override; virtual dword read_dword() override; virtual qword read_qword() override; virtual bool read_field_to_buf(void* ptr, int32 bytes) override; virtual void rewind_to(int32 bytes) override { _file.seek(bytes, SEEK_SET); } virtual int32 current_dev_pos() const override { return _file.current(); } protected: file& _file; }; __ariel_end__ #endif
function K = covSM(Q, hyp, x, z, i) % Gaussian Spectral Mixture covariance function. The covariance function % parametrization depends on the sign of Q. % % Let t(Dx1) be an offset vector in dataspace e.g. t = x_i - z_j. Then w(DxP) % are the weights and m(Dx|Q|) = 1/p, v(Dx|Q|) = (2*pi*ell)^-2 are spectral % means (frequencies) and variances, where p is the period and ell the length % scale of the Gabor function h(t2v,tm) given by the expression % h(t2v,tm) = exp(-2*pi^2*t2v).*cos(2*pi*tm) % % Then, the two covariances are obtained as follows: % % SM, spectral mixture: Q>0 => P = 1 % k(x_i,z_j) = w'*h(v'*(t.*t),m'*t) % % SMP, spectral mixture product: Q<0 => P = D % k(x_i,z_j) = prod(w'*h(T*T*v,T*m)), T = diag(t) % % The hyperparameters are: % % hyp = [ log(w(:)) % log(m(:)) % log(sqrt(v(:))) ] % % For more help on design of covariance functions, try "help covFunctions". % % Note that the spectral density H(s) = F[ h(t) ] of covGaboriso is given by % H(s) = N(s|m,v)/2 + N(s|-m,v)/2 where m=1/p is the mean and v=(2*pi*ell)^-2 % is the variance of a symmetric Gaussian mixture. Hence the covGaboriso % covariance forms a basis for the class of stationary covariances since a % weighted sum of covGaboriso covariances corresponds to an isotropic % location-scale mixture of a symmetric Gaussian mixture in the spectral domain. % % Internally, covSM constructs a weighted sum of products of 1d covGaboriso % covariances using covMask, covProd, covScale and covSum. % % For more details, see % 1) Gaussian Process Kernels for Pattern Discovery and Extrapolation, % ICML, 2013, by Andrew Gordon Wilson and Ryan Prescott Adams. % 2) GPatt: Fast Multidimensional Pattern Extrapolation with Gaussian % Processes, arXiv 1310.5288, 2013, by Andrew Gordon Wilson, Elad Gilboa, % Arye Nehorai and John P. Cunningham, and % http://mlg.eng.cam.ac.uk/andrew/pattern % % For Q>0, covSM corresponds to Eq. 12 in Ref (1) % For Q<0, covSM corresponds to Eq. 14 in Ref (2) (but w here = w^2 in (14)) % % Copyright (c) by Andrew Gordon Wilson and Hannes Nickisch, 2014-09-24. % % See also COVFUNCTIONS.M, COVGABORISO.M, COVGABORARD.M. smp = Q<0; Q = abs(Q); % switch between covSM and covSMP mode if nargin<3 % report no of parameters if smp, K = '3*D*'; else K = '(1+2*D)*'; end, K = [K,sprintf('%d',Q)]; return end if nargin<4, z = []; end % make sure, z exists D = size(x,2); P = smp*D+(1-smp); % dimensionality, P=D or P=1 lw = reshape(hyp( 1:P*Q) ,P,Q); % log mixture weights lm = reshape(hyp(P*Q+ (1:D*Q)),D,Q); % log spectral means ls = reshape(hyp(P*Q+D*Q+(1:D*Q)),D,Q); % log spectral standard deviations % In the following, we construct nested cell arrays to finally obtain either if smp % 1) the product of weighted sums of 1d covGabor covariance functions or fac = cell(1,D); for d=1:D add = cell(1,Q); % a) addends for weighted sum of univariate Gabor functions for q=1:Q, add{q} = {'covScale',{'covMask',{d,{'covGaboriso'}}}}; end fac{d} = {'covSum',add}; % b) combine addends into sum end cov = {'covProd',fac}; % c) combine factors into product else % 2) the weighted sum of multivariate covGaborard covariance functions. % weighted sum of multivariate Gabor functions add = cell(1,Q); for q=1:Q, add{q} = {'covScale',{'covGaborard'}}; end cov = {'covSum',add}; % combine into sum end if smp % assemble hyp; covGabor is parametrised using -ls-log(2*pi) and -lm hyp = [lw(:)'/2; -ls(:)'-log(2*pi); -lm(:)']; else hyp = [lw/2; -ls-log(2*pi); -lm ]; end if nargin<5 % evaluation of the covariance K = feval(cov{:},hyp(:),x,z); else % We compute the indices j in the new hyperparameter vector hyp. The % correction constants c are needed because some hyperparameters in hyp are % powers of hyperparameters accepted by covSM. if i<=P*Q % derivatives w.r.t. w c = 0.5; if smp, j = 1+3*(i-1); else j = 1+(i-1)*(2*D+1); end elseif i<=(P+ D)*Q % derivatives w.r.t. m c = -1.0; j = i- P *Q; [j1,j2] = ind2sub([D,Q],j); if smp, j = 3+3*(j-1); else j = 1+j1+D+(j2-1)*(2*D+1); end elseif i<=(P+2*D)*Q % derivatives w.r.t. v c = -1.0; j = i-(P+D)*Q; [j1,j2] = ind2sub([D,Q],j); if smp, j = 2+3*(j-1); else j = 1+j1+ (j2-1)*(2*D+1); end else error('Unknown hyperparameter') end K = c*feval(cov{:},hyp(:),x,z,j); end
Nick Cutroneo is currently on faculty at Central Connecticut State University. There he is the adjunct professor of classical guitar teaching lessons for majors and non-majors. Nick Cutroneo is currently accepting private students as well as offering remote (Skype/FaceTime/etc...) lessons. For those interested in taking lessons with Nick, please visit his teaching website: http://www.nickcutroneoguitarstudio.com. NCGS is located out of Manchester, CT and services the Greater Hartford area of Connecticut as well as providing lessons nationally and internationally via remote lessons.
State Before: F : Type ?u.474133 α : Type u_1 β : Type ?u.474139 γ : Type ?u.474142 inst✝³ : DecidableEq α inst✝² : DecidableEq β inst✝¹ : Monoid α s t : Finset α a : α m n : ℕ inst✝ : Fintype α hn : n ≠ 0 ⊢ ↑(univ ^ n) = ↑univ State After: no goals Tactic: rw [coe_pow, coe_univ, Set.univ_pow hn]
[STATEMENT] lemma states_Times [simp]: "states (Times fsm1 fsm2) = states fsm1 * states fsm2" [PROOF STATE] proof (prove) goal (1 subgoal): 1. states (Times fsm1 fsm2) = states fsm1 * states fsm2 [PROOF STEP] by (simp add: Times_def)
subroutine t_bx use box_module implicit none type(box) :: bx bx = allbox(2) print *, bx bx = allbox_grc(bx, grow = 2) print *, bx contains function allbox_grc(bx, grow, refine, coarsen) result(r) type(box) :: r type(box), intent(in) :: bx integer, intent(in), optional :: grow, refine, coarsen integer :: dm r = bx dm = r%dim if ( present(grow) ) then else if ( present(refine) ) then else if ( present(coarsen) ) then end if end function allbox_grc end subroutine t_bx subroutine t_ba_self_intersection use bl_error_module use ml_boxarray_module use box_util_module use layout_module use bl_prof_module implicit none type(boxarray) :: ba integer :: dm integer :: ng integer, allocatable, dimension(:) :: ext, plo, phi, vsz, crsn, vrng type(ml_boxarray) :: mba character(len=64) :: test_set integer :: i, n, j, k, sz type(box) :: bx, cbx type(bl_prof_timer), save :: bpt, bpt_r, bpt_s, bpt_b integer :: cnt, cnt1, cnt2, cnt3 integer(ll_t) :: vol, vol1, vol2, vol3 integer, pointer :: ipv(:) integer :: mxsz logical :: verbose type(layout) :: la type bin integer, pointer :: iv(:) => Null() end type bin type(bin), allocatable, dimension(:,:,:) :: bins call build(bpt, "t_ba_self_intersection") verbose = .true. ng = 1 test_set = "grids.5034" test_set = "grids.1071" test_set = "grids.213" test_set = "grids.60" call build(bpt_r, "ba_read") call read_a_mglib_grid(mba, test_set) call destroy(bpt_r) ba = mba%bas(1) call build(la, ba, pd = mba%pd(1)) dm = get_dim(ba) allocate(ext(dm), plo(dm), phi(dm), vsz(dm), crsn(dm), vrng(dm)) cnt = 0; cnt1 = 0; cnt2 = 0; cnt3 = 0 vol = 0; vol1 = 0; vol2 = 0; vol3 = 0 crsn = 32 call init_box_hash_bin(la) call build(bpt_b, "build hash") bx = boxarray_bbox(ba) cbx = coarsen(bx,crsn) plo = lwb(cbx) phi = upb(cbx) vsz = -Huge(1) do n = 1, nboxes(ba) vsz = max(vsz,extent(get_box(ba,n))) end do print *, 'max extent', vsz print *, 'crsn max extent', int_coarsen(vsz,crsn+1) vrng = int_coarsen(vsz,crsn+1) print *, 'vrng = ', vrng allocate(bins(plo(1):phi(1),plo(2):phi(2),plo(3):phi(3))) do k = plo(3), phi(3); do j = plo(2), phi(2); do i = plo(1), phi(1) allocate(bins(i,j,k)%iv(0)) end do;end do; end do do n = 1, nboxes(ba) ext = int_coarsen(lwb(get_box(ba,n)),crsn) if ( .not. contains(cbx, ext) ) then call bl_error("Not Contained!") end if sz = size(bins(ext(1),ext(2),ext(3))%iv) allocate(ipv(sz+1)) ipv(1:sz) = bins(ext(1),ext(2),ext(3))%iv(1:sz) ipv(sz+1) = n deallocate(bins(ext(1),ext(2),ext(3))%iv) bins(ext(1),ext(2),ext(3))%iv => ipv end do call destroy(bpt_b) if ( verbose ) then call print(bx, 'bbox(ba) ') call print(cbx, 'coarsen(bbox(ba),crsn) ') print *, 'extents(bx)', extent(bx) print *, 'extents(cbx)', extent(cbx) print *, 'plo ', plo print *, 'phi ', phi mxsz = -Huge(1) do k = plo(3), phi(3); do j = plo(2), phi(2); do i = plo(1), phi(1) mxsz = max(mxsz, size(bins(i,j,k)%iv)) end do;end do; end do print *, 'max bin sz ', mxsz sz = Huge(1) do k = plo(3), phi(3); do j = plo(2), phi(2); do i = plo(1), phi(1) sz = min(sz, size(bins(i,j,k)%iv)) end do;end do; end do print *, 'min bin sz ', sz sz = 0 do k = plo(3), phi(3); do j = plo(2), phi(2); do i = plo(1), phi(1) sz = sz + size(bins(i,j,k)%iv) end do;end do; end do print *, 'tot bins ', sz if ( sz /= nboxes(ba) ) then call bl_error("sz /= nboxes(ba): ", sz) end if end if call build(bpt_s, "ba_s") do i = 1, nboxes(ba) bx = grow(get_box(ba,i), ng) call self_intersection(bx, ba) call self_intersection_1(bx, ba) call la_chk_box(la, bx) end do call destroy(bpt_s) ! Just a check of the result print *, 'cnt = ', cnt print *, 'cnt1 = ', cnt1 print *, 'cnt2 = ', cnt2 print *, 'cnt3 = ', cnt3 print *, 'vol = ', vol print *, 'vol1 = ', vol1 print *, 'vol2 = ', vol2 print *, 'vol3 = ', vol3 do k = plo(3), phi(3); do j = plo(2), phi(2); do i = plo(1), phi(1) deallocate(bins(i,j,k)%iv) end do;end do; end do call destroy(la) call destroy(mba) call destroy(bpt) contains subroutine la_chk_box(la, bx) type(layout), intent(inout) :: la type(box), intent(in) :: bx type(box_intersector), pointer :: bi(:) integer :: i type(bl_prof_timer), save :: bpt_h1 call build(bpt_h1, "ba_h1") bi => layout_get_box_intersector(la, bx) do i = 1, size(bi) cnt3 = cnt3 + 1 vol3 = vol3 + volume(bi(i)%bx) end do deallocate(bi) call destroy(bpt_h1) end subroutine la_chk_box subroutine self_intersection(bx, ba) type(box), intent(in) :: bx type(boxarray), intent(in) :: ba integer :: i type(bl_prof_timer), save :: bpt_i type(box) :: bx1 call build(bpt_i, "ba_i") do i = 1, nboxes(ba) bx1 = intersection(bx, get_box(ba,i)) if ( empty(bx1) ) cycle cnt = cnt + 1 vol = vol + volume(bx1) end do call destroy(bpt_i) end subroutine self_intersection subroutine self_intersection_1(bx, ba) type(box), intent(in) :: bx type(boxarray), intent(in) :: ba integer :: i type(bl_prof_timer), save :: bpt_i type(box) :: bx1(nboxes(ba)),bx2(nboxes(ba)) logical :: is_empty(nboxes(ba)) call build(bpt_i, "ba_i1") do i = 1, nboxes(ba) bx2(i) = get_box(ba,i) end do call box_intersection_and_empty(bx1, is_empty, bx, bx2) do i = 1, size(bx1) if ( is_empty(i) ) cycle vol1 = vol1 + volume(bx1(i)) end do cnt1 = cnt1 + count(.not.is_empty) call destroy(bpt_i) end subroutine self_intersection_1 end subroutine t_ba_self_intersection function log2(vin) result(r) implicit none integer :: r integer, intent(in) :: vin integer :: v r = 0 v = vin do v = ishft(v, -1) if ( v == 0 ) exit r = r + 1 end do end function log2
\section{Covariant approaches to quantum gravity}
[STATEMENT] lemma MAX:"Suc (max k m) \<le> n \<Longrightarrow> k \<le> n \<and> m \<le> n" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Suc (max k m) \<le> n \<Longrightarrow> k \<le> n \<and> m \<le> n [PROOF STEP] by (simp add: max_def, case_tac "k \<le> m", simp+)
1. Changed by pressure so as to be no longer straight; crooked; as, a bent pin; a bent lever. 2. Strongly inclined toward something, so as to be resolved, determined, set, etc.; said of the mind, character, disposition, desires, etc, and used with on; as, to be bent on going to college; he is bent on mischief. 3. <botany> A reedlike grass of the genus Agrostis, especially. Agrostis vulgaris, or redtop. The name is also used of many other grasses, esp. In America. 4. <agriculture> Any neglected field or broken ground; a common; a moor. "Bowmen bickered upon the bent." Origin: AS. Beonet; akin to OHG. Pinuz, G. Binse, rush, bent grass; of unknown origin.
State Before: 𝕜 : Type u_1 inst✝⁴ : NontriviallyNormedField 𝕜 E : Type u_2 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace 𝕜 E F : Type u_3 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace 𝕜 F f : E → F K : Set (E →L[𝕜] F) L : E →L[𝕜] F r ε δ : ℝ h : ε ≤ δ ⊢ A f L r ε ⊆ A f L r δ State After: case intro.intro 𝕜 : Type u_1 inst✝⁴ : NontriviallyNormedField 𝕜 E : Type u_2 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace 𝕜 E F : Type u_3 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace 𝕜 F f : E → F K : Set (E →L[𝕜] F) L : E →L[𝕜] F r ε δ : ℝ h : ε ≤ δ x : E r' : ℝ r'r : r' ∈ Ioc (r / 2) r hr' : ∀ (y : E), y ∈ ball x r' → ∀ (z : E), z ∈ ball x r' → ‖f z - f y - ↑L (z - y)‖ ≤ ε * r ⊢ x ∈ A f L r δ Tactic: rintro x ⟨r', r'r, hr'⟩ State Before: case intro.intro 𝕜 : Type u_1 inst✝⁴ : NontriviallyNormedField 𝕜 E : Type u_2 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace 𝕜 E F : Type u_3 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace 𝕜 F f : E → F K : Set (E →L[𝕜] F) L : E →L[𝕜] F r ε δ : ℝ h : ε ≤ δ x : E r' : ℝ r'r : r' ∈ Ioc (r / 2) r hr' : ∀ (y : E), y ∈ ball x r' → ∀ (z : E), z ∈ ball x r' → ‖f z - f y - ↑L (z - y)‖ ≤ ε * r ⊢ x ∈ A f L r δ State After: case intro.intro 𝕜 : Type u_1 inst✝⁴ : NontriviallyNormedField 𝕜 E : Type u_2 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace 𝕜 E F : Type u_3 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace 𝕜 F f : E → F K : Set (E →L[𝕜] F) L : E →L[𝕜] F r ε δ : ℝ h : ε ≤ δ x : E r' : ℝ r'r : r' ∈ Ioc (r / 2) r hr' : ∀ (y : E), y ∈ ball x r' → ∀ (z : E), z ∈ ball x r' → ‖f z - f y - ↑L (z - y)‖ ≤ ε * r y : E hy : y ∈ ball x r' z : E hz : z ∈ ball x r' ⊢ 0 ≤ r Tactic: refine' ⟨r', r'r, fun y hy z hz => (hr' y hy z hz).trans (mul_le_mul_of_nonneg_right h _)⟩ State Before: case intro.intro 𝕜 : Type u_1 inst✝⁴ : NontriviallyNormedField 𝕜 E : Type u_2 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace 𝕜 E F : Type u_3 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace 𝕜 F f : E → F K : Set (E →L[𝕜] F) L : E →L[𝕜] F r ε δ : ℝ h : ε ≤ δ x : E r' : ℝ r'r : r' ∈ Ioc (r / 2) r hr' : ∀ (y : E), y ∈ ball x r' → ∀ (z : E), z ∈ ball x r' → ‖f z - f y - ↑L (z - y)‖ ≤ ε * r y : E hy : y ∈ ball x r' z : E hz : z ∈ ball x r' ⊢ 0 ≤ r State After: no goals Tactic: linarith [mem_ball.1 hy, r'r.2, @dist_nonneg _ _ y x]
module InsSort import Data.Vect %default total insert : Ord a => a -> Vect n a -> Vect (S n) a insert x [] = [x] insert x (y :: ys) = case compare x y of GT => y :: insert x ys _ => x :: y :: ys isort : Ord a => Vect n a -> Vect n a isort [] = [] isort (x :: xs) = insert x (isort xs)
------------------------------------------ -- Mathematical induction derived from Z ------------------------------------------ module sv20.assign2.SetTheory.PMI where open import sv20.assign2.SetTheory.Logic open import sv20.assign2.SetTheory.ZAxioms open import sv20.assign2.SetTheory.Algebra open import sv20.assign2.SetTheory.Subset open import sv20.assign2.SetTheory.Pairs -- Axiom of infinity postulate infinity : ∃ (λ I → ∅ ∈ I ∧ ∀ x → x ∈ I → x ∪ singleton x ∈ I) succ : 𝓢 → 𝓢 succ x = x ∪ singleton x -- Inductive property Inductive : 𝓢 → Set Inductive A = ∅ ∈ A ∧ ((x : 𝓢) → x ∈ A → succ x ∈ A) -- An inductive set. I : 𝓢 I = proj₁ infinity formulaN : 𝓢 → Set formulaN x = (A : 𝓢) → Inductive A → x ∈ A fullN : ∃ (λ B → {z : 𝓢} → z ∈ B ⇔ z ∈ I ∧ formulaN z) fullN = sub formulaN I ℕ : 𝓢 ℕ = proj₁ fullN x∈ℕ→x∈InductiveSet : (x : 𝓢) → x ∈ ℕ → (A : 𝓢) → Inductive A → x ∈ A x∈ℕ→x∈InductiveSet x h = ∧-proj₂ (∧-proj₁ (proj₂ _ fullN) h) -- PMI version from Ivorra Castillo (n.d.), Teorema 8.13. PMI : (A : 𝓢) → A ⊆ ℕ → ∅ ∈ A → ((n : 𝓢) → n ∈ A → succ n ∈ A) → A ≡ ℕ PMI A h₁ h₂ h₃ = equalitySubset A ℕ (prf₁ , prf₂) where prf₁ : (z : 𝓢) → z ∈ A → z ∈ ℕ prf₁ z h = h₁ z h inductiveA : Inductive A inductiveA = h₂ , h₃ prf₂ : (z : 𝓢) → z ∈ ℕ → z ∈ A prf₂ z h = x∈ℕ→x∈InductiveSet z h A inductiveA -- References -- -- Suppes, Patrick (1960). Axiomatic Set Theory. -- The University Series in Undergraduate Mathematics. -- D. Van Nostrand Company, inc. -- -- Enderton, Herbert B. (1977). Elements of Set Theory. -- Academic Press Inc. -- -- Ivorra Castillo, Carlos (n.d.). Lógica y Teoría de -- Conjuntos. https://www.uv.es/ivorra/
1 -- @@stderr -- dtrace: invalid probe specifier foofile: probe description foofile::: does not match any probes
#' Download BEA metadata into library/data folder if needed #' #' @param datasetList list of BEA datasets to update local metadata file for (e.g., list('NIPA', 'FixedAssets')) #' @param beaKey Your API key #' @keywords metadata search #' @return Nothing. This updates local .RData files to be used in beaSearch. #' @import httr data.table #' @importFrom jsonlite fromJSON #' @export #' @examples #' beaUpdateMetadata(list('RegionalData', 'NIPA'), beaKey = 'yourAPIkey') beaUpdateMetadata <- function(datasetList, beaKey){ 'Datasetname' <- NULL 'MetaDataUpdated' <- NULL 'DatasetName' <- NULL 'TableID' <- NULL 'Line' <- NULL '.' <- NULL 'SeriesCode' <- NULL 'RowNumber' <- NULL 'LineDescription' <- NULL 'LineNumber' <- NULL 'ParentLineNumber' <- NULL 'Tier' <- NULL 'Path' <- NULL 'APITable' <- NULL 'TableName' <- NULL 'ReleaseDate' <- NULL 'NextReleaseDate' <- NULL 'Parameter' <- NULL 'ParamValue' <- NULL #datasetList <- list('nipa','niunderlyingdetail','fixedassets','regionalproduct','regionalincome') #update as of 2017-07-12: 'regionaldata' dataset removed from API, merged into regionalproduct and regionalincome requireNamespace('data.table', quietly = TRUE) requireNamespace('httr', quietly = TRUE) requireNamespace('jsonlite', quietly = TRUE) beaMetadataStore <- paste0(.libPaths()[1], '/beaR/data') beaMetaSpecs <- list( 'UserID' = beaKey , 'method' = 'GetData', 'datasetname' = 'APIDatasetMetaData', 'dataset' = paste(datasetList, collapse = ','), 'ResultFormat' = 'json' ) #Get as httr response beaResponse <- bea.R::beaGet(beaMetaSpecs, asList = FALSE, asTable = FALSE, isMeta = TRUE) #Check to ensure it is httr response if(class(beaResponse) != 'response'){ warning('API metadata not returned. Verify that you are using a valid API key, represented as a character string.') return('API metadata not returned. Verify that you are using a valid API key, represented as a character string.') } lapply(datasetList, function(outdat){ try(suppressWarnings(file.remove(paste0(beaMetadataStore,'/', outdat, '.RData'))), silent = TRUE) }) #Get JSON String respStr <- httr::content(beaResponse, as = 'text') #Actually, we can get this same info faster using GetParamValsList or something #The line below should be suppressed if fixed - JSON was malformed due to missing commas #respStr <- gsub('}{', '},{', respStr, fixed = TRUE) metaList <-jsonlite::fromJSON(respStr) metasetInfo <- data.table::as.data.table(metaList$BEAAPI$Datasets) if(dim(metasetInfo)[1] == 0){ warning('API metadata not returned. Verify that you are using a valid API key, represented as a character string.') return('API metadata not returned. Verify that you are using a valid API key, represented as a character string.') } #bind dataset metadata together #This is a bit of a time drag, so we want to only do it if we need to #And do it separately for each dataset if('nipa' %in% tolower(datasetList)){try({ nipaMDU <- metasetInfo[tolower(Datasetname) == 'nipa', MetaDataUpdated] nipaTabs <- data.table::rbindlist(metasetInfo[tolower(Datasetname) == 'nipa', APITable]) nipaTabs[, DatasetName := 'NIPA'] #TableIDN has become obsolete; we should no longer overwrite to rename #setnames(nipaTabs, old = names(nipaTabs)[grepl('tableidn', tolower(names(nipaTabs)),fixed = T)], new = 'TableID') #...however, there does appear to be an issue with capitalization setnames(nipaTabs, old = names(nipaTabs)[tolower(names(nipaTabs)) == 'tableid'], new = 'TableID') #Backend issue: Sometimes, NIPA table 38 has a NULL table for the line descriptions. Handle and warn the user. handler <- c() nipaRowList <- lapply(nipaTabs[, TableID], function(thisTab){ tabPart <- nipaTabs[TableID == thisTab, data.table::as.data.table(Line[[1]])] tryCatch({tabPart[, TableID := thisTab]}, error = function(e){handler <<- c(handler, paste0(e, ': NIPA Table ', thisTab))}) return(tabPart) }) nipaRows <- data.table::rbindlist(nipaRowList, use.names = TRUE) data.table::setkey(nipaTabs, key = TableID) data.table::setkey(nipaRows, key = TableID) nipaIndex <- nipaTabs[nipaRows][,.( SeriesCode, RowNumber, LineDescription, LineNumber, ParentLineNumber, Tier, Path, TableID, DatasetName, TableName, ReleaseDate, NextReleaseDate, MetaDataUpdated = nipaMDU )] save(nipaIndex, file=paste0(beaMetadataStore, '/NIPA.RData')) })} if('niunderlyingdetail' %in% tolower(datasetList)){try({ niudMDU <- metasetInfo[tolower(Datasetname) == 'niunderlyingdetail', MetaDataUpdated] niudTabs <- data.table::rbindlist(metasetInfo[tolower(Datasetname) == 'niunderlyingdetail', APITable]) niudTabs[, DatasetName := 'NIUnderlyingDetail'] #TableIDN has become obsolete; we should no longer overwrite to rename #setnames(niudTabs, old = names(niudTabs)[grepl('tableidn', tolower(names(niudTabs)),fixed = T)], new = 'TableID') #...however, there does appear to be an issue with capitalization setnames(niudTabs, old = names(niudTabs)[tolower(names(niudTabs)) == 'tableid'], new = 'TableID') niudRows <- data.table::rbindlist(lapply(niudTabs[, TableID], function(thisTab){ tabPart <- niudTabs[TableID == thisTab, data.table::as.data.table(Line[[1]])] tabPart[, TableID := thisTab] return(tabPart) })) data.table::setkey(niudTabs, key = TableID) data.table::setkey(niudRows, key = TableID) niudIndex <- niudTabs[niudRows][,.( SeriesCode, RowNumber, LineDescription, LineNumber, ParentLineNumber, Tier, Path, TableID, DatasetName, TableName, ReleaseDate, NextReleaseDate, MetaDataUpdated = niudMDU )] save(niudIndex, file=paste0(beaMetadataStore, '/NIUnderlyingDetail.RData')) })} if('fixedassets' %in% tolower(datasetList)){try({ fixaMDU <- metasetInfo[tolower(Datasetname) == 'fixedassets', MetaDataUpdated] fixaTabs <- data.table::rbindlist(metasetInfo[tolower(Datasetname) == 'fixedassets', APITable]) fixaTabs[, DatasetName := 'FixedAssets'] #No TableIDN here #setnames(fixaTabs, old = names(fixaTabs)[grepl('tableidn', tolower(names(fixaTabs)),fixed = T)], new = 'TableID') #...however, there does appear to be an issue with capitalization setnames(fixaTabs, old = names(fixaTabs)[tolower(names(fixaTabs)) == 'tableid'], new = 'TableID') fixaRows <- data.table::rbindlist(lapply(fixaTabs[, TableID], function(thisTab){ tabPart <- fixaTabs[TableID == thisTab, data.table::as.data.table(Line[[1]])] tabPart[, TableID := thisTab] return(tabPart) })) data.table::setkey(fixaTabs, key = TableID) data.table::setkey(fixaRows, key = TableID) fixaIndex <- fixaTabs[fixaRows][,.( SeriesCode, RowNumber, LineDescription, LineNumber, ParentLineNumber, Tier, Path, TableID, DatasetName, TableName, ReleaseDate, NextReleaseDate, MetaDataUpdated = fixaMDU )] save(fixaIndex, file=paste0(beaMetadataStore, '/FixedAssets.RData')) })} #Regional data: Treated differently from National data #Set "RegionalData" if('regionaldata' %in% tolower(datasetList)){ message('The RegionalData dataset has been removed from the API; please use RegionalIncome and RegionalProduct instead.'); return('The RegionalData dataset has been removed from the API; please use RegionalIncome and RegionalProduct instead.'); # try({ # # rdatMDU <- metasetInfo[tolower(Datasetname) == 'regionaldata', MetaDataUpdated] # rdatParam <- metaList$BEAAPI$Datasets$Parameter[[grep('regionaldata', tolower(metaList$BEAAPI$Datasets$Datasetname), fixed=T)]] # #rbindlist(rdatParam[[1]])[ParamValue != 'NULL'] # rdatKeys <- as.data.table(rdatParam$Keycode$ParamValue[[1]]) # rdatKeys[, Parameter := 'Keycode'] # rdatFips <- as.data.table(rdatParam$GeoFIPS$ParamValue[[2]]) # rdatFips[, Parameter := 'GeoFIPS'] # # rdatIndex <- rbindlist(list(rdatKeys, rdatFips), use.names = TRUE) # rdatIndex[, DatasetName := 'RegionalData'] # rdatIndex[, MetaDataUpdated := rdatMDU] # # save(rdatIndex, file=paste0(beaMetadataStore, '/RegionalData.RData')) # }) } #Dataset "RegionalProduct" if('regionalproduct' %in% tolower(datasetList)){try({ rprdMDU <- metasetInfo[tolower(Datasetname) == 'regionalproduct', MetaDataUpdated] rprdParams <- metaList$BEAAPI$Datasets$Parameters[[grep('regionalproduct', tolower(metaList$BEAAPI$Datasets$Datasetname), fixed=T)]] rprdParNms <- attributes(rprdParams)$names rprdPages <- data.table::rbindlist(rprdParams)[ParamValue != 'NULL', ParamValue] rprdIndex <- data.table::rbindlist(lapply(1:length(rprdPages), function(x){ rprdDT <- data.table::as.data.table(rprdPages[[x]]) rprdDT[, Parameter := rprdParNms[x]] return(rprdDT) })) rprdIndex[, DatasetName := 'RegionalProduct'] rprdIndex[, MetaDataUpdated := rprdMDU] save(rprdIndex, file=paste0(beaMetadataStore, '/RegionalProduct.RData')) }, silent = TRUE)} #Dataset "RegionalIncome" if('regionalincome' %in% tolower(datasetList)){try({ rincMDU <- metasetInfo[tolower(Datasetname) == 'regionalincome', MetaDataUpdated] rincParams <- metaList$BEAAPI$Datasets$Parameters[[grep('regionalincome', tolower(metaList$BEAAPI$Datasets$Datasetname), fixed=T)]] rincParNms <- attributes(rincParams)$names rincPages <- data.table::rbindlist(rincParams)[ParamValue != 'NULL', ParamValue] rincIndex <- data.table::rbindlist(lapply(1:length(rincPages), function(x){ rincDT <- data.table::as.data.table(rincPages[[x]]) rincDT[, Parameter := rincParNms[x]] return(rincDT) })) rincIndex[, DatasetName := 'RegionalIncome'] rincIndex[, MetaDataUpdated := rincMDU] save(rincIndex, file=paste0(beaMetadataStore, '/RegionalIncome.RData')) }, silent = TRUE)} # if(length(datasetList) > length(metasetInfo[, Datasetname])){ # staleList <- datasetList[ # !(tolower(datasetList) %in% tolower(metasetInfo[, Datasetname])) # ] # message('beaR attempted to update metadata for the following dataset(s) which could not be returned from the API: ') # message(paste( # toupper(staleList), # collapse = ', ' # )) # message('Removing stale data from local storage...') ## return(staleList) # }# else {return(list())} }
subroutine Bamp_ppm(q,mc,ms,Bppm) c--- u + g -> c + s + d (t-channel single-charm) ************************************************************************ * * * AUTHORS: R. FREDERIX AND F. TRAMONTANO * * DATE : 12/17/2008 * * * ************************************************************************ implicit none include 'constants.f' include 'zprods_com.f' include 'epinv.f' include 'stopf1inc.f' double precision q(mxpart,4),dot,cDs,gDs,cDg,mc,ms, . mc2,ms2,u,xsn,xsd,xs double complex trc,trg,trs,trsgc,zppm,Bppm mc2=mc**2 ms2=ms**2 cDs=dot(q,3,4)+mc2*dot(q,4,2)/2d0/dot(q,3,2) . +ms2*dot(q,3,2)/2d0/dot(q,4,2) cDg=dot(q,3,2) gDs=dot(q,4,2) u=mc2+ms2+2d0*cDs xsn=(1d0-dsqrt(1d0-4d0*ms*mc/(u-(ms-mc)**2))) xsd=(1d0+dsqrt(1d0-4d0*ms*mc/(u-(ms-mc)**2))) xs=-xsn/xsd trg=2d0*za(5,2)*zb(2,1) trs=2d0*za(5,4)*zb(4,1)+ms**2*za(5,2)*zb(2,1)/gDs trc=2d0*za(5,3)*zb(3,1)+mc**2*za(5,2)*zb(2,1)/cDg trsgc=2d0*zb(1,4)*za(4,2)*zb(2,3)*za(3,5) zppm=za(2,3)**2*zb(4,3) Bppm = mc*ms*(gDs+cDg)*(cDs*(-4*trc*gDs**4+2*(trsgc+mc2*trg-2*ms2 & *trc)*gDs**3+ms2*(-2*(trs+trg)*cDg+trsgc+3*mc2*trg)*gDs**2+ms2* & cDg*(2*(trs+trg)*cDg-trsgc-ms2*trg)*gDs+2*ms2**2*trg*cDg**2)+ms & 2*gDs*(cDg*(4*trc*gDs**2-2*(trsgc+mc2*trs-2*ms2*trc)*gDs+ms2*(m & c2*trg-trsgc))+mc2*gDs*(2*trs*gDs-2*trg*gDs+trsgc-3*ms2*trg))+2 & *trg*cDs**2*gDs*(2*gDs*(gDs+ms2)-cDg*(2*gDs+3*ms2)))*tr5Xs/((cD & s**2-mc2*ms2)*gDs**3)/2.0d+0 Bppm = mc*mc2*ms*(gDs+cDg)*(2*mc2*trg*cDs*gDs**2+cDg**2*(cDs*(-2* & trc*gDs+trsgc+3*ms2*trg)+4*mc2*trs*gDs-2*ms2*trc*gDs+4*trg*cDs* & *2+ms2*trsgc-3*mc2*ms2*trg)-cDg*gDs*(cDs*(-2*trc*gDs+trsgc+mc2* & trg)+6*trg*cDs**2+mc2*(trsgc-ms2*trg))+2*cDg**3*(ms2*trc-2*trs* & cDs))*tr5Xc/(cDg**2*(cDs**2-mc2*ms2)*gDs)/2.0d+0+Bppm Bppm = mc*ms*(cDs*(4*trc*gDs**4-2*(trsgc+mc2*trg-2*ms2*trc)*gDs** & 3+ms2*(2*(trs+trg)*cDg-trsgc-3*mc2*trg)*gDs**2+ms2*cDg*(-2*(trs & +trg)*cDg+trsgc+ms2*trg)*gDs-2*ms2**2*trg*cDg**2)+ms2*gDs*(cDg* & (-4*trc*gDs**2+2*(trsgc+mc2*trs-2*ms2*trc)*gDs+ms2*(trsgc-mc2*t & rg))+mc2*gDs*(2*(trg-trs)*gDs-trsgc+3*ms2*trg))+2*trg*cDs**2*gD & s*(cDg*(2*gDs+3*ms2)-2*gDs*(gDs+ms2)))*tr4Xs/((cDs**2-mc2*ms2)* & gDs**2)/2.0d+0+Bppm Bppm = mc*mc2*ms*(-2*mc2*trg*cDs*gDs**2-cDg**2*(cDs*(-2*trc*gDs+t & rsgc+3*ms2*trg)+4*mc2*trs*gDs-2*ms2*trc*gDs+4*trg*cDs**2+ms2*tr & sgc-3*mc2*ms2*trg)+cDg*gDs*(cDs*(-2*trc*gDs+trsgc+mc2*trg)+6*tr & g*cDs**2+mc2*(trsgc-ms2*trg))+cDg**3*(4*trs*cDs-2*ms2*trc))*tr4 & Xc/(cDg*(cDs**2-mc2*ms2)*gDs)/2.0d+0+Bppm Bppm = Bppm-mc*ms*(2*mc2**2*ms2*trg*gDs**2+cDg**2*(cDs*(4*mc2*tr & s*gDs-2*ms2*trc*gDs+ms2*trsgc+mc2*ms2*trg)+mc2*ms2*(2*trg*gDs-2 & *trc*gDs+trsgc+3*ms2*trg)-2*trg*cDs**2*gDs)+cDg*gDs*(2*(trg*cDs & **2+mc2*ms2*(trc-trg))*gDs-mc2*((trsgc+5*ms2*trg)*cDs+ms2*(trsg & c+mc2*trg)))+2*ms2*cDg**3*(trc*cDs-2*mc2*trs))*tr3Xs/(cDg*(cDs* & *2-mc**2*ms**2)*gDs)/2.0d+0 Bppm = Bppm-mc*ms*(cDg*gDs*(cDs*(4*trc*gDs**2-2*(trsgc+mc2*trs+2 & *mc2*trg-2*ms2*trc)*gDs-ms2*(trsgc+5*mc2*trg))-mc2*ms2*(2*(trs+ & trg)*gDs+trsgc+ms2*trg))+mc2*gDs**2*(-4*trc*gDs**2+2*((trs+trg) & *cDs+trsgc+mc2*trg-2*ms2*trc)*gDs+trsgc*(cDs+ms2)+ms2*trg*(cDs+ & 3*mc2))+2*mc2*ms2*cDg**2*((trs+trg)*gDs+ms2*trg))*tr3Xc/((cDs-m & c*ms)*(cDs+mc*ms)*gDs**2)/2.0d+0 Bppm = ms*(cDg**3*(cDs**2*(8*trc*gDs**3+2*(-trsgc+mc2*trs+3*ms2*t & rc)*gDs**2-ms2*(trsgc+mc2*trg)*gDs-2*mc2*ms2**2*trc)+mc2*ms2*cD & s*(2*(-trs-trg+trc)*gDs**2+ms2**2*trc)+mc2*ms2*gDs*(-4*trc*gDs* & *2-4*(mc2*trs+ms2*trc)*gDs+ms2*(trsgc+mc2*trg))+2*ms2*trc*cDs** & 4-ms2**2*trc*cDs**3)+mc2*cDg**2*gDs**2*(2*cDs*gDs*(-trc*(2*gDs+ & ms2)+trsgc+mc2*trs)+mc2*ms2*((2*trs+4*trg-2*trc)*gDs+trsgc-ms2* & trs)-cDs**2*(2*trg*gDs+trsgc-ms2*trs))+mc2*(cDs-mc*ms)*(cDs+mc* & ms)*gDs**4*((trg+trc)*(8*gDs-ms2)+trs*(2*gDs+2*cDs+ms2-mc2))+2* & mc2*cDg*(cDs-mc*ms)*(cDs+mc*ms)*gDs**3*(trg*gDs-ms2*trs)+2*ms2* & trc*cDg**4*cDs*(cDs-mc*ms)*(cDs+mc*ms))*lVs/(mc*cDg**2*(cDs-mc* & ms)*(cDs+mc*ms)*gDs**3)/4.0d+0+Bppm Bppm = Bppm-mc*(cDs**2*(2*(mc2*(trs+4*trg+4*trc)-trg*cDg)*gDs**5 & -(-2*trg*cDg**2+mc2**2*trs+mc2*ms2*(-trs+trg+trc))*gDs**4+cDg*( & -4*trs*cDg**2-2*(-trsgc+2*mc2*trs+ms2*trc)*cDg+mc2*(trsgc-2*ms2 & *trs+ms2*trg))*gDs**3+ms2*cDg**2*(3*trg*cDg-3*trc*cDg+trsgc+mc2 & *trs+2*mc2*trg)*gDs**2-ms2**2*trc*cDg**3*gDs-2*mc2*ms2**2*trc*c & Dg**3)+ms2*cDs*(2*mc2*trg*cDg*gDs**4-2*mc2**2*trs*gDs**4+cDg**3 & *(-4*trc*gDs**3+2*(trsgc+mc2*trs-ms2*trc)*gDs**2+mc2*ms2**2*trc & )+2*mc2*(-trs-2*trg+trc)*cDg**2*gDs**3-2*mc2*ms2*trc*cDg**4)+cD & s**3*(-2*trg*cDg*gDs**4+2*mc2*trs*gDs**4+2*trg*cDg**2*gDs**3+2* & ms2*trc*cDg**4-ms2**2*trc*cDg**3)+mc2*ms2*gDs*(cDg**3*(4*trs*gD & s**2+ms2*(2*trs-trg+trc)*gDs+ms2**2*trc)+cDg*gDs**2*(2*trg*gDs* & *2-mc2*(trsgc+ms2*(trg-2*trs)))+cDg**2*gDs*((4*trc-2*trg)*gDs** & 2+2*(-2*trsgc+mc2*trs+2*ms2*trc)*gDs-ms2*(trsgc+mc2*(trs+2*trg) & ))+mc2*gDs**3*(-2*(trs+4*trg+4*trc)*gDs+mc2*trs+ms2*(-trs+trg+t & rc)))+2*ms2*trc*cDg**3*cDs**4)*lVc/(ms*cDg**2*(cDs**2-mc**2*ms* & *2)*gDs**3)/4.0d+0 Bppm = trg*xs*cDs*(mc2*gDs**2-2*cDg*cDs*gDs+ms2*cDg**2)*lRcs/((xs & **2-1)*cDg*gDs**2)+Bppm Bppm = (mc2*cDg**3*(-80*trs*gDs**4-cDs*(72*trs*gDs**3+4*ms2*(5*tr & s+22*trg+30*trc)*gDs**2+2*ms2*(-17*mc2*trs+9*ms2*trg-26*mc2*trg & +34*ms2*trc)*gDs+ms2**2*(-9*trsgc+mc2*(-8*trs-17*trg+3*trc)+5*m & s2*trc))+4*ms2*(-9*trs-4*trg+37*trc)*gDs**3+ms2*(-66*trsgc+ms2* & (88*trc-6*(trs+7*trg))+mc2*(158*trs-13*trg-3*trc))*gDs**2+9*(mc & 2-2*ms2)*ms2*trsgc*gDs+mc2*ms2**2*(26*trs+17*trg+13*trc)*gDs+6* & (mc-ms)*(ms+mc)*ms2*trc*cDs**2+mc2*ms2**2*(9*trsgc+ms2*(-8*trs+ & trg+8*trc)))+mc2*cDg**2*gDs*(4*(41*trg+32*trc)*gDs**4-12*(-6*tr & g*cDs-3*trsgc+7*mc2*trs+3*ms2*(trc-2*trg))*gDs**3+2*(18*trg*cDs & **2+2*(9*trsgc-27*mc2*trs+26*ms2*trg+17*ms2*trc)*cDs+ms2*(9*trs & gc+6*ms2*trs-31*mc2*trs+8*mc2*trg+58*mc2*trc))*gDs**2-ms2*(2*(9 & *trsgc+5*mc2*trs+31*mc2*trg+13*mc2*trc)*cDs+mc2*(54*trsgc+3*ms2 & *trs-31*mc2*trs+39*ms2*trg+23*mc2*trg-44*ms2*trc))*gDs-9*mc2*ms & 2*((trsgc+ms2*trg)*cDs+ms2*(trsgc+mc2*trg)))+mc2*cDg*gDs**2*(4* & (23*trg+32*trc)*gDs**4+cDs*(8*(7*trg+16*trc)*gDs**3+12*(-ms2*tr & s+mc2*trs+3*mc2*trg)*gDs**2+2*mc2*(18*trsgc-18*mc2*trs+35*ms2*t & rg+17*ms2*trc)*gDs-9*mc2*ms2*(trsgc+mc2*trg))-2*(6*ms2*(trs+4*t & rg+4*trc)+mc2*(-6*trs-trg+8*trc))*gDs**3+(4*mc2*(9*trsgc+3*ms2* & trs+8*ms2*trg-19*ms2*trc)-12*mc2**2*trs+6*ms2**2*(-trs+trg+trc) & )*gDs**2+18*trg*cDs**2*(mc2-2*gDs)*gDs+mc2*ms2*(27*trsgc+6*ms2* & trs+mc2*(-22*trs+27*trg+18*trc))*gDs-9*mc2**2*ms2*(trsgc+ms2*tr & g))+mc2**2*gDs**3*((46*trg+64*trc)*gDs**3+cDs*(4*(7*trg+16*trc) & *gDs**2+6*(mc-ms)*(ms+mc)*trs*gDs+9*mc2*(trsgc+ms2*trg))+2*(mc2 & *(3*trs-20*(trg+trc))-3*ms2*(trs+4*(trg+trc)))*gDs**2-18*trg*cD & s**2*gDs+(mc2*(9*trsgc+ms2*(6*trs-2*trg-29*trc))+5*mc2**2*trs+3 & *ms2**2*(-trs+trg+trc))*gDs+9*mc2*ms2*(trsgc+mc2*trg))+ms2*cDg* & *4*(mc2*(-24*(-8*trs-3*trg+3*trc)*gDs**2+(36*trsgc+ms2*(52*trs+ & 70*trg-28*trc)-18*mc2*trs)*gDs+ms2*(27*trsgc-9*mc2*(2*trs+trg)+ & 2*ms2*(-8*trs+trg+8*trc)))-2*cDs*(68*trc*gDs**2+2*(-9*trsgc-17* & mc2*trs-26*mc2*trg+34*ms2*trc)*gDs+ms2*(5*ms2*trc-9*trsgc)+mc2* & ms2*(-8*trs-17*trg+6*trc)-3*mc2**2*trc)+12*(mc-ms)*(ms+mc)*trc* & cDs**2)-6*ms2*cDg**5*(24*trc*gDs**2+6*(-trsgc+mc2*trs+3*ms2*trc & )*gDs+2*(ms**2-mc**2)*trc*cDs+3*ms2*(-trsgc+2*mc2*trs+mc2*trg)) & )/(mc*ms*cDg**2*(2*cDg+mc2)*gDs**3)/1.2d+1+Bppm Bppm = tr3s002ft*(3*mc*trs*(2*cDg+mc2)**2*gDs**2-3*mc*(trg+trc)*( & 8*(2*cDg+mc2)*gDs**3+ms2*cDg**2*(gDs+cDs)))/(ms*cDg**2*gDs)+Bp & pm Bppm = B0cgsf*(cDg**3*(-4*(mc2*trs+2*ms2*trc)*gDs**3+ms2*cDs*(-8* & trc*gDs**2+2*(trsgc+2*mc2*trs+3*mc2*trg-4*ms2*trc)*gDs+ms2*(trs & gc+mc2*(trs+2*trg-trc)))+ms2*(2*trsgc+mc2*(5*trs+7*trg-3*trc)-6 & *ms2*trc)*gDs**2+ms2*(ms2+mc2)*trsgc*gDs+mc2*ms2**2*(3*trs+5*tr & g+trc)*gDs+2*(mc-ms)*(ms+mc)*ms2*trc*cDs**2+mc2*ms2**2*(trsgc+m & s2*(trc-trs)))+mc2*cDg**2*gDs*(2*(trg-2*trs)*gDs**3+cDs*(2*(trg & -2*trs)*gDs**2-ms2*(trs+trg+3*trc)*gDs-ms2*(trsgc+ms2*trg))+(2* & trsgc-3*ms2*trs-4*mc2*trs+5*ms2*trg+3*ms2*trc)*gDs**2+ms2*(-2*t & rsgc-ms2*trs+4*mc2*trs+mc2*trg+5*ms2*trc)*gDs-ms2**2*(trsgc+mc2 & *trg))+mc2*gDs**3*((6*trg+8*trc)*gDs**3+cDs*(4*(trg+2*trc)*gDs* & *2+2*(mc-ms)*(ms+mc)*trs*gDs+mc2*(trsgc+ms2*trg))+2*(mc2*trs-ms & 2*(trs+4*(trg+trc)))*gDs**2-2*trg*cDs**2*gDs+mc2*trsgc*gDs+ms2* & (ms2*(-trs+trg+trc)-mc2*(-2*trs+trg+4*trc))*gDs+mc2*ms2*(trsgc+ & mc2*trg))+mc2*cDg*gDs**2*(8*(trg+trc)*gDs**3+2*(trg*cDs+trsgc-m & c2*trs+ms2*(trg-trc))*gDs**2+2*(trg*cDs**2+(-2*mc2*trs+3*ms2*tr & g+2*ms2*trc)*cDs+ms2*(ms2*trs+mc2*(-2*trs+trg+trc)))*gDs+trsgc* & (2*cDs+ms2+mc2)*gDs+ms2*(-mc2*trg*(cDs+ms2)-trsgc*(cDs+mc2)))-m & s2*cDg**4*(8*trc*gDs**2+2*(-trsgc+mc2*trs+3*ms2*trc)*gDs+2*(ms* & *2-mc**2)*trc*cDs+ms2*(-trsgc+2*mc2*trs+mc2*trg)))/(mc*ms*cDg** & 2*gDs**3)/4.0d+0+Bppm Bppm = Bppm-mc*tr3s00ft*(cDg*((26*trg+24*trc)*gDs**3+2*(2*trg*cD & s+trsgc-3*mc2*trs+2*ms2*trg-ms2*trc)*gDs**2+(2*trg*cDs**2+2*(tr & sgc-2*mc2*trs+5*ms2*trg+4*ms2*trc)*cDs+ms2*(trsgc+2*mc2*(-3*trs & +trg+trc)))*gDs-ms2*((trsgc+mc2*trg)*cDs+mc2*(trsgc+ms2*trg)))+ & gDs*((22*trg+24*trc)*gDs**3+cDs*(4*(5*trg+6*trc)*gDs**2+mc2*(tr & sgc+ms2*trg))-2*trg*cDs**2*gDs+mc2*(trsgc-2*ms2*trg-5*ms2*trc)* & gDs+mc2*ms2*(trsgc+mc2*trg))-cDg**2*(8*trs*gDs**2+cDs*(4*trs*gD & s+ms2*(-3*trs+4*trg+2*trc))+ms2*(9*trs-4*trc)*gDs+ms2*(3*trsgc- & 4*mc2*trs+2*ms2*trg))+9*ms2*trs*cDg**3)/(ms*cDg**2*gDs) Bppm = lc*mc*(cDg*(-4*trg*gDs**3+2*trg*(mc2-2*cDs)*gDs**2+2*mc2*( & trg*cDs+2*trsgc-2*mc2*trs+ms2*(trc-2*trg))*gDs+mc2*ms2*(3*mc2*t & rg-trsgc))+2*cDg**2*(2*trg*gDs**2+2*(trg*cDs+trsgc-3*mc2*trs+2* & ms2*trc)*gDs-ms2*(2*trsgc+mc2*(trc-5*trg)))-mc2*trg*gDs*(2*gDs* & (gDs+cDs)+mc2*ms2)+cDg**3*(6*ms2*(trg-trc)-8*trs*gDs)+mc2**2*tr & sgc*gDs)/(ms*(2*cDg+mc2)**2*gDs)/2.0d+0+Bppm Bppm = LsB2*mc*ms*(-2*mc2**2*trg*cDs*gDs**3+cDg**3*(cDs*(8*mc2*tr & s*gDs-2*ms2*trc*gDs+ms2*trsgc-7*mc2*ms2*trg)+4*cDs**2*(-trc*gDs & +trsgc+ms2*trg)+8*trg*cDs**3-mc2*ms2*(3*trsgc+ms2*trg))-2*cDg** & 2*gDs*(2*mc2**2*(trs*gDs-ms2*trg)+mc2*cDs*(trsgc-trc*gDs)+cDs** & 2*(-2*trc*gDs+trsgc+3*mc2*trg)+4*trg*cDs**3)+mc2*cDg*gDs**2*(cD & s*(-2*trc*gDs+trsgc+mc2*trg)+8*trg*cDs**2+mc2*(trsgc-ms2*trg))+ & cDg**4*(-8*trs*cDs**2+2*ms2*trc*cDs+4*mc2*ms2*trs))/(cDg**2*(cD & s**2-mc2*ms2)*gDs)+Bppm Bppm = ms*tr3c00fs*(cDg*(cDs*(16*trc*gDs**2+2*(-trsgc-mc2*(trs+2* & trg)+8*ms2*trc)*gDs+ms2*(-trsgc-mc2*trg+3*ms2*trc))-mc2*(2*(trs & +2*trg)*gDs**2+(trsgc+ms2*(trg-trs))*gDs+ms2*(trsgc-3*ms2*trs-2 & *ms2*trg)))+cDg**2*(8*trc*gDs**2+2*(-trsgc+mc2*trs+3*ms2*trc)*g & Ds+ms2*(mc2*(2*trs+trg)-trsgc))+mc2*gDs*(-10*trc*gDs**2+(2*(trs & +trg)*cDs+trsgc+2*mc2*trg-7*ms2*trc)*gDs+trsgc*(cDs+ms2)+ms2*tr & g*(cDs+mc2)))/(mc*gDs**3)+Bppm Bppm = BfunX*(ms2*cDg**3*(mc2*((trs+trg-trc)*gDs**2+ms2*(trs+trg+ & trc)*gDs+ms2**2*(trs+trg+trc))+mc2*cDs*(2*(trs+trg)*gDs+ms2*(tr & s+trg-trc))+2*trc*cDs**2*(2*gDs+mc2)+4*trc*cDs**3)+2*mc2*cDg*gD & s**3*((trg+trc)*(4*gDs**2-ms2*(gDs+cDs))+trs*(gDs-ms2)*(2*(gDs+ & cDs)+ms2))+mc2*gDs**4*((trg+trc)*(8*gDs*(gDs+cDs)-2*ms2*(cDs-3* & gDs)-ms2**2)+trs*(2*(gDs+cDs)+ms2)**2)+mc2*ms2*cDg**2*gDs**2*(t & rs*(-gDs+cDs+ms2)-(trc-trg)*(gDs+cDs+ms2))+2*ms2*trc*cDg**4*cDs & *(2*gDs+4*cDs+mc2)+4*ms2*trc*cDg**5*cDs)/(mc*ms*cDg**2*gDs**3)/ & 4.0d+0+Bppm Bppm = LsB1*mc*ms*(-2*cDg*gDs**2*(cDs*(-4*trc*gDs**2+(2*trsgc+mc2 & *trs+3*mc2*trg-4*ms2*trc)*gDs+ms2*(trsgc+2*mc2*trg))+mc2*ms2*(2 & *trs*gDs+trsgc-ms2*trg)+2*trg*cDs**2*(gDs+ms2)+2*trg*cDs**3)+cD & g**2*gDs*(-4*ms2*trc*gDs**2+2*(2*trg*cDs**2+ms2*((trs+trg)*cDs+ & trsgc+2*mc2*trs+mc2*trg)-2*ms2**2*trc)*gDs+ms2*(trg*(8*cDs**2+m & s2*cDs-mc2*ms2)+trsgc*(cDs+ms2)))+gDs**3*(-4*mc2*trc*gDs**2+2*m & c2*((trs+trg)*cDs+trsgc+mc2*trg-2*ms2*trc)*gDs+2*(mc2*trg-trsgc & )*cDs**2+mc2*(trsgc+ms2*trg)*cDs+mc2*ms2*(3*trsgc+mc2*trg))-2*m & s2*cDg**3*cDs*((trs+trg)*gDs+ms2*trg))/((cDs-mc*ms)*(cDs+mc*ms) & *gDs**3)+Bppm Bppm = B0csf*mc*ms*(mc2*(2*trc*gDs**2+(-trsgc-mc2*trs+ms2*(trg-tr & s))*gDs+ms2*(ms2+mc2)*trg)+cDs*(2*trc*gDs**2+(-trsgc+mc2*(-2*tr & s-trg+trc)+ms2*trc)*gDs+2*mc2*ms2*trg)+cDg*(ms2*(-trc*(2*gDs+ms & 2+mc2)+trsgc+mc2*trg)+cDs*(-2*trc*gDs+trsgc+ms2*(trs+trg-2*trc) & +mc2*trs)+2*trs*cDs**2)+cDs**2*(2*trc*gDs-trg*(2*gDs+ms2+mc2))- & 2*trg*cDs**3)/((cDs-mc*ms)*(cDs+mc*ms)*gDs)/2.0d+0+Bppm Bppm = ls*ms*(cDg*(-8*trc*gDs**2+2*(trsgc+mc2*trs-3*ms2*trc)*gDs+ & ms2*(trsgc-mc2*trg))+mc2*gDs*(-2*trs*gDs+4*trg*gDs-trsgc+3*ms2* & trg))/(mc*gDs*(2*gDs+ms2))/2.0d+0+Bppm Bppm = 3*mc*ms*tr3c002fs*(cDg*((trs+trg)*cDs+ms2*trc)*(2*gDs+ms2) & -mc2*(trs+trg)*gDs**2)/gDs**3+Bppm Bppm = 3*ms*tr3c001fs*(2*gDs+ms2)*(cDg*(trc*cDs*(2*gDs+ms2)+mc2*m & s2*(trs+trg))-mc2*trc*gDs**2)/(mc*gDs**3)+Bppm Bppm = epinv*trg*(4*lp*xs*cDs+mc*(ms-ms*xs**2))*(mc2*gDs**2-2*cDg & *cDs*gDs+ms2*cDg**2)/((xs**2-1)*cDg*gDs**2)/4.0d+0+Bppm Bppm = mc*ms*tr2fu*trg*cDs*(mc2*gDs**2-2*cDg*cDs*gDs+ms2*cDg**2)/ & (cDg*gDs**2)+Bppm Bppm = 3*mc*tr3s001ft*((trg+trc)*gDs*(ms2*(mc2*gDs-2*cDg*cDs)-8*g & Ds**2*(gDs+cDs))+ms2*trs*cDg*(3*cDg*gDs+2*mc2*gDs-cDg*cDs))/(ms & *cDg**2*gDs)+Bppm Bppm=Bppm/zppm return end
function lvmResultsClick(modelType, dataSet, number, dataType, varargin) % LVMRESULTSCLICK Load a results file and visualise them with clicks % FORMAT % DESC loads results of a latent variable model and visualises them. % ARG modelType : the type of model ran on the data set. % ARG dataSet : the name of the data set to load. % ARG number : the number of the run used. % ARG dataType : the type of data to visualise. % ARG arg1, arg2, arg3 ... : additional arguments to be passed to the % lvmVisualise command. % % SEEALSO : lvmLoadResult, lvmVisualise % % COPYRIGHT : Neil D. Lawrence, 2008, 2009 % MLTOOLS [model, lbls] = lvmLoadResult(modelType, dataSet, number); % Visualise the results switch size(model.X, 2) case 2 lvmClickVisualise(model, lbls, [dataType 'Visualise'], [dataType 'Modify'], ... varargin{:}); otherwise lvmClickVisualise(model, lbls, [dataType 'Visualise'], [dataType 'Modify'], ... varargin{:}); end
{-# OPTIONS --without-K --safe #-} module Dodo.Unary.Equality where -- Stdlib imports import Relation.Binary.PropositionalEquality as Eq open Eq using (_≡_; refl) open import Level using (Level; _⊔_) open import Function using (_∘_) open import Relation.Unary using (Pred) -- # Definitions infix 4 _⊆₁'_ _⊆₁_ _⇔₁_ -- Binary relation subset helper. Generally, use `_⊆₁_` (below). _⊆₁'_ : {a ℓ₁ ℓ₂ : Level} {A : Set a} → (P : Pred A ℓ₁) → (R : Pred A ℓ₂) → Set (a ⊔ ℓ₁ ⊔ ℓ₂) _⊆₁'_ {A = A} P R = ∀ (x : A) → P x → R x -- Somehow, Agda cannot infer P and R from `P ⇒ R`, and requires them explicitly passed. -- For proof convenience, wrap the proof in this structure, which explicitly conveys P and R -- to the type-checker. data _⊆₁_ {a ℓ₁ ℓ₂ : Level} {A : Set a} (P : Pred A ℓ₁) (R : Pred A ℓ₂) : Set (a ⊔ ℓ₁ ⊔ ℓ₂) where ⊆: : P ⊆₁' R → P ⊆₁ R data _⇔₁_ {a ℓ₁ ℓ₂ : Level} {A : Set a} (P : Pred A ℓ₁) (R : Pred A ℓ₂) : Set (a ⊔ ℓ₁ ⊔ ℓ₂) where ⇔: : P ⊆₁' R → R ⊆₁' P → P ⇔₁ R -- # Helpers ⇔₁-intro : {a ℓ₁ ℓ₂ : Level} {A : Set a} → {P : Pred A ℓ₁} {R : Pred A ℓ₂} → P ⊆₁ R → R ⊆₁ P → P ⇔₁ R ⇔₁-intro (⊆: P⊆R) (⊆: R⊆P) = ⇔: P⊆R R⊆P ⇔₁-compose : ∀ {a b ℓ₁ ℓ₂ ℓ₃ ℓ₄ : Level} {A : Set a} {B : Set b} {P : Pred A ℓ₁} {Q : Pred A ℓ₂} {R : Pred B ℓ₃} {S : Pred B ℓ₄} → ( P ⊆₁ Q → R ⊆₁ S ) → ( Q ⊆₁ P → S ⊆₁ R ) → P ⇔₁ Q → R ⇔₁ S ⇔₁-compose ⊆-proof ⊇-proof (⇔: P⊆Q R⊆S) = ⇔₁-intro (⊆-proof (⊆: P⊆Q)) (⊇-proof (⊆: R⊆S)) -- # Properties -- ## Properties: ⊆₁ module _ {a ℓ : Level} {A : Set a} {R : Pred A ℓ} where ⊆₁-refl : R ⊆₁ R ⊆₁-refl = ⊆: (λ _ Rx → Rx) module _ {a ℓ₁ ℓ₂ ℓ₃ : Level} {A : Set a} {P : Pred A ℓ₁} {Q : Pred A ℓ₂} {R : Pred A ℓ₃} where ⊆₁-trans : P ⊆₁ Q → Q ⊆₁ R → P ⊆₁ R ⊆₁-trans (⊆: P⊆Q) (⊆: Q⊆R) = ⊆: (λ x Qx → Q⊆R x (P⊆Q x Qx)) -- ## Properties: ⇔₁ module _ {a ℓ : Level} {A : Set a} {R : Pred A ℓ} where ⇔₁-refl : R ⇔₁ R ⇔₁-refl = ⇔₁-intro ⊆₁-refl ⊆₁-refl module _ {a ℓ₁ ℓ₂ : Level} {A : Set a} {Q : Pred A ℓ₁} {R : Pred A ℓ₂} where ⇔₁-sym : Q ⇔₁ R → R ⇔₁ Q -- WARNING: Do *NOT* use `Symmetric _⇔_`. It messes up the universe levels. ⇔₁-sym (⇔: Q⊆R R⊆Q) = ⇔: R⊆Q Q⊆R module _ {a ℓ₁ ℓ₂ ℓ₃ : Level} {A : Set a} {P : Pred A ℓ₁} {Q : Pred A ℓ₂} {R : Pred A ℓ₃} where ⇔₁-trans : P ⇔₁ Q → Q ⇔₁ R → P ⇔₁ R ⇔₁-trans (⇔: P⊆Q Q⊆P) (⇔: Q⊆R R⊆Q) = ⇔₁-intro (⊆₁-trans (⊆: P⊆Q) (⊆: Q⊆R)) (⊆₁-trans (⊆: R⊆Q) (⊆: Q⊆P)) -- # Operations -- ## Operations: ⇔₁ and ⊆₁ conversion un-⊆₁ : ∀ {a ℓ₁ ℓ₂ : Level} {A : Set a} {P : Pred A ℓ₁} {R : Pred A ℓ₂} → P ⊆₁ R → P ⊆₁' R un-⊆₁ (⊆: P⊆R) = P⊆R unlift-⊆₁ : ∀ {a b ℓ₁ ℓ₂ ℓ₃ ℓ₄ : Level} {A : Set a} {B : Set b} {P : Pred A ℓ₁} {Q : Pred A ℓ₂} {R : Pred B ℓ₃} {S : Pred B ℓ₄} → ( P ⊆₁ Q → R ⊆₁ S ) → ( P ⊆₁' Q → R ⊆₁' S ) unlift-⊆₁ f P⊆Q = un-⊆₁ (f (⊆: P⊆Q)) lift-⊆₁ : ∀ {a b ℓ₁ ℓ₂ ℓ₃ ℓ₄ : Level} {A : Set a} {B : Set b} {P : Pred A ℓ₁} {Q : Pred A ℓ₂} {R : Pred B ℓ₃} {S : Pred B ℓ₄} → ( P ⊆₁' Q → R ⊆₁' S ) → ( P ⊆₁ Q → R ⊆₁ S ) lift-⊆₁ f (⊆: P⊆Q) = ⊆: (f P⊆Q) ⇔₁-to-⊆₁ : {a ℓ₁ ℓ₂ : Level} {A : Set a} {P : Pred A ℓ₁} {Q : Pred A ℓ₂} → P ⇔₁ Q ------ → P ⊆₁ Q ⇔₁-to-⊆₁ (⇔: P⊆Q _) = ⊆: P⊆Q ⇔₁-to-⊇₁ : {a ℓ₁ ℓ₂ : Level} {A : Set a} {P : Pred A ℓ₁} {Q : Pred A ℓ₂} → P ⇔₁ Q ------ → Q ⊆₁ P ⇔₁-to-⊇₁ (⇔: _ Q⊆P) = ⊆: Q⊆P -- ## Operations: ⊆₁ ⊆₁-apply : ∀ {a ℓ₁ ℓ₂ : Level} {A : Set a} {P : Pred A ℓ₁} {Q : Pred A ℓ₂} → P ⊆₁ Q → {x : A} → P x ------- → Q x ⊆₁-apply (⊆: P⊆Q) {x} = P⊆Q x ⊆₁-substˡ : ∀ {a ℓ₁ ℓ₂ ℓ₃ : Level} {A : Set a} {P : Pred A ℓ₁} {Q : Pred A ℓ₂} {R : Pred A ℓ₃} {x : A} → P ⇔₁ Q → P ⊆₁ R ------ → Q ⊆₁ R ⊆₁-substˡ (⇔: _ Q⊆P) P⊆R = ⊆₁-trans (⊆: Q⊆P) P⊆R ⊆₁-substʳ : ∀ {a ℓ₁ ℓ₂ ℓ₃ : Level} {A : Set a} {P : Pred A ℓ₁} {Q : Pred A ℓ₂} {R : Pred A ℓ₃} → Q ⇔₁ R → P ⊆₁ Q ------ → P ⊆₁ R ⊆₁-substʳ (⇔: Q⊆R _) P⊆Q = ⊆₁-trans P⊆Q (⊆: Q⊆R) ≡-to-⊆₁ : {a b ℓ : Level} {A : Set a} {P : Pred A ℓ} {Q : Pred A ℓ} → P ≡ Q ------ → P ⊆₁ Q ≡-to-⊆₁ refl = ⊆: (λ _ Px → Px) -- ## Operations: ⇔₁ ⇔₁-apply-⊆₁ : {a ℓ₁ ℓ₂ : Level} {A : Set a} {P : Pred A ℓ₁} {Q : Pred A ℓ₂} → P ⇔₁ Q → {x : A} → P x ------- → Q x ⇔₁-apply-⊆₁ = ⊆₁-apply ∘ ⇔₁-to-⊆₁ ⇔₁-apply-⊇₁ : {a ℓ₁ ℓ₂ : Level} {A : Set a} {P : Pred A ℓ₁} {Q : Pred A ℓ₂} → P ⇔₁ Q → {x : A} → Q x ------- → P x ⇔₁-apply-⊇₁ = ⊆₁-apply ∘ ⇔₁-to-⊇₁ ≡-to-⇔₁ : {a ℓ : Level} {A : Set a} {P : Pred A ℓ} {Q : Pred A ℓ} → P ≡ Q ------ → P ⇔₁ Q ≡-to-⇔₁ refl = ⇔₁-intro ⊆₁-refl ⊆₁-refl -- # Reasoning -- ## Reasoning: ⊆₁ module ⊆₁-Reasoning {a ℓ₁ : Level} {A : Set a} where infix 3 _⊆₁∎ infixr 2 step-⊆₁ infix 1 begin⊆₁_ begin⊆₁_ : {ℓ₂ : Level} {P : Pred A ℓ₁} {Q : Pred A ℓ₂} → P ⊆₁ Q ------ → P ⊆₁ Q begin⊆₁_ P⊆Q = P⊆Q step-⊆₁ : ∀ {ℓ₂ ℓ₃ : Level} → (P : Pred A ℓ₁) → {Q : Pred A ℓ₂} → {R : Pred A ℓ₃} → Q ⊆₁ R → P ⊆₁ Q ------ → P ⊆₁ R step-⊆₁ P Q⊆R P⊆Q = ⊆₁-trans P⊆Q Q⊆R _⊆₁∎ : ∀ (P : Pred A ℓ₁) → P ⊆₁ P _⊆₁∎ _ = ⊆₁-refl syntax step-⊆₁ P Q⊆R P⊆Q = P ⊆₁⟨ P⊆Q ⟩ Q⊆R -- ## Reasoning: ⇔₁ module ⇔₁-Reasoning {a ℓ₁ : Level} {A : Set a} where infix 3 _⇔₁∎ infixr 2 _⇔₁⟨⟩_ step-⇔₁ infix 1 begin⇔₁_ begin⇔₁_ : {ℓ₂ : Level} {P : Pred A ℓ₁} {Q : Pred A ℓ₂} → P ⇔₁ Q ------ → P ⇔₁ Q begin⇔₁_ P⇔Q = P⇔Q _⇔₁⟨⟩_ : {ℓ₂ : Level} (P : Pred A ℓ₁) → {Q : Pred A ℓ₂} → P ⇔₁ Q --------------- → P ⇔₁ Q _ ⇔₁⟨⟩ x≡y = x≡y step-⇔₁ : ∀ {ℓ₂ ℓ₃ : Level} → (P : Pred A ℓ₁) → {Q : Pred A ℓ₂} → {R : Pred A ℓ₃} → Q ⇔₁ R → P ⇔₁ Q --------------- → P ⇔₁ R step-⇔₁ _ Q⇔R P⇔Q = ⇔₁-trans P⇔Q Q⇔R _⇔₁∎ : ∀ (P : Pred A ℓ₁) → P ⇔₁ P _⇔₁∎ _ = ⇔₁-refl syntax step-⇔₁ P Q⇔R P⇔Q = P ⇔₁⟨ P⇔Q ⟩ Q⇔R
{- null not null -} import CIL.FFI putNullableStrLn : Nullable String -> IO () putNullableStrLn = putStrLn . nullable "null" id main : IO () main = do putNullableStrLn null putNullableStrLn (asNullable "not null") -- Local Variables: -- idris-load-packages: ("cil") -- End:
Formal statement is: lemma prime_factor_nat: "n \<noteq> (1::nat) \<Longrightarrow> \<exists>p. prime p \<and> p dvd n" Informal statement is: If $n$ is a natural number greater than 1, then there exists a prime number $p$ that divides $n$.
module C import B foo : BFunc x foo1 : BFunc x foo2 : BFunc x foo3 : BFunc x
# Euler Problem 203 The binomial coefficients nCk can be arranged in triangular form, Pascal's triangle, like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 ......... It can be seen that the first eight rows of Pascal's triangle contain twelve distinct numbers: 1, 2, 3, 4, 5, 6, 7, 10, 15, 20, 21 and 35. A positive integer n is called squarefree if no square of a prime divides n. Of the twelve distinct numbers in the first eight rows of Pascal's triangle, all except 4 and 20 are squarefree. The sum of the distinct squarefree numbers in the first eight rows is 105. Find the sum of the distinct squarefree numbers in the first 51 rows of Pascal's triangle. ```python N = 51 def binom(n, k): if k > n // 2: k = n - k b = 1 for i in range(k): b = (b * (n - i)) // (i + 1) return b ``` ```python from sympy import primerange, nextprime MAXIMUM_ROW_NUMBER = 100 smallprimes = list(primerange(2, MAXIMUM_ROW_NUMBER + 1)) ``` ```python def squarefree_binom(n, k): assert n <= MAXIMUM_ROW_NUMBER for p in smallprimes: if p > n: return True if binom_order(n, k, p) > 1: return False return True ``` The exponent of a prime $p$ in the prime factorization of $n!$ is equal to $(n-s)/(p-1)$, where $s$ is the sum of the base-$p$ digits of $n$. This is a consequence of [Legendre's formula](https://en.wikipedia.org/wiki/Legendre%27s_formula). We can use this formula to calculate the exponent of $p$ in the prime factorization of a binomial coefficient. ```python def sum_of_digits(n, p): return n if n < p else (n % p) + sum_of_digits(n // p, p) def fact_order(n, p): return (n - sum_of_digits(n, p)) // (p - 1) def binom_order(n, k, p): return fact_order(n, p) - fact_order(k, p) - fact_order(n-k, p) ``` ```python results = set() for n in range(N): for k in range(n//2 + 1): if squarefree_binom(n, k): results.add(binom(n, k)) print(sum(results)) ``` 34029210557338
\chapter{``A'' Standard Extension for Atomic Instructions, Version 2.0} \label{atomics} \begin{commentary} This section is somewhat out of date as the RISC-V memory model is currently under revision to ensure it can efficiently support current programming language memory models. The revised base memory model will contain further ordering constraints, including at least that loads to the same address from the same hart cannot be reordered, and that syntactic data dependencies between instructions are respected. \end{commentary} The standard atomic instruction extension is denoted by instruction subset name ``A'', and contains instructions that atomically read-modify-write memory to support synchronization between multiple RISC-V harts running in the same memory space. The two forms of atomic instruction provided are load-reserved/store-conditional instructions and atomic fetch-and-op memory instructions. Both types of atomic instruction support various memory consistency orderings including unordered, acquire, release, and sequentially consistent semantics. These instructions allow RISC-V to support the RCsc memory consistency model~\cite{Gharachorloo90memoryconsistency}. \begin{commentary} After much debate, the language community and architecture community appear to have finally settled on release consistency as the standard memory consistency model and so the RISC-V atomic support is built around this model. \end{commentary} \section{Specifying Ordering of Atomic Instructions} The base RISC-V ISA has a relaxed memory model, with the FENCE instruction used to impose additional ordering constraints. The address space is divided by the execution environment into memory and I/O domains, and the FENCE instruction provides options to order accesses to one or both of these two address domains. To provide more efficient support for release consistency~\cite{Gharachorloo90memoryconsistency}, each atomic instruction has two bits, {\em aq} and {\em rl}, used to specify additional memory ordering constraints as viewed by other RISC-V harts. The bits order accesses to one of the two address domains, memory or I/O, depending on which address domain the atomic instruction is accessing. No ordering constraint is implied to accesses to the other domain, and a FENCE instruction should be used to order across both domains. If both bits are clear, no additional ordering constraints are imposed on the atomic memory operation. If only the {\em aq} bit is set, the atomic memory operation is treated as an {\em acquire} access, i.e., no following memory operations on this RISC-V hart can be observed to take place before the acquire memory operation. If only the {\em rl} bit is set, the atomic memory operation is treated as a {\em release} access, i.e., the release memory operation can not be observed to take place before any earlier memory operations on this RISC-V hart. If both the {\em aq} and {\em rl} bits are set, the atomic memory operation is {\em sequentially consistent} and cannot be observed to happen before any earlier memory operations or after any later memory operations in the same RISC-V hart, and can only be observed by any other hart in the same global order of all sequentially consistent atomic memory operations to the same address domain. \begin{commentary} Theoretically, the definition of the {\em aq} and {\em rl} bits allows for implementations without global store atomicity. When both {\em aq} and {\em rl} bits are set, however, we require full sequential consistency for the atomic operation which implies global store atomicity in addition to both acquire and release semantics. In practice, hardware systems are usually implemented with global store atomicity, embodied in local processor ordering rules together with single-writer cache coherence protocols. \end{commentary} \section{Load-Reserved/Store-Conditional Instructions} \vspace{-0.2in} \begin{center} \begin{tabular}{R@{}W@{}W@{}R@{}R@{}F@{}R@{}O} \\ \instbitrange{31}{27} & \instbit{26} & \instbit{25} & \instbitrange{24}{20} & \instbitrange{19}{15} & \instbitrange{14}{12} & \instbitrange{11}{7} & \instbitrange{6}{0} \\ \hline \multicolumn{1}{|c|}{funct5} & \multicolumn{1}{c|}{aq} & \multicolumn{1}{c|}{rl} & \multicolumn{1}{c|}{rs2} & \multicolumn{1}{c|}{rs1} & \multicolumn{1}{c|}{funct3} & \multicolumn{1}{c|}{rd} & \multicolumn{1}{c|}{opcode} \\ \hline 5 & 1 & 1 & 5 & 5 & 3 & 5 & 7 \\ LR & \multicolumn{2}{c}{ordering} & 0 & addr & width & dest & AMO \\ SC & \multicolumn{2}{c}{ordering} & src & addr & width & dest & AMO \\ \end{tabular} \end{center} Complex atomic memory operations on a single memory word are performed with the load-reserved (LR) and store-conditional (SC) instructions. LR loads a word from the address in {\em rs1}, places the sign-extended value in {\em rd}, and registers a reservation on the memory address. SC writes a word in {\em rs2} to the address in {\em rs1}, provided a valid reservation still exists on that address. SC writes zero to {\em rd} on success or a nonzero code on failure. \begin{commentary} Both compare-and-swap (CAS) and LR/SC can be used to build lock-free data structures. After extensive discussion, we opted for LR/SC for several reasons: 1) CAS suffers from the ABA problem, which LR/SC avoids because it monitors all accesses to the address rather than only checking for changes in the data value; 2) CAS would also require a new integer instruction format to support three source operands (address, compare value, swap value) as well as a different memory system message format, which would complicate microarchitectures; 3) Furthermore, to avoid the ABA problem, other systems provide a double-wide CAS (DW-CAS) to allow a counter to be tested and incremented along with a data word. This requires reading five registers and writing two in one instruction, and also a new larger memory system message type, further complicating implementations; 4) LR/SC provides a more efficient implementation of many primitives as it only requires one load as opposed to two with CAS (one load before the CAS instruction to obtain a value for speculative computation, then a second load as part of the CAS instruction to check if value is unchanged before updating). The main disadvantage of LR/SC over CAS is livelock, which we avoid with an architected guarantee of eventual forward progress as described below. Another concern is whether the influence of the current x86 architecture, with its DW-CAS, will complicate porting of synchronization libraries and other software that assumes DW-CAS is the basic machine primitive. A possible mitigating factor is the recent addition of transactional memory instructions to x86, which might cause a move away from DW-CAS. \end{commentary} The failure code with value 1 is reserved to encode an unspecified failure. Other failure codes are reserved at this time, and portable software should only assume the failure code will be non-zero. \begin{commentary} We reserve a failure code of 1 to mean ``unspecified'' so that simple implementations may return this value using the existing mux required for the SLT/SLTU instructions. More specific failure codes might be defined in future versions or extensions to the ISA. \end{commentary} The execution environment may require that the address held in {\em rs1} be naturally aligned to the size of the operand (i.e., eight-byte aligned for 64-bit words and four-byte aligned for 32-bit words). If, in such an execution environment, an LR or SC address is not naturally aligned, a misaligned address exception will be generated. If the execution environment permits misaligned LR and SC addresses, then LR and SC instructions using misaligned addresses execute atomically with respect to other accesses to the same address and of the same size. In such environments, regular loads and stores using misaligned addresses also execute atomically with respect to other accesses to the same address and of the same size. \label{lrscseq} In the standard A extension, certain constrained LR/SC sequences are guaranteed to succeed eventually. The static code for the LR/SC sequence plus the code to retry the sequence in case of failure must comprise at most 16 integer instructions placed sequentially in memory. For the sequence to be guaranteed to eventually succeed, the dynamic code executed between the LR and SC instructions can only contain other instructions from the base ``I'' subset, excluding loads, stores, backward jumps or taken backward branches, FENCE, FENCE.I, and SYSTEM instructions. The code to retry a failing LR/SC sequence can contain backward jumps and/or branches to repeat the LR/SC sequence, but otherwise has the same constraints. The SC must be to the same address and of the same data size as the latest LR executed. LR/SC sequences that do not meet these constraints might complete on some attempts on some implementations, but there is no guarantee of eventual success. \begin{commentary} One advantage of CAS is that it guarantees that some hart eventually makes progress, whereas an LR/SC atomic sequence could livelock indefinitely on some systems. To avoid this concern, we added an architectural guarantee of forward progress to LR/SC atomic sequences. The restrictions on LR/SC sequence contents allows an implementation to capture a cache line on the LR and complete the LR/SC sequence by holding off remote cache interventions for a bounded short time. Interrupts and TLB misses might cause the reservation to be lost, but eventually the atomic sequence can complete. We restricted the length of LR/SC sequences to fit within 64 contiguous instruction bytes in the base ISA to avoid undue restrictions on instruction cache and TLB size and associativity. Similarly, we disallowed other loads and stores within the sequences to avoid restrictions on data cache associativity. The restrictions on branches and jumps limits the time that can be spent in the sequence. Floating-point operations and integer multiply/divide were disallowed to simplify the operating system's emulation of these instructions on implementations lacking appropriate hardware support. Although software is not forbidden from using LR/SC sequences that do not meet the forward-progress constraints, portable software must detect the case that the sequence repeatedly fails, then fall back to an alternate code sequence that does not run afoul of the forward-progress constraints. \end{commentary} An implementation can reserve an arbitrary subset of the memory space on each LR and multiple LR reservations might be active simultaneously for a single hart. An SC can succeed if no accesses from other harts to the address can be observed to have occurred between the SC and the last LR in this hart to reserve the address. Note this LR might have had a different address argument, but reserved the SC's address as part of the memory subset. Following this model, in systems with memory translation, an SC is allowed to succeed if the earlier LR reserved the same location using an alias with a different virtual address, but is also allowed to fail if the virtual address is different. The SC must fail if there is an observable memory access from another hart to the address, or a preemptive context switch on this hart, between the LR and the SC. \begin{commentary} The privileged architecture specifies the mechanism by which the implementation yields a load reservation during a preemptive context switch. Cooperative user-level context switches might not cause a load reservation to be yielded, so user-level threads should generally avoid voluntary context switches in the middle of an LR/SC sequence. \end{commentary} \begin{commentary} The specification explicitly allows implementations to support more powerful implementations with wider guarantees, provided they do not void the atomicity guarantees for the constrained sequences. \end{commentary} LR/SC can be used to construct lock-free data structures. An example using LR/SC to implement a compare-and-swap function is shown in Figure~\ref{cas}. If inlined, compare-and-swap functionality need only take three instructions. \begin{figure}[h!] \begin{center} \begin{verbatim} # a0 holds address of memory location # a1 holds expected value # a2 holds desired value # a0 holds return value, 0 if successful, !0 otherwise cas: lr.w t0, (a0) # Load original value. bne t0, a1, fail # Doesn't match, so fail. sc.w a0, a2, (a0) # Try to update. jr ra # Return. fail: li a0, 1 # Set return to failure. jr ra # Return. \end{verbatim} \end{center} \caption{Sample code for compare-and-swap function using LR/SC.} \label{cas} \end{figure} An SC instruction can never be observed by another RISC-V hart before the immediately preceding LR. Due to the atomic nature of the LR/SC sequence, no memory operations from any hart can be observed to have occurred between the LR and a successful SC. The LR/SC sequence can be given acquire semantics by setting the {\em aq} bit on the SC instruction. The LR/SC sequence can be given release semantics by setting the {\em rl} bit on the LR instruction. Setting both {\em aq} and {\em rl} bits on the LR instruction, and setting the {\em aq} bit on the SC instruction makes the LR/SC sequence sequentially consistent with respect to other sequentially consistent atomic operations. If neither bit is set on both LR and SC, the LR/SC sequence can be observed to occur before or after surrounding memory operations from the same RISC-V hart. This can be appropriate when the LR/SC sequence is used to implement a parallel reduction operation. \begin{commentary} In general, a multi-word atomic primitive is desirable but there is still considerable debate about what form this should take, and guaranteeing forward progress adds complexity to a system. Our current thoughts are to include a small limited-capacity transactional memory buffer along the lines of the original transactional memory proposals as an optional standard extension ``T''. \end{commentary} \section{Atomic Memory Operations} \vspace{-0.2in} \begin{center} \begin{tabular}{O@{}W@{}W@{}R@{}R@{}F@{}R@{}R} \\ \instbitrange{31}{27} & \instbit{26} & \instbit{25} & \instbitrange{24}{20} & \instbitrange{19}{15} & \instbitrange{14}{12} & \instbitrange{11}{7} & \instbitrange{6}{0} \\ \hline \multicolumn{1}{|c|}{funct5} & \multicolumn{1}{c|}{aq} & \multicolumn{1}{c|}{rl} & \multicolumn{1}{c|}{rs2} & \multicolumn{1}{c|}{rs1} & \multicolumn{1}{c|}{funct3} & \multicolumn{1}{c|}{rd} & \multicolumn{1}{c|}{opcode} \\ \hline 5 & 1 & 1 & 5 & 5 & 3 & 5 & 7 \\ AMOSWAP.W/D & \multicolumn{2}{c}{ordering} & src & addr & width & dest & AMO \\ AMOADD.W/D & \multicolumn{2}{c}{ordering} & src & addr & width & dest & AMO \\ AMOAND.W/D & \multicolumn{2}{c}{ordering} & src & addr & width & dest & AMO \\ AMOOR.W/D & \multicolumn{2}{c}{ordering} & src & addr & width & dest & AMO \\ AMOXOR.W/D & \multicolumn{2}{c}{ordering} & src & addr & width & dest & AMO \\ AMOMAX[U].W/D & \multicolumn{2}{c}{ordering} & src & addr & width & dest & AMO \\ AMOMIN[U].W/D & \multicolumn{2}{c}{ordering} & src & addr & width & dest & AMO \\ \end{tabular} \end{center} \vspace{-0.1in} The atomic memory operation (AMO) instructions perform read-modify-write operations for multiprocessor synchronization and are encoded with an R-type instruction format. These AMO instructions atomically load a data value from the address in {\em rs1}, place the value into register {\em rd}, apply a binary operator to the loaded value and the original value in {\em rs2}, then store the result back to the address in {\em rs1}. AMOs can either operate on 64-bit (RV64 only) or 32-bit words in memory. For RV64, 32-bit AMOs always sign-extend the value placed in {\em rd}. The execution environment may require that the address held in {\em rs1} be naturally aligned to the size of the operand (i.e., eight-byte aligned for 64-bit words and four-byte aligned for 32-bit words). If, in such an execution environment, an AMO address is not naturally aligned, a misaligned address exception will be generated. If the execution environment permits misaligned AMO addresses, then AMO instructions using misaligned addresses execute atomically with respect to other accesses to the same address and of the same size. In such environments, regular loads and stores using misaligned addresses also execute atomically with respect to other accesses to the same address and of the same size. The operations supported are swap, integer add, logical AND, logical OR, logical XOR, and signed and unsigned integer maximum and minimum. Without ordering constraints, these AMOs can be used to implement parallel reduction operations, where typically the return value would be discarded by writing to {\tt x0}. \begin{commentary} We provided fetch-and-op style atomic primitives as they scale to highly parallel systems better than LR/SC or CAS. A simple microarchitecture can implement AMOs using the LR/SC primitives. More complex implementations might also implement AMOs at memory controllers, and can optimize away fetching the original value when the destination is {\tt x0}. The set of AMOs was chosen to support the C11/C++11 atomic memory operations efficiently, and also to support parallel reductions in memory. Another use of AMOs is to provide atomic updates to memory-mapped device registers (e.g., setting, clearing, or toggling bits) in the I/O space. \end{commentary} To help implement multiprocessor synchronization, the AMOs optionally provide release consistency semantics. If the {\em aq} bit is set, then no later memory operations in this RISC-V hart can be observed to take place before the AMO. Conversely, if the {\em rl} bit is set, then other RISC-V harts will not observe the AMO before memory accesses preceding the AMO in this RISC-V hart. \begin{commentary} The AMOs were designed to implement the C11 and C++11 memory models efficiently. Although the FENCE R, RW instruction suffices to implement the {\em acquire} operation and FENCE RW, W suffices to implement {\em release}, both imply additional unnecessary ordering as compared to AMOs with the corresponding {\em aq} or {\em rl} bit set. \end{commentary} An example code sequence for a critical section guarded by a test-and-set spinlock is shown in Figure~\ref{critical}. Note the first AMO is marked {\em aq} to order the lock acquisition before the critical section, and the second AMO is marked {\em rl} to order the critical section before the lock relinquishment. \begin{figure}[h!] \begin{center} \begin{verbatim} li t0, 1 # Initialize swap value. again: amoswap.w.aq t0, t0, (a0) # Attempt to acquire lock. bnez t0, again # Retry if held. # ... # Critical section. # ... amoswap.w.rl x0, x0, (a0) # Release lock by storing 0. \end{verbatim} \end{center} \caption{Sample code for mutual exclusion. {\tt a0} contains the address of the lock.} \label{critical} \end{figure} \begin{commentary} We recommend the use of the AMO Swap idiom shown above for both lock acquire and release to simplify the implementation of speculative lock elision~\cite{Rajwar:2001:SLE}. At the risk of complicating the implementation of atomic operations, microarchitectures can elide the store within the acquire swap if the lock value matches the swap value, to avoid dirtying a cache line held in a shared or exclusive clean state. The effect is similar to a test-and-test-and-set lock but with shorter code paths. \end{commentary} The instructions in the ``A'' extension can also be used to provide sequentially consistent loads and stores. A sequentially consistent load can be implemented as an LR with both {\em aq} and {\em rl} set. A sequentially consistent store can be implemented as an AMOSWAP that writes the old value to x0 and has both {\em aq} and {\em rl} set.
using DiffEqJump, DiffEqBase using Test function regular_rate(out,u,p,t) out[1] = (0.1/1000.0)*u[1]*u[2] out[2] = 0.01u[2] end function regular_c(dc,u,p,t,mark) dc[1,1] = -1 dc[2,1] = 1 dc[2,2] = -1 dc[3,2] = 1 end dc = zeros(3,2) rj = RegularJump(regular_rate,regular_c,dc;constant_c=true) jumps = JumpSet(rj) prob = DiscreteProblem([999.0,1.0,0.0],(0.0,250.0)) jump_prob = JumpProblem(prob,Direct(),rj) sol = solve(jump_prob,SimpleTauLeaping();dt=1.0) sol = solve(jump_prob,RegularSSA())
Though Townsend was proud of what he had accomplished so early in his career , he was discouraged by his experience with the music industry . " I was becoming a product of somebody else 's imagination , and it was mixing with my own personality , " he later reflected . " This combination was appalling . " He pushed to get his own projects off the ground . Despite getting notable touring gigs with other musicians , however , Townsend continued to face rejection of his own music . Relativity Records dropped Noisescapes from their label shortly after Townsend accepted Vai 's offer , seeing no commercial appeal in Townsend 's music . " I have a hunch they only offered me a deal to get me to sing with Steve , " he mused . While touring with the Wildhearts , Townsend received a phone call from an A & R representative for Roadrunner Records , expressing an interest in his demos and an intention to sign him . The offer was ultimately rescinded by the head of Roadrunner , who regarded Townsend 's recordings as " just noise " .
Require Export P05. Theorem ins_relate: forall k v t cts, SearchTree t -> Abs t cts -> Abs (ins k v t) (t_update cts (int2Z k) v). Proof. exact FILL_IN_HERE. Qed. Theorem insert_relate: forall k v t cts, SearchTree t -> Abs t cts -> Abs (insert k v t) (t_update cts (int2Z k) v). Proof. intros. unfold insert. apply makeBlack_relate. apply ins_relate; auto. Qed. (** * Final Correctness Theorem *) Theorem redblack_correct: forall (l: list (key*D.V)) k, lookup k (map_reduce (fun kv tr => insert (fst kv) (snd kv) tr) empty_tree l) = (map_reduce (fun kv tm => t_update tm (int2Z (fst kv)) (snd kv)) (t_empty D.default) l) (int2Z k). Proof. assert (ABS: forall l, SearchTree (map_reduce (fun kv tr => insert (fst kv) (snd kv) tr) empty_tree l) /\ Abs (map_reduce (fun kv tr => insert (fst kv) (snd kv) tr) empty_tree l) (map_reduce (fun kv tm => t_update tm (int2Z (fst kv)) (snd kv)) (t_empty D.default) l)). { intros. induction l; simpl. - eauto using empty_tree_SearchTree, empty_tree_relate. - destruct IHl. eauto using insert_SearchTree, insert_relate. } intros. eapply lookup_relate, ABS. Qed.
% hohmann.m July 9, 2013 % Hohmann two impulse orbit transfer between % planar and non-coplanar circular orbits % includes three-dimensional orbit graphics % and graphical primer vector analysis % Orbital Mechanics with MATLAB %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% global rtd dtr pvi pvdi global mu req hn1 hn2 hn3 dinc % astrodynamic and utility constants om_constants; % Brent root-finding tolerance rtol = 1.0e-8; % request inputs clc; home; fprintf('\nHohmann Orbit Transfer Analysis\n'); while (1) fprintf('\n\nplease input the initial altitude (kilometers)\n'); alt1 = input('? '); if (alt1 > 0.0) break; end end while (1) fprintf('\n\nplease input the final altitude (kilometers)\n'); alt2 = input('? '); if (alt2 > 0.0) break; end end while (1) fprintf('\n\nplease input the initial orbital inclination (degrees)'); fprintf('\n(0 <= inclination <= 180)\n'); inc1 = input('? '); if (inc1 >= 0.0 && inc1 <= 180.0) break; end end while (1) fprintf('\n\nplease input the final orbital inclination (degrees)'); fprintf('\n(0 <= inclination <= 180)\n'); inc2 = input('? '); if (inc2 >= 0.0 && inc2 <= 180.0) break; end end % convert orbit inclinations to radians inc1 = inc1 * dtr; inc2 = inc2 * dtr; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % solve the orbit transfer problem % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % calculate total inclination change (radians) dinc = abs(inc2 - inc1); % compute geocentric radii of initial and final orbits (kilometers) r1 = req + alt1; r2 = req + alt2; % compute "normalized" radii hn1 = sqrt(2.0 * r2 / (r2 + r1)); hn2 = sqrt(r1 / r2); hn3 = sqrt(2.0 * r1 / (r2 + r1)); % compute "local circular velocity" of initial and final orbits (km/sec) v1 = sqrt(mu / r1); v2 = sqrt(mu / r2); % compute transfer orbit semimajor axis (kilometers) smat = 0.5 * (r1 + r2); % compute transfer orbit eccentricity (non-dimensional) ecct = (max(r1, r2) - min(r1, r2)) / (r1 + r2); % compute transfer orbit perigee and apogee radii and velocities rp = smat * (1.0 - ecct); ra = smat * (1.0 + ecct); vt1 = sqrt(2.0 * mu * ra / (rp * (rp + ra))); vt2 = sqrt(2.0 * mu * rp / (ra * (rp + ra))); % compute transfer orbit period (seconds) taut = 2.0 * pi * sqrt(smat^3 / mu); tof = 0.5 * taut; if (abs(dinc) == 0) % coplanar orbit transfer if (r2 > r1) % higher-to-lower transfer dv1 = vt1 - v1; dv2 = v2 - vt2; else % lower-to-higher transfer dv1 = v1 - vt2; dv2 = vt1 - v2; end dinc1 = 0; dinc2 = 0; inct = inc1; else % non-coplanar orbit transfer [xroot, froot] = brent('hohmfunc', 0, dinc, rtol); % calculate delta-v's dinc1 = xroot; dinc2 = dinc - dinc1; dv1 = v1 * sqrt(1.0 + hn1 * hn1 - 2.0 * hn1 * cos(dinc1)); dv2 = v1 * sqrt(hn2 * hn2 * hn3 * hn3 + hn2 * hn2 ... - 2.0 * hn2 * hn2 * hn3 * cos(dinc2)); if (inc2 > inc1) inct = inc1 + dinc1; else inct = inc1 - dinc1; end end % print results clc; home; fprintf('\nHohmann Orbit Transfer Analysis'); fprintf('\n-------------------------------\n\n'); fprintf('initial orbit altitude %10.4f kilometers \n\n', alt1); fprintf('initial orbit radius %10.4f kilometers \n\n', alt1 + req); fprintf('initial orbit inclination %10.4f degrees \n\n', inc1 * rtd); fprintf('initial orbit velocity %10.4f meters/second \n\n\n', 1000.0 * v1); fprintf('final orbit altitude %10.4f kilometers \n\n', alt2); fprintf('final orbit radius %10.4f kilometers \n\n', alt2 + req); fprintf('final orbit inclination %10.4f degrees \n\n', inc2 * rtd); fprintf('final orbit velocity %10.4f meters/second \n', 1000.0 * v2); fprintf('\n\nfirst inclination change %10.4f degrees\n\n', dinc1 * rtd); fprintf('second inclination change %10.4f degrees\n\n', dinc2 * rtd); fprintf('total inclination change %10.4f degrees\n\n\n', rtd * (dinc1 + dinc2)); fprintf('first delta-v %10.4f meters/second \n\n', 1000.0 * dv1); fprintf('second delta-v %10.4f meters/second \n\n', 1000.0 * dv2); fprintf('total delta-v %10.4f meters/second \n\n\n', 1000.0 * (dv1 + dv2)); fprintf('transfer orbit semimajor axis %10.4f kilometers \n\n', smat); fprintf('transfer orbit eccentricity %10.8f \n\n', ecct); fprintf('transfer orbit inclination %10.4f degrees \n\n', rtd * inct); fprintf('transfer orbit perigee velocity %10.4f meters/second \n\n', 1000.0 * vt1); fprintf('transfer orbit apogee velocity %10.4f meters/second \n\n', 1000.0 * vt2); fprintf('transfer orbit coast time %10.4f seconds \n', tof); fprintf(' %10.4f minutes \n', tof / 60.0); fprintf(' %10.4f hours \n\n', tof / 3600.0); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % create trajectory graphics % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % load orbital elements arrays, create state vectors and plot orbits oevi(1) = r1; oevi(2) = 0.0; oevi(3) = inc1; oevi(4) = 0.0; oevi(5) = 0.0; % determine correct true anomaly (radians) if (alt2 > alt1) oevi(6) = 0.0; else oevi(6) = 180.0 * dtr; end [ri, vi] = orb2eci(mu, oevi); oevti(1) = smat; oevti(2) = ecct; oevti(3) = inct; oevti(4) = 0.0; oevti(5) = 0.0; % determine correct true anomaly (radians) if (alt2 > alt1) oevti(6) = 0.0; else oevti(6) = 180.0 * dtr; end [rti, vti] = orb2eci(mu, oevti); oevtf(1) = smat; oevtf(2) = ecct; oevtf(3) = inct; oevtf(4) = 0.0; oevtf(5) = 0.0; % determine correct true anomaly (radians) if (alt2 > alt1) oevtf(6) = 180.0 * dtr; else oevtf(6) = 0.0; end [rtf, vtf] = orb2eci(mu, oevtf); oevf(1) = r2; oevf(2) = 0.0; oevf(3) = inc2; oevf(4) = 0.0; oevf(5) = 0.0; % determine correct true anomaly (radians) if (alt2 > alt1) oevf(6) = 180.0 * dtr; else oevf(6) = 0.0; end [rf, vf] = orb2eci(mu, oevf); % compute orbital periods period1 = 2.0 * pi * oevi(1) * sqrt(oevi(1) / mu); period2 = 2.0 * pi * oevti(1) * sqrt(oevti(1) / mu); period3 = 2.0 * pi * oevf(1) * sqrt(oevf(1) / mu); deltat1 = period1 / 300; simtime1 = -deltat1; deltat2 = 0.5 * period2 / 300; simtime2 = -deltat2; deltat3 = period3 / 300; simtime3 = -deltat3; for i = 1:1:301 simtime1 = simtime1 + deltat1; simtime2 = simtime2 + deltat2; simtime3 = simtime3 + deltat3; % compute initial orbit "normalized" position vector [rwrk, vwrk] = twobody2 (mu, simtime1, ri, vi); rp1_x(i) = rwrk(1) / req; rp1_y(i) = rwrk(2) / req; rp1_z(i) = rwrk(3) / req; % compute transfer orbit position vector [rwrk, vwrk] = twobody2 (mu, simtime2, rti, vti); rp2_x(i) = rwrk(1) / req; rp2_y(i) = rwrk(2) / req; rp2_z(i) = rwrk(3) / req; % compute final orbit position vector [rwrk, vwrk] = twobody2 (mu, simtime3, rf, vf); rp3_x(i) = rwrk(1) / req; rp3_y(i) = rwrk(2) / req; rp3_z(i) = rwrk(3) / req; end figure(1); % create axes vectors xaxisx = [1 1.5]; xaxisy = [0 0]; xaxisz = [0 0]; yaxisx = [0 0]; yaxisy = [1 1.5]; yaxisz = [0 0]; zaxisx = [0 0]; zaxisy = [0 0]; zaxisz = [1 1.5]; figure (1); hold on; grid on; % plot earth [x y z] = sphere(24); h = surf(x, y, z); colormap([127/255 1 222/255]); set (h, 'edgecolor', [1 1 1]); % plot coordinate system axes plot3(xaxisx, xaxisy, xaxisz, '-g', 'LineWidth', 1); plot3(yaxisx, yaxisy, yaxisz, '-r', 'LineWidth', 1); plot3(zaxisx, zaxisy, zaxisz, '-b', 'LineWidth', 1); % plot initial orbit plot3(rp1_x, rp1_y, rp1_z, '-r', 'LineWidth', 1.5); plot3(rp1_x(1), rp1_y(1), rp1_z(1), 'ob'); % plot transfer orbit plot3(rp2_x, rp2_y, rp2_z, '-b', 'LineWidth', 1.5); plot3(rp2_x(end), rp2_y(end), rp2_z(end), 'ob'); % plot final orbit plot3(rp3_x, rp3_y, rp3_z, '-g', 'LineWidth', 1.5); xlabel('X coordinate (ER)', 'FontSize', 12); ylabel('Y coordinate (ER)', 'FontSize', 12); zlabel('Z coordinate (ER)', 'FontSize', 12); title('Hohmann Transfer: Initial, Transfer and Final Orbits', 'FontSize', 16); axis equal; view(50, 20); rotate3d on; print -depsc -tiff -r300 hohmann1.eps %%%%%%%%%%%%%%%%%%%%%%%% % create primer graphics %%%%%%%%%%%%%%%%%%%%%%%% dvi = (vti - vi)'; dvf = (vf - vtf)'; % perform primer vector initialization pviniz(tof, rti, vti, dvi, dvf); % number of graphic data points npts = 300; % plot behavior of primer vector magnitude dt = tof / npts; for i = 1:1:npts + 1 t = (i - 1) * dt; if (t == 0) % initial value of primer magnitude and derivative pvm = norm(pvi); pvdm = dot(pvi, pvdi) / pvm; else % primer vector and derivative magnitudes at time t [pvm, pvdm] = pvector(rti, vti, t); end % load data array x1(i) = t / 60.0; y1(i) = pvm; y2(i) = pvdm; end figure(2); hold on; plot(x1, y1, '-r', 'LineWidth', 1.5); plot(x1(1), y1(1), 'or'); plot(x1(end), y1(end), 'or'); title('Primer Vector Analysis of the Hohmann Transfer', 'FontSize', 16); xlabel('simulation time (minutes)', 'FontSize', 12); ylabel('primer vector magnitude', 'FontSize', 12); grid; % create eps graphics file with tiff preview print -depsc -tiff -r300 primer.eps; % plot behavior of magnitude of primer derivative figure(3); hold on; plot(x1, y2, '-r', 'LineWidth', 1.5); plot(x1(1), y2(1), 'or'); plot(x1(end), y2(end), 'or'); title('Primer Vector Analysis of the Hohmann Transfer', 'FontSize', 16); xlabel('simulation time (minutes)', 'FontSize', 12); ylabel('primer derivative magnitude', 'FontSize', 12); grid; % create eps graphics file with tiff preview print -depsc -tiff -r300 primer_der.eps;
module Category.FAM where open import Level open import Relation.Binary.PropositionalEquality open import Function using (_∘_; id; _∘′_) ------------------------------------------------------------------------ -- Functors record IsFunctor {ℓ} (F : Set ℓ → Set ℓ) (_<$>_ : ∀ {A B} → (A → B) → F A → F B) : Set (suc ℓ) where field identity : {A : Set ℓ} (a : F A) → id <$> a ≡ a homo : ∀ {A B C} (f : B → C) (g : A → B) (a : F A) → (f ∘ g) <$> a ≡ f <$> (g <$> a) record Functor {ℓ} (F : Set ℓ → Set ℓ) : Set (suc ℓ) where infixl 4 _<$>_ _<$_ field _<$>_ : ∀ {A B} → (A → B) → F A → F B isFunctor : IsFunctor F _<$>_ -- An textual synonym of _<$>_ fmap : ∀ {A B} → (A → B) → F A → F B fmap = _<$>_ -- Replace all locations in the input with the same value. -- The default definition is fmap . const, but this may be overridden with a -- more efficient version. _<$_ : ∀ {A B} → A → F B → F A x <$ y = Function.const x <$> y open IsFunctor isFunctor public -- open Functor {{...}} public ------------------------------------------------------------------------ -- Applicatives (not indexed) record IsApplicative {ℓ} (F : Set ℓ → Set ℓ) (pure : {A : Set ℓ} → A → F A) (_⊛_ : {A B : Set ℓ} → (F (A → B)) → F A → F B) : Set (suc ℓ) where field identity : {A : Set ℓ} (x : F A) → pure id ⊛ x ≡ x compose : {A B C : Set ℓ} (f : F (B → C)) (g : F (A → B)) → (x : F A) → ((pure _∘′_ ⊛ f) ⊛ g) ⊛ x ≡ f ⊛ (g ⊛ x) homo : ∀ {A B} (f : A → B) (x : A) → pure f ⊛ pure x ≡ pure (f x) interchange : ∀ {A B} (f : F (A → B)) (x : A) → f ⊛ pure x ≡ pure (λ f → f x) ⊛ f record Applicative {ℓ} (F : Set ℓ → Set ℓ) : Set (suc ℓ) where infixl 4 _⊛_ _<⊛_ _⊛>_ infix 4 _⊗_ field pure : {A : Set ℓ} → A → F A _⊛_ : {A B : Set ℓ} → (F (A → B)) → F A → F B isApplicative : IsApplicative F pure _⊛_ open IsApplicative isApplicative public _<⊛_ : ∀ {A B} → F A → F B → F A x <⊛ y = x _⊛>_ : ∀ {A B} → F A → F B → F B x ⊛> y = y functor : Functor F functor = record { _<$>_ = λ f x → pure f ⊛ x ; isFunctor = record { identity = App.identity ; homo = λ {A} {B} {C} f g x → begin pure (f ∘ g) ⊛ x ≡⟨ cong (λ w → _⊛_ w x) (sym (App.homo (λ g → (f ∘ g)) g)) ⟩ (pure ((λ g → (f ∘ g))) ⊛ pure g) ⊛ x ≡⟨ cong (λ w → (w ⊛ pure g) ⊛ x) (sym (App.homo (λ f → _∘_ f) f)) ⟩ ((pure (λ f → _∘_ f) ⊛ pure f) ⊛ pure g) ⊛ x ≡⟨ App.compose (pure f) (pure g) x ⟩ pure f ⊛ (pure g ⊛ x) ∎ } } where open ≡-Reasoning module App = IsApplicative isApplicative instance ApplicativeFunctor : Functor F ApplicativeFunctor = functor open import Data.Product open Functor {{...}} _⊗_ : ∀ {A B} → F A → F B → F (A × B) x ⊗ y = _,_ <$> x ⊛ y zipWith : ∀ {A B C} → (A → B → C) → F A → F B → F C zipWith f x y = f <$> x ⊛ y -- open Applicative {{...}} public ---------------------------------------------------------------------- -- Monad record IsMonad {ℓ} (M : Set ℓ → Set ℓ) (return : {A : Set ℓ} → A → M A) (_>>=_ : {A B : Set ℓ} → M A → (A → M B) → M B) : Set (suc ℓ) where field left-identity : {A B : Set ℓ} (x : A) (fs : A → M B) → return x >>= fs ≡ fs x right-identity : {A : Set ℓ} (xs : M A) → xs >>= return ≡ xs assoc : {A B C : Set ℓ} (x : M A) (fs : A → M B) (g : B → M C) → (x >>= fs) >>= g ≡ (x >>= λ x' → fs x' >>= g) temp : {A B : Set ℓ} (x : A) (fs : M (A → B)) → (fs >>= λ f → return x >>= (return ∘ f)) ≡ (fs >>= λ f → (return ∘ f) x) record Monad {ℓ} (M : Set ℓ → Set ℓ) : Set (suc ℓ) where infixl 1 _>>=_ _>>_ _>=>_ infixr 1 _=<<_ _<=<_ field return : {A : Set ℓ} → A → M A _>>=_ : {A B : Set ℓ} → M A → (A → M B) → M B isMonad : IsMonad M return _>>=_ _>>_ : ∀ {A B} → M A → M B → M B m₁ >> m₂ = m₁ >>= λ _ → m₂ _=<<_ : ∀ {A B} → (A → M B) → M A → M B f =<< c = c >>= f _>=>_ : ∀ {A : Set ℓ} {B C} → (A → M B) → (B → M C) → (A → M C) f >=> g = _=<<_ g ∘ f _<=<_ : ∀ {A : Set ℓ} {B C} → (B → M C) → (A → M B) → (A → M C) g <=< f = f >=> g join : ∀ {A} → M (M A) → M A join m = m >>= id congruence : ∀ {A B : Set ℓ} (fs : M A) (g h : A → M B) → (∀ f → g f ≡ h f) → (fs >>= g) ≡ (fs >>= h) congruence fs g h prop = begin (fs >>= g) ≡⟨ sym (right-identity (fs >>= g)) ⟩ (fs >>= g >>= return) ≡⟨ assoc fs g return ⟩ (fs >>= (λ f → g f >>= return)) ≡⟨ cong (λ w → fs >>= (λ f → w f >>= return)) {! !} ⟩ (fs >>= (λ f → h f >>= return)) ≡⟨ sym (assoc fs h return) ⟩ (fs >>= h >>= return) ≡⟨ right-identity (fs >>= h) ⟩ (fs >>= h) ∎ where open ≡-Reasoning open IsMonad isMonad -- (fs >>= (λ f → return x >>= return ∘ f)) -- (fs >>= (λ f → (return ∘ f) x)) applicative : Applicative M applicative = record { pure = return ; _⊛_ = λ fs xs → fs >>= λ f → xs >>= return ∘′ f ; isApplicative = record { identity = λ xs → begin (return id >>= λ f → xs >>= λ x → return (f x)) ≡⟨ Mon.left-identity id (λ f → xs >>= λ x → return (f x)) ⟩ (xs >>= λ x → return (id x)) ≡⟨ refl ⟩ (xs >>= λ x → return x) ≡⟨ refl ⟩ (xs >>= return) ≡⟨ Mon.right-identity xs ⟩ xs ∎ -- { identity = λ xs → begin -- (do -- f ← (return id) -- x ← xs -- (return (f x))) -- ≡⟨ Mon.left-identity id (λ f → do -- x ← xs -- (return (f x))) -- ⟩ -- (do -- x ← xs -- return (id x)) -- ≡⟨ refl ⟩ -- (do -- x ← xs -- return x) -- ≡⟨ Mon.right-identity xs ⟩ -- xs -- ∎ -- left-identity : {A B : Set ℓ} (x : A) (f : A → M B) → return x >>= f ≡ f x -- right-identity : {A : Set ℓ} (xs : M A) → xs >>= return ≡ xs -- → (x >>= f) >>= g ≡ (x >>= λ x' → f x' >>= g) ; compose = λ fs gs xs → begin (return _∘′_ >>= (λ flip → fs >>= return ∘′ flip) >>= (λ f → gs >>= return ∘′ f) >>= (λ f → xs >>= return ∘′ f)) ≡⟨ cong (λ w → w >>= (λ f → gs >>= return ∘′ f) >>= (λ f → xs >>= return ∘′ f)) (Mon.left-identity _∘′_ (λ flip → fs >>= return ∘′ flip)) ⟩ (fs >>= return ∘′ _∘′_ >>= (λ f → gs >>= return ∘′ f) >>= (λ f → xs >>= return ∘′ f)) ≡⟨ Mon.assoc (fs >>= return ∘′ _∘′_) (λ f → gs >>= return ∘′ f) (λ f → xs >>= return ∘′ f) ⟩ ((fs >>= return ∘′ _∘′_) >>= (λ h → gs >>= return ∘′ h >>= λ f → xs >>= return ∘′ f)) ≡⟨ {! !} ⟩ -- {! !} -- ≡⟨ cong (λ w → fs >>= λ r → {! !}) {! !} ⟩ (fs >>= (λ f → (gs >>= λ g → xs >>= return ∘′ g) >>= return ∘′ f)) ∎ ; homo = λ f x → begin (return f >>= λ f' → return x >>= return ∘ f') ≡⟨ Mon.left-identity f (λ f' → return x >>= return ∘ f') ⟩ (return x >>= return ∘ f) ≡⟨ Mon.left-identity x (return ∘ f) ⟩ return (f x) ∎ -- left-identity : return x >>= f ≡ f x -- right-identity : xs >>= return ≡ xs -- assoc : (x >>= f) >>= g ≡ (x >>= λ x' → f x' >>= g) ; interchange = λ fs x → begin (fs >>= (λ f → return x >>= return ∘ f)) ≡⟨ congruence fs (λ f → return x >>= return ∘ f) (λ f → (return ∘ f) x) (λ f → Mon.left-identity x (return ∘ f)) ⟩ (fs >>= (λ f → (return ∘ f) x)) ≡⟨ sym (Mon.left-identity (λ f → f x) (λ f' → fs >>= (λ f → return (f' f)))) ⟩ (return (λ f → f x) >>= (λ f' → fs >>= (λ f → return (f' f)))) ∎ } } -- -- ≡⟨ sym (Mon.right-identity (fs >>= (λ f → return x >>= return ∘ f))) ⟩ -- -- (fs >>= (λ f → return x >>= return ∘ f) >>= return) -- -- ≡⟨ Mon.assoc fs (λ f → return x >>= return ∘ f) return ⟩ -- -- (fs >>= (λ f → return x >>= return ∘ f >>= return)) -- -- ≡⟨ cong (λ w → fs >>= λ f → w f >>= return) {! !} ⟩ -- ≡⟨ cong (λ w → w >>= (λ f → return x >>= return ∘ f)) (sym (Mon.right-identity fs)) ⟩ -- (fs >>= return >>= (λ f → return x >>= return ∘ f)) -- ≡⟨ Mon.assoc fs return (λ f → return x >>= return ∘ f) ⟩ -- (fs >>= λ f → return f >>= λ f → return x >>= return ∘ f) -- ≡⟨ cong (λ w → fs >>= λ f → w f) {! !} ⟩ -- {! !} -- ≡⟨ {! !} ⟩ -- (fs >>= (λ f → (return ∘ f) x >>= return)) -- ≡⟨ sym (Mon.assoc fs (λ f → return (f x)) return) ⟩ -- ((fs >>= λ f → (return ∘ f) x) >>= return) -- ≡⟨ Mon.right-identity (fs >>= λ f → return (f x)) ⟩ where open ≡-Reasoning open Applicative applicative module Mon = IsMonad isMonad -- -- lemma : {A B : Set ℓ} (x : A) → (λ f → return x >>= return ∘′ f) ≡ (λ f → return (f x)) -- lemma x = begin -- (λ f → return x >>= return ∘′ f) -- ≡⟨ cong (λ w f → w) (Mon.left-identity x (λ f → {! !})) ⟩ -- {! !} -- ≡⟨ {! !} ⟩ -- {! !} -- ≡⟨ {! !} ⟩ -- {! !} -- ≡⟨ {! !} ⟩ -- (λ f → return (f x)) -- ∎ -- begin -- (return x >>= return ∘′ f) -- ≡⟨ Mon.left-identity x (return ∘′ f) ⟩ -- return (f x) -- ∎ -- lemma : {A B : Set ℓ} (x : A) (f : A → M B) → (return x >>= return ∘′ f) ≡ return (f x) -- lemma x f = begin -- (return x >>= return ∘′ f) -- ≡⟨ Mon.left-identity x (return ∘′ f) ⟩ -- return (f x) -- ∎ -- -- rawIApplicative : RawIApplicative M -- rawIApplicative = record -- { pure = return -- ; _⊛_ = λ f x → f >>= λ f' → x >>= λ x' → return (f' x') -- }
#ifndef GP_HPP_INCLUDED #define GP_HPP_INCLUDED #include <vector> #include <memory> #include <iostream> #include <Eigen/Dense> #include <Eigen/Cholesky> namespace boat { double normal_lnp(double x, double mean, double variance); typedef enum { SQUARED_EXP, MATERN52 } kernel_t; class GPParams{ public: GPParams():mean_(0.0), amplitude_(1.0), default_noise_(0.1), kernel_(MATERN52) {} void amplitude(double amplitude) { amplitude_ = amplitude; } void stdev(double stdev) { amplitude_ = stdev * stdev; } void default_noise(double default_noise) { assert(default_noise >= 0.0); //default_noise_ = std::max(default_noise, 1e-4); default_noise_ = default_noise; } void mean(double mean) { mean_ = mean; } void linear_scales(const std::vector<double>& linear_scales){ linear_scales_ = linear_scales; inv_linear_scales_ = Eigen::VectorXd::Map(linear_scales.data(), linear_scales.size()) .array() .inverse(); } void kernel(kernel_t kernel){ kernel_ = kernel; } double stdev() const { return sqrt(amplitude_); } double amplitude() const { return amplitude_; } double mean() const { return mean_; } double default_noise() const { return default_noise_; } const Eigen::VectorXd& inv_linear_scales() const { return inv_linear_scales_; } const std::vector<double>& linear_scales() const { return linear_scales_; } kernel_t kernel() const { return kernel_; } private: double mean_; double amplitude_; double default_noise_; std::vector<double> linear_scales_; Eigen::VectorXd inv_linear_scales_; kernel_t kernel_; }; struct GaussianDistrib { double mu_; double var_; double mu() { return mu_; } double var() { return var_; } double stdev() { return sqrt(var_); } }; class GP { friend class TreedGPS; public: GP(); GP(GPParams params); void set_params(GPParams params); int num_dims() const; double observe(const std::vector<double>& x_new, double y_new); double observe(const std::vector<double>& x_new, double y_new, double noise); double predict_mean(const std::vector<double>& x_new) const; GaussianDistrib predict_distrib(const std::vector<double>& x_new) const; void print() const; //private: double observe_i(const std::vector<double>& x_new, double y_new, double noise_var); void compute_cholesky() const; int at_index(const Eigen::RowVectorXd& v) const; void remove_observation(int i); Eigen::MatrixXd covariance(const Eigen::MatrixXd& x1, const Eigen::MatrixXd& x2) const; void compute_cholesky_from_scratch() const; // Parameters GPParams params_; // Processed data Eigen::MatrixXd observed_x_; Eigen::VectorXd observed_y_; Eigen::VectorXd noise_var_; mutable Eigen::MatrixXd covariance_cholesky_; mutable Eigen::VectorXd alpha_; }; class TreedGPS { public: TreedGPS(); TreedGPS(GPParams params, int observation_thresh = 64, int overlap = 3); TreedGPS(const TreedGPS& other); TreedGPS& operator=(const TreedGPS& other); void set_params(GPParams params); double observe(const std::vector<double>& x_new, double y_new); double observe(const std::vector<double>& x_new, double y_new, double noise); double predict_mean(const std::vector<double>& x_new) const; GaussianDistrib predict_distrib(const std::vector<double>& x_new) const; private: bool side(const std::vector<double>& x_new) const; //Lots of helpers for the splitting std::pair<std::vector<int>, std::vector<int>> compute_thresh_and_divide(double max_diff); std::pair<std::vector<int>, std::vector<int>> compute_thresh_props(); void check_thresh(); void copy_observation(bool s, int i); void compute_children_cholesky(); int observation_thresh_; int overlap_; int thresh_dim_; double thresh_; double inv_ls_along_thresh_dim_; std::unique_ptr<GP> gp_; std::unique_ptr<TreedGPS> left_; std::unique_ptr<TreedGPS> right_; }; } #endif // GP_HPP_INCLUDED
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura ! This file was ported from Lean 3 source module init.algebra.order ! leanprover-community/mathlib commit c2bcdbcbe741ed37c361a30d38e179182b989f76 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ prelude import Leanbin.Init.Logic import Leanbin.Init.Classical import Leanbin.Init.Meta.Name import Leanbin.Init.Algebra.Classes /- ./././Mathport/Syntax/Translate/Basic.lean:334:40: warning: unsupported option default_priority -/ /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 universe u variable {α : Type u} /- ./././Mathport/Syntax/Translate/Basic.lean:334:40: warning: unsupported option auto_param.check_exists -/ set_option auto_param.check_exists false section Preorder /-! ### Definition of `preorder` and lemmas about types with a `preorder` -/ #print Preorder /- /- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic order_laws_tac -/ /-- A preorder is a reflexive, transitive relation `≤` with `a < b` defined in the obvious way. -/ class Preorder (α : Type u) extends LE α, LT α where le_refl : ∀ a : α, a ≤ a le_trans : ∀ a b c : α, a ≤ b → b ≤ c → a ≤ c lt := fun a b => a ≤ b ∧ ¬b ≤ a lt_iff_le_not_le : ∀ a b : α, a < b ↔ a ≤ b ∧ ¬b ≤ a := by run_tac order_laws_tac #align preorder Preorder -/ variable [Preorder α] #print le_refl /- /-- The relation `≤` on a preorder is reflexive. -/ @[refl] theorem le_refl : ∀ a : α, a ≤ a := Preorder.le_refl #align le_refl le_refl -/ #print le_trans /- /-- The relation `≤` on a preorder is transitive. -/ @[trans] theorem le_trans : ∀ {a b c : α}, a ≤ b → b ≤ c → a ≤ c := Preorder.le_trans #align le_trans le_trans -/ #print lt_iff_le_not_le /- theorem lt_iff_le_not_le : ∀ {a b : α}, a < b ↔ a ≤ b ∧ ¬b ≤ a := Preorder.lt_iff_le_not_le #align lt_iff_le_not_le lt_iff_le_not_le -/ #print lt_of_le_not_le /- theorem lt_of_le_not_le : ∀ {a b : α}, a ≤ b → ¬b ≤ a → a < b | a, b, hab, hba => lt_iff_le_not_le.mpr ⟨hab, hba⟩ #align lt_of_le_not_le lt_of_le_not_le -/ #print le_not_le_of_lt /- theorem le_not_le_of_lt : ∀ {a b : α}, a < b → a ≤ b ∧ ¬b ≤ a | a, b, hab => lt_iff_le_not_le.mp hab #align le_not_le_of_lt le_not_le_of_lt -/ #print le_of_eq /- theorem le_of_eq {a b : α} : a = b → a ≤ b := fun h => h ▸ le_refl a #align le_of_eq le_of_eq -/ #print ge_trans /- @[trans] theorem ge_trans : ∀ {a b c : α}, a ≥ b → b ≥ c → a ≥ c := fun a b c h₁ h₂ => le_trans h₂ h₁ #align ge_trans ge_trans -/ #print lt_irrefl /- theorem lt_irrefl : ∀ a : α, ¬a < a | a, haa => match le_not_le_of_lt haa with | ⟨h1, h2⟩ => False.ndrec _ (h2 h1) #align lt_irrefl lt_irrefl -/ #print gt_irrefl /- theorem gt_irrefl : ∀ a : α, ¬a > a := lt_irrefl #align gt_irrefl gt_irrefl -/ #print lt_trans /- @[trans] theorem lt_trans : ∀ {a b c : α}, a < b → b < c → a < c | a, b, c, hab, hbc => match le_not_le_of_lt hab, le_not_le_of_lt hbc with | ⟨hab, hba⟩, ⟨hbc, hcb⟩ => lt_of_le_not_le (le_trans hab hbc) fun hca => hcb (le_trans hca hab) #align lt_trans lt_trans -/ #print gt_trans /- @[trans] theorem gt_trans : ∀ {a b c : α}, a > b → b > c → a > c := fun a b c h₁ h₂ => lt_trans h₂ h₁ #align gt_trans gt_trans -/ #print ne_of_lt /- theorem ne_of_lt {a b : α} (h : a < b) : a ≠ b := fun he => absurd h (he ▸ lt_irrefl a) #align ne_of_lt ne_of_lt -/ #print ne_of_gt /- theorem ne_of_gt {a b : α} (h : b < a) : a ≠ b := fun he => absurd h (he ▸ lt_irrefl a) #align ne_of_gt ne_of_gt -/ #print lt_asymm /- theorem lt_asymm {a b : α} (h : a < b) : ¬b < a := fun h1 : b < a => lt_irrefl a (lt_trans h h1) #align lt_asymm lt_asymm -/ #print le_of_lt /- theorem le_of_lt : ∀ {a b : α}, a < b → a ≤ b | a, b, hab => (le_not_le_of_lt hab).left #align le_of_lt le_of_lt -/ #print lt_of_lt_of_le /- @[trans] theorem lt_of_lt_of_le : ∀ {a b c : α}, a < b → b ≤ c → a < c | a, b, c, hab, hbc => let ⟨hab, hba⟩ := le_not_le_of_lt hab lt_of_le_not_le (le_trans hab hbc) fun hca => hba (le_trans hbc hca) #align lt_of_lt_of_le lt_of_lt_of_le -/ #print lt_of_le_of_lt /- @[trans] theorem lt_of_le_of_lt : ∀ {a b c : α}, a ≤ b → b < c → a < c | a, b, c, hab, hbc => let ⟨hbc, hcb⟩ := le_not_le_of_lt hbc lt_of_le_not_le (le_trans hab hbc) fun hca => hcb (le_trans hca hab) #align lt_of_le_of_lt lt_of_le_of_lt -/ #print gt_of_gt_of_ge /- @[trans] theorem gt_of_gt_of_ge {a b c : α} (h₁ : a > b) (h₂ : b ≥ c) : a > c := lt_of_le_of_lt h₂ h₁ #align gt_of_gt_of_ge gt_of_gt_of_ge -/ #print gt_of_ge_of_gt /- @[trans] theorem gt_of_ge_of_gt {a b c : α} (h₁ : a ≥ b) (h₂ : b > c) : a > c := lt_of_lt_of_le h₂ h₁ #align gt_of_ge_of_gt gt_of_ge_of_gt -/ #print not_le_of_gt /- theorem not_le_of_gt {a b : α} (h : a > b) : ¬a ≤ b := (le_not_le_of_lt h).right #align not_le_of_gt not_le_of_gt -/ #print not_lt_of_ge /- theorem not_lt_of_ge {a b : α} (h : a ≥ b) : ¬a < b := fun hab => not_le_of_gt hab h #align not_lt_of_ge not_lt_of_ge -/ #print le_of_lt_or_eq /- theorem le_of_lt_or_eq : ∀ {a b : α}, a < b ∨ a = b → a ≤ b | a, b, Or.inl hab => le_of_lt hab | a, b, Or.inr hab => hab ▸ le_refl _ #align le_of_lt_or_eq le_of_lt_or_eq -/ #print le_of_eq_or_lt /- theorem le_of_eq_or_lt {a b : α} (h : a = b ∨ a < b) : a ≤ b := Or.elim h le_of_eq le_of_lt #align le_of_eq_or_lt le_of_eq_or_lt -/ /-- `<` is decidable if `≤` is. -/ def decidableLtOfDecidableLe [@DecidableRel α (· ≤ ·)] : @DecidableRel α (· < ·) | a, b => if hab : a ≤ b then if hba : b ≤ a then isFalse fun hab' => not_le_of_gt hab' hba else isTrue <| lt_of_le_not_le hab hba else isFalse fun hab' => hab (le_of_lt hab') #align decidable_lt_of_decidable_le decidableLtOfDecidableLe end Preorder section PartialOrder /-! ### Definition of `partial_order` and lemmas about types with a partial order -/ #print PartialOrder /- /-- A partial order is a reflexive, transitive, antisymmetric relation `≤`. -/ class PartialOrder (α : Type u) extends Preorder α where le_antisymm : ∀ a b : α, a ≤ b → b ≤ a → a = b #align partial_order PartialOrder -/ variable [PartialOrder α] #print le_antisymm /- theorem le_antisymm : ∀ {a b : α}, a ≤ b → b ≤ a → a = b := PartialOrder.le_antisymm #align le_antisymm le_antisymm -/ #print le_antisymm_iff /- theorem le_antisymm_iff {a b : α} : a = b ↔ a ≤ b ∧ b ≤ a := ⟨fun e => ⟨le_of_eq e, le_of_eq e.symm⟩, fun ⟨h1, h2⟩ => le_antisymm h1 h2⟩ #align le_antisymm_iff le_antisymm_iff -/ #print lt_of_le_of_ne /- theorem lt_of_le_of_ne {a b : α} : a ≤ b → a ≠ b → a < b := fun h₁ h₂ => lt_of_le_not_le h₁ <| mt (le_antisymm h₁) h₂ #align lt_of_le_of_ne lt_of_le_of_ne -/ /-- Equality is decidable if `≤` is. -/ def decidableEqOfDecidableLe [@DecidableRel α (· ≤ ·)] : DecidableEq α | a, b => if hab : a ≤ b then if hba : b ≤ a then isTrue (le_antisymm hab hba) else isFalse fun heq => hba (HEq ▸ le_refl _) else isFalse fun heq => hab (HEq ▸ le_refl _) #align decidable_eq_of_decidable_le decidableEqOfDecidableLe namespace Decidable variable [@DecidableRel α (· ≤ ·)] #print Decidable.lt_or_eq_of_le /- theorem lt_or_eq_of_le {a b : α} (hab : a ≤ b) : a < b ∨ a = b := if hba : b ≤ a then Or.inr (le_antisymm hab hba) else Or.inl (lt_of_le_not_le hab hba) #align decidable.lt_or_eq_of_le Decidable.lt_or_eq_of_le -/ #print Decidable.eq_or_lt_of_le /- theorem eq_or_lt_of_le {a b : α} (hab : a ≤ b) : a = b ∨ a < b := (lt_or_eq_of_le hab).symm #align decidable.eq_or_lt_of_le Decidable.eq_or_lt_of_le -/ #print Decidable.le_iff_lt_or_eq /- theorem le_iff_lt_or_eq {a b : α} : a ≤ b ↔ a < b ∨ a = b := ⟨lt_or_eq_of_le, le_of_lt_or_eq⟩ #align decidable.le_iff_lt_or_eq Decidable.le_iff_lt_or_eq -/ end Decidable attribute [local instance] Classical.propDecidable #print lt_or_eq_of_le /- theorem lt_or_eq_of_le {a b : α} : a ≤ b → a < b ∨ a = b := Decidable.lt_or_eq_of_le #align lt_or_eq_of_le lt_or_eq_of_le -/ #print le_iff_lt_or_eq /- theorem le_iff_lt_or_eq {a b : α} : a ≤ b ↔ a < b ∨ a = b := Decidable.le_iff_lt_or_eq #align le_iff_lt_or_eq le_iff_lt_or_eq -/ end PartialOrder section LinearOrder /-! ### Definition of `linear_order` and lemmas about types with a linear order -/ #print maxDefault /- /-- Default definition of `max`. -/ def maxDefault {α : Type u} [LE α] [DecidableRel ((· ≤ ·) : α → α → Prop)] (a b : α) := if a ≤ b then b else a #align max_default maxDefault -/ #print minDefault /- /-- Default definition of `min`. -/ def minDefault {α : Type u} [LE α] [DecidableRel ((· ≤ ·) : α → α → Prop)] (a b : α) := if a ≤ b then a else b #align min_default minDefault -/ #print LinearOrder /- /- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic tactic.interactive.reflexivity -/ /- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic tactic.interactive.reflexivity -/ /-- A linear order is reflexive, transitive, antisymmetric and total relation `≤`. We assume that every linear ordered type has decidable `(≤)`, `(<)`, and `(=)`. -/ class LinearOrder (α : Type u) extends PartialOrder α where le_total : ∀ a b : α, a ≤ b ∨ b ≤ a decidableLe : DecidableRel (· ≤ ·) DecidableEq : DecidableEq α := @decidableEqOfDecidableLe _ _ decidable_le decidableLt : DecidableRel ((· < ·) : α → α → Prop) := @decidableLtOfDecidableLe _ _ decidable_le max : α → α → α := @maxDefault α _ _ max_def : max = @maxDefault α _ decidable_le := by run_tac tactic.interactive.reflexivity min : α → α → α := @minDefault α _ _ min_def : min = @minDefault α _ decidable_le := by run_tac tactic.interactive.reflexivity #align linear_order LinearOrder -/ variable [LinearOrder α] attribute [local instance] LinearOrder.decidableLe #print le_total /- theorem le_total : ∀ a b : α, a ≤ b ∨ b ≤ a := LinearOrder.le_total #align le_total le_total -/ #print le_of_not_ge /- theorem le_of_not_ge {a b : α} : ¬a ≥ b → a ≤ b := Or.resolve_left (le_total b a) #align le_of_not_ge le_of_not_ge -/ #print le_of_not_le /- theorem le_of_not_le {a b : α} : ¬a ≤ b → b ≤ a := Or.resolve_left (le_total a b) #align le_of_not_le le_of_not_le -/ #print not_lt_of_gt /- theorem not_lt_of_gt {a b : α} (h : a > b) : ¬a < b := lt_asymm h #align not_lt_of_gt not_lt_of_gt -/ #print lt_trichotomy /- theorem lt_trichotomy (a b : α) : a < b ∨ a = b ∨ b < a := Or.elim (le_total a b) (fun h : a ≤ b => Or.elim (Decidable.lt_or_eq_of_le h) (fun h : a < b => Or.inl h) fun h : a = b => Or.inr (Or.inl h)) fun h : b ≤ a => Or.elim (Decidable.lt_or_eq_of_le h) (fun h : b < a => Or.inr (Or.inr h)) fun h : b = a => Or.inr (Or.inl h.symm) #align lt_trichotomy lt_trichotomy -/ #print le_of_not_lt /- theorem le_of_not_lt {a b : α} (h : ¬b < a) : a ≤ b := match lt_trichotomy a b with | Or.inl hlt => le_of_lt hlt | Or.inr (Or.inl HEq) => HEq ▸ le_refl a | Or.inr (Or.inr hgt) => absurd hgt h #align le_of_not_lt le_of_not_lt -/ #print le_of_not_gt /- theorem le_of_not_gt {a b : α} : ¬a > b → a ≤ b := le_of_not_lt #align le_of_not_gt le_of_not_gt -/ #print lt_of_not_ge /- theorem lt_of_not_ge {a b : α} (h : ¬a ≥ b) : a < b := lt_of_le_not_le ((le_total _ _).resolve_right h) h #align lt_of_not_ge lt_of_not_ge -/ #print lt_or_le /- theorem lt_or_le (a b : α) : a < b ∨ b ≤ a := if hba : b ≤ a then Or.inr hba else Or.inl <| lt_of_not_ge hba #align lt_or_le lt_or_le -/ #print le_or_lt /- theorem le_or_lt (a b : α) : a ≤ b ∨ b < a := (lt_or_le b a).symm #align le_or_lt le_or_lt -/ #print lt_or_ge /- theorem lt_or_ge : ∀ a b : α, a < b ∨ a ≥ b := lt_or_le #align lt_or_ge lt_or_ge -/ #print le_or_gt /- theorem le_or_gt : ∀ a b : α, a ≤ b ∨ a > b := le_or_lt #align le_or_gt le_or_gt -/ #print lt_or_gt_of_ne /- theorem lt_or_gt_of_ne {a b : α} (h : a ≠ b) : a < b ∨ a > b := match lt_trichotomy a b with | Or.inl hlt => Or.inl hlt | Or.inr (Or.inl HEq) => absurd HEq h | Or.inr (Or.inr hgt) => Or.inr hgt #align lt_or_gt_of_ne lt_or_gt_of_ne -/ #print ne_iff_lt_or_gt /- theorem ne_iff_lt_or_gt {a b : α} : a ≠ b ↔ a < b ∨ a > b := ⟨lt_or_gt_of_ne, fun o => Or.elim o ne_of_lt ne_of_gt⟩ #align ne_iff_lt_or_gt ne_iff_lt_or_gt -/ #print lt_iff_not_ge /- theorem lt_iff_not_ge (x y : α) : x < y ↔ ¬x ≥ y := ⟨not_le_of_gt, lt_of_not_ge⟩ #align lt_iff_not_ge lt_iff_not_ge -/ #print not_lt /- @[simp] theorem not_lt {a b : α} : ¬a < b ↔ b ≤ a := ⟨le_of_not_gt, not_lt_of_ge⟩ #align not_lt not_lt -/ #print not_le /- @[simp] theorem not_le {a b : α} : ¬a ≤ b ↔ b < a := (lt_iff_not_ge _ _).symm #align not_le not_le -/ instance (a b : α) : Decidable (a < b) := LinearOrder.decidableLt a b instance (a b : α) : Decidable (a ≤ b) := LinearOrder.decidableLe a b instance (a b : α) : Decidable (a = b) := LinearOrder.decidableEq a b #print eq_or_lt_of_not_lt /- theorem eq_or_lt_of_not_lt {a b : α} (h : ¬a < b) : a = b ∨ b < a := if h₁ : a = b then Or.inl h₁ else Or.inr (lt_of_not_ge fun hge => h (lt_of_le_of_ne hge h₁)) #align eq_or_lt_of_not_lt eq_or_lt_of_not_lt -/ instance : IsTotalPreorder α (· ≤ ·) where trans := @le_trans _ _ Total := le_total -- TODO(Leo): decide whether we should keep this instance or not instance isStrictWeakOrder_of_linearOrder : IsStrictWeakOrder α (· < ·) := isStrictWeakOrder_of_isTotalPreorder lt_iff_not_ge #align is_strict_weak_order_of_linear_order isStrictWeakOrder_of_linearOrder -- TODO(Leo): decide whether we should keep this instance or not instance isStrictTotalOrder_of_linearOrder : IsStrictTotalOrder α (· < ·) where trichotomous := lt_trichotomy #align is_strict_total_order_of_linear_order isStrictTotalOrder_of_linearOrder /-- Perform a case-split on the ordering of `x` and `y` in a decidable linear order. -/ def ltByCases (x y : α) {P : Sort _} (h₁ : x < y → P) (h₂ : x = y → P) (h₃ : y < x → P) : P := if h : x < y then h₁ h else if h' : y < x then h₃ h' else h₂ (le_antisymm (le_of_not_gt h') (le_of_not_gt h)) #align lt_by_cases ltByCases /- warning: le_imp_le_of_lt_imp_lt -> le_imp_le_of_lt_imp_lt is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : LinearOrder.{u1} α] {β : Type.{u2}} [_inst_2 : Preorder.{u1} α] [_inst_3 : LinearOrder.{u2} β] {a : α} {b : α} {c : β} {d : β}, ((LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (LinearOrder.toPartialOrder.{u2} β _inst_3))) d c) -> (LT.lt.{u1} α (Preorder.toLT.{u1} α _inst_2) b a)) -> (LE.le.{u1} α (Preorder.toLE.{u1} α _inst_2) a b) -> (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (LinearOrder.toPartialOrder.{u2} β _inst_3))) c d) but is expected to have type forall {α : Type.{u2}} {_inst_1 : Type.{u1}} [β : Preorder.{u2} α] [_inst_2 : LinearOrder.{u1} _inst_1] {_inst_3 : α} {a : α} {b : _inst_1} {c : _inst_1}, ((LT.lt.{u1} _inst_1 (Preorder.toLT.{u1} _inst_1 (PartialOrder.toPreorder.{u1} _inst_1 (LinearOrder.toPartialOrder.{u1} _inst_1 _inst_2))) c b) -> (LT.lt.{u2} α (Preorder.toLT.{u2} α β) a _inst_3)) -> (LE.le.{u2} α (Preorder.toLE.{u2} α β) _inst_3 a) -> (LE.le.{u1} _inst_1 (Preorder.toLE.{u1} _inst_1 (PartialOrder.toPreorder.{u1} _inst_1 (LinearOrder.toPartialOrder.{u1} _inst_1 _inst_2))) b c) Case conversion may be inaccurate. Consider using '#align le_imp_le_of_lt_imp_lt le_imp_le_of_lt_imp_ltₓ'. -/ theorem le_imp_le_of_lt_imp_lt {β} [Preorder α] [LinearOrder β] {a b : α} {c d : β} (H : d < c → b < a) (h : a ≤ b) : c ≤ d := le_of_not_lt fun h' => not_le_of_gt (H h') h #align le_imp_le_of_lt_imp_lt le_imp_le_of_lt_imp_lt end LinearOrder
Formal statement is: lemma convex_sum: fixes C :: "'a::real_vector set" assumes "finite S" and "convex C" and "(\<Sum> i \<in> S. a i) = 1" assumes "\<And>i. i \<in> S \<Longrightarrow> a i \<ge> 0" and "\<And>i. i \<in> S \<Longrightarrow> y i \<in> C" shows "(\<Sum> j \<in> S. a j *\<^sub>R y j) \<in> C" Informal statement is: If $C$ is a convex set, $S$ is a finite set, and $y_i \in C$ for all $i \in S$, then $\sum_{i \in S} a_i y_i \in C$ for any $a_i \geq 0$ such that $\sum_{i \in S} a_i = 1$.
// =-=-=-=-=-=-=- #include "apiHeaderAll.hpp" #include "msParam.hpp" #include "reGlobalsExtern.hpp" #include "irods_ms_plugin.hpp" // =-=-=-=-=-=-=- // STL/boost Includes #include <string> #include <iostream> #include <vector> #include <boost/algorithm/string.hpp> #include <ImageMagick/Magick++.h> std::string convertCompressTypeToStr(const MagickCore::CompressionType& t); std::string convertColorSpaceTypeToStr(const MagickCore::ColorspaceType& t); using namespace Magick; extern "C" { // =-=-=-=-=-=-=- // Returns the meta data as a string for the image. Example: CompressionType=JPEG%Width=10%Height=20 int msiget_image_meta(msParam_t* _in, msParam_t* _out, ruleExecInfo_t* rei) { using std::cout; using std::endl; using std::string; char *filePath = parseMspForStr( _in ); if( !filePath ) { cout << "msiget_image_meta - null filePath parameter" << endl; return SYS_INVALID_INPUT_PARAM; } cout << "File Path: " << filePath << endl; InitializeMagick((const char*)0); Image imgObj; imgObj.read(filePath); std::stringstream metaData; metaData << "ImageDepth=" << imgObj.modulusDepth() << "%Width=" << imgObj.columns() << "%Height=" << imgObj.rows() << "%CompressionType=" << convertCompressTypeToStr(imgObj.compressType()) << "%Format=" << imgObj.format() << "%Colorspace=" << convertColorSpaceTypeToStr(imgObj.colorSpace()); fillStrInMsParam(_out, metaData.str().c_str()); // Done return 0; } // =-=-=-=-=-=-=- // 2. Create the plugin factory function which will return a microservice // table entry irods::ms_table_entry* plugin_factory() { // =-=-=-=-=-=-=- // 3. allocate a microservice plugin which takes the number of function // params as a parameter to the constructor irods::ms_table_entry* msvc = new irods::ms_table_entry(2); // =-=-=-=-=-=-=- // 4. add the microservice function as an operation to the plugin // the first param is the name / key of the operation, the second // is the name of the function which will be the microservice msvc->add_operation("msiget_image_meta", "msiget_image_meta"); // =-=-=-=-=-=-=- // 5. return the newly created microservice plugin return msvc; } } // extern "C" std::string convertCompressTypeToStr(const MagickCore::CompressionType& t) { switch (t) { case UndefinedCompression: return "undefined"; case NoCompression: return "none"; case FaxCompression: return "FAX"; case Group4Compression: return "GROUP4"; case JPEGCompression: return "JPEG"; case LZWCompression: return "LZW"; case RLECompression: return "RLE"; case LZMACompression: return "LZMA"; default: return "undefined"; } } std::string convertColorSpaceTypeToStr(const MagickCore::ColorspaceType& t) { switch (t) { case UndefinedColorspace: return "undefined"; case RGBColorspace: return "RGB"; case GRAYColorspace: return "GRAY"; case TransparentColorspace: return "TRANSPARENT"; case OHTAColorspace: return "OHTA"; case XYZColorspace: return "XYZ"; case YCbCrColorspace: return "YCbCr"; case YCCColorspace: return "YCC"; case YIQColorspace: return "YIQ"; case YPbPrColorspace: return "YPbPr"; case YUVColorspace: return "YUV"; case CMYKColorspace: return "CMYK"; case sRGBColorspace: return "sRGB"; case HSLColorspace: return "HSL"; case HWBColorspace: return "HWB"; case Rec601LumaColorspace: return "REC601Luma"; case Rec709LumaColorspace: return "REC709"; case LogColorspace: return "LOG"; default: return "undefined"; } }
Parameters p1 p2 t1 t2 : Prop. Definition aff1 := (p1 \/ p2). Definition aff2 := t1. Definition k := (aff1 /\ aff2) \/ (~aff1 /\ ~aff2). Definition h1 := ~(p1 /\ t1) /\ ~(p2 /\ t2). Definition h2 := (p1 \/ t1) /\ (p2 \/ t2). Lemma epreuve_2 : h1 /\ h2 /\ k -> t1 /\ p2. Proof. unfold k, h1, h2. unfold aff1, aff2. intros. destruct H. destruct H. destruct H0. destruct H0. destruct H2. destruct H2. split; try assumption. destruct H3; try assumption. destruct H2; try assumption. elimtype False. auto. destruct H2. destruct H0. elimtype False. auto. elimtype False. auto. Qed.
# Author: Karl Stratos ([email protected]) import dynet as dy import numpy as np import os import pickle import random import time from common_architecture import CommonArchitecture from model import Model from window import Window class PartOfSpeechInducer(Model): def __init__(self, cmd=""): self.common = CommonArchitecture(self) super(PartOfSpeechInducer, self).__init__(cmd) def config(self, arch, loss_type, zsize, wdim, cdim, jdim, width, swap, pseudocount, metric, verbose=False): self.arch = arch self.loss_type = loss_type self.zsize = zsize self.wdim = wdim self.cdim = cdim self.jdim = jdim self.width = width self.swap = swap self.pseudocount = pseudocount self.metric = metric self._verbose = verbose def init_parameters(self, wembs): crep_dim = self.common.init_common_parameters(wembs) if self.arch == "default": assert self.wdim > 0 self.W_X = self.m.add_parameters((self.zsize, 2 * self.wdim * self.width)) self.W_Y = self.m.add_parameters((self.zsize, self.wdim + crep_dim)) elif self.arch == "default-char": assert crep_dim > 0 self.W_X = self.m.add_parameters((self.zsize, 2 * crep_dim * self.width)) self.W_Y = self.m.add_parameters((self.zsize, crep_dim)) elif self.arch == "brown": assert self.wdim > 0 self.W = self.m.add_parameters((self.zsize, self.wdim)) elif self.arch == "brown-sep": assert self.wdim > 0 self.W_X = self.m.add_parameters((self.zsize, self.wdim)) self.W_Y = self.m.add_parameters((self.zsize, self.wdim)) elif self.arch == "widen1": assert self.wdim > 0 self.W_X = self.m.add_parameters((self.zsize, 2 * self.wdim * self.width)) self.W_Y = self.m.add_parameters((self.zsize, 2 * self.wdim + crep_dim)) elif self.arch == "widen2": assert self.wdim > 0 self.W_X = self.m.add_parameters((self.zsize, 2 * self.wdim * self.width)) self.W_Y = self.m.add_parameters((self.zsize, 3 * self.wdim + crep_dim)) elif self.arch == "lstm": assert self.wdim > 0 self.context_lstm1 = dy.LSTMBuilder(1, self.wdim, self.wdim, self.m) self.context_lstm2 = dy.LSTMBuilder(1, self.wdim, self.wdim, self.m) self.W_X = self.m.add_parameters((self.zsize, 2 * self.wdim)) self.W_Y = self.m.add_parameters((self.zsize, self.wdim + crep_dim)) else: raise ValueError("unknown architecture: {0}".format(self.arch)) def compute_qp_pairs(self, wseqs, batch): dy.renew_cg() def assert_sentence_batch(wseqs, batch): (i, j) = batch[0] assert j == 0 assert len(batch) == len(wseqs[i]) for (i_next, j_next) in batch[1:]: assert i_next == i assert j_next == j + 1 j = j_next return i if self.arch == "lstm": i = assert_sentence_batch(wseqs, batch) return self.compute_qp_pairs_lstm(wseqs[i]) if self.arch == "default": compute_qp_pair = self.compute_qp_pair_default elif self.arch == "default-char": compute_qp_pair = self.compute_qp_pair_default_char elif self.arch == "brown": compute_qp_pair = self.compute_qp_pair_brown elif self.arch == "brown-sep": compute_qp_pair = self.compute_qp_pair_brown_sep elif self.arch == "widen1": compute_qp_pair = self.compute_qp_pair_widen1 elif self.arch == "widen2": compute_qp_pair = self.compute_qp_pair_widen2 else: raise ValueError("unknown self.architecture: {0}".format(self.arch)) qp_pairs = [] for (i, j) in batch: (qZ_X, pZ_Y) = compute_qp_pair(wseqs[i], j) qp_pairs.append((pZ_Y, qZ_X) if self.swap else (qZ_X, pZ_Y)) return qp_pairs def compute_qp_pair_default(self, wseq, j): window = Window(wseq, self._BUF) X = window.left(j, self.width) + window.right(j, self.width) v_X = [self.common.get_wemb(w) for w in X] qZ_X = dy.softmax(self.W_X * dy.concatenate(v_X)) v_Y = [v for v in [self.common.get_wemb(wseq[j]), self.common.get_crep(wseq[j])] if v] pZ_Y = dy.softmax(self.W_Y * dy.concatenate(v_Y)) return qZ_X, pZ_Y def compute_qp_pair_default_char(self, wseq, j): window = Window(wseq, self._BUF) X = window.left(j, self.width) + window.right(j, self.width) v_X = [self.common.get_crep(w) for w in X] qZ_X = dy.softmax(self.W_X * dy.concatenate(v_X)) v_Y = [self.common.get_crep(wseq[j])] pZ_Y = dy.softmax(self.W_Y * dy.concatenate(v_Y)) return qZ_X, pZ_Y def compute_qp_pair_brown(self, wseq, j): window = Window(wseq, self._BUF) X = window.left(j, 1) v_X = [self.common.get_wemb(w) for w in X] qZ_X = dy.softmax(self.W * dy.concatenate(v_X)) Y = [wseq[j]] v_Y = [self.common.get_wemb(w) for w in Y] pZ_Y = dy.softmax(self.W * dy.concatenate(v_Y)) return qZ_X, pZ_Y def compute_qp_pair_brown_sep(self, wseq, j): window = Window(wseq, self._BUF) X = window.left(j, 1) v_X = [self.common.get_wemb(w) for w in X] qZ_X = dy.softmax(self.W_X * dy.concatenate(v_X)) Y = [wseq[j]] v_Y = [self.common.get_wemb(w) for w in Y] pZ_Y = dy.softmax(self.W_Y * dy.concatenate(v_Y)) return qZ_X, pZ_Y def compute_qp_pair_widen1(self, wseq, j): window = Window(wseq, self._BUF) X = window.left(max(0, j - 1), self.width) X += window.right(j, self.width) v_X = [self.common.get_wemb(w) for w in X] qZ_X = dy.softmax(self.W_X * dy.concatenate(v_X)) Y = window.left(j, 1) Y += [wseq[j]] v_Y = [v for v in [self.common.get_wemb(w) for w in Y] + [self.common.get_crep(wseq[j])] if v] pZ_Y = dy.softmax(self.W_Y * dy.concatenate(v_Y)) return qZ_X, pZ_Y def compute_qp_pair_widen2(self, wseq, j): window = Window(wseq, self._BUF) X = window.left(max(0, j - 1), self.width) X += window.right(min(len(wseq) - 1, j + 1), self.width) v_X = [self.common.get_wemb(w) for w in X] qZ_X = dy.softmax(self.W_X * dy.concatenate(v_X)) Y = window.left(j, 1) Y += [wseq[j]] Y += window.right(j, 1) v_Y = [v for v in [self.common.get_wemb(w) for w in Y] + [self.common.get_crep(wseq[j])] if v] pZ_Y = dy.softmax(self.W_Y * dy.concatenate(v_Y)) return qZ_X, pZ_Y def compute_qp_pairs_lstm(self, wseq): # <*> <-> the <-> dog <-> saw <-> the <-> cat <-> <*> inputs = [self.common.get_wemb(w) for w in [self._BUF] + wseq + [self._BUF]] outputs1, outputs2 = self.common.run_bilstm(inputs, self.context_lstm1, self.context_lstm2) qp_pairs = [] for j in xrange(len(wseq)): v_X = self.common.get_bilstm_left_right_from_outputs(outputs1, outputs2, j + 1, j + 1) qZ_X = dy.softmax(self.W_X * v_X) v_Y = [v for v in [self.common.get_wemb(wseq[j]), self.common.get_crep(wseq[j])] if v] pZ_Y = dy.softmax(self.W_Y * dy.concatenate(v_Y)) qp_pairs.append((qZ_X, pZ_Y)) return qp_pairs def prepare_batches(self, wseqs, batch_size): if batch_size == 0: # sentence-level batching inds = [i for i in xrange(len(wseqs))] random.shuffle(inds) batches = [[(i, j) for j in xrange(len(wseqs[i]))] for i in inds] else: pairs = [] for i in xrange(len(wseqs)): for j in xrange(len(wseqs[i])): pairs.append((i, j)) random.shuffle(pairs) batches = [] for i in xrange(0, len(pairs), batch_size): batches.append(pairs[i:min(i + batch_size, len(pairs))]) return batches def _enable_lstm_dropout(self, drate): if self.arch == "lstm": self.context_lstm1.set_dropout(drate) self.context_lstm2.set_dropout(drate) def _disable_lstm_dropout(self): if self.arch == "lstm": self.context_lstm1.disable_dropout() self.context_lstm2.disable_dropout() def measure_mi(self, wseqs): assert not self._is_training num_samples = 0 joint = np.zeros((self.zsize, self.zsize)) batches = self.prepare_batches(wseqs, 0) for batch in batches: qp_pairs = self.compute_qp_pairs(wseqs, batch) for (qZ_X, pZ_Y) in qp_pairs: num_samples += 1 outer = qZ_X * dy.transpose(pZ_Y) joint += outer.value() joint /= num_samples mi = self.evaluator.mi_zero(joint) return mi def train(self, model_path, wseqs, lrate, drate, epochs, batch_size, wemb_path, tseqs=[]): wembs = self.read_wembs(wemb_path, self.wdim) self.m = dy.ParameterCollection() self._prepare_model_directory(model_path) self.build_dicts(wseqs, tseqs, wembs) self.init_parameters(wembs) trainer = dy.AdamTrainer(self.m, lrate) self._train_report(lrate, drate, epochs, batch_size) self.common.turn_on_training(drate) perf_best = 0.0 for epoch in xrange(epochs): self._log("Epoch {0:2d} ".format(epoch + 1), False) epoch_start_time = time.time() batches = self.prepare_batches(wseqs, batch_size) total_batch_loss = 0.0 for batch in batches: qp_pairs = self.compute_qp_pairs(wseqs, batch) batch_loss = self.common.get_loss(qp_pairs) total_batch_loss += batch_loss.value() batch_loss.backward() trainer.update() avg_loss = total_batch_loss / len(batches) self._log("updates: {0} ".format(len(batches)), False) self._log("loss: {0:.2f} ".format(avg_loss), False) self._log("({0:.1f}s) ".format(time.time() - epoch_start_time), False) if tseqs: self.common.turn_off_training() zseqs_X, zseqs_Y, zseqs_XY, infer_time = self.tag_all(wseqs) perf_max = self.common.evaluator_report(wseqs, tseqs, zseqs_X, zseqs_Y, zseqs_XY, infer_time, self.measure_mi(wseqs), self.metric) self.common.turn_on_training(drate) if perf_max > perf_best: perf_best = perf_max self._log("new best {0:.2f} - saving ".format(perf_best), False) self.save(model_path) else: self.save(model_path) self._log("") def save(self, model_path): self.m.save(os.path.join(model_path, "model")) with open(os.path.join(model_path, "info.pickle"), 'w') as outf: pickle.dump( (self._w2i, self._c2i, self._jamo2i, self.arch, self.loss_type, self.zsize, self.wdim, self.cdim, self.jdim, self.width, self.swap, self.pseudocount), outf) def load_and_populate(self, model_path): self.m = dy.ParameterCollection() with open(os.path.join(model_path, "info.pickle")) as inf: (self._w2i, self._c2i, self._jamo2i, self.arch, self.loss_type, self.zsize, self.wdim, self.cdim, self.jdim, self.width, self.swap, self.pseudocount) = pickle.load(inf) self.init_parameters(wembs={}) self.m.populate(os.path.join(model_path, "model")) def _train_report(self, lrate, drate, epochs, batch_size): self._log("___Data___") self._log(" # sents: {0}".format(self.num_seqs)) self._log(" # words: {0}".format(self.num_words)) self._log(" # pretrained wembs: {0}".format(self.num_pretrained_wembs)) self._log(" # distinct words: {0}".format(self.wsize())) self._log(" # distinct chars: {0}".format(self.csize())) self._log(" # distinct jamos: {0}".format(self.jamo_size())) self._log("") self._log("___Model___") self._log(" arch: {0}".format(self.arch)) self._log(" loss type: {0}".format(self.loss_type)) self._log(" zsize: {0}".format(self.zsize)) self._log(" wdim: {0}".format(self.wdim)) self._log(" cdim: {0}".format(self.cdim)) self._log(" jdim: {0}".format(self.jdim)) self._log(" width: {0}".format(self.width)) self._log(" swap: {0}".format(self.swap)) self._log(" pseudocount: {0}".format(self.pseudocount)) self._log("") self._log("___Training___") self._log(" lrate: {0}".format(lrate)) self._log(" drate: {0}".format(drate)) self._log(" epochs: {0}".format(epochs)) self._log(" batch size: {0}".format(batch_size)) self._log(" metric: {0}".format(self.metric)) self._log("") def tag(self, wseq): """ LB: I(Z; X) MI: I(Z_Y; Z_X) Z Z_X Z_Y q/|p q| |p / | | | X Y X Y """ assert not self._is_training qp_pairs = self.compute_qp_pairs([wseq], [(0, j) for j in xrange(len(wseq))]) zseq_X = [] zseq_Y = [] zseq_XY = [] for (qZ_X, pZ_Y) in qp_pairs: zseq_X.append(np.argmax(qZ_X.npvalue())) zseq_Y.append(np.argmax(pZ_Y.npvalue())) if self.loss_type == "lb": zseq_XY.append(np.argmax(dy.cmult(qZ_X, pZ_Y).npvalue())) return zseq_X, zseq_Y, zseq_XY def tag_all(self, wseqs): infer_start_time = time.time() zseqs_X = [] zseqs_Y = [] zseqs_XY = [] for wseq in wseqs: zseq_X, zseq_Y, zseq_XY = self.tag(wseq) zseqs_X.append(zseq_X) zseqs_Y.append(zseq_Y) if zseq_XY: zseqs_XY.append(zseq_XY) return zseqs_X, zseqs_Y, zseqs_XY, time.time() - infer_start_time
(* Title: HOL/Auth/n_flash_lemma_on_inv__30.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_flash Protocol Case Study*} theory n_flash_lemma_on_inv__30 imports n_flash_base begin section{*All lemmas on causal relation between inv__30 and some rule r*} lemma n_PI_Remote_GetVsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_Get src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_Get src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_PI_Remote_GetXVsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_GetX src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_GetX src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_NakVsinv__30: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Nak dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Nak dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Nak__part__0Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Nak__part__1Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Nak__part__2Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Get__part__0Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Get__part__1Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Put_HeadVsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_PutVsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Put_DirtyVsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_Get_NakVsinv__30: assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_Get_PutVsinv__30: assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_Nak__part__0Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_Nak__part__1Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_Nak__part__2Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_GetX__part__0Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_GetX__part__1Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_1Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" 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_NI_Local_GetX_PutX_2Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" 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_NI_Local_GetX_PutX_3Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" 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_NI_Local_GetX_PutX_4Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" 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_NI_Local_GetX_PutX_5Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" 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_NI_Local_GetX_PutX_6Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" 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_NI_Local_GetX_PutX_7__part__0Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" 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_NI_Local_GetX_PutX_7__part__1Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" 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_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" 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_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" 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_NI_Local_GetX_PutX_8_HomeVsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" 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_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" 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_NI_Local_GetX_PutX_8Vsinv__30: assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)" 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_NI_Local_GetX_PutX_8_NODE_GetVsinv__30: assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)" 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_NI_Local_GetX_PutX_9__part__0Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" 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_NI_Local_GetX_PutX_9__part__1Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" 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_NI_Local_GetX_PutX_10_HomeVsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" 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_NI_Local_GetX_PutX_10Vsinv__30: assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)" 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_NI_Local_GetX_PutX_11Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" 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_NI_Remote_GetX_NakVsinv__30: assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_GetX_PutXVsinv__30: assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') dst) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Local'')) (Const true))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_PutVsinv__30: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Put dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Put dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_PutXVsinv__30: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_PutX dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_PutX dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_InvAck_1Vsinv__30: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_InvAck_1 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_InvAck_1 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" 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_PI_Local_Get_PutVsinv__30: assumes a1: "(r=n_PI_Local_Get_Put )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_GetX_PutX_HeadVld__part__0Vsinv__30: assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__0 N )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_GetX_PutX_HeadVld__part__1Vsinv__30: assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__1 N )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_GetX_PutX__part__0Vsinv__30: assumes a1: "(r=n_PI_Local_GetX_PutX__part__0 )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_GetX_PutX__part__1Vsinv__30: assumes a1: "(r=n_PI_Local_GetX_PutX__part__1 )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_PutXVsinv__30: assumes a1: "(r=n_PI_Local_PutX )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const true))) s))" by auto moreover { assume c1: "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const true)) s))" have "?P2 s" proof(cut_tac a1 a2 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const true))) s))" have "?P1 s" proof(cut_tac a1 a2 c1, 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_PI_Local_ReplaceVsinv__30: assumes a1: "(r=n_PI_Local_Replace )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_PutVsinv__30: assumes a1: "(r=n_NI_Local_Put )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Put))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_PutXAcksDoneVsinv__30: assumes a1: "(r=n_NI_Local_PutXAcksDone )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__30 p__Inv4" apply fastforce done have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_PutX))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Remote_GetX_PutX_HomeVsinv__30: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_WbVsinv__30: assumes a1: "r=n_NI_Wb " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_StoreVsinv__30: assumes a1: "\<exists> src data. src\<le>N\<and>data\<le>N\<and>r=n_Store src data" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_3Vsinv__30: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_3 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_GetX_GetX__part__1Vsinv__30: assumes a1: "r=n_PI_Local_GetX_GetX__part__1 " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_GetX_GetX__part__0Vsinv__30: assumes a1: "r=n_PI_Local_GetX_GetX__part__0 " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Remote_ReplaceVsinv__30: assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Replace src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_Store_HomeVsinv__30: assumes a1: "\<exists> data. data\<le>N\<and>r=n_Store_Home data" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_existsVsinv__30: assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_InvAck_exists src pp" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Remote_PutXVsinv__30: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_PI_Remote_PutX dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_Get_Put_HomeVsinv__30: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvVsinv__30: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Inv dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_ShWbVsinv__30: assumes a1: "r=n_NI_ShWb N " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_ReplaceVsinv__30: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Replace src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_GetX_Nak_HomeVsinv__30: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_Get_Nak_HomeVsinv__30: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_exists_HomeVsinv__30: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_exists_Home src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Replace_HomeVsinv__30: assumes a1: "r=n_NI_Replace_Home " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Nak_ClearVsinv__30: assumes a1: "r=n_NI_Nak_Clear " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_Get_GetVsinv__30: assumes a1: "r=n_PI_Local_Get_Get " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Nak_HomeVsinv__30: assumes a1: "r=n_NI_Nak_Home " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_2Vsinv__30: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_2 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_FAckVsinv__30: assumes a1: "r=n_NI_FAck " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__30 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done end
(* Title: HOL/Auth/n_moesi_lemma_on_inv__3.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_moesi Protocol Case Study*} theory n_moesi_lemma_on_inv__3 imports n_moesi_base begin section{*All lemmas on causal relation between inv__3 and some rule r*} lemma n_rule_t1Vsinv__3: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_rule_t1 i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__3 p__Inv0 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_rule_t1 i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__3 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>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__Inv0)" 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__Inv0\<and>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_rule_t2Vsinv__3: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_rule_t2 N i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__3 p__Inv0 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_rule_t2 N i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__3 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "((formEval (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E)) s))\<or>((formEval (andForm (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const M)) (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const M))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E)))) s))" by auto moreover { assume c1: "((formEval (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E)) s))" have "?P1 s" proof(cut_tac a1 a2 b1 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (andForm (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const M)) (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E)))) s))" have "?P1 s" proof(cut_tac a1 a2 b1 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (andForm (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const M))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E)))) s))" have "?P1 s" proof(cut_tac a1 a2 b1 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately have "invHoldForRule s f r (invariants N)" by satx } moreover { assume b1: "(i=p__Inv0)" have "((formEval (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)) s))\<or>((formEval (andForm (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const M)) (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const M))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)))) s))" by auto moreover { assume c1: "((formEval (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)) s))" have "?P1 s" proof(cut_tac a1 a2 b1 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (andForm (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const M)) (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)))) s))" have "?P1 s" proof(cut_tac a1 a2 b1 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (andForm (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const M))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)))) s))" have "?P1 s" proof(cut_tac a1 a2 b1 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately have "invHoldForRule s f r (invariants N)" by satx } moreover { assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)" have "((formEval (andForm (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)) (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E))) s))\<or>((formEval (andForm (andForm (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const M)) (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E))) s))\<or>((formEval (andForm (andForm (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const M))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E))) s))\<or>((formEval (andForm (andForm (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)) (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const M))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E)))) s))\<or>((formEval (andForm (andForm (andForm (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const M)) (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const M))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E)))) s))\<or>((formEval (andForm (andForm (andForm (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const M))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const M))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E)))) s))\<or>((formEval (andForm (andForm (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)) (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E)))) s))\<or>((formEval (andForm (andForm (andForm (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const M)) (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E)))) s))\<or>((formEval (andForm (andForm (andForm (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const M))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E)))) s))" by auto moreover { assume c1: "((formEval (andForm (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)) (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E))) s))" have "?P1 s" proof(cut_tac a1 a2 b1 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (andForm (andForm (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const M)) (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E))) s))" have "?P1 s" proof(cut_tac a1 a2 b1 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (andForm (andForm (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const M))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E))) s))" have "?P1 s" proof(cut_tac a1 a2 b1 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (andForm (andForm (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)) (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const M))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E)))) s))" have "?P1 s" proof(cut_tac a1 a2 b1 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (andForm (andForm (andForm (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const M)) (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const M))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E)))) s))" have "?P1 s" proof(cut_tac a1 a2 b1 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (andForm (andForm (andForm (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const M))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)))) (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const M))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E)))) s))" have "?P1 s" proof(cut_tac a1 a2 b1 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (andForm (andForm (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)) (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E)))) s))" have "?P1 s" proof(cut_tac a1 a2 b1 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (andForm (andForm (andForm (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const M)) (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E)))) s))" have "?P1 s" proof(cut_tac a1 a2 b1 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (andForm (andForm (andForm (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const M))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv2)) (Const E)))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const M)))) (neg (eqn (IVar (Para (Ident ''a'') p__Inv0)) (Const E)))) s))" have "?P2 s" proof(cut_tac a1 a2 b1 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately have "invHoldForRule s f r (invariants N)" by satx } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_rul_t3Vsinv__3: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_rul_t3 N i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__3 p__Inv0 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_rul_t3 N i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__3 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>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__Inv0)" 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__Inv0\<and>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_rul_t4Vsinv__3: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_rul_t4 N i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__3 p__Inv0 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_rul_t4 N i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__3 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>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__Inv0)" 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__Inv0\<and>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_rul_t5Vsinv__3: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_rul_t5 N i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__3 p__Inv0 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_rul_t5 N i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__3 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>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__Inv0)" 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__Inv0\<and>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 end
module Collections.BSTree.Map.Quantifiers import Collections.BSTree.Map.Core import Collections.Util.Bnd import Decidable.Order.Strict ||| A proof that a tree is non-empty. public export data NonEmpty : BST pre tot vTy mn mx -> Type where IsNode : {pre : StrictPreorder kTy sto} -> {tot : StrictOrdered kTy sto} -> {l : BST pre tot vTy mn (Mid k)} -> {r : BST pre tot vTy (Mid k) mx} -> NonEmpty (Node k v l r)
!> !! \brief This module contains basic size parameter definitions !! !! Module for Capreole !! !! \b Author: Garrelt Mellema !! !! \b Date: 2010-02-04 !! !! This module is also accepted by the F compiler (Dec 9, 2003) module sizes private integer,public,parameter :: nrOfDim=3 !< number of dimensions integer,public,parameter :: mbc=2 !< number of ghost cells integer,public,parameter :: neuler=2+NrOfDim !< number of Euler equations integer,public,parameter :: neq=neuler+2 !< number of equations (Euler + advected quantities) ! Indices of state array integer,public,parameter :: RHO=1 !< Indices of state array: density integer,public,parameter :: RHVX=2 !< Indices of state array: x momentum density integer,public,parameter :: RHVY=3 !< Indices of state array: y momentum density integer,public,parameter :: RHVZ=4 !< Indices of state array: z momentum density integer,public,parameter :: EN=5 !< Indices of state array: energy density !integer,public,parameter :: TRACER1=6 integer,public,parameter :: XHI=6 !< Indices of state array: neutral hydrogen fraction integer,public,parameter :: XHII=7 !< Indices of state array: ionized hydrogen fraction ! The following define constants for identifying the coordinate system integer,public,parameter :: CART =1 !< constant for defining cartesian coordinate system integer,public,parameter :: CYL =2 !< constant for defining cylindrical coordinate system integer,public,parameter :: SPHER=3 !< constant for defining spherical coordinate system end module sizes
/- Copyright (c) 2019 Abhimanyu Pallavi Sudhir. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Abhimanyu Pallavi Sudhir, Yury Kudryashov ! This file was ported from Lean 3 source module order.filter.filter_product ! leanprover-community/mathlib commit 2738d2ca56cbc63be80c3bd48e9ed90ad94e947d ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.Order.Filter.Ultrafilter import Mathlib.Order.Filter.Germ /-! # Ultraproducts If `φ` is an ultrafilter, then the space of germs of functions `f : α → β` at `φ` is called the *ultraproduct*. In this file we prove properties of ultraproducts that rely on `φ` being an ultrafilter. Definitions and properties that work for any filter should go to `Order.Filter.Germ`. ## Tags ultrafilter, ultraproduct -/ universe u v variable {α : Type u} {β : Type v} {φ : Ultrafilter α} open Classical namespace Filter local notation3"∀* "(...)", "r:(scoped p => Filter.Eventually p φ) => r namespace Germ open Ultrafilter local notation "β*" => Germ (φ : Filter α) β instance divisionSemiring [DivisionSemiring β] : DivisionSemiring β* := { Germ.semiring, Germ.divInvMonoid, Germ.nontrivial with mul_inv_cancel := fun f => inductionOn f fun f hf => coe_eq.2 <| (φ.em fun y => f y = 0).elim (fun H => (hf <| coe_eq.2 H).elim) fun H => H.mono fun x => mul_inv_cancel inv_zero := coe_eq.2 <| by simp only [Function.comp, inv_zero] exact EventuallyEq.refl _ fun _ => 0} instance divisionRing [DivisionRing β] : DivisionRing β* := { Germ.ring, Germ.divisionSemiring with } instance semifield [Semifield β] : Semifield β* := { Germ.commSemiring, Germ.divisionSemiring with } instance field [Field β] : Field β* := { Germ.commRing, Germ.divisionRing with } theorem coe_lt [Preorder β] {f g : α → β} : (f : β*) < g ↔ ∀* x, f x < g x := by simp only [lt_iff_le_not_le, eventually_and, coe_le, eventually_not, EventuallyLE] #align filter.germ.coe_lt Filter.Germ.coe_lt theorem coe_pos [Preorder β] [Zero β] {f : α → β} : 0 < (f : β*) ↔ ∀* x, 0 < f x := coe_lt #align filter.germ.coe_pos Filter.Germ.coe_pos theorem const_lt [Preorder β] {x y : β} : x < y → (↑x : β*) < ↑y := coe_lt.mpr ∘ liftRel_const #align filter.germ.const_lt Filter.Germ.const_lt @[simp, norm_cast] theorem lt_def [Preorder β] : ((· < ·) : β* → β* → Prop) = LiftRel (· < ·) := by ext (⟨f⟩⟨g⟩) exact coe_lt #align filter.germ.lt_def Filter.Germ.lt_def instance sup [Sup β] : Sup β* := ⟨map₂ (· ⊔ ·)⟩ instance inf [Inf β] : Inf β* := ⟨map₂ (· ⊓ ·)⟩ @[simp, norm_cast] theorem const_sup [Sup β] (a b : β) : ↑(a ⊔ b) = (↑a ⊔ ↑b : β*) := rfl #align filter.germ.const_sup Filter.Germ.const_sup @[simp, norm_cast] theorem const_inf [Inf β] (a b : β) : ↑(a ⊓ b) = (↑a ⊓ ↑b : β*) := rfl #align filter.germ.const_inf Filter.Germ.const_inf instance semilatticeSup [SemilatticeSup β] : SemilatticeSup β* := { Germ.partialOrder with sup := (· ⊔ ·) le_sup_left := fun f g => inductionOn₂ f g fun _f _g => eventually_of_forall fun _x => le_sup_left le_sup_right := fun f g => inductionOn₂ f g fun _f _g => eventually_of_forall fun _x => le_sup_right sup_le := fun f₁ f₂ g => inductionOn₃ f₁ f₂ g fun _f₁ _f₂ _g h₁ h₂ => h₂.mp <| h₁.mono fun _x => sup_le } instance semilatticeInf [SemilatticeInf β] : SemilatticeInf β* := { Germ.partialOrder with inf := (· ⊓ ·) inf_le_left := fun f g => inductionOn₂ f g fun _f _g => eventually_of_forall fun _x => inf_le_left inf_le_right := fun f g => inductionOn₂ f g fun _f _g => eventually_of_forall fun _x => inf_le_right le_inf := fun f₁ f₂ g => inductionOn₃ f₁ f₂ g fun _f₁ _f₂ _g h₁ h₂ => h₂.mp <| h₁.mono fun _x => le_inf } instance lattice [Lattice β] : Lattice β* := { Germ.semilatticeSup, Germ.semilatticeInf with } instance distribLattice [DistribLattice β] : DistribLattice β* := { Germ.semilatticeSup, Germ.semilatticeInf with le_sup_inf := fun f g h => inductionOn₃ f g h fun _f _g _h => eventually_of_forall fun _ => le_sup_inf } instance isTotal [LE β] [IsTotal β (· ≤ ·)] : IsTotal β* (· ≤ ·) := ⟨fun f g => inductionOn₂ f g fun _f _g => eventually_or.1 <| eventually_of_forall fun _x => total_of _ _ _⟩ /-- If `φ` is an ultrafilter then the ultraproduct is a linear order. -/ noncomputable instance linearOrder [LinearOrder β] : LinearOrder β* := Lattice.toLinearOrder _ @[to_additive] instance orderedCommMonoid [OrderedCommMonoid β] : OrderedCommMonoid β* := { Germ.partialOrder, Germ.commMonoid with mul_le_mul_left := fun f g => inductionOn₂ f g fun _f _g H h => inductionOn h fun _h => H.mono fun _x H => mul_le_mul_left' H _ } @[to_additive] instance orderedCancelCommMonoid [OrderedCancelCommMonoid β] : OrderedCancelCommMonoid β* := { Germ.orderedCommMonoid with le_of_mul_le_mul_left := fun f g h => inductionOn₃ f g h fun _f _g _h H => H.mono fun _x => le_of_mul_le_mul_left' } @[to_additive] instance orderedCommGroup [OrderedCommGroup β] : OrderedCommGroup β* := { Germ.orderedCancelCommMonoid, Germ.commGroup with } @[to_additive] noncomputable instance linearOrderedCommGroup [LinearOrderedCommGroup β] : LinearOrderedCommGroup β* := { Germ.orderedCommGroup, Germ.linearOrder with } instance orderedSemiring [OrderedSemiring β] : OrderedSemiring β* := { Germ.semiring, Germ.orderedAddCommMonoid with zero_le_one := const_le zero_le_one mul_le_mul_of_nonneg_left := fun x y z => inductionOn₃ x y z fun _f _g _h hfg hh => hh.mp <| hfg.mono fun _a => mul_le_mul_of_nonneg_left mul_le_mul_of_nonneg_right := fun x y z => inductionOn₃ x y z fun _f _g _h hfg hh => hh.mp <| hfg.mono fun _a => mul_le_mul_of_nonneg_right } instance orderedCommSemiring [OrderedCommSemiring β] : OrderedCommSemiring β* := { Germ.orderedSemiring, Germ.commSemiring with } instance orderedRing [OrderedRing β] : OrderedRing β* := { Germ.ring, Germ.orderedAddCommGroup with zero_le_one := const_le zero_le_one mul_nonneg := fun x y => inductionOn₂ x y fun _f _g hf hg => hg.mp <| hf.mono fun _a => mul_nonneg } instance orderedCommRing [OrderedCommRing β] : OrderedCommRing β* := { Germ.orderedRing, Germ.orderedCommSemiring with } instance strictOrderedSemiring [StrictOrderedSemiring β] : StrictOrderedSemiring β* := { Germ.orderedSemiring, Germ.orderedAddCancelCommMonoid, Germ.nontrivial with mul_lt_mul_of_pos_left := fun x y z => inductionOn₃ x y z fun _f _g _h hfg hh => coe_lt.2 <| (coe_lt.1 hh).mp <| (coe_lt.1 hfg).mono fun _a => mul_lt_mul_of_pos_left mul_lt_mul_of_pos_right := fun x y z => inductionOn₃ x y z fun _f _g _h hfg hh => coe_lt.2 <| (coe_lt.1 hh).mp <| (coe_lt.1 hfg).mono fun _a => mul_lt_mul_of_pos_right } instance strictOrderedCommSemiring [StrictOrderedCommSemiring β] : StrictOrderedCommSemiring β* := { Germ.strictOrderedSemiring, Germ.orderedCommSemiring with } instance strictOrderedRing [StrictOrderedRing β] : StrictOrderedRing β* := { Germ.ring, Germ.strictOrderedSemiring with zero_le_one := const_le zero_le_one mul_pos := fun x y => inductionOn₂ x y fun _f _g hf hg => coe_pos.2 <| (coe_pos.1 hg).mp <| (coe_pos.1 hf).mono fun _x => mul_pos } instance strictOrderedCommRing [StrictOrderedCommRing β] : StrictOrderedCommRing β* := { Germ.strictOrderedRing, Germ.orderedCommRing with } noncomputable instance linearOrderedRing [LinearOrderedRing β] : LinearOrderedRing β* := { Germ.strictOrderedRing, Germ.linearOrder with } noncomputable instance linearOrderedField [LinearOrderedField β] : LinearOrderedField β* := { Germ.linearOrderedRing, Germ.field with } noncomputable instance linearOrderedCommRing [LinearOrderedCommRing β] : LinearOrderedCommRing β* := { Germ.linearOrderedRing, Germ.commMonoid with } theorem max_def [LinearOrder β] (x y : β*) : max x y = map₂ max x y := inductionOn₂ x y fun a b => by cases' le_total (a : β*) b with h h · rw [max_eq_right h, map₂_coe, coe_eq] exact h.mono fun i hi => (max_eq_right hi).symm · rw [max_eq_left h, map₂_coe, coe_eq] exact h.mono fun i hi => (max_eq_left hi).symm #align filter.germ.max_def Filter.Germ.max_def theorem min_def [K : LinearOrder β] (x y : β*) : min x y = map₂ min x y := inductionOn₂ x y fun a b => by cases' le_total (a : β*) b with h h · rw [min_eq_left h, map₂_coe, coe_eq] exact h.mono fun i hi => (min_eq_left hi).symm · rw [min_eq_right h, map₂_coe, coe_eq] exact h.mono fun i hi => (min_eq_right hi).symm #align filter.germ.min_def Filter.Germ.min_def theorem abs_def [LinearOrderedAddCommGroup β] (x : β*) : |x| = map abs x := inductionOn x fun _a => rfl #align filter.germ.abs_def Filter.Germ.abs_def @[simp] theorem const_max [LinearOrder β] (x y : β) : (↑(max x y : β) : β*) = max ↑x ↑y := by rw [max_def, map₂_const] #align filter.germ.const_max Filter.Germ.const_max @[simp] theorem const_min [LinearOrder β] (x y : β) : (↑(min x y : β) : β*) = min ↑x ↑y := by rw [min_def, map₂_const] #align filter.germ.const_min Filter.Germ.const_min @[simp] theorem const_abs [LinearOrderedAddCommGroup β] (x : β) : (↑(|x|) : β*) = |↑x| := by rw [abs_def, map_const] #align filter.germ.const_abs Filter.Germ.const_abs end Germ end Filter
import Numeric.LinearAlgebra import Graphics.Plot vector l = fromList l :: Vector Double matrix ls = fromLists ls :: Matrix Double diagl = diag . vector f = matrix [[1,0,0,0], [1,1,0,0], [0,0,1,0], [0,0,0,1]] h = matrix [[0,-1,1,0], [0,-1,0,1]] q = diagl [1,1,0,0] r = diagl [2,2] s0 = State (vector [0, 0, 10, -10]) (diagl [10,0, 100, 100]) data System = System {kF, kH, kQ, kR :: Matrix Double} data State = State {sX :: Vector Double , sP :: Matrix Double} type Measurement = Vector Double kalman :: System -> State -> Measurement -> State kalman (System f h q r) (State x p) z = State x' p' where px = f <> x -- prediction pq = f <> p <> trans f + q -- its covariance y = z - h <> px -- residue cy = h <> pq <> trans h + r -- its covariance k = pq <> trans h <> inv cy -- kalman gain x' = px + k <> y -- new state p' = (ident (dim x) - k <> h) <> pq -- its covariance sys = System f h q r zs = [vector [15-k,-20-k] | k <- [0..]] xs = s0 : zipWith (kalman sys) xs zs des = map (sqrt.takeDiag.sP) xs evolution n (xs,des) = vector [1.. fromIntegral n]:(toColumns $ fromRows $ take n (zipWith (-) (map sX xs) des)) ++ (toColumns $ fromRows $ take n (zipWith (+) (map sX xs) des)) main = do print $ fromRows $ take 10 (map sX xs) mapM_ (print . sP) $ take 10 xs mplot (evolution 20 (xs,des))
What Can You Benefit When You Find the Best Source of Planners? If you are looking forward to the New Year, you may feel a great deal of excitement, as you might be planning a lot of things for it. You might, then, want to do everything that you can that will help you to stay organized, to keep your plans in your mind and before you as you meet the brand new year that is before you. One will be glad to know that doing this is easy when he or she is able to find a good source of planners. If one is able to find a good source of planers, then, he or she can be sure that when this is accomplished, a lot of wonderful benefits and advantages can be gained altogether. Finding a good source of planners is definitely something that will be beneficial to you in a lot of ways, one of which is the fact that when you do so, you can be sure that you can find many beautiful items for sale there. You can be sure that when you are able to find a good source like this, you can find beautiful calendars, as well as oversize planners, planners that will make it so much easier for you to organize yourself. It will be possible, then, to find something that is very inspiring, and one can be sure that when he or she buys at this source, making plans for the New Year will become something that is very enjoyable altogether. Visit oversizeplanner.com for more info. One who finds a good source of planners will also be glad to know that when he or she does so, it will be possible to give the perfect gifts to friends and to loved-ones. One who loves the holiday season might be very excited, as it is certainly just around the corner, and he or she might already be looking for the best presents that will bring joy to his or her friends and family members. They will be glad to know that when they are able to find the best source of planners, they can be sure that they will have a very good gift to give to people they care about. One who finds a good source of oversize planners will also be glad to know that when he or she does so, it will be possible to use the planners and calendars bought there the whole year. They can be sure that these items will be made out of very good quality materials, which will assure them that they will remain beautiful and attractive throughout time. One who finds the best source of planners, then, can be sure that when he or she does so, a lot of wonderful benefits can be gained. For more tips, check out http://www.youtube.com/watch?v=vWUh77KOi-0.
On this page you can set alarm for 2:02 AM at night. This is free and simple online alarm for specific time - alarm for two hours and two minutes AM. Just click on the button "Start alarm" and this online alarm clock will start. If you like to sleep and think on wake me up at 2:02 AM, this online alarm clock page is right for you. Set alarm at 2:02 AM and an alarm wakes you in time. Take look on instructions on "Online alarm clock" page for more information.
Sant Satguru Sadhu Ram in a talk/satsang given this evening, New Delhi, India time, quoted his Guru, Sant Satguru Ajaib Singh ji: This (spiritual) path is sharper than the edge of sword. Then Sadhu Ram ji said: It’s easier to climb on (get on) the cross than to carry on with love (It’s more difficult to maintain living this life with love.) (Yet) Love is very close by, within. Satguru’s Court is more beautiful than everything else. There is no other door like this one. Satguru’s Court is more beautiful than everything else. He puts the forgetful ones on the straight path. He makes the lost souls meet the Creator. Come, those who want to make their life successful. He has made the likes of the dirt of the alleys successful. I, the lowly one, am embraced by the Higher Ones. One will not find such a Master. Ajaib Ji has cast His gracious sight. He has filled the empty jholi of Sadhu Ram. I will never lose the gifts You have given me. So please, why not throw something into my begging bowl? Why is Rumi begging from His پیر? Because this physical reality is too harsh, even for Saints like Rumi as they compose poems. We don’t know what’s behind all this “Maya” or illusion unless the Guru پیر and the “Word” or “Naam” put us in the state of consciousness where we simply absorb true knowledge and feel the love that has created and sustains all. We’re dyed in the color of this world but the ones who are initiated by a perfect master, Guru مرشد کامل، پیر learn how dyed their mind in the color of Naam. It comes in Gurubani that it is only by getting dyed in the color of Naam we can reach salvation. So we pray that we may be intoxicated with Naam so we can be one with uOu. Poem above is by Rumi and آرش تبرستانی has given his interpretation of the poem in Persian. Basically they are saying that most people don’t see this world as reality and don’t look behind the invisible curtain. And the ones who do look and see are either considered mad, crazy or mentally disoriented. But Rumi is saying wait a second اوست دیوانه که دیوانه نشد ‘the one who hasn’t gone mad is the mad one’. Your body is the temple of God, O man, Satguru is sitting inside. You will not find anything outside, everything is inside you, O man. You clean and sweep the temples made of stones and bricks, you ring bells and conch every day, you burn incense to add fragrance. What benefit does outer bathing do, inside you the ocean is flowing, O man. You read Vedas, Puranas and Granths, but you have never practiced. His will is understood by those who have won over the mind and the world. Even after winning the entire world, Sikandar (Alexander the Conqueror) left empty handed, O man. I meditated on Satguru Ajaib’s Naam and I saw God. Sadhu Ram woke up in the ambrosial hour and took a dip within. The body and the mind became pure, I became intoxicated and carefree, O man. Mind, the very essence of Kal, has wrecked the garden through force, violence and hierarchy in religion. When will this mind surrender and when will this ego leave me be? Satguru ji, ای مرشد کامل, please take these coverings off my soul by showering your grace. You’re the light of all lights Master, ای پیر من, my salvation in your hands. Let’s cover up my faults behind this wine stained initiation rope for, uOu, my Guru پیر، is coming. And I might get a chance to be forgiven, I’m sure I will, by the shower of uOs grace I’ll be cleansed once again even for just a moment. If you know some Persian Google the poem in Persian and enjoy reading the whole poem. I don’t care if you call me an infidel. I’ll be an infidel of Love if I don’t worship Shamms. He’s openly referring to his deep devotion to his پیر Master. But حافظ Hafez is more loved in Iran, his book of poetry in almost every house, because the codes he used such “pray” in the verse above can be interpreted in many ways; give me a good job, a good spouse, etc, to give me a taste of your Divine Love for that is all I need. حافظ Hafez means the one who has memorised all of Quran/Koran. حافظ comes from حفظ memory, something we all have as well as the potential to memorize a whole book line by line. So when in a last verse we hear the word حافظ Hafez, especially in Persian, we don’t just think about the poet, the mystic, the Master who wrote the poem, we hear that potential within us to be حافظ Hafez. The last line of the stanza where حافظ Hafez often uses his name as if reminding himself is in fact a message to us, at the level of our individual capacity to be with the Divine. Hey gardener what’s going on? Why are you giving me so much trouble? If I’ve taken some of your grapes you’re taking away my stomach. The Ocean of Love or The Anurag Sagar of Kabir is epic poem which “centers around the impact of Time on Eternity and Eternity’s response. It is Eternity which is the anurag sagar, or “ocean of love,” and it’s Time’s perversion of that part of Eternity which it touches which produces the bhav sagar, “ocean of the world” – the only reality most of us know, the mock world we are trapped in. The creator of the bhava sagar, “ the butcher Kal” (Kal means, literally, Time) is mad: one of the sons of Eternity (San Purush, Ture or Original Person), Kal or Time was unable to handle the separation from his father that the creation process demanded, and went mad. Ignoring the wishes of Eternity, he misused the tools of creation entrusted to him and, through his impatience and megalomania, created a sewer where a garden was intended. Convinced that he is God, demanding to be worshiped as God, and setting up a Law so stringent that no one can keep it,he presides to his day over a closed-circuit universe that would be utterly without hope if it were not for the fact that, as the poet Blake puts it, “Eternity is ever in love with the product of Time.” Because Eternity does love those of us caught in the trap of Time, It has set up a series of invasions in which the true Reality enters into the mock universe and illumines it, awakening those who are ready to gasp the truth and showing the the way out. How much my body has suffered, only True Satguru knows. If you meet a Perfect Master only then the soul reaches the true destination. May my body and mind become a mirror so I could have the Darshan of my Master. Not even after dying, could I forget the favors of my Master. I could never feel satisfied looking at Him, His Darshan to me is like millions of pilgrimages. I bow down to pay respect to my Satguru. For Whom this life is suffering, only He knows what is in my heart. No one has the medicine for this ailment; my affliction is for my Master. The sleep does not come into my eyes, Your remembrance torments me. Even today these two eyes are only waiting for the Master. In the end, Ajaib will save Sadhu Ram and take him across. The court of the Master never disappears from my eyes. Repeat the Unrepeated and with the grace of the Perfect Master, test it. Keeping the wing of mind at rest, see the Shabda; and climbing the mind, finish you Karma. Merging into the Essential Shabda, go to the world of immortality. To die while still alive, to reach the state of Samati, has been the goal and the message of the Masters. Rumi is talking about the kind of death which erases his sense of ego and the desire to die in that sense, he says, has kept him alive and now old. Then he uses the metaphor of a wheat grain which has the potential to be sowed and turned into a plant and more wheat produced from it which shows the ego of the seed, no matter how small to us human beings, nevertheless an identity and ego of a seed. But once it enters the mills and gets crushed into flour it loses its identity as a seed. It has the potential to become part of a loaf of bread but it’s individual seed ego is no longer recognizable. It can become one with the bread. And once a Master enters the state of Samati and loses the ego, uOu becomes one with the Beloved, the Creator, the all Compassionate and Merciful. Finally the Master comes back from the state of Samati and fully occupies the body with all it’s worldly senses (touch, smell, taste, sight, etc.) and gets the minimal ego needed to identity with the body. The Master may not enjoy this “normal state” as much as the state of samati but the disciples are elated to be in presence of the One who has been drenched with love and compassion in the field beyond the ideas of right-doing and wrong-doing and has come to shower them with that grace. The Persian word شیر means milk as well as lion. One who reads this verse in Persian could on a subliminal level think of the hair as the metaphor for part the person, the strength of a person. Hence Rumi might also be saying; If I become as daring and strong as a lion then I could enter the state of Samati. The more practical part of our brain will say that Rumi is talking about getting old so of course he’s talking about the color of milk and hair turning white as we age. However just the fact that this idea crossed my mind that he might also be referring to lion, shows me the power of Rumi’s poetry if read in a delightful Persian language and especially if we get lucky to have a day or even an especial hour to contemplate on one or two of His verses. From a talk, Satsang, given by Sant Sadhu Ram on January 01, 2004 in New Delhi, India. Saints and Masters have in one way or another tried to say the same thing but in different languages and ways according to their circumstances and the way they were assigned to give that message. From the word of mouth and the translations this is what Jesus said, “I’m the gate; whoever enters through me will be saved” – while He was alive, in the body. Jesus wasn’t afraid to die and neither was Hafez. The Middle Eastern folks has shown that they’re into martyrdom and it’s a blessing if “God” is willing. Hafez was to write poetry in a delicate way instead of having his head chopped off by the clergy – and to write in such a beautiful way in such a beautiful language to reveal the secret behind the curtain in a way that the clergy couldn’t accuse Him of blasphemy even though some tried. And Jesse had another mission before He was put on the cross and returned to His Father’s Home at such young age.
[STATEMENT] lemma product_language[simp]: "c.language (product A B) = a.language A \<inter> b.language B" [PROOF STATE] proof (prove) goal (1 subgoal): 1. c.language (product A B) = a.language A \<inter> b.language B [PROOF STEP] by force
function img = read_pfm(filename, bPhotoshopCompatibility) % % % img = read_pfm(filename, bPhotoshopCompatibility) % % Input: % -filename: the name of the file to open % -bPhotoshopCompatibility: a flag for enabling compability with % Adobe Photoshop. If it is set to 1 the compability is on. % % Output: % -img: the opened image % % Copyright (C) 2011-14 Francesco Banterle % % This program is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program. If not, see <http://www.gnu.org/licenses/>. % if(~exist('bPhotoshopCompatibility', 'var')) bPhotoshopCompatibility = 0; end %by default PFM files are open in little-endian format fid = fopen(filename, 'r', 'l'); %reading the header str = fscanf(fid, '%c', 3); channels = 3; iValid = 0; if(str(1) == 'P') iValid = 1; end if(str(2) == 'f') channels = 1; iValid = iValid + 1; end if(str(2) == 'F') iValid = iValid + 1; end if(iValid ~= 2) fclose(fid); error('This is not a valid PFM file.'); end %image size m = fscanf(fid,'%d',1); fscanf(fid,'%c',1); n = fscanf(fid,'%d',1); fscanf(fid,'%c',1); endian_selector = fscanf(fid,'%f',1); fscanf(fid,'%c',1); %we have a big-endian encoded file if(endian_selector > 0.0) fclose(fid); %reopen the file in big-endian mode fid = fopen(filename, 'r', 'b'); fscanf(fid,'%c',3); m = fscanf(fid,'%d',1); fscanf(fid,'%c',1); n = fscanf(fid,'%d',1); fscanf(fid,'%c',1); endian_selector = fscanf(fid,'%f',1); fscanf(fid,'%c',1); end img = zeros([m, n, channels]); total = n * m * channels; tmpImg = fread(fid, total, 'float'); for i=1:channels tmpC = i:channels:total; img(:,:,i) = reshape(tmpImg(tmpC), m, n); end img = imrotate(img, 90, 'nearest'); if(bPhotoshopCompatibility) for i=1:channels img(:,:,i) = flipud(img(:,:,i)); end end fclose(fid); end
(* Title: HOL/Auth/n_germanSymIndex_lemma_on_inv__49.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_germanSymIndex Protocol Case Study*} theory n_germanSymIndex_lemma_on_inv__49 imports n_germanSymIndex_base begin section{*All lemmas on causal relation between inv__49 and some rule r*} lemma n_RecvReqSVsinv__49: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 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_RecvReqS N i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Ident ''CurCmd'')) (Const Empty)) (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv2) ''Cmd'')) (Const Inv))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv0)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Ident ''CurCmd'')) (Const Empty)) (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv2) ''Cmd'')) (Const Inv))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Ident ''CurCmd'')) (Const Empty)) (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv2) ''Cmd'')) (Const Inv))))" 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_RecvReqEVsinv__49: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 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_RecvReqE N i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>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__Inv0)" 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__Inv0\<and>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_SendInv__part__0Vsinv__49: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 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_SendInv__part__0 i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>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__Inv0)" 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__Inv0\<and>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_SendInv__part__1Vsinv__49: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 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_SendInv__part__1 i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Ident ''CurCmd'')) (Const ReqS)) (eqn (IVar (Para (Ident ''InvSet'') p__Inv2)) (Const true))) (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv0) ''Cmd'')) (Const Inv))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv0)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Ident ''CurCmd'')) (Const ReqS)) (eqn (IVar (Para (Ident ''InvSet'') p__Inv0)) (Const true))) (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv2) ''Cmd'')) (Const Inv))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv0\<and>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_SendInvAckVsinv__49: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 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_SendInvAck i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>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__Inv0)" 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__Inv0\<and>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_SendGntSVsinv__49: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 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_SendGntS i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>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__Inv0)" 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__Inv0\<and>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_SendGntEVsinv__49: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 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_SendGntE N i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>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__Inv0)" 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__Inv0\<and>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_RecvGntSVsinv__49: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 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_RecvGntS i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>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__Inv0)" 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__Inv0\<and>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_RecvGntEVsinv__49: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 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_RecvGntE i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>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__Inv0)" 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__Inv0\<and>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_SendReqE__part__1Vsinv__49: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_StoreVsinv__49: assumes a1: "\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_RecvInvAckVsinv__49: assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvInvAck i" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendReqE__part__0Vsinv__49: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendReqSVsinv__49: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqS i" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__49 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done end
"abc" <- 1 1 -> "abc" "odd name"("strange tag" = 5, y) "zz":::qq() "c"::a()
# The MIT License (MIT) # # Copyright (c) <2016> <Haruka Ozaki> # # 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. # version 1.7 options(stringsAsFactors = F) args=(commandArgs(TRUE)) if(length(args)==0){ print("No arguments supplied.") }else{ for(i in 1:length(args)){ eval(parse(text=args[[i]])) } } print("Visualizing MOCCS result...") sprintf("file: %s", file) sprintf("file2: %s", file2) sprintf("label: %s", label) sprintf("len: %s", len) sprintf("k: %s", k) # Universal colors cols <- c("#000000", "#ff2800","#faf500","#35a16b","#0041ff","#66ccff","#ff99a0","#ff9900","#9a0079","#663300") crf <- read.table(gzfile(file), header=T, stringsAsFactors=F, check.names=F, row.names=1) crf <- as.data.frame(t(apply(crf, 1, function(x){x/x[length(x)]}))) d.auc <- read.table(file2, header=T, stringsAsFactors=F, row.names=1) auc <- d.auc$auc names(auc) <- rownames(d.auc) auc <- auc[ order(auc, decreasing=T) ] xlab <- "Distance from peak center [bp]" ylab <- "Cumulative relative freqency" end <- as.numeric(colnames(crf)[ncol(crf)]) print(sprintf("x-axis: [0, %d]", end)) # make roc-like curve plot of auc for top 10 k-mers # auc <- auc[1:10] crf2 <- crf[names(auc),] pdfname <- paste0(label, "_", k, "-mer_auc_plot", ".pdf") sprintf("outfile: %s", pdfname) pdf(pdfname) matplot(t(crf2), type="n", col="gray", lwd=0.5, main=label, lty=1, sub=paste0("Top ", k, "-mers based on AUC"), xlab=xlab, ylab=ylab, axes=F) box() # axis(1, 1:ncol(crf2), 0:end) axis(1, seq(1, ncol(crf2), by=50), seq(0, end, by = 50)) axis(2) # i.max <- ifelse(length(auc)<10, length(auc), 10) i.max = min(length(auc), 10) for(i in i.max:1){ matpoints(t(crf2[grep(names(auc)[i],rownames(crf2)),]), type="l", col=cols[i], lwd=1, lty=1) } legend("bottomright", legend=names(auc[1:i.max]), col=cols[1:i.max], lwd=1) dev.off() ################################# # Top 10 k-mers based on MOCCS2score ################################################################## # Top 10 k-mers based on MOCCS2score MOCCS2score <- d.auc$MOCCS2score names(MOCCS2score) <- rownames(d.auc) MOCCS2score <- MOCCS2score[ order(MOCCS2score, decreasing=T) ] xlab <- "Distance from peak center [bp]" ylab <- "Cumulative relative freqency" end <- as.numeric(colnames(crf)[ncol(crf)]) print(sprintf("x-axis: [0, %d]", end)) # make roc-like curve plot of MOCCS2score for top 10 k-mers # MOCCS2score <- MOCCS2score[1:10] crf2 <- crf[names(MOCCS2score),] pdfname <- paste0(label, "_", k, "-mer_MOCCS2score_plot", ".pdf") sprintf("outfile: %s", pdfname) pdf(pdfname) matplot(t(crf2), type="n", col="gray", lwd=0.5, main=label, lty=1, sub=paste0("Top ", k, "-mers based on MOCCS2score"), xlab=xlab, ylab=ylab, axes=F) box() # axis(1, 1:ncol(crf2), 0:end) axis(1, seq(1, ncol(crf2), by=50), seq(0, end, by = 50)) axis(2) # i.max <- ifelse(length(MOCCS2score)<10, length(MOCCS2score), 10) i.max = min(length(MOCCS2score), 10) for(i in i.max:1){ matpoints(t(crf2[grep(names(MOCCS2score)[i],rownames(crf2)),]), type="l", col=cols[i], lwd=1, lty=1) } legend("bottomright", legend=names(MOCCS2score[1:i.max]), col=cols[1:i.max], lwd=1) dev.off() ################################# print("Visualized MOCCS result") sessionInfo()
{-# OPTIONS --omega-in-omega --no-termination-check --overlapping-instances #-} module Light.Package where open import Light.Level using (Setω) record Meta : Setω where field Dependencies : Setω field Library : Dependencies → Setω record Package (meta : Meta) : Setω where instance constructor package open Meta meta field ⦃ dependencies ⦄ : Dependencies field ⦃ library ⦄ : Library dependencies open Package ⦃ ... ⦄ public
[STATEMENT] lemma lfinite_prepend[simp]: "lfinite (prepend xs ys) \<longleftrightarrow> lfinite ys" [PROOF STATE] proof (prove) goal (1 subgoal): 1. lfinite (prepend xs ys) = lfinite ys [PROOF STEP] by (induct xs) auto
subroutine scanin !*********************************************************************** ! Copyright, 1993, 2004, The Regents of the University of California. ! This program was prepared by the Regents of the University of ! California at Los Alamos National Laboratory (the University) under ! contract No. W-7405-ENG-36 with the U.S. Department of Energy (DOE). ! All rights in the program are reserved by the DOE and the University. ! Permission is granted to the public to copy and use this software ! without charge, provided that this Notice and any statement of ! authorship are reproduced on all copies. Neither the U.S. Government ! nor the University makes any warranty, express or implied, or ! assumes any liability or responsibility for the use of this software. C*********************************************************************** CD1 CD1 PURPOSE CD1 CD1 Scan input file for parameters needed prior to data input. CD1 C*********************************************************************** CD2 CD2 REVISION HISTORY CD2 CD2 Revision ECD CD2 Date Programmer Number Comments CD2 CD2 13-JAN-94 Z. Dash 22 Initial implementation. CD2 CD2 $Log: /pvcs.config/fehm90/src/scanin.f_a $ CD2 !D2 !D2 Rev 2.5 06 Jan 2004 10:43:50 pvcs !D2 FEHM Version 2.21, STN 10086-2.21-00, Qualified October 2003 !D2 !D2 Rev 2.4 29 Jan 2003 09:15:06 pvcs !D2 FEHM Version 2.20, STN 10086-2.20-00 !D2 !D2 Rev 2.3 14 Nov 2001 13:12:22 pvcs !D2 FEHM Version 2.12, STN 10086-2.12-00 !D2 !D2 Rev 2.2 06 Jun 2001 13:26:26 pvcs !D2 FEHM Version 2.11, STN 10086-2.11-00 !D2 !D2 Rev 2.1 30 Nov 2000 12:07:20 pvcs !D2 FEHM Version 2.10, STN 10086-2.10-00 !D2 !D2 Rev 2.0 Fri May 07 14:45:12 1999 pvcs !D2 FEHM Version 2.0, SC-194 (Fortran 90) CD2 CD2 Rev 1.12 Wed Jun 12 15:21:20 1996 zvd CD2 Modified optional input file routines and reduced number of calls CD2 CD2 Rev 1.11 Mon Jun 03 11:18:34 1996 hend CD2 Added macro name & comment capabi. to new input CD2 CD2 Rev 1.10 Fri May 31 10:59:28 1996 hend CD2 Added optional input from specified file CD2 CD2 Rev 1.9 Wed Feb 07 12:13:28 1996 gaz CD2 checked for bous macro CD2 CD2 Rev 1.8 Thu Feb 01 16:05:08 1996 hend CD2 Updated Requirements Traceability CD2 CD2 Rev 1.7 Tue Jan 09 14:08:20 1996 llt CD2 gaz changes CD2 CD2 Rev 1.6 12/13/95 10:30:24 robinson CD2 Incorporated new zeolite hydration module CD2 CD2 Rev 1.5 12/13/95 08:47:00 gaz CD2 changes to accodate variable rlp number of data CD2 CD2 Rev 1.4 04/25/95 10:11:20 llt CD2 retrieved lost log history information CD2 CD2 Rev 1.3 01/31/95 16:24:42 llt CD2 addition to the modification for the new particle tracking module CD2 CD2 Rev 1.2 01/28/95 14:03:58 llt CD2 modified for new particle tracking module CD2 CD2 Rev 1.1 03/18/94 16:03:54 gaz CD2 Added solve_new and cleaned up memory management. CD2 CD2 Rev 1.0 01/20/94 10:27:26 pvcs CD2 original version in process of being certified CD2 C*********************************************************************** CD3 CD3 INTERFACES CD3 CD3 Formal Calling Parameters CD3 CD3 None CD3 CD3 Interface Tables CD3 CD3 None CD3 CD3 Files CD3 CD3 Name Use Description CD3 CD3 inpt I Main input data file. CD3 C*********************************************************************** CD4 CD4 GLOBAL OBJECTS CD4 CD4 Global Constants CD4 CD4 None CD4 CD4 Global Types CD4 CD4 None CD4 CD4 Global Variables c add grouping stuff 8/1/94 CD4 max_groups, ngroups, group, pos, n_couple_species, mdof_sol CD4 num_particles CD4 CD4 COMMON CD4 Identifier Type Block Description CD4 CD4 icnl INT faai Problem dimension CD4 idpdp INT faai Parameter which indicates if the double CD4 porosity / double permeability CD4 solution is enabled CD4 idualp INT faai Parameter which indicates if the dual CD4 porosity solution is enabled CD4 inpt INT faai Unit number for input file CD4 neq INT faai Number of nodes, not including dual CD4 nspeci INT fdd1i Number of species for tracer solution CD4 wdd1 CHAR faac Alternate character input string c add grouping stuff 8/1/94 CD4 ngroups int comrxni.h The number of groups of CD4 coupled species CD4 group int comrxni.h Array indicating the coupling CD4 between species CD4 pos int comrxni.h Array containing the species CD4 numbers of the coupled species CD4 in each group CD4 n_couple_species int comrxni.h Array containg the number of CD4 coupled species contained in CD4 each grouping CD4 mdof_sol int comrxni.h The maximum number of degrees CD4 of freedom necessary to solve CD4 the tracer solution CD4 CD4 Global Subprograms CD4 CD4 None CD4 C*********************************************************************** CD5 CD5 LOCAL IDENTIFIERS CD5 CD5 Local Constants CD5 CD5 None CD5 CD5 Local Types CD5 CD5 None CD5 CD5 Local variables CD5 CD5 Identifier Type Description CD5 CD5 adumm REAL*8 Dummy real variable for input CD5 cdumm CHAR Dummy character variable for input CD5 idumm INT Dummy integer variable for input CD5 ja INT Loop index input CD5 jb INT Loop index input CD5 jc INT Loop index input CD5 macro CHAR Current macro being read c changed to incorporate coupling 8/4/94 CD5 igrp INT Do loop index indicating the current CD5 group number CD5 pos_index INT Index denoting the position of a CD5 coupled species in a grouping CD5 trac_flag INT Flag to search for group macro CD5 only if the rxn macro has been read CD5 ispecies INT Species number for variable we are CD5 computing rate contribution for CD5 CD5 CD5 Local Subprograms CD5 CD5 None CD5 C*********************************************************************** CD6 CD6 FUNCTIONAL DESCRIPTION CD6 CD6 CD6 C*********************************************************************** CD7 CD7 ASSUMPTIONS AND LIMITATIONS CD7 CD7 None CD7 C*********************************************************************** CD8 CD8 SPECIAL COMMENTS CD8 CD8 Requirements from SDN: 10086-RD-2.20-00 CD8 SOFTWARE REQUIREMENTS DOCUMENT (RD) for the CD8 FEHM Application Version 2.20 CD8 C*********************************************************************** CD9 CD9 REQUIREMENTS TRACEABILITY CD9 CD9 2.6 Provide Input/Output Data Files CD9 3.0 INPUT AND OUTPUT REQUIREMENTS CD9 2.8 Provide Multiple Realization Option CD9 C*********************************************************************** CDA CDA REFERENCES CDA CDA None CDA C*********************************************************************** CPS CPS PSEUDOCODE CPS CPS BEGIN scanin CPS CPS rewind input tape CPS CPS REPEAT CPS read input line CPS EXIT IF macro read is stop CPS ELSE IF macro read is alti CPS read number of nodes CPS ELSE IF macro read is coor CPS read number of nodes CPS ELSE IF macro read is ctrl CPS read a line CPS REPEAT CPS read a line CPS UNTIL null line is found CPS read two lines CPS read geometry parameter CPS ELSE IF macro read is dual CPS set idualp to 1 CPS ELSE IF macro read is dpdp CPS set idpdp to 1 CPS ELSE IF macro read is trac CPS read 3 lines CPS read number of tracer species CPS ELSE IF macro read is rxn CPS read keyword CPS IF keyword is gr CPS read in the number of groupings CPS read in grouping indicator which indicates the coupling CPS ... between species CPS FOR each group CPS FOR each species CPS IF the ith species is to be included in the ... CPS ... current group THEN CPS set up position array to indicate the species ... CPS ... number to be coupled CPS deterimine the number of coupled species in a group CPS determine the maximum # of degrees of freedom ... CPS ... needed to solve the tracer equations CPS ENDIF CPS ENDFOR each species CPS ENDFOR each group c end change CPS CPS ELSE IF macro read is ptrk CPS set nspeci to 1 CPS Read in the number of particles CPS END IF CPS UNTIL end of input file is found CPS CPS rewind input file CPS IF grup was not read then set variables to solve for each CPS species separately CPS set the total number of coupled groups to the total CPS number of species in the system CPS FOR each group CPS construct default grouping information CPS ENDFOR CPS ENDIF CPS CPS END scanin CPS C*********************************************************************** use comai use combi use comchem use comco2 use comcouple use comdi use comdti use compart use comriv use comrlp, only: rlpnew, ntable, ntblines,nphases,rlp_phase, + rlp_group use comrxni use comsi use comsk use comsplitts use comsptr use comwellphys use comwt use comxi, only : nmfil, cform use comzeoli use davidi use trxnvars implicit none logical blank integer ith, iscan, isorp logical null1, opened, done, ok, null_new integer idumm, ja, jb, jc, numtime character* 4 cdumm, macro, ctmp real*8 adumm, rdum1 integer igrp,pos_index,trac_flag,ispeci integer ic2 integer, allocatable :: group_mat(:,:) integer matnum,itemp,jj,ii,idum character*80 dumstring character*100 dummy_line, filename integer msg(20) integer nwds real*8 xmsg(20) integer imsg(20) character*32 cmsg(20) integer kz,iz2,iz2p,i1,i2,ipivt,sehindexl,sehindexv,neqp1 integer ireaddum, inptread, open_file integer locunitnum, kk, j integer ngdpm_models, nsize_layer integer, allocatable :: itemporary(:) integer idum1, idum2, ilines, i integer icount, tprp_num integer jjj, isimnum, realization_num,maxrp logical nulldum, found_end c logical gdkm_new real*8 rflag maxrp = 30 if(.not.allocated (rlp_phase)) then allocate (rlp_phase(20, maxrp),rlp_group(20)) endif c**** read startup parameters **** rewind inpt iccen = 0 ice = 0 ico2 = 0 icarb = 0 c gaz 112817 iwater_table = 0 icgts = 0 idoff = 1 ihead = 0 irlp_fac = 0 iflxc = 0 iflux_ts = 0 istrs = 0 isalt = 0 iread_rcoll = 0 total_colloids = 0 total_daughters = 0 total_irrev = 0 total_rev = 0 maxprobdivs = 0 ianpe = 0 ivboun = 0 nflxt = 0 nspeci = 0 numd = 0 numsorp = 0 numtime = 0 ncplx = 0 numrxn = 0 numvcon = 0 nriver = 0 rlp_flag = 0 rxn_flag = 0 ipermstr1 = 0 ipermstr2 = 0 ipermstr3 = 0 ipermstr4 = 0 ipermstr5 = 0 ipermstr6 = 0 ipermstr8 = 0 ipermstr11 = 0 ipermstr31 = 0 iactive = 0 c zvd 17-Aug-09 move boun flag initializations here iqa=0 ixa = 0 iha = 0 ipha = 0 itha = 0 iqw=0 iqf=0 iqenth=0 isatb=0 ienth=0 itempb=0 ipresa=0 ipresw=0 imped=0 its=0 ifd=0 isf=0 ixperm = 0 iyperm = 0 izperm = 0 i_init = 0 c new initial value stuff 12/3/98 GAZ itempb_ini=0 ipresa_ini=0 ipresw_ini=0 isatb_ini=0 icm=0 iwght = 1 isty = 0 icoef_neg = 0 nflxz = 0 sv_hex_tet = .false. ipr_tets = 0 c gaz 100118 set nrlp here to enable mulpiple rlp macros nrlp = 0 c zvd 17-Aug-09 move boun flag initializations here if(allocated(izone_free_nodes)) izone_free_nodes = 0 if(allocated(move_type)) move_type=0 compute_flow = .true. reverse_flow = .false. pod_flag = .false. omr_flag = .false. save_omr = .false. sptr_flag = .false. fperm_flag = .false. c gaz 070619 variables used in newer itfc nitf_use = .false. ncol_use = .false. 10 continue filename = '' read (inpt, '(a80)', END = 50) dumstring if (dumstring(1:1) .eq. '#') go to 10 read (dumstring, '(a4)') macro call parse_string2(dumstring,imsg,msg,xmsg,cmsg,nwds) if (nwds .gt. 1) then c Check for "OFF" keyword for skipping macro found_end = .false. do i = 2, nwds if (msg(i) .eq. 3) then if (cmsg(i) .eq. 'off' .or. cmsg(i) .eq. 'OFF') then call skip_macro (macro, inpt, found_end) exit end if end if end do if (found_end) goto 10 end if if (macro.eq.'stop') then go to 40 else if(macro.eq.'file') then ! Read filename to ensure we skip this line and don't interpret start ! of filename as a macro read (inpt, '(a100)') filename else if (macro .eq. 'cden') then if (nwds .gt. 1) then if (cmsg(2) .eq. 'multi' .or. cmsg(2) .eq. 'table') then cden_flag = 1 else if (cmsg(2) .eq. 'co2') then cden_flag = 2 if (nwds .gt. 2 .and. msg(3) .eq. 3) then cden_spnam = cmsg(3) else cden_spnam = 'Na' end if end if end if else if (macro .eq. 'cont') then call start_macro(inpt, locunitnum, macro) ! Read over keywords if avs, tecplot or surfer read (locunitnum, '(a3)', END = 50) macro if(macro(1:3) .eq. 'avs' .or. macro(1:3) .eq. 'tec' .or. & macro(1:3) .eq. 'sur' .or. macro .eq. 'csv') then ok = .false. do read (locunitnum, *, END = 60) dumstring if (dumstring(1:1) .eq. 'e' .or. dumstring(1:1) .eq. & 'E') then ok = .true. exit ! Check for other macros that may use 'end' keyword else if (dumstring(1:4) .eq. 'boun' .or. dumstring(1:4) & .eq. 'hist' .or. dumstring(1:4) .eq. 'rest' & .or. dumstring(1:4) .eq. 'stea' .or. & dumstring(1:4) .eq. 'rlpm' .or. dumstring(1:4) & .eq. 'trxn') then exit end if end do 60 if (.not. ok) then write (ierr, 55) 'ENDAVS' write (ierr, 56) 'cont' if (iptty .ne. 0) then write (iptty, 55) 'ENDAVS' write (iptty, 56) 'cont' end if stop end if end if call done_macro(locunitnum) else if(macro .eq. 'hist') then call start_macro(inpt, locunitnum, macro) ! Read through keywords so no conflict with actual macro names ok = .false. do read (locunitnum, '(a3)', END = 70) dumstring if (dumstring(1:3) .eq. 'end' .or. dumstring(1:3) .eq. & 'END') then ok = .true. exit ! Check for other macros that may use 'end' keyword else if (dumstring(1:4) .eq. 'boun' .or. dumstring(1:4) & .eq. 'cont' .or. dumstring(1:4) .eq. 'rest' .or. & dumstring(1:4) .eq. 'stea' .or. dumstring(1:4) & .eq. 'rlpm' .or. dumstring(1:4) .eq. 'trxn') then exit end if end do 70 if (.not. ok) then write (ierr, 55) 'END' write (ierr, 56) 'hist' if (iptty .ne. 0) then write (iptty, 55) 'END' write (iptty, 56) 'hist' end if stop end if call done_macro(locunitnum) else if(macro.eq.'zone') then call start_macro(inpt, locunitnum, macro) call done_macro(locunitnum) else if(macro.eq.'zonn') then call start_macro(inpt, locunitnum, macro) call done_macro(locunitnum) else if(macro.eq.'rflo') then compute_flow = .false. backspace inpt read (inpt, *) dumstring if (dumstring(1:5) .eq. 'rflor') reverse_flow = .true. else if (macro.eq.'hcon') then idoff = -1 else if (macro .eq. 'flxz') then call start_macro(inpt, locunitnum, macro) read (locunitnum, *) nflxz c Read zones to name flxz output files in inhist if necessary if(.not.allocated(iflxz)) allocate(iflxz(max(1,nflxz))) read (locunitnum, *)(iflxz(i),i=1,nflxz) call done_macro(locunitnum) else if (macro .eq. 'iter') then call start_macro(inpt, locunitnum, macro) read (locunitnum,*)g1, g2, g3, tmch, overf read (locunitnum, *) irdof, islord, iback, icoupl, rnmax if (ihead .eq. 1 .and. irdof .ne. 13) then irdof = 13 end if call done_macro(locunitnum) else if (macro.eq.'sol ') then call start_macro(inpt, locunitnum, macro) read(locunitnum,*) idoff, intg if (idoff .le. 0) idoff = -1 call done_macro(locunitnum) else if (macro .eq. 'time') then numtime = numtime + 1 if (numtime .gt. 1) then write (ierr,*) 'More than one time macro in input file' write (ierr,*) 'STOPPING' if (iptty .ne. 0) then write (iptty,*) & 'More than one time macro in input file' write (iptty,*) 'STOPPING' end if stop end if call start_macro(inpt, locunitnum, macro) read(locunitnum, *) 5 read(locunitnum, '(a)') dummy_line if (.not. null1(dummy_line)) then icgts = icgts + 1 goto 5 end if call done_macro(locunitnum) else if (macro .eq. 'phys'.or. macro .eq. 'ndph') then c find number of wellphysics or non darcy models models c eg drift flux iwellp_flag = 1 call start_macro(inpt, locunitnum, macro) nwellphy = 0 111 continue read(locunitnum,'(a80)') wdd1 if(.not. null1(wdd1)) then backspace locunitnum read(locunitnum,*) idumm backspace locunitnum nwellphy = nwellphy + 1 if(idumm.eq.1.or.idumm.eq.2) then read(locunitnum,*) idumm,(adumm,ja=1,6) elseif(idumm.eq.-1) then end if else go to 211 endif go to 111 211 continue call done_macro(locunitnum) else if (macro.eq.'rlp ') then c old model c find number of relative perm models c use nrlp (comai.h) to transfer size of rlp arrays c no longer use variable ichng so value can be saved c check for read from other file rlp_flag = 1 call start_macro(inpt, locunitnum, macro) c gaz 100118 will set nrlp = 0 at start on routine so multiple rlp macros can be used c nrlp = 0 11 continue read(locunitnum,'(a80)') wdd1 if(.not. null1(wdd1)) then backspace locunitnum read(locunitnum,*) idumm backspace locunitnum ichng=ichng+1 nrlp = nrlp + 1 if(idumm.eq.1) then read(locunitnum,*) idumm,(adumm,ja=1,6) elseif(idumm.eq.-1) then read(locunitnum,*) idumm,(adumm,ja=1,4) elseif(idumm.eq.2) then read(locunitnum,*) idumm,(adumm,ja=1,4) elseif(idumm.eq.3) then read(locunitnum,*) idumm,(adumm,ja=1,6) elseif(idumm.eq.-4) then read(locunitnum,*) idumm,(adumm,ja=1,15) elseif(idumm.eq.4) then read(locunitnum,*) idumm,(adumm,ja=1,15) elseif(idumm.eq.5) then read(locunitnum,*) idumm,(adumm,ja=1,6) elseif(idumm.eq.6) then read(locunitnum,*) idumm,(adumm,ja=1,15) elseif(idumm.eq.7) then read(locunitnum,*) idumm,(adumm,ja=1,16) elseif(idumm.eq.8) then read(locunitnum,*) idumm,(adumm,ja=1,6) elseif(idumm.eq.9) then read(locunitnum,*) idumm,(adumm,ja=1,10) elseif(idumm.eq.10) then read(locunitnum,*) idumm,(adumm,ja=1,8) elseif(idumm.eq.11) then read(locunitnum,*) idumm,(adumm,ja=1,6) elseif(idumm.eq.12) then read(locunitnum,*) idumm,(adumm,ja=1,10) elseif(idumm.eq.13) then read(locunitnum,*) idumm,(adumm,ja=1,10) c elseif(idumm.eq.14) then c read(locunitnum,*) idumm,(adumm,ja=1,6) c elseif(idumm.eq.15) then c read(locunitnum,*) idumm,(adumm,ja=1,6) c temma add 2005/11/07 elseif(idumm.eq.14) then read(locunitnum,*) idumm,(adumm,ja=1,12) elseif(idumm.eq.15) then read(locunitnum,*) idumm,(adumm,ja=1,12) elseif(idumm.eq.16) then read(locunitnum,*) idumm,(adumm,ja=1,12) elseif(idumm.eq.17) then read(locunitnum,*) idumm,(adumm,ja=1,14) nphases(nrlp)=3 rlp_phase(nrlp,1)=20 rlp_phase(nrlp,2)=21 rlp_phase(nrlp,3)=22 rlp_group(nrlp)=nrlp elseif(idumm.eq.18) then read(locunitnum,*) idumm,(adumm,ja=1,14) elseif(idumm.eq.19) then read(locunitnum,*) idumm,(adumm,ja=1,7) elseif(idumm.eq.20) then read(locunitnum,*) idumm,(adumm,ja=1,16) elseif(idumm.eq.21) then read(locunitnum,*) idumm,(adumm,ja=1,6) c temma add 2005/11/07 c elseif(idumm.eq.14) then c read(locunitnum,*) idumm,(adumm,ja=1,12) c elseif(idumm.eq.15) then c read(locunitnum,*) idumm,(adumm,ja=1,12) c elseif(idumm.eq.18) then c read(locunitnum,*) idumm,(adumm,ja=1,14) c elseif(idumm.eq.19) then c read(locunitnum,*) idumm,(adumm,ja=1,14) c elseif(idumm.eq.20) then c read(locunitnum,*) idumm,(adumm,ja=1,16) else c Undefined rlp model, stop write (ierr, 12) nrlp, idumm if (iout .ne. 0) write (iout, 12) nrlp, idumm if (iptty .ne. 0) write (iptty, 12) nrlp, idumm stop end if else go to 21 endif go to 11 12 format ('STOP: Error in rlp macro at entry', i3, & 'Invalid model specified: ', i3) 21 continue call done_macro(locunitnum) else if (macro .eq. 'rlpm') then call start_macro(inpt, locunitnum, macro) if (.not. rlpnew) nrlp = 0 rlp_flag = 1 rlpnew = .true. idum2 = 0 do read (locunitnum, '(a80)') dumstring if (null1(dumstring) .or. dumstring(1:3) .eq. 'end' .or. & dumstring(1:3) .eq. 'END') then exit else if (dumstring(1:5) .eq. 'group' .or. dumstring(1:5) & .eq. 'GROUP') then nrlp = nrlp + 1 else if (dumstring(1:3) .eq. 'tab' .or. dumstring(1:3) & .eq. 'TAB') then c Count number of tables that will be read, c and number of entries in each table ntable = ntable + 1 read (locunitnum, '(a80)') dumstring if (dumstring(1:4) .eq. 'file') then read (locunitnum, '(a80)') filename idum = open_file (filename, 'old') do read (idum, '(a80)', end = 24) dumstring if (null_new(dumstring) .or. dumstring(1:3) .eq. & 'end' .or. dumstring(1:3) .eq. 'END') exit call parse_string2(dumstring, imsg, msg, xmsg, & cmsg, nwds) c Don't count header lines (header lines should start with a character) if (msg(1) .ne. 3) ntblines = ntblines + 1 end do 24 close (idum) else backspace (locunitnum) do read (locunitnum, '(a80)') dumstring if (null_new(dumstring) .or. dumstring(1:3) .eq. & 'end' .or. dumstring(1:3) .eq. 'END') exit ntblines = ntblines + 1 end do end if end if end do call done_macro(locunitnum) else if (macro.eq.'boun') then c find number of boun models c c check for read from other file call start_macro(inpt, locunitnum, macro) 31 continue c read(locunitnum,'(a80)') wdd1 c if(.not. null1(wdd1)) then c backspace locunitnum read(locunitnum,'(a80)') wdd1(1:80) if(wdd1(1:4).eq.'mode') then maxmodel=maxmodel+1 else if(wdd1(1:2).eq.'cy') then read(locunitnum,*) idumm maxtimes=max(maxtimes,idumm) else if(wdd1(1:2).eq.'ti') then read(locunitnum,*) idumm, rdum1 if (rdum1 .ne. 0.0) then maxtimes=max(maxtimes,idumm+1) else maxtimes=max(maxtimes,idumm) end if else if(wdd1(1:3).eq.'huf') then iha=1 else if(wdd1(1:2).eq.'hu') then iha=1 else if(wdd1(1:2).eq.'ph') then ipha=1 else if(wdd1(1:2).eq.'th') then itha=1 else if(wdd1(1:3).eq.'chm') then icm=1 else if(wdd1(1:2).eq.'sa') then iqa=1 else if(wdd1(1:3).eq.'fxa') then ixa=1 else if(wdd1(1:3).eq.'swf') then iqf=1 else if(wdd1(1:2).eq.'sw') then iqw=1 else if(wdd1(1:4).eq.'sco2') then iqco2=1 else if(wdd1(1:3).eq.'sfh') then isf=1 else if(wdd1(1:2).eq.'sf') then isf=1 else if(wdd1(1:2).eq.'fd') then ifd=1 else if(wdd1(1:3).eq.'dfd') then ifd=1 else if(wdd1(1:2).eq.'se') then iqenth=1 else if(wdd1(1:3).eq.'dsa') then iqa=1 else if(wdd1(1:3).eq.'dsw') then iqw=1 else if(wdd1(1:5).eq.'dsco2') then iqco2=1 else if(wdd1(1:3).eq.'dse') then iqenth=1 else if(wdd1(1:2).eq.'si') then isatb_ini=1 else if(wdd1(1:2).eq.'s ') then isatb=1 else if(wdd1(1:3).eq.'pwi') then ipresw_ini=1 else if(wdd1(1:3).eq.'pwo') then ipresw=1 isatb=1 else if(wdd1(1:2).eq.'pw') then ipresw=1 isatb=1 else if(wdd1(1:3).eq.'pai') then ipresa_ini=1 else if(wdd1(1:3).eq.'pao') then ipresa=1 isatb=1 else if(wdd1(1:2).eq.'pa') then ipresa=1 isatb=1 else if(wdd1(1:4).eq.'tran') then isty=1 else if(wdd1(1:3).eq.'tmi') then itempb_ini=1 else if(wdd1(1:2).eq.'tc') then itempb2=1 else if(wdd1(1:2).eq.'ts') then its=1 else if(wdd1(1:2).eq.'t') then itempb=1 else if(wdd1(1:2).eq.'hd') then itempb=1 else if(wdd1(1:3).eq.'hdo') then itempb=1 else if(wdd1(1:1).eq.'h') then isatb=1 else if(wdd1(1:2).eq.'hu') then iha=1 else if(wdd1(1:2).eq.'ph') then ipha=1 else if(wdd1(1:2).eq.'th') then itha=1 else if(wdd1(1:4).eq.'wgtp') then iwght=2 else if(wdd1(1:4).eq.'wgtu') then iwght=3 else if(wdd1(1:3).eq.'wgt') then iwght=1 else if(wdd1(1:2).eq.'if') then imped=1 else if(wdd1(1:2).eq.'en' .and. wdd1(1:3).ne.'end') then ienth=1 else if(wdd1(1:2).eq.'ft') then ienth=1 else if(wdd1(1:3).eq.'fen') then ienth=1 else if(wdd1(1:2).eq.'kx') then ixperm=1 else if(wdd1(1:2).eq.'ky') then iyperm=1 else if(wdd1(1:2).eq.'kz') then izperm=1 else if(wdd1(1:20).eq.' ') then if(null1(wdd1)) go to 41 else if(wdd1(1:3).eq.'end') then go to 41 endif go to 31 c end if 41 continue call done_macro(locunitnum) else if (macro .eq. 'alti') then c**** We need to know number of nodes if alternate geometry data is used **** call start_macro(inpt, locunitnum, macro) read (locunitnum, *) cdumm, neq call done_macro(locunitnum) else if (macro(1:3) .eq. 'nap' .or. macro .eq. 'szna') then c need to know if napl-water is envoked ico2 = -3 c gaz 112817 else if (macro(1:3) .eq. 'eos') then c need to know if a table with water props is read call start_macro(inpt, locunitnum, macro) read(locunitnum,'(a80)') wdd1(1:80) call done_macro(locunitnum) if(wdd1(1:5).eq.'table') iwater_table = 1 else if (macro(1:3) .eq. 'air') then c need to know if air-water is envoked ico2 = -2 else if (macro .eq. 'ice ' .or. macro .eq. 'meth') then ice = 1 c RJP added carbon flag else if (macro .eq. 'carb') then icarb = 1 else if (macro .eq. 'boun') then c need to know if boussinesq approx is envoked iboun = 1 else if (macro .eq. 'head') then c need to know if head input instead of pressures c airwater isothermal c bous automatically enabled ihead = 1 icons = 100000 irdof = 13 else if (macro .eq. 'wtsi') then c need to know if simplified water table is invoked ifree = 1 else if (macro .eq. 'salt') then c DRH 1/2/2013: need to know if modeling salt isalt = 1 else if (macro .eq. 'coor') then c**** We need to know number of nodes if coor is in inpt **** call start_macro(inpt, locunitnum, macro) read (locunitnum, *) neq call done_macro(locunitnum) else if (macro .eq. 'elem') then c**** We need to know number of elements if elem is in inpt **** call start_macro(inpt, locunitnum, macro) read (locunitnum, *) idumm,nei call done_macro(locunitnum) else if (macro .eq. 'ctrl') then call start_macro(inpt,locunitnum, macro) read (locunitnum, *) idumm, rdum1, north maxor = north + 1 igauss = 1 20 continue read (locunitnum, '(a80)') wdd1 if (null1(wdd1)) go to 30 backspace locunitnum read (locunitnum, *) ja, jb, jc, idumm igauss = max (igauss, idumm) if(ja .eq. 0) go to 30 go to 20 30 read (locunitnum, *) adumm read (locunitnum, *) idumm c**** We need to know problem geometry **** read (locunitnum, *) icnl call done_macro(locunitnum) c**** We need to know if dual porosity or c**** dual porosity/dual permeability problem **** else if(macro .eq. 'dual') then idualp = 1 else if (macro .eq. 'fper') then c need to know if fperms are being used fperm_flag = .true. else if (macro .eq. 'frlp') then c need to know if rel perm factor is used irlp_fac = 1 else if (macro .eq. 'flxo') then iflxc = iflxc +1 call start_macro(inpt, locunitnum, macro) read(locunitnum,*) nflx ivelo = 1 nflxt = nflxt + nflx call done_macro(locunitnum) else if (macro .eq. 'dvel') then iflxc = iflxc +1 call start_macro(inpt, locunitnum, macro) read(locunitnum,*) nflx ivelo = -1 nflxt = nflxt + nflx call done_macro(locunitnum) else if (macro .eq. 'dpdp') then idpdp = 1 c Section for determining Generalized Dual Porosity Model (GDPM) c and Generalized Dual Permeability Model (GDKM) parameters else if(macro .eq. 'gdpm' .or. macro .eq. 'gdkm') then if(macro .eq. 'gdkm') then gdkm_flag = 1 backspace locunitnum read(locunitnum,'(a80)') dumstring gdkm_new = .false. c---------------------------------------- c Shaoping add, 10/23/2017 c do i = 1, 80 do i = 1, 78 c---------------------------------------- if(dumstring(i:i+2).eq.'new') then gdkm_new =.true. go to 690 endif enddo endif 690 call start_macro(inpt, locunitnum, macro) if(.not.gdkm_new) then read (locunitnum, *) gdpm_flag, ngdpmnodes else ngdpmnodes = -999 endif if(gdkm_flag.eq.1) then gdpm_flag = 1 endif maxgdpmlayers = 0 ngdpm_models = 0 c Code scans the file to determine the number of models and the c maximum number of node points in the matrix so that array c sizes can be set and arrays allocated in allocmem 1000 continue read(locunitnum,'(a80)') dumstring if (.not.null1(dumstring)) then backspace locunitnum ngdpm_models = ngdpm_models + 1 c gaz 091516 if(gdkm_flag.eq.0) then read(locunitnum,*) nsize_layer,adumm,(adumm,i=1, & nsize_layer) else read(locunitnum,*) nsize_layer,adumm nsize_layer = 1 endif maxgdpmlayers = max(nsize_layer,maxgdpmlayers) goto 1000 end if c At this point, we have the number of models in the gdpm c formulation (ngdpm_models), and the maximum number of layers c in any of the models c Allocate arrays needed for gdpm ngdpm_models = max(1,ngdpm_models) maxgdpmlayers = max(1,maxgdpmlayers) if(.not.allocated(ngdpm_layers)) then allocate(ngdpm_layers(0:ngdpm_models)) allocate(vfrac_primary(0:ngdpm_models)) allocate(gdpm_x(0:ngdpm_models,maxgdpmlayers)) allocate(gdpm_vol(0:ngdpm_models,maxgdpmlayers)) allocate(wgt_length(ngdpm_models)) ngdpm_layers = 0 vfrac_primary = 0. gdpm_x = 0. end if if(gdkm_flag.ne.0) then if(.not.allocated(gdkm_dir)) then allocate(gdkm_dir(0:ngdpm_models)) gdkm_dir = 0 endif endif call done_macro(locunitnum) else if (macro .eq. 'rare') then c**** over write area/d terms and volumes **** c**** can be used with gdkm and gdpm models ***** c**** need to count entries call start_macro(inpt, locunitnum, macro) icoef_replace = 1 call coef_replace_ctr(-1) call done_macro(locunitnum) c Section for determining Element enrichment else if(macro .eq. 'enri') then call start_macro(inpt, locunitnum, macro) read (locunitnum, *) enri_flag, nenrinodes maxenrichlayers = 0 ienrich_models = 0 c Code scans the file to determine the number of models and the c maximum number of node points in the matrix so that array c sizes can be set and arrays allocated in allocmem 1010 continue read(locunitnum,'(a80)') dumstring if (.not.null1(dumstring)) then backspace locunitnum ienrich_models = ienrich_models + 1 read(locunitnum,*) nsize_layer,adumm,(adumm,i=1, & nsize_layer) maxenrichlayers = max(nsize_layer,maxenrichlayers) goto 1010 end if c c Allocate arrays needed for enri c call done_macro(locunitnum) c RJP 12/14/06 added following for river/wellbore c Section for determining implicit river or well model (riv ) c parameters else if(macro .eq. 'rive'.or. macro .eq. 'well') then call start_macro(inpt, locunitnum, macro) 785 read (locunitnum, '(a9)') dumstring(1:9) if (dumstring(1:1) .eq. '#') go to 785 if (dumstring(1:9) .eq. 'wellmodel') then read (locunitnum, *) nriver,iriver if(iriver.eq.1) then npoint_riv = 0 do i = 1,nriver read (locunitnum, *) idum1,ii,jj idum = ii do kk = 1,jj npoint_riv = npoint_riv + 1 do j = 1,idum npoint_riv = npoint_riv + 1 enddo enddo do ii = 1,jj+1 read(locunitnum,'(a80)') wdd1 if(null1(wdd1)) goto 441 backspace locunitnum read (locunitnum, *) idum1 if (idum1 .lt. 0) goto 441 enddo 441 continue enddo else if(iriver.eq.2) then c allocate(coor_dum(nriver,3)) do i = 1,nriver read (locunitnum, *) ii, & coor_dum(ii,1),coor_dum(ii,2),coor_dum(ii,3) enddo read(locunitnum,*) n_well_seg allocate(iwell_seg(n_well_seg,2)) allocate(well_rad(n_well_seg)) allocate(well_dz(n_well_seg)) do i = 1,n_well_seg read(locunitnum,*) j,iwell_seg(j,1),iwell_seg(j,2), & well_rad(j),well_dz(j) enddo npoint_riv = 0 max_seg_div = 0 do j = 1,n_well_seg ii = iwell_seg(j,1) kk = iwell_seg(j,2) adumm = (coor_dum(ii,1)-coor_dum(kk,1))**2 + & (coor_dum(ii,2)-coor_dum(kk,2))**2 + & (coor_dum(ii,3)-coor_dum(kk,3))**2 adumm = sqrt(adumm) jj = adumm/well_dz(j) + 1 max_seg_div = max(max_seg_div,jj) npoint_riv = npoint_riv + jj nnelm_riv = nnelm_riv + (jj-1) enddo deallocate(coor_dum,iwell_seg,well_rad,well_dz) endif endif call done_macro(locunitnum) else if (macro .eq. 'init') then i_init = 1 else if (macro .eq. 'itfc') then call start_macro(inpt, locunitnum, macro) opened = .false. interface_flag = 1 nitfcpairs = 0 ncoldpairs = 0 nitfcitfc = 0 nitfcsizes = 0 c Flow interface portion of input kk = 0 6000 continue read(locunitnum,'(a80)') dummy_line if(null1(dummy_line)) then goto 6001 else nitfcpairs = nitfcpairs + 1 end if goto 6000 c Transport part of interface input 6001 continue read(locunitnum,'(a80)') dummy_line if(null1(dummy_line)) goto 6002 6003 continue read(locunitnum,'(a80)') dummy_line if(null1(dummy_line)) then goto 6002 else kk = kk+1 backspace locunitnum read(locunitnum,*) idum1, idum2, rflag if(rflag.lt.0) then nitfcitfc = nitfcitfc + 1 ilines = 0 read(locunitnum,'(a80)') dummy_line if(dummy_line(1:4).eq.'file') then read(locunitnum,'(a100)') filename inptread = open_file(filename,'old') opened = .true. else backspace locunitnum inptread = locunitnum opened = .false. end if 7001 continue read(inptread,'(a80)') dummy_line if(null1(dummy_line)) then goto 7002 else ilines = ilines + 1 goto 7001 end if end if 7002 continue if(opened) then close (inptread) opened = .false. end if nitfcsizes = max(ilines,nitfcsizes) end if goto 6003 6002 continue if(nitfcpairs.gt.0) nitf_use = .true. if(kk.gt.0) ncol_use = .true. nitfcpairs = max(1,nitfcpairs) ncoldpairs = max(1,kk) call done_macro(locunitnum) else if (macro .eq. 'ngas') then c need to know if noncondensible present ico2 = 3 else if (macro .eq. 'trac') then iccen = 1 call start_macro(inpt, locunitnum, macro) c--------- Hari added 6/10/04 read(locunitnum,'(a80)') dummy_line if(dummy_line(1:3).eq.'rip') then read(locunitnum,'(a80)') dummy_line else backspace(locunitnum) end if c---------------------- Hari read (locunitnum, '(a5)') dumstring if (dumstring(1:5) .eq. 'userc') then c check for file keyword, and read past filename if present read (locunitnum, '(a4)') dumstring if (dumstring(1:4) .eq. 'file') then read (locunitnum, *) else backspace locunitnum end if end if read (locunitnum, *) read (locunitnum, *) read (locunitnum, '(a4)')dumstring if(dumstring(1:4).eq.'tpor')then tpor_flag = .TRUE. do read(locunitnum,'(a80)') dumstring if (null1(dumstring)) exit enddo else tpor_flag = .FALSE. backspace locunitnum endif read (locunitnum, *) nspeci if(.not.allocated(species)) allocate (species(nspeci)) species=' ' trac_flag=1 read(locunitnum,'(a4)') dumstring if (dumstring(1:4).eq.'ldsp') then ! longitudinal and transverse dispersion coefficients keyword was read ! read another line read(locunitnum,'(a4)') dumstring endif if ((dumstring(1:4).ne.'dspl').and.(dumstring(1:4) & .ne.'dspb').and.(dumstring(1:4).ne.'dspb')) then ! Same dispersivity and diffusivity are not used for all liquid / vapor ! calculations backspace locunitnum else do read(locunitnum,'(a80)') dumstring if (null1(dumstring)) exit ! Count number of regions with same dispersivity and diffusivity numd = numd + 1 enddo do read(locunitnum,'(a80)') dumstring if (null1(dumstring)) exit enddo endif ncpnt = 0 nimm = 0 nvap = 0 do ii = 1,nspeci read(locunitnum,*) ispeci if(ispeci.eq.1.or.abs(ispeci).eq.2)then ncpnt = ncpnt + 1 elseif(ispeci.eq.0)then nimm = nimm + 1 else nvap = nvap + 1 endif isorp = 0 if (ispeci.eq.0) then ! Solid, do nothing continue else do read(locunitnum,'(a80)') dumstring if(null1(dumstring)) exit ! Count number of sorption models for this species isorp = isorp + 1 ! Liquid or vapor, abs(ispeci).eq.1, do nothing else if (abs(ispeci).eq.2) then ! Henry's law species read additional input line if data is on two lines call parse_string(dumstring, imsg, msg, xmsg, & cmsg, nwds) if ((numd .eq. 0 .and. nwds .lt. 16) .or. & (numd .gt. 0 .and. nwds .lt. 8)) then read(locunitnum,*) end if endif end do do read(locunitnum,'(a80)') dumstring if (null1(dumstring)) exit enddo if (abs(ispeci).eq.2) then ! Henry's law species, model parameters read (locunitnum,*) idum if (idum.eq.1 .or. idum.eq.2 .or. idum.eq.3) then continue else write(ierr,*)' ** Using Old Input ' write(ierr,*)' Enter Temperature Dependency ' write(ierr,*)' Model Number: 1 - Van Hoff ' write(ierr,*)' 2 - awwa model, see manual' write(ierr,*)' for details **' if (iptty .gt. 0) then write(iptty,*)' Using Old Input ' write(iptty,*)' Enter Temperature Dependency ' write(iptty,*)' Model Number: 1 - Van Hoff ' write(iptty,*)' 2 - awwa model, see manual' write(iptty,*)' for details **' end if stop endif endif endif do read(locunitnum,'(a80)') dumstring if (null1(dumstring)) exit enddo do read(locunitnum,'(a80)') dumstring if (null1(dumstring)) exit enddo ! maximum number of sorption models for any species numsorp = max (isorp, numsorp) enddo call done_macro(locunitnum) else if(macro(1:3) .eq. 'rxn') then call start_macro( inpt, locunitnum, macro) rxn_flag = 1 read(locunitnum,*) read(locunitnum,*)ncplx,numrxn read (locunitnum, *) read (locunitnum, *)ngroups allocate(group_mat(ncpnt,ncpnt)) group_mat = 0 if(irun.eq.1) then if (ngroups .ne. 0) then allocate(group(ngroups,ncpnt),pos(ngroups,ncpnt)) allocate(n_couple_species(ngroups),fzero(ngroups)) end if end if group = 0 pos = 0 n_couple_species = 0 do igrp = 1, ngroups read(locunitnum, *)(group(igrp,ic),ic = 1,ncpnt) enddo c add grouping stuff 8/1/94 mdof_sol = 0 do igrp = 1, ngroups pos_index = 0 do ic = 1, ncpnt if(group(igrp,ic).ne.0)then do ic2 = 1, ncpnt if(group(igrp,ic2).ne.0)then group_mat(ic,ic2)=1 else group_mat(ic,ic2)=0 endif enddo pos_index = pos_index + 1 pos(igrp,pos_index)= ic n_couple_species(igrp)=n_couple_species(igrp)+1 mdof_sol = max(n_couple_species(igrp), 2 mdof_sol) endif enddo enddo dimdrc = 0 matnum = 0 do ic = 1, ncpnt itemp = 0 do ic2 = 1,ncpnt matnum = matnum + 1 if(group_mat(ic,ic2).ne.0)then dimdrc=dimdrc+1 matpos(matnum)=dimdrc itemp = itemp + 1 drcpos(ic,itemp)=ic2 endif enddo nderivs(ic)=itemp enddo call done_macro(locunitnum) else if (macro .eq. 'trxn') then iccen = 1 call start_macro(inpt, locunitnum, 'trxn') inpttmp = inpt inpt = locunitnum call trxninit inpt = inpttmp call done_macro(locunitnum) if(rxn_flag .eq. 0) then if (iout .ne. 0) write (iout, 8000) if (iptty .ne. 0) write(iptty, 8000) endif 8000 format ('Reactions disabled for this simulation.') if(rxn_flag .eq. 1) then allocate(group_mat(ncpnt, ncpnt)) group_mat = 0 do igrp = 1, ngroups pos_index = 0 do ic = 1, ncpnt if(group(igrp,ic).ne.0)then do ic2 = 1, ncpnt if(group(igrp,ic2).ne.0)then group_mat(ic,ic2)=1 else group_mat(ic,ic2)=0 endif enddo pos_index = pos_index + 1 pos(igrp,pos_index)= ic n_couple_species(igrp)=n_couple_species(igrp)+1 mdof_sol = max(n_couple_species(igrp), 2 mdof_sol) endif enddo enddo dimdrc = 0 matnum = 0 do ic = 1, ncpnt itemp = 0 do ic2 = 1,ncpnt matnum = matnum + 1 if(group_mat(ic,ic2).ne.0)then dimdrc=dimdrc+1 matpos(matnum)=dimdrc itemp = itemp + 1 drcpos(ic,itemp)=ic2 endif enddo nderivs(ic)=itemp enddo endif else if (macro .eq. 'mptr') then ptrak=.true. ctmp=macro call start_macro(inpt, locunitnum, macro) read (locunitnum, *) nspeci,maxlayers,max_particles c Line with pout read(locunitnum,*) idum1 c Read past group with tcurve read(locunitnum,'(a80)') dummy_line if(dummy_line(1:6).eq.'tcurve') then read(locunitnum,'(a80)') dummy_line read(locunitnum,'(a80)') dummy_line else backspace(locunitnum) endif c Read past group with zptr read(locunitnum,'(a80)') dummy_line if(dummy_line(1:4).eq.'zptr') then read(locunitnum,*) ipzone allocate(itemporary(ipzone)) read(locunitnum,*) (itemporary(i),i=1,ipzone) deallocate(itemporary) else backspace(locunitnum) end if c read rseed line read(locunitnum,*) idum1 c*** water table rise modification c Read past group with wtri read(locunitnum,'(a80)') dummy_line if(dummy_line(1:4).eq.'wtri') then read(locunitnum,*)water_table wtrise_flag = .true. else wtrise_flag = .false. water_table = -1.d+10 backspace(locunitnum) end if c*** water table rise modification c read daycs line read(locunitnum,*) rdum1 c read file name if this option is used read(locunitnum,'(a80)') dummy_line if(dummy_line(1:4).eq.'file') then read(locunitnum,'(a80)') dummy_line else backspace(locunitnum) end if c Read afm if it exists read(locunitnum,'(a80)') dummy_line if(dummy_line(1:3).ne.'afm') then backspace(locunitnum) end if c zvd 02/28/07 Add for free water diffusion coefficient and tortuosity c Read dfree keyword if it exists read(locunitnum,'(a80)') dummy_line if(dummy_line(1:4).ne.'dfre') then backspace(locunitnum) end if c read until next black line to get past dispersivities blank = .false. do while(.not.blank) read(locunitnum,'(a80)') dummy_line if(null1(dummy_line)) blank = .true. end do c read until next blank line to get past itrc lines blank = .false. do while(.not.blank) read(locunitnum,'(a80)') dummy_line if(null1(dummy_line)) blank = .true. end do c Loop through each species, read ith, determine if the c particles have a size distribution ncolspec = 0 ncolsizes = 0 do i = 1, nspeci read(locunitnum,*) ith c Ready to look for size distribution, count the number c of species with size distributions, count the number c of entries, record the maximum number of entries read(locunitnum,'(a80)') dummy_line if(dummy_line(1:4).eq.'size') then ncolspec = ncolspec + 1 jj = 0 2991 continue read(locunitnum,'(a80)') dummy_line if (null1(dummy_line)) then goto 2992 else jj = jj + 1 goto 2991 end if 2992 continue ncolsizes = max(jj,ncolsizes) else backspace(locunitnum) end if CHari 01-Nov-06 read in parameters for the colloid diversity model c find max_probdivs read(locunitnum,'(a80)') wdd1 if(wdd1(1:4).eq.'dive') then ! Flag for non-colloid daughter products read(locunitnum,*) idum if (idum.eq.0) then total_colloids = total_colloids + 1 else total_daughters = total_daughters + 1 goto 18933 endif read(locunitnum,'(a80)') dummy_line if (dummy_line(1:4) .eq. 'file') then do icount = 1, 80 filename(icount:icount) = ' ' enddo read(locunitnum,'(a80)') filename if(total_colloids.eq. 1)then iread_rcoll = open_file(filename,'old') endif else backspace locunitnum end if read(locunitnum,'(a80)') dummy_line call parse_string(dummy_line,imsg,msg,xmsg,cmsg,nwds) tprp_num = imsg(1) ! Use multiple simulation number - irun for GoldSim or msim run isimnum = int(irun+0.01) if(isimnum<=0) isimnum = 1 if (ripfehm .eq. 0 .and. nwds .ge. 2) isimnum = imsg(2) ! if(tprp_num.ge.11.and.tprp_num.le.14.and. ! 2 total_colloids.eq.1) then if(tprp_num.ge.11.and.tprp_num.le.14) then if(tprp_num.lt.13) then if(iread_rcoll .eq. 0) then write (ierr, 18929) if (iout .ne. 0) write (iptty, 18929) if (iptty .ne. 0) write (iptty, 18929) stop end if 18929 format ('STOP - CDF table data must be input using ', & 'an external data file -- check mptr macro.') read(iread_rcoll,'(a80)',end=18928) dummy_line read(iread_rcoll,*,end=18928)idum do while (idum.ne.isimnum) nulldum=.false. do while(.not.nulldum) read(iread_rcoll,'(a80)',end=18928)dummy_line nulldum=null1(dummy_line) enddo read(iread_rcoll,*,end=18928)idum enddo 18928 if (idum .ne. isimnum) then write(ierr,18930) tprp_num, isimnum, & trim(filename) if (iout .ne. 0) write(iout, 18930) tprp_num, & isimnum, trim(filename) if (iptty .ne. 0) write(iptty, 18930) tprp_num, & isimnum, trim(filename) stop end if 18930 format ('STOP - Error in inmptr for tprpflag = ', i2, & ' realization_num ', i4, ' not found in ', a) jjj=0 read(iread_rcoll,'(a80)',end=18931) dummy_line nulldum=null1(dummy_line) do while(.not.nulldum) jjj=jjj+1 read(iread_rcoll,'(a80)',end=18931) dummy_line nulldum=null1(dummy_line) enddo 18931 if (jjj .lt. 2) then write(ierr,18932) tprp_num, isimnum, & trim(filename) if (iout .ne. 0) write(iout, 18932) tprp_num, & isimnum, trim(filename) if (iptty .ne. 0) write(iptty, 18932) tprp_num, & isimnum, trim(filename) stop end if 18932 format ('STOP - Error in inmptr for tprpflag = ', & i2, ' realization_num ', i4, & ' data not found in ', a) maxprobdivs = max(jjj,maxprobdivs) rewind(iread_rcoll) else if(iread_rcoll .eq. 0) read(locunitnum,'(a80)') wdd1 endif endif read(locunitnum,'(a80)') wdd1 cHari setup pointer arrays for reversible and irreversible colloids if(wdd1(1:4).eq.'irre')then total_irrev = total_irrev +1 elseif(wdd1(1:4).eq.'reve')then total_rev = total_rev+1 else write(ierr,*)'must specify irre or reve in mptr' if(iout.ne.0)then write(iout,*)'must specify irre or reve in mptr' endif if(iptty.ne.0)then write(iptty,*)'must specify irre or reve in mptr' endif endif else backspace(locunitnum) endif c read past transport parameter information 18933 continue read(locunitnum, *) idum1 do iscan = 1, idum1 read(locunitnum,'(a80)') dummy_line end do c read past source information read(locunitnum, *) idum1 do iscan = 1, idum1 c read until next black line to get past current source blank = .false. do while(.not.blank) read(locunitnum,'(a80)') dummy_line if(null1(dummy_line)) blank = .true. end do end do c Ready to loop back to the next species end do call done_macro(locunitnum) else if (macro .eq. 'ptrk') then ptrak=.true. call start_macro(inpt, locunitnum, macro) read (locunitnum, *) max_particles nspeci = 1 c maxlayers = n0 c Determine actual number of transport maylayers there are c*** water table rise modification c Read past group with wtri read(locunitnum,'(a80)') dummy_line if(dummy_line(1:4).eq.'wtri') then read(locunitnum,*)water_table else backspace(locunitnum) end if c*** water table rise modification c Read 'rip' string read(locunitnum,'(a80)') dummy_line if(dummy_line(1:3).eq.'rip') then read(locunitnum,'(a80)') dummy_line end if read(locunitnum,'(a80)') dummy_line read(locunitnum,'(a80)') dummy_line if(dummy_line(1:6).eq.'tcurve') then read(locunitnum,'(a80)') dummy_line read(locunitnum,'(a80)') dummy_line else backspace(locunitnum) endif read(locunitnum,'(a80)') dummy_line if(dummy_line(1:4).eq.'zptr') then read(locunitnum,*) ipzone allocate(itemporary(ipzone)) read(locunitnum,*) (itemporary(i),i=1,ipzone) deallocate(itemporary) else backspace(locunitnum) end if read(locunitnum,'(a80)') dummy_line if(dummy_line(1:4).eq.'file') then read(locunitnum,'(a80)') dummy_line else backspace(locunitnum) end if c Get past afm keyword if it exists read(locunitnum,'(a80)') dummy_line if(dummy_line(1:3).ne.'afm') then backspace(locunitnum) end if c zvd 02/28/07 Add for free water diffusion coefficient and tortuosity c Get past dfree keyword if it exists read(locunitnum,'(a80)') dummy_line if(dummy_line(1:4).ne.'dfre') then backspace(locunitnum) end if c Look for colloid size information read(locunitnum,'(a80)') dummy_line if(dummy_line(1:4).eq.'size') then ncolspec = 1 jj = 0 1991 continue read(locunitnum,'(a80)') dummy_line if (null1(dummy_line)) then goto 1992 else jj = jj + 1 goto 1991 end if 1992 continue ncolsizes = jj else backspace(locunitnum) end if CHari 01-Nov-06 read in parameters for the colloid diversity model c find max_probdivs read(locunitnum,'(a80)') wdd1 if(wdd1(1:4).eq.'dive') then total_colloids = 1 read(locunitnum,'(a80)') dummy_line if (dummy_line(1:4) .eq. 'file') then do icount = 1, 80 filename(icount:icount) = ' ' enddo read(locunitnum,'(a80)') filename if(total_colloids.eq. 1)then iread_rcoll = open_file(filename,'old') endif else backspace locunitnum end if read(locunitnum,'(a80)') dummy_line call parse_string(dummy_line,imsg,msg,xmsg,cmsg,nwds) tprp_num = imsg(1) ! Use multiple simulation number - irun for GoldSim or msim run isimnum = int(irun+0.01) if(isimnum<=0) isimnum = 1 if (ripfehm .eq. 0 .and. nwds .ge. 2) isimnum = imsg(2) if(tprp_num.ge.11.and.tprp_num.le.14.and. 2 total_colloids.eq.1) then maxprobdivs = 1 if(tprp_num.lt.13) then if(iread_rcoll .eq. 0) then write (ierr, 17929) if (iout .ne. 0) write (iptty, 17929) if (iptty .ne. 0) write (iptty, 17929) stop end if 17929 format ('STOP - CDF table data must be input using ', & 'an external data file -- check ptrk macro.') read(iread_rcoll,'(a80)',end=17928) dummy_line read(iread_rcoll,*,end=17928)idum do while (idum.ne.isimnum) nulldum=.false. do while(.not.nulldum) read(iread_rcoll,'(a80)',end=17928)dummy_line nulldum=null1(dummy_line) enddo read(iread_rcoll,*,end=17928)idum enddo 17928 if (idum .ne. isimnum) then write(ierr,17930) tprp_num, isimnum, & trim(filename) if (iout .ne. 0) write(iout, 17930) tprp_num, & isimnum, trim(filename) if (iptty .ne. 0) write(iptty, 17930) tprp_num, & isimnum, trim(filename) stop end if 17930 format ('STOP - Error in inptrk for tprpflag = ', i2, & ' realization_num ', i4, ' not found in ', a) jjj=0 read(iread_rcoll,'(a80)',end=17931) dummy_line nulldum=null1(dummy_line) do while(.not.nulldum) jjj=jjj+1 read(iread_rcoll,'(a80)',end=17931) dummy_line nulldum=null1(dummy_line) enddo 17931 if (jjj .lt. 2) then write(ierr,17932) tprp_num, isimnum, & trim(filename) if (iout .ne. 0) write(iout, 17932) tprp_num, & isimnum, trim(filename) if (iptty .ne. 0) write(iptty, 17932) tprp_num, & isimnum, trim(filename) stop end if 17932 format ('STOP - Error in inptrk for tprpflag = ', i2, & ' realization_num ', i4, ' data not found in ', & a) maxprobdivs = jjj rewind(iread_rcoll) else if(iread_rcoll .eq. 0) read(locunitnum,'(a80)') wdd1 endif endif read(locunitnum,'(a80)') wdd1 cHari setup pointer arrays for reversible and irreversible colloids if(wdd1(1:4).eq.'irre')then total_irrev = 1 elseif(wdd1(1:4).eq.'reve')then total_rev = 1 else write(ierr,*)'must specify irre or reve in ptrk' if(iout.ne.0)then write(iout,*)'must specify irre or reve in ptrk' endif if(iptty.ne.0)then write(iptty,*)'must specify irre or reve in ptrk' endif endif else backspace(locunitnum) endif c We are now at the point where we can count the c number of maxlayers maxlayers = 0 991 continue read(locunitnum,'(a80)') dummy_line if(null1(dummy_line)) then goto 99 else maxlayers = maxlayers + 1 end if goto 991 99 continue maxlayers = max(1,maxlayers) call done_macro(locunitnum) c***********sptr***groemer 5/1/98*************************************** else if (macro .eq. 'sptr') then nspeci = 1 sptrak=.true. nzbtc = 0 nsize_tprp = 0 nplum = 0 itensor = -999 call start_macro(inpt, locunitnum, macro) read (locunitnum,'(a80)') dummy_line c Section to read past keywords done=.false. do while(.not.done) done=.true. read(locunitnum,'(a80)') dummy_line read_flags:select case(dummy_line(1:2)) case('tc', 'TC') ! If tcurve data is to be input read two more lines, zvd 18-Nov-02 done = .false. read(locunitnum,'(a80)') dummy_line read(locunitnum,'(a80)') dummy_line ! If omr grid is being used case ('om', 'OM') done = .false. omr_flag = .true. read(locunitnum,'(i8)') omr_nodes read (locunitnum,'(a80)') dummy_line if (dummy_line(1:4).eq.'file') then save_omr = .TRUE. read (locunitnum,'(a100)') nmfil(23) read (locunitnum,'(a11)') cform(23) else save_omr = .FALSE. backspace (locunitnum) end if case('po', 'PO') done = .false. ! If POD basis funtion derivatives are needed, zvd 16-Aug-04 if (dummy_line(3:3) .eq. 'd' .or. & dummy_line(3:3) .eq. 'D') then pod_flag = .true. ! Else po represents porosity end if case ('tp', 'TP') done = .false. if (dummy_line(3:3) .eq. 'o' .or. & dummy_line(3:3) .eq. 'O') then ! We are reading transport porosities 'tpor' tpor_flag = .TRUE. read(locunitnum,'(a80)') dumstring if (dumstring(1:4) .ne. 'file') then do if (null1(dumstring)) exit read(locunitnum,'(a80)') dumstring enddo else read(locunitnum,'(a80)') dumstring end if else ! Else we are reading the transport property 'tprp' models if (itensor .eq. 0) itensor = 5 do read(locunitnum,'(a80)') dummy_line if(null1(dummy_line)) exit nsize_tprp = nsize_tprp + 1 read(dummy_line, *) tprp_num if(tprp_num.ge.11.and.tprp_num.le.14) then div_flag=.true. read(locunitnum,'(a80)') dummy_line if (dummy_line(1:4) .eq. 'file') then backspace(locunitnum) backspace(locunitnum) read(locunitnum,*) tprp_num,realization_num read(locunitnum,'(a80)') dummy_line else c We are reading eqn parameters from tprp line backspace(locunitnum) end if if (dummy_line(1:4) .eq. 'file') then do icount = 1, 80 filename(icount:icount) = ' ' enddo read(locunitnum,'(a80)') filename iread_rcoll = open_file(filename,'old') maxprobdivs = 1 end if if(tprp_num.lt.13) then if(iread_rcoll .eq. 0) then write (ierr, 19929) if (iout .ne. 0) write (iptty, 19929) if (iptty .ne. 0) write (iptty, 19929) stop end if 19929 format('STOP - CDF table data must be ', & 'input using an external data file -- ', & 'check sptr macro.') read(iread_rcoll,'(a80)', end=19928) & dummy_line read(iread_rcoll,*,end=19928)idum do while (idum.ne.realization_num) nulldum=.false. do while(.not.nulldum) read(iread_rcoll,'(a80)',end=19928) & dummy_line nulldum=null1(dummy_line) enddo read(iread_rcoll,*,end=19928)idum enddo 19928 if (idum .ne. realization_num) then write(ierr,19930) tprp_num, & realization_num, trim(filename) if (iout .ne. 0) write(iout, 19930) & tprp_num, realization_num, & trim(filename) if (iptty .ne. 0) write(iptty, 19930) & tprp_num, realization_num, & trim(filename) stop end if 19930 format ('STOP - Error in insptr for ', & 'tprpflag = ', i2, ' realization_num ', & i4, ' not found in ', a) jjj=0 read(iread_rcoll,'(a80)', end=19931) & dummy_line nulldum=null1(dummy_line) do while(.not.nulldum) jjj=jjj+1 read(iread_rcoll,'(a80)',end=19931) & dummy_line nulldum=null1(dummy_line) enddo 19931 if (jjj .lt. 2) then write(ierr,19932) tprp_num, & realization_num, trim(filename) if (iout .ne. 0) write(iout, 19932) & tprp_num, realization_num, & trim(filename) if (iptty .ne. 0) write(iptty, 19932) & tprp_num, realization_num, & trim(filename) stop end if 19932 format ('STOP - Error in insptr for ', & 'tprpflag = ', i2, ' realization_num ', & i4, ' data not found in ', a) maxprobdivs = jjj rewind(iread_rcoll) c exit endif exit end if end do c Read past the itrc group (model assignment) do read(locunitnum,'(a80)') dummy_line if(null1(dummy_line)) exit end do end if case('sa', 'SA') done = .false. case('pe', 'PE') done = .false. case('de', 'DE') done = .false. case('pr', 'PR') done = .false. case('te', 'TE') done = .false. case('zo', 'ZO') done = .false. case('id', 'ID') done = .false. case('wt', 'WT') done = .false. case('vo','VO') done = .false. case('xy','XY') done = .false. case ('ip', 'IP') done = .false. case ('tr', 'TR') done = .false. case ('in', 'IN') done = .false. case ('ex', 'EX') done = .false. case ('ou', 'OU') done = .false. case('zb','ZB') done = .false. read(locunitnum,*) ireaddum if(ireaddum.gt.0) then read(locunitnum,'(a80)') dummy_line nzbtc = ireaddum else nzbtc = 0 end if case('pl','PL') c march 14, 02 s kelkar, from /scratch/ymp/kelkar/fehmv2.12....... c Read past plum input done = .false. read(locunitnum,*) ireaddum if(ireaddum.gt.0) then read(locunitnum,'(a80)') dummy_line nplum = ireaddum else nplum = 0 end if case('cl','CL') c Jan 5, 06 S kelkar read past keyword cliff done = .false. if (dummy_line(1:6).eq.'cliffg') then read(locunitnum,'(a80)') dummy_line read(locunitnum,'(a80)') dummy_line read(locunitnum,'(a80)') dummy_line else if (dummy_line(1:6).eq.'cliffr') then read(locunitnum,'(a80)') dummy_line end if case('co','CO') c Jan 27, 06 S kelkar read past keyword corner done = .false. case('ca','CA') c Jan 13, 05 S kelkar read past capture node list done = .false. do read(locunitnum,'(a80)') wdd1 if (wdd1(1:4) .eq. 'file') then read (locunitnum,'(a80)') wdd1 exit else if (null1(wdd1)) then exit end if end do case('sp','SP') c Jan 27, 05 S kelkar read past "spring" node list done = .false. do read(locunitnum,'(a80)') wdd1 if (wdd1(1:4) .eq. 'file') then read (locunitnum,'(a80)') wdd1 exit else if (null1(wdd1)) then exit end if end do case default ! The first non-character line read should contain courant factor, etc. if (itensor .eq. -999) then done = .false. call parse_string(dummy_line, imsg, msg, xmsg, cmsg, & nwds) if(nwds.ge.3) then itensor = imsg(3) else itensor = 0 end if else if (itensor .eq. 0) then ! We are done with keywords and haven't ready any transport properties ! This is really old style input, so we needed to read past the ! transport property line nsize_tprp = max(1,nsize_tprp) else backspace (locunitnum) end if end select read_flags end do c................................................................... read (locunitnum, '(a80)') dumstring call parse_string(dumstring, imsg, msg, xmsg, cmsg, nwds) if (msg(2).eq.1) then ist=imsg(2) else ist=xmsg(2) end if if (nwds .gt. 2) then do i = 3, nwds if (msg(i) .eq. 3) then if (cmsg(i)(1:4) .eq. 'save') sptr_flag = .true. end if end do end if read (locunitnum, *) nx,ny,nz read (locunitnum,'(a80)') dummy_line read (locunitnum,'(a80)') dummy_line read (locunitnum,'(a80)') dummy_line num_part = 0 if(ist.eq.2) then if(.not. null1(dummy_line)) then ! There shouldn't be any more data for sptr macro write (ierr, 110) ist if (iptty .ne. 0) write(iptty, 110) ist stop else if(icnl.ne.0) nz = 1 num_part=nx*ny*nz end if else if (ist .eq. 0 .or. abs(ist) .eq. 1 .or. ist .eq. 3) then if(null1(dummy_line)) then ! There should be more data for sptr macro write (ierr, 120) ist if (iptty .ne. 0) write(iptty, 120) ist stop else if (dummy_line(1:4) .eq. 'file') then read(locunitnum,'(a100)') filename inptread = open_file(filename,'old') opened = .true. read (inptread,'(a80)') dummy_line if (dummy_line(1:4) .eq. 'FEHM') then ! This file was generated by FEHM and the title, last seed and ! ending time were written to the file read(inptread,'(a80)') dummy_line read(inptread,'(a80)') dummy_line else backspace inptread end if else backspace locunitnum inptread = locunitnum opened = .false. end if do read (inptread,'(a80)') dummy_line if (dummy_line(1:4) .eq. 'zbtc' .or. & null1(dummy_line)) exit num_part = num_part + 1 end do if (opened) then close (inptread) opened = .false. end if end if else write(ierr,130) ist if (iptty .ne. 0) write(iptty, 130) ist stop end if 110 format ('Error at end of sptr macro, input not terminated', & ' with blank line, ist = ', i2) 120 format ('Error at end of sptr macro, no particle position', & ' input for ist = ', i2) 130 format ('Error in sptr macro, illegal value for ist:', i2) call done_macro(locunitnum) c***********sptr***groemer 5/1/98*************************************** else if (macro .eq. 'ppor') then c need porosity model call start_macro(inpt, locunitnum, macro) read (locunitnum,*) iporos call done_macro(locunitnum) else if (macro .eq. 'vcon') then ! need number of variable conductivity models call start_macro(inpt, locunitnum, macro) do read(locunitnum,'(a80)') dumstring if (null1(dumstring)) exit numvcon = numvcon + 1 enddo call done_macro(locunitnum) else if (macro .eq. 'vbou') then ivboun = 1 else if (macro .eq. 'zeol') then izeolites = 1 else if (macro .eq. 'strs') then call start_macro(inpt, locunitnum, macro) read(locunitnum,*) istrs, ihms i = 0 do read(locunitnum,'(a80)') dumstring if(dumstring(1:9).eq.'stressend' .or. dumstring(1:8) .eq. & 'end strs' .or. dumstring(1:7) .eq. 'endstrs') exit if(dumstring(1:9).eq.'permmodel') then do read(locunitnum,'(a80)') dumstring if (null1(dumstring)) exit read(dumstring,*) idumm backspace locunitnum i = i + 1 if(idumm.eq.1) then read(locunitnum,*) idumm c else if (idumm .eq. 2 .or. idumm .eq. 4) then else if (idumm .eq. 2) then read(locunitnum,*) idumm, (adumm, ja = 1, 9) else if (idumm .eq. 3) then read(locunitnum,*) idumm, (adumm, ja = 1, 9) else if (idumm .eq. 4) then read(locunitnum,*) idumm, (adumm, ja = 1, 14) else if(idumm.eq.5) then read(locunitnum,*) idumm,(adumm,ja=1,6) else if(idumm.eq.6) then read(locunitnum,*) idumm,(adumm,ja=1,11) else if(idumm.eq.7) then read(locunitnum,*) idumm,(adumm,ja=1,6) else if(idumm.eq.8) then read(locunitnum,*) idumm,(adumm,ja=1,9) else if(idumm.eq.11) then read(locunitnum,*) idumm,(adumm,ja=1,3) else if(idumm.eq.21) then read(locunitnum,*) idumm,(adumm,ja=1,13) else if(idumm.eq.22) then read(locunitnum,*) idumm,(adumm,ja=1,10) else if(idumm.eq.222) then read(locunitnum,*) idumm,(adumm,ja=1,9) read(locunitnum,*) (adumm,ja=1,10) else if(idumm.eq.31) then read(locunitnum,*) idumm,(adumm,ja=1,2) else if(idumm.eq.91) then c open(unit=97,file='debug_permmodel_91.dat') read(locunitnum,*) read(locunitnum,*) else read(locunitnum,*) idumm endif enddo endif enddo if(i.ge.1) then allocate(ispmt(i)) allocate(spm1f(i),spm2f(i),spm3f(i),spm4f(i),spm5f(i)) allocate(spm6f(i),spm7f(i),spm8f(i),spm9f(i),spm10f(i)) allocate(spm11f(i),spm12f(i),spm13f(i),spm14f(i)) allocate(spm1f222(i),spm2f222(i),spm3f222(i),spm4f222(i)) allocate(spm5f222(i),spm6f222(i),spm7f222(i),spm8f222(i)) allocate(spm9f222(i),spm10f222(i)) ispmt = 0 spm1f = 0. spm2f = 0. spm3f = 0. spm4f = 0. spm5f = 0. spm6f = 0. spm7f = 0. spm8f = 0. spm9f = 0. spm10f = 0. spm11f = 0. spm12f = 0. spm13f = 0. spm14f = 0. spm1f222 = 0. spm2f222 = 0. spm3f222 = 0. spm4f222 = 0. spm5f222 = 0. spm6f222 = 0. spm7f222 = 0. spm8f222 = 0. spm9f222 = 0. spm10f222 = 0. endif call done_macro(locunitnum) end if go to 10 40 rewind locunitnum if(ngroups.eq.0)then ngroups=ncpnt if(irun.eq.1) then allocate(fzero(max(ngroups,1))) allocate(group(max(ngroups,1),ncpnt)) allocate(pos(max(ngroups,1),ncpnt)) allocate(n_couple_species(max(ngroups,1))) end if mdof_sol = 1 n_couple_species = 0 do igrp = 1, ngroups pos(igrp,1)= igrp n_couple_species(igrp)=1 enddo endif if(idpdp.ne.0)mdof_sol=mdof_sol*2 if(allocated(group_mat)) deallocate(group_mat) if ((iccen.eq.1).and.ptrak) then write(ierr,*) 'ERROR: Can not have both particle tracking' write(ierr,*) '(ptrk) and tracer input (trac).' write(ierr,*) 'Code Aborted in scanin' if (iatty.ne.0) then write(iatty,*) 'ERROR: Can not have both particle tracking' write(iatty,*) '(ptrk) and tracer input (trac).' write(iatty,*) 'Code Aborted in scanin' endif stop endif c gaz added 112014 if (iccen.eq.1 .and. rxn_flag .eq. 0) then c Check that no solid species are used without reaction if (nimm .ne. 0) then write(ierr,*) 'ERROR: Can not using solid species in trac', & ' without rxn' write(ierr,*) 'Code Aborted in scanin' if (iatty.ne.0) then write(iatty,*) 'ERROR: Can not using solid species in ', & 'trac without rxn' write(iatty,*) 'Code Aborted in scanin' end if stop end if end if return 50 write (ierr, 55) 'STOP' if (iptty .ne. 0) & write (iptty, 55) 'STOP' stop 55 format ("Missing '", a, "' statement in input. STOPPING") 56 format ("Check macro: ", a) end subroutine scanin
C C *** LAST REVISED ON 20-AUG-1987 16:47:03.07 C *** SOURCE FILE: [DL.GRAPHICS.LONGLIB]REFTERM.FOR C PROGRAM REFTERM C C THIS PROGRAM PLOTS A RAMTEK EMULATION FILE INTO THE LONGLIB C PLOT PACKAGE C WRITTEN: NOV 1986 DGL C C THIS PROGRAM USING THE VAX FORTRAN "BYTE" VARIABLE TYPE C BYTE B(1280) INTEGER PEN CHARACTER*70 FNAME C C PROMPT USER FOR FILE INPUT C 35 WRITE(*,15) 15 FORMAT('$Enter Ramtek Emulation File Name: ') READ(*,20) FNAME 20 FORMAT(A70) WRITE(*,25) 25 FORMAT(' Note: Select only one output graphics device') C C OPEN GRAPHICS PACKAGE C CALL FRAME(0,0,0.,0.,1.) C C OUTPUT RAMTEK EMULATION ARRAY TO SELECTED DEVICE C OPEN REF FILE ASSUMING LARGE RAMTEK C IXWIDE=1280 IYWIDE=1024 OPEN(UNIT=2,FILE=FNAME,ACCESS='DIRECT',STATUS='UNKNOWN', $ RECL=IXWIDE,FORM='FORMATTED',ERR=199) C C DETERMINE WHICH GRAPHICS DEVICE IS OPEN C 65 IXW=IXWIDE IF (IXWIDE.EQ.512) IXW=512 C C CHECK TERMINAL, RAMTEK, AND METAFILE C CALL WHEREVT(XS,YS,XS,YS,RX,RY,ILU,IY,IX,IX,IY) RX=RX*4 RY=RY*4 IF (ILU.LE.0) THEN CALL WHERERM(XS,YS,XS,YS,RX,RY,IY,IX,IX,ILU) IF (ILU.LE.0) THEN CALL WHEREPR(XS,YS,XS,YS,XS,YS,RX,RY,ILU,IY,IX,IX) RX=RX*5./3. RY=RY*5./3. IDEV=2 ELSE ICHAN=IRMCHAN(IDDEV) IDEV=1 ENDIF ELSE IDEV=0 ENDIF C C SEE IF ANY DEVICE IS IN USE, EXIT IF NOT C IF (ILU.LE.0) CALL EXIT C C READ EACH LINE OF IMAGE AND PLOT IT OUT C LPEN=-3 DO 250 IY1=1,IYWIDE IY=IYWIDE-IY1 IF (IXW.EQ.512) THEN READ(2'IY1,260,ERR=97) (B(II),II=1,512) 260 FORMAT(512A1) ELSE READ(2'IY1,261,ERR=97) B 261 FORMAT(1280A1) ENDIF IF (IDEV.NE.1) THEN C C OUTPUT DIRECTLY TO RAMTEK USING IMAGE MODE WRITE C CALL RMSTART(ICHAN,IY1,0,IERR) CALL RMWRITEBYTE(ICHAN,B,IXW,IERR) ELSE C C CONVERT PIXEL ROW INTO SCAN LINES FOR METAFILE AND TERMINAL C PEN=-1 DO 305 IX=0,IXWIDE II=B(IX+1).AND.255 IF (IX.EQ.IXWIDE) II=-2 IF (II.NE.PEN) THEN IF (PEN.NE.-1.AND.PEN.NE.0) THEN XS=(IX0+0.5)*RX XS1=(IX-0.5)*RX YS=(IY+0.5)*RX IF (LPEN.NE.PEN) $ CALL PLOT(FLOAT(PEN),0.,0) CALL PLOT(XS,YS,3) CALL PLOT(XS1,YS,2) ENDIF LPEN=PEN PEN=II IX0=IX ENDIF 305 CONTINUE ENDIF 250 CONTINUE C 350 CALL PLOT(0.,0.,3) CALL CTERM(2) CALL PLOTND C STOP C 199 CONTINUE C C IF WE GET TO HERE WE GOT AN ERROR OPENING REF FILE C MAY BE IT WAS A 512 SIZE FILE, TRY AGAIN C IXWIDE=512 IYWIDE=512 OPEN(UNIT=2,FILE=FNAME,ACCESS='DIRECT',STATUS='UNKNOWN', $ RECL=IXWIDE,FORM='FORMATTED',ERR=99) GOTO 65 C 99 WRITE(*,98) 98 FORMAT(' *** ERROR OPENING RAMTEK EMULATION FILE ***') GOTO 35 C 97 WRITE(*,96) IY1 96 FORMAT(' *** ERROR READING RAMTEK EMULATION FILE ***',I5) GOTO 350 END
/- 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.multiset.lattice import order.order_dual import order.complete_lattice /-! # Lattice operations on finsets -/ variables {α β γ : Type*} namespace finset open multiset order_dual /-! ### sup -/ section sup variables [semilattice_sup_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 : β → α} 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] 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] 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 lemma sup_const {s : finset β} (h : s.nonempty) (c : α) : s.sup (λ _, c) = c := eq_of_forall_ge_iff $ λ b, sup_le_iff.trans h.forall_const lemma sup_le {a : α} : (∀b ∈ s, f b ≤ a) → s.sup f ≤ a := sup_le_iff.2 lemma le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f := sup_le_iff.1 (le_refl _) _ hb lemma sup_mono_fun {g : β → α} (h : ∀b∈s, f b ≤ g b) : s.sup f ≤ s.sup g := sup_le (λ b hb, le_trans (h b hb) (le_sup hb)) lemma sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f := sup_le $ assume b hb, le_sup (h hb) @[simp] lemma sup_lt_iff [is_total α (≤)] {a : α} (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)⟩ @[simp] lemma le_sup_iff [is_total α (≤)] {a : α} (ha : ⊥ < a) : a ≤ s.sup f ↔ (∃ b ∈ s, a ≤ f b) := by { rw [←not_iff_not, not_bex], simp only [@not_le (as_linear_order α), sup_lt_iff ha], } @[simp] lemma lt_sup_iff [is_total α (≤)] {a : α} : a < s.sup f ↔ (∃ b ∈ s, a < f b) := by { rw [←not_iff_not, not_bex], simp only [@not_lt (as_linear_order α), sup_le_iff], } lemma comp_sup_eq_sup_comp [semilattice_sup_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]) lemma comp_sup_eq_sup_comp_of_is_total [is_total α (≤)] {γ : Type} [semilattice_sup_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 /-- Computating `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_bot Pbot Psup) 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 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₁ a₂ : α), p 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_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, _root_.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 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_eq_Sup [complete_lattice α] (s : finset α) : s.sup id = Sup s := by simp [Sup_eq_supr, sup_eq_supr] /-! ### inf -/ section inf variables [semilattice_inf_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 : β → α} 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 (order_dual α) _ _ _ _ _ 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 (order_dual α) _ _ _ _ _ _ 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 lemma le_inf_iff {a : α} : a ≤ s.inf f ↔ ∀ b ∈ s, a ≤ f b := @sup_le_iff (order_dual α) _ _ _ _ _ lemma inf_le {b : β} (hb : b ∈ s) : s.inf f ≤ f b := le_inf_iff.1 (le_refl _) _ hb lemma le_inf {a : α} : (∀b ∈ s, a ≤ f b) → a ≤ s.inf f := le_inf_iff.2 lemma inf_mono_fun {g : β → α} (h : ∀b∈s, f b ≤ g b) : s.inf f ≤ s.inf g := le_inf (λ b hb, le_trans (inf_le hb) (h b hb)) lemma inf_mono (h : s₁ ⊆ s₂) : s₂.inf f ≤ s₁.inf f := le_inf $ assume b hb, inf_le (h hb) @[simp] lemma lt_inf_iff [is_total α (≤)] {a : α} (ha : a < ⊤) : a < s.inf f ↔ (∀ b ∈ s, a < f b) := @sup_lt_iff (order_dual α) _ _ _ _ _ _ ha @[simp] lemma inf_le_iff [is_total α (≤)] {a : α} (ha : a < ⊤) : s.inf f ≤ a ↔ (∃ b ∈ s, f b ≤ a) := @le_sup_iff (order_dual α) _ _ _ _ _ _ ha @[simp] lemma inf_lt_iff [is_total α (≤)] {a : α} : s.inf f < a ↔ (∃ b ∈ s, f b < a) := @lt_sup_iff (order_dual α) _ _ _ _ _ _ lemma comp_inf_eq_inf_comp [semilattice_inf_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 (order_dual α) _ (order_dual γ) _ _ _ _ _ g_inf top lemma comp_inf_eq_inf_comp_of_is_total [h : is_total α (≤)] {γ : Type} [semilattice_inf_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 /-- Computating `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_top Ptop Pinf) t f : α) = t.inf (λ x, f x) := @sup_coe (order_dual α) _ _ _ Ptop Pinf t f lemma inf_induction {p : α → Prop} (ht : p ⊤) (hp : ∀ (a₁ a₂ : α), p a₁ → p a₂ → p (a₁ ⊓ a₂)) (hs : ∀ b ∈ s, p (f b)) : p (s.inf f) := @sup_induction (order_dual α) _ _ _ _ _ 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 end inf lemma inf_eq_infi [complete_lattice β] (s : finset α) (f : α → β) : s.inf f = (⨅a∈s, f a) := @sup_eq_supr _ (order_dual β) _ _ _ lemma inf_eq_Inf [complete_lattice α] (s : finset α) : s.inf id = Inf s := by simp [Inf_eq_infi, inf_eq_infi] 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 : β → α) : α := option.get $ let ⟨b, hb⟩ := H in option.is_some_iff_exists.2 (sup_of_mem f hb) 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.some_eq_coe, option.some_get] @[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 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, apply le_refl, }, { 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) @[simp] lemma sup'_lt_iff [is_total α (≤)] {a : α} : s.sup' H f < a ↔ (∀ b ∈ s, f b < a) := begin rw [←with_bot.coe_lt_coe, coe_sup', sup_lt_iff (with_bot.bot_lt_coe a)], exact ball_congr (λ b hb, with_bot.coe_lt_coe), end @[simp] lemma le_sup'_iff [is_total α (≤)] {a : α} : a ≤ s.sup' H f ↔ (∃ b ∈ s, a ≤ f b) := begin rw [←with_bot.coe_le_coe, coe_sup', 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 [is_total α (≤)] {a : α} : a < s.sup' H f ↔ (∃ b ∈ s, a < f b) := begin rw [←with_bot.coe_lt_coe, coe_sup', lt_sup_iff], exact bex_congr (λ b hb, with_bot.coe_lt_coe), end 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 α → with_bot γ := with_bot.rec_bot_coe ⊥ (λ x, ↑(g x)), 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₂, cases f₁, { rw [with_bot.none_eq_bot, bot_sup_eq], exact bot_sup_eq.symm, }, { cases f₂, refl, exact congr_arg coe (g_sup f₁ f₂), }, end lemma sup'_induction {p : α → Prop} (hp : ∀ (a₁ a₂ : α), p 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, intros a₁ a₂ h₁ h₂, cases a₁, { rw [with_bot.none_eq_bot, bot_sup_eq], exact h₂, }, { cases a₂, exact h₁, exact hp a₁ a₂ h₁ h₂, }, end lemma exists_mem_eq_sup' [is_total α (≤)] : ∃ b, b ∈ s ∧ s.sup' H f = f b := begin induction s using finset.cons_induction with c s hc ih, { exact false.elim (not_nonempty_empty H), }, { rcases s.eq_empty_or_nonempty with rfl | hs, { exact ⟨c, mem_singleton_self c, rfl⟩, }, { rcases ih hs 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 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 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 (order_dual α) _ _ _ 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 : β → α) : α := @sup' (order_dual α) _ _ s H f variables {s : finset β} (H : s.nonempty) (f : β → α) @[simp] lemma coe_inf' : ((s.inf' H f : α) : with_top α) = s.inf (coe ∘ f) := @coe_sup' (order_dual α) _ _ _ 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 (order_dual α) _ _ _ H f _ _ _ @[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 (order_dual α) _ _ _ H f _ _ _ @[simp] lemma inf'_singleton {b : β} {h : ({b} : finset β).nonempty} : ({b} : finset β).inf' h f = f b := rfl lemma le_inf' {a : α} (hs : ∀ b ∈ s, a ≤ f b) : a ≤ s.inf' H f := @sup'_le (order_dual α) _ _ _ H f _ hs lemma inf'_le {b : β} (h : b ∈ s) : s.inf' ⟨b, h⟩ f ≤ f b := @le_sup' (order_dual α) _ _ _ f _ h @[simp] lemma inf'_const (a : α) : s.inf' H (λ b, a) = a := @sup'_const (order_dual α) _ _ _ _ _ @[simp] lemma le_inf'_iff {a : α} : a ≤ s.inf' H f ↔ ∀ b ∈ s, a ≤ f b := @sup'_le_iff (order_dual α) _ _ _ H f _ @[simp] lemma lt_inf'_iff [is_total α (≤)] {a : α} : a < s.inf' H f ↔ (∀ b ∈ s, a < f b) := @sup'_lt_iff (order_dual α) _ _ _ H f _ _ @[simp] lemma inf'_le_iff [is_total α (≤)] {a : α} : s.inf' H f ≤ a ↔ (∃ b ∈ s, f b ≤ a) := @le_sup'_iff (order_dual α) _ _ _ H f _ _ @[simp] lemma inf'_lt_iff [is_total α (≤)] {a : α} : s.inf' H f < a ↔ (∃ b ∈ s, f b < a) := @lt_sup'_iff (order_dual α) _ _ _ H f _ _ 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 (order_dual α) _ (order_dual γ) _ _ _ H f g g_inf lemma inf'_induction {p : α → Prop} (hp : ∀ (a₁ a₂ : α), p a₁ → p a₂ → p (a₁ ⊓ a₂)) (hs : ∀ b ∈ s, p (f b)) : p (s.inf' H f) := @sup'_induction (order_dual α) _ _ _ H f _ hp hs lemma exists_mem_eq_inf' [is_total α (≤)] : ∃ b, b ∈ s ∧ s.inf' H f = f b := @exists_mem_eq_sup' (order_dual α) _ _ _ H f _ 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 end inf' section sup variable [semilattice_sup_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)) (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⦄, a ∈ s → b ∈ s → a ⊔ b ∈ s) : t.sup id ∈ s := sup'_eq_sup htne id ▸ sup'_induction _ _ h h_subset lemma exists_mem_eq_sup [is_total α (≤)] (s : finset β) (h : s.nonempty) (f : β → α) : ∃ b, b ∈ s ∧ s.sup f = f b := sup'_eq_sup h f ▸ exists_mem_eq_sup' h f end sup section inf variable [semilattice_inf_top α] lemma inf'_eq_inf {s : finset β} (H : s.nonempty) (f : β → α) : s.inf' H f = s.inf f := @sup'_eq_sup (order_dual α) _ _ _ H f lemma inf_closed_of_inf_closed {s : set α} (t : finset α) (htne : t.nonempty) (h_subset : ↑t ⊆ s) (h : ∀⦃a b⦄, a ∈ s → b ∈ s → a ⊓ b ∈ s) : t.inf id ∈ s := @sup_closed_of_sup_closed (order_dual α) _ _ t htne h_subset h lemma exists_mem_eq_inf [is_total α (≤)] (s : finset β) (h : s.nonempty) (f : β → α) : ∃ a, a ∈ s ∧ s.inf f = f a := @exists_mem_eq_sup (order_dual α) _ _ _ _ h f end inf section sup variables {C : β → Type*} [Π (b : β), semilattice_sup_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_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, order_dual (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, order_dual (C b)) _ _ H f b end inf' /-! ### 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 `none` otherwise. It belongs to `option α`. If you want to get an element of `α`, see `s.max'`. -/ protected def max : finset α → option α := fold (option.lift_or_get max) none some theorem max_eq_sup_with_bot (s : finset α) : s.max = @sup (with_bot α) α _ s some := rfl @[simp] theorem max_empty : (∅ : finset α).max = none := rfl @[simp] theorem max_insert {a : α} {s : finset α} : (insert a s).max = option.lift_or_get max (some a) s.max := fold_insert_idem @[simp] theorem max_singleton {a : α} : finset.max {a} = some a := by { rw [← insert_emptyc_eq], exact max_insert } theorem max_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.max := (@le_sup (with_bot α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem max_of_nonempty {s : finset α} (h : s.nonempty) : ∃ a, a ∈ s.max := let ⟨a, ha⟩ := h in max_of_mem ha theorem max_eq_none {s : finset α} : s.max = none ↔ 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 : α}, a ∈ s.max → a ∈ s := finset.induction_on s (λ _ H, by cases H) (λ b s _ (ih : ∀ {a}, a ∈ s.max → a ∈ s) a (h : a ∈ (insert b s).max), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice max_choice (some 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) theorem le_max_of_mem {s : finset α} {a b : α} (h₁ : a ∈ s) (h₂ : b ∈ s.max) : a ≤ b := by rcases @le_sup (with_bot α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption /-- Let `s` be a finset in a linear order. Then `s.min` is the minimum of `s` if `s` is not empty, and `none` otherwise. It belongs to `option α`. If you want to get an element of `α`, see `s.min'`. -/ protected def min : finset α → option α := fold (option.lift_or_get min) none some theorem min_eq_inf_with_top (s : finset α) : s.min = @inf (with_top α) α _ s some := rfl @[simp] theorem min_empty : (∅ : finset α).min = none := rfl @[simp] theorem min_insert {a : α} {s : finset α} : (insert a s).min = option.lift_or_get min (some a) s.min := fold_insert_idem @[simp] theorem min_singleton {a : α} : finset.min {a} = some a := by { rw ← insert_emptyc_eq, exact min_insert } theorem min_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.min := (@inf_le (with_top α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem min_of_nonempty {s : finset α} (h : s.nonempty) : ∃ a, a ∈ s.min := let ⟨a, ha⟩ := h in min_of_mem ha theorem min_eq_none {s : finset α} : s.min = none ↔ 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 : α}, a ∈ s.min → a ∈ s := @mem_of_max (order_dual α) _ s theorem min_le_of_mem {s : finset α} {a b : α} (h₁ : b ∈ s) (h₂ : a ∈ s.min) : a ≤ b := by rcases @inf_le (with_top α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption /-- 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 `option α`. -/ def min' (s : finset α) (H : s.nonempty) : α := @option.get _ s.min $ let ⟨k, hk⟩ := H in let ⟨b, hb⟩ := min_of_mem hk in by simp at hb; simp [hb] /-- 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 `option α`. -/ def max' (s : finset α) (H : s.nonempty) : α := @option.get _ s.max $ let ⟨k, hk⟩ := H in let ⟨b, hb⟩ := max_of_mem hk in by simp at hb; simp [hb] variables (s : finset α) (H : s.nonempty) theorem min'_mem : s.min' H ∈ s := mem_of_min $ by simp [min'] theorem min'_le (x) (H2 : x ∈ s) : s.min' ⟨x, H2⟩ ≤ x := min_le_of_mem H2 $ option.get_mem _ 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'] theorem le_max' (x) (H2 : x ∈ s) : x ≤ s.max' ⟨x, H2⟩ := le_max_of_mem H2 $ option.get_mem _ 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 /-- `{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 max'_eq_of_dual_min' {s : finset α} (hs : s.nonempty) : max' s hs = of_dual (min' (image to_dual s) (nonempty.image hs to_dual)) := begin rw [of_dual, to_dual, equiv.coe_fn_mk, equiv.coe_fn_symm_mk, id.def], simp_rw (@image_id (order_dual α) (s : finset (order_dual α))), refl, end lemma min'_eq_of_dual_max' {s : finset α} (hs : s.nonempty) : min' s hs = of_dual (max' (image to_dual s) (nonempty.image hs to_dual)) := begin rw [of_dual, to_dual, equiv.coe_fn_mk, equiv.coe_fn_symm_mk, id.def], simp_rw (@image_id (order_dual α) (s : finset (order_dual α))), refl, end @[simp] lemma of_dual_max_eq_min_of_dual {a b : α} : of_dual (max a b) = min (of_dual a) (of_dual b) := rfl @[simp] lemma of_dual_min_eq_max_of_dual {a b : α} : of_dual (min a b) = max (of_dual a) (of_dual b) := rfl 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 _ } /-- 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 hn : s.card with n ihn generalizing s, { rwa [card_eq_zero.1 hn] }, { have A : s.nonempty, from card_pos.1 (hn.symm ▸ n.succ_pos), have B : s.max' A ∈ s, from max'_mem s A, rw [← insert_erase B], refine step _ _ (λ x hx, _) (ihn _ _), { rw [mem_erase] at hx, exact (le_max' s x hx.2).lt_of_ne hx.1 }, { rw [card_erase_of_mem B, hn, nat.pred_succ] } } 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 (order_dual α) _ _ _ s h0 step end max_min 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_mem (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 (order_dual α) β _ s f h end exists_max_min end finset namespace multiset lemma count_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], } end finset section lattice variables {ι : Type*} {ι' : 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_refl _) (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 (order_dual α) _ _ _ /-- 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' (order_dual α) _ _ _ end lattice namespace set variables {ι : Type*} {ι' : 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 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 { congr, ext, rw [option.mem_to_finset] } lemma infi_option_to_finset (o : option α) (f : α → β) : (⨅ x ∈ o.to_finset, f x) = ⨅ x ∈ o, f x := @supr_option_to_finset _ (order_dual β) _ _ _ 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) := by simp [infi_or, infi_inf_eq] 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) := by { rw insert_eq, simp only [infi_union, finset.infi_singleton] } 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_bot β] (f : γ → α) (g : α → β) (s : finset γ) : (s.image f).sup g = s.sup (g ∘ f) := begin classical, apply finset.induction_on s, { simp }, { intros a s' ha ih, rw [sup_insert, image_insert, sup_insert, ih] } 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 α (order_dual β) _ _ _ _ f _ hx lemma supr_bUnion (s : finset γ) (t : γ → finset α) (f : α → β) : (⨆ y ∈ s.bUnion t, f y) = ⨆ (x ∈ s) (y ∈ t x), f y := calc (⨆ y ∈ s.bUnion t, f y) = ⨆ y (hy : ∃ x ∈ s, y ∈ t x), f y : congr_arg _ $ funext $ λ y, by rw [mem_bUnion] ... = _ : by simp only [supr_exists, @supr_comm _ α] lemma infi_bUnion (s : finset γ) (t : γ → finset α) (f : α → β) : (⨅ y ∈ s.bUnion t, f y) = ⨅ (x ∈ s) (y ∈ t x), f y := @supr_bUnion _ (order_dual β) _ _ _ _ _ _ end lattice @[simp] theorem set_bUnion_coe (s : finset α) (t : α → set β) : (⋃ x ∈ (↑s : set α), t x) = ⋃ x ∈ s, t x := rfl @[simp] theorem set_bInter_coe (s : finset α) (t : α → set β) : (⋂ x ∈ (↑s : set α), t x) = ⋂ x ∈ s, t x := rfl @[simp] theorem set_bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : finset α), s x) = s a := supr_singleton a s @[simp] 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 @[simp] 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 @[simp] 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 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 @[simp] 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 @[simp] 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 @[simp] lemma set_bUnion_finset_image {f : γ → α} {g : α → set β} {s : finset γ} : (⋃x ∈ s.image f, g x) = (⋃y ∈ s, g (f y)) := supr_finset_image @[simp] 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 @[simp] 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 @[simp] 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
#ifndef ASSOCIATIVE_TEST_BENCH_HPP #define ASSOCIATIVE_TEST_BENCH_HPP #include <string> #include <boost/optional.hpp> #include "../util/parameters.hpp" #include "../env/environment.hpp" namespace associative { namespace test { class TestParameters { private: static Parameters* parameters; public: static Parameters& get(); static bool parseCommandLine(int argc, char** argv); }; class Bench { public: boost::shared_ptr<Logger> logger; boost::shared_ptr<Process> process; boost::shared_ptr<Connection> conn; boost::shared_ptr<VFS> vfs; Environment env; Bench(const Parameters& parameters); virtual ~Bench(); Bench& operator=(Bench&) = delete; Bench(Bench&) = delete; }; } } #endif
import numpy as np import cPickle as pickle import scipy import combo from Objectives.ObjFunc import IndTimeModel from IPython import embed import os, sys # from pyDOE import lhs # objective_model = IndTimeModel(problemID="QU_GR",noisy=True) # from scipy.stats.qmc import LatinHypercube if len(sys.argv)!=2: sys.exit("Script needs an integer argument to be used as the batch index.") else: batch = int(sys.argv[1]) print("Running batch "+str(batch)) class simulator: def __init__(self): self.objective_model = IndTimeModel(problemID="QU_GR",noisy=True) b = self.objective_model.bounds Ngrid = 25 x = []; lengthscales = []; m= []; n = [] for i in range(b.shape[0]): x.append(np.linspace(b[i][0],b[i][1],Ngrid)) lengthscales.append(abs(b[i][1]-b[i][0])/10.) m.append(max(b[i][0],b[i][1])) n.append(min(b[i][0],b[i][1])) self.lengthscales = np.array(lengthscales) r = np.meshgrid(*x) action_size = Ngrid**b.shape[0] X = np.empty((action_size,b.shape[0])) for i in range(b.shape[0]): X[:,[i]] = r[i].reshape(-1,1) # engine = LatinHypercube(d=b.shape[0]) # sample = engine.random(n=action_size) # embed() # sample = np.array(n).reshape((1,b.shape[0]))+np.dot(np.random.rand(action_size,b.shape[0]),np.diag(np.array(m)-np.array(n)))# lhs(action_size, [samples, criterion, iterations]) self.X = X # self.X = sample def getsamples(self,Ngrid = 25): b = self.objective_model.bounds m= []; n = []; action_size = Ngrid**b.shape[0] for i in range(b.shape[0]): m.append(max(b[i][0],b[i][1])) n.append(min(b[i][0],b[i][1])) return np.array(n).reshape((1,b.shape[0]))+np.dot(np.random.rand(action_size,b.shape[0]),np.diag(np.array(m)-np.array(n))) def __call__(self,action): r = self.X[action,:] # embed() x = self.objective_model.evaluate(r) return -x[0][0] def compute_regret(self,action_best,policy): # embed() x = policy.test.X[action_best.astype(int).tolist(),:] y = self.objective_model.evaluate_true(x) return y - self.objective_model.f_opt sim = simulator() X = sim.X #combo.misc.centering( sim.X ) model = combo.gp.core.model(cov = combo.gp.cov.gauss( num_dim = None, ard = False ), mean = combo.gp.mean.const(), lik = combo.gp.lik.gauss()) # params are taken by combo as [noise_std_dev,prior_mean,kernel_var_scale,kernel_len_scale_inv] for the sq. exp kernel (kernel_var_scale^2)*e^{-0.5*(x-y)^2*kernel_len_scale_inv^2} params = np.array([1,0,1,np.min(sim.lengthscales)**(-1)]) model.set_params(params) predictor = combo.gp.predictor(config=None, model = model) policy = combo.search.discrete.policy(test_X=X) # policy.set_seed( 0 ) res = policy.random_search(max_num_probes=1, simulator=sim) # embed() # res = policy.bayes_search(max_num_probes=200, simulator=sim, score='EI', # interval=10,num_search_each_probe=1,num_rand_basis=5000) #predictor=predictor # embed() Bs= 2000/10 x_comp = np.empty((0,X.shape[1])) regrets = np.empty((0,1)) for i in range(Bs): # policy = combo.search.discrete.policy(test_X=sim.getsamples()) policy.test = policy._set_test(np.vstack((x_comp,sim.getsamples()))) res = policy.bayes_search(max_num_probes=10, simulator=sim, score='EI', interval=-1,num_search_each_probe=1, predictor=predictor) best_fx, best_action = res.export_all_sequence_best_fx() x_comp = policy.test.X #[best_action[-1].astype(int).tolist(),:] # regrets = np.vstack((regrets,sim.compute_regret(best_action,policy))) # embed() print 'f(x)=' print -res.fx[0:res.total_num_search] best_fx, best_action = res.export_all_sequence_best_fx() print 'current best' print -best_fx print 'current best action=' print best_action print 'history of chosed actions=' print res.chosed_actions[0:res.total_num_search] # embed() basedir = os.path.join('results_GP12','batch'+str(batch)) if not os.path.exists(basedir): os.makedirs(basedir) regrets = sim.compute_regret(best_action,policy) np.save(os.path.join(basedir,'com_regrets.npy'),regrets) res.save(os.path.join(basedir,'results.npz')) del res # load the results # res = combo.search.discrete.results.history() # res.load('test.npz') # embed()
(* Title: Small-Gain Theorem Author: Omar A. Jasim <[email protected]>, Sandor M. Veres <[email protected]> Maintainer: Omar A. Jasim <[email protected]>, Sandor M. Veres <[email protected]> *) theory Small_Gain_Theorem imports "~~/src/HOL/Probability/Analysis" "~~/src/HOL/Probability/Probability" "~~/src/HOL/Library/Function_Algebras" "~~/L2Norm_Integral" begin section \<open> Definitions of Signals\<close> text \<open>Time Interval Definition\<close> definition T :: "real set" where "T ={t. (0\<le>t \<and> t<\<infinity>)}" definition T\<^sub>\<tau> :: "real set" where "T\<^sub>\<tau> ={t. (\<forall>\<tau>\<in>T. 0\<le>t \<and> t\<le>\<tau> )}" lemma T\<^sub>\<tau>_subset_T: "T\<^sub>\<tau> \<subseteq> T" using T\<^sub>\<tau>_def T_def by auto text \<open>Signal Range Definition\<close> definition R :: "real set" where "R ={r. (-\<infinity><r \<and> r<\<infinity>)}" text \<open>Signal Definition\<close> definition Signal ::"(real \<Rightarrow> real) \<Rightarrow> bool" where "Signal u = (\<forall>t\<in>T. \<exists>!x\<in>R. x = u t \<and> u:T\<rightarrow>R \<and> u t\<in> u ` T \<and> u piecewise_differentiable_on T \<and> continuous_on T u)" lemma signal_integration_bound: fixes M assumes "Signal u" and "set_integrable M T u" shows "(LINT t:T|M. (u t)\<^sup>2) < \<infinity>" using assms by simp lemma sig1: "Signal u \<Longrightarrow> \<forall>t\<in>T. u t \<in> range (\<lambda>t\<in>T. u t)" by auto lemma sig2: "Signal u \<Longrightarrow> \<forall>t\<in>T. u t \<in> R" using Signal_def by blast lemma sig3: "Signal u \<Longrightarrow> range (\<lambda>t\<in>T. u t) \<subseteq> R" unfolding Signal_def by (simp add:R_def) lemma sig4: "Signal u \<Longrightarrow>\<forall> A. range (\<lambda>t\<in>T. u t) = (\<lambda>t\<in>T. u t) ` A \<Longrightarrow> A\<subseteq>T " using Signal_def by blast section \<open>Definitions of Signals Space\<close> consts signal_prod :: " real \<Rightarrow> 'a \<Rightarrow> 'a " (infixl "\<cdot>" 70) text \<open>\<open>Domain Space Definition\<close>\<close> locale Domain_Space = fixes D :: "(real \<Rightarrow> real) set" assumes non_empty_D [iff, intro?]: "D \<noteq> {}" and spaceD_mem [iff]: "range (\<lambda>t\<in>T. u t)\<subseteq>R \<Longrightarrow>\<lbrakk>range (\<lambda>t\<in>T. u t) = (\<lambda>t\<in>T. u t)`A \<Longrightarrow>A\<subseteq>T\<rbrakk>\<Longrightarrow>(\<lambda>t\<in>T. u t)\<in>D" and spaceD_add1[iff]: "u\<in>D \<Longrightarrow> s\<in>D \<Longrightarrow> u + s \<in> D" and spaceD_add2[simp]:"u\<in>D \<Longrightarrow> s\<in>D \<Longrightarrow> u + s = (\<lambda>t\<in>T. u t + s t)" and spaceD_add3 : "u\<in>D \<Longrightarrow> s\<in>D \<Longrightarrow> u + s = s + u" and spaceD_add_assoc: "u\<in>D \<Longrightarrow> s\<in>D \<Longrightarrow> g\<in>D \<Longrightarrow> (u + s) + g = u + (s + g) " and spaceD_pointwise[simp]:"u\<in>D \<Longrightarrow> s\<in>D \<Longrightarrow>\<forall>t\<in>T. (u + s)t = u t + s t" and spaceD_sub[iff]: "u\<in>D \<Longrightarrow> s\<in>D \<Longrightarrow> u - s \<in> D" and spaceD_mult1[iff]: "u\<in>D \<Longrightarrow>a\<in>\<real>\<Longrightarrow> (a \<cdot> u) \<in>D" and spaceD_mult2: "u\<in>D \<Longrightarrow>a\<in>\<real>\<Longrightarrow>\<forall>t\<in>T. (a \<cdot> u)t = a * u t" and spaceD_mult_distr1: "u\<in>D \<Longrightarrow> s\<in>D \<Longrightarrow>a\<in>\<real>\<Longrightarrow> a \<cdot> (u + s) = a \<cdot> u + a \<cdot> s" and spaceD_mult_distr2: "u\<in>D \<Longrightarrow> s\<in>D \<Longrightarrow>a\<in>\<real>\<Longrightarrow>\<forall>t\<in>T. a \<cdot> (u + s)t = a * u t + a * s t" and spaceD_mult_distr3: "u\<in>D \<Longrightarrow>a\<in>\<real>\<Longrightarrow>b\<in>\<real>\<Longrightarrow> (a + b) \<cdot> u = a \<cdot> u + b \<cdot> u" and spaceD_mult_assoc: "u\<in>D \<Longrightarrow>a\<in>\<real>\<Longrightarrow>b\<in>\<real>\<Longrightarrow> (a * b) \<cdot> u = a \<cdot> (b \<cdot> u)" text \<open>\<open>Range Space Definition\<close>\<close> locale Range_Space = fixes G :: "(real \<Rightarrow> real) set" assumes non_empty_G [iff, intro?]: "G \<noteq> {}" and spaceG_mem[iff]: "range (\<lambda>t\<in>T. y t)\<subseteq>R \<Longrightarrow> \<lbrakk>range (\<lambda>t\<in>T. y t) = (\<lambda>t\<in>T. y t)`B \<Longrightarrow>B\<subseteq>T\<rbrakk> \<Longrightarrow> (\<lambda>t\<in>T. y t)\<in>G" and spaceG_add1[iff]: "y\<in>G \<Longrightarrow> z\<in>G \<Longrightarrow> y + z \<in>G" and spaceG_add2[simp]:"y\<in>G \<Longrightarrow> z\<in>G \<Longrightarrow> y + z = (\<lambda>t\<in>T. y t + z t)" and spaceG_add3 : "y\<in>G \<Longrightarrow> z\<in>G \<Longrightarrow> y + z = z + y" and spaceG_add_assoc: "y\<in>G \<Longrightarrow> z\<in>G \<Longrightarrow> j\<in>G \<Longrightarrow> (y + z) + j = y + (z + j) " and spaceG_pointwise[simp]:"y\<in>G \<Longrightarrow> z\<in>G \<Longrightarrow>\<forall>t\<in>T. (y + z)t = y t + z t" and spaceG_mult1[iff]: "y\<in>G \<Longrightarrow>a\<in>\<real>\<Longrightarrow> (a \<cdot> y) \<in>G" and spaceG_mult2 : "y\<in>G \<Longrightarrow>a\<in>\<real>\<Longrightarrow>\<forall>t\<in>T. (a \<cdot> y)t = a * y t" and spaceG_mult_distr1 : "y\<in>G \<Longrightarrow> z\<in>G \<Longrightarrow>a\<in>\<real>\<Longrightarrow> a \<cdot> (y + z) = a \<cdot> y + a \<cdot> z" and spaceG_mult_distr2 : "y\<in>G \<Longrightarrow> z\<in>G \<Longrightarrow>a\<in>\<real>\<Longrightarrow>\<forall>t\<in>T. a \<cdot> (y + z)t = a * y t + a * z t" and spaceG_mult_distr3 : "y\<in>G \<Longrightarrow>a\<in>\<real>\<Longrightarrow>b\<in>\<real>\<Longrightarrow> (a + b) \<cdot> y = a \<cdot> y + b \<cdot> y" and spaceG_mult_assoc : "y\<in>G \<Longrightarrow>a\<in>\<real>\<Longrightarrow>b\<in>\<real>\<Longrightarrow> (a * b) \<cdot> y = a \<cdot> (b \<cdot> y)" text \<open>\<open>Operator Space Definition\<close>\<close> locale Operator_Space = fixes OP :: "((real \<Rightarrow> real) \<Rightarrow> (real \<Rightarrow> real)) set" assumes non_empty_OP [iff, intro?]: "OP \<noteq> {}" and spaceG_mem [iff]:"Domain_Space D \<Longrightarrow> Range_Space G \<Longrightarrow> H\<in>OP" and asm_op1 [iff] : "H\<in>OP \<Longrightarrow>Domain_Space D\<Longrightarrow>Range_Space G\<Longrightarrow> H: D\<rightarrow>G " and asm_op2 [iff] : "H\<in>OP \<Longrightarrow>Domain_Space D\<Longrightarrow>Range_Space G\<Longrightarrow> H: G\<rightarrow>D " and asm_op3 [iff] : "H\<in>OP \<Longrightarrow>range H \<subseteq> T\<rightarrow>R" and asm_op4 [iff] : "H\<in>OP \<Longrightarrow>Domain_Space D\<Longrightarrow>Range_Space G\<Longrightarrow> H: D\<rightarrow>G \<Longrightarrow>range H = H`D \<Longrightarrow>D \<subseteq> T\<rightarrow>R " and asm_op5 [iff] : "H\<in>OP \<Longrightarrow>Domain_Space D\<Longrightarrow>Range_Space G\<Longrightarrow> H: G\<rightarrow>D \<Longrightarrow>range H = H`G \<Longrightarrow>G \<subseteq> T\<rightarrow>R " and asm_op6 : "H\<in>OP \<Longrightarrow> Domain_Space D \<Longrightarrow> Range_Space G \<Longrightarrow> s\<in>D \<Longrightarrow> z\<in>G \<Longrightarrow> z= H(s)" definition Signal_Y :: "(real \<Rightarrow> real) \<Rightarrow> ((real \<Rightarrow> real) \<Rightarrow> real \<Rightarrow> real) \<Rightarrow> (real \<Rightarrow> real) \<Rightarrow> ((real \<Rightarrow> real) \<Rightarrow> real \<Rightarrow> real) set \<Rightarrow> bool" where "Signal_Y y H e OP = (\<forall>a. \<exists>!b. (a=e \<and> b=y \<and>Operator_Space OP \<and> H\<in>OP \<and> range y \<subseteq> R ) \<longrightarrow> y = H e )" (* signal truncation *) definition trunc :: "(real \<Rightarrow> real) \<Rightarrow> (real \<Rightarrow> real) \<Rightarrow> real set \<Rightarrow> real set \<Rightarrow> bool" where "trunc u u\<^sub>\<tau> U U\<^sub>\<tau> = (Signal u \<and> u ` T = U \<and> (\<forall>\<tau>\<in>T. \<forall>t\<in>T. if t\<le>\<tau> then ((u t\<in>U \<longrightarrow> u t\<in>U\<^sub>\<tau>) \<and> u t = u\<^sub>\<tau> t) else ((u t\<in>U \<longrightarrow> 0\<in>U\<^sub>\<tau>) \<and> u\<^sub>\<tau> t=0 )))" text \<open>\<open>Truncation Space Definition\<close>\<close> locale TR_Space = fixes TR :: "(real \<Rightarrow> real) set" assumes non_empty_TR [iff, intro?]: "TR \<noteq> {}" and spaceTR_mem [iff]: "trunc u u\<^sub>\<tau> U U\<^sub>\<tau> \<Longrightarrow> (\<lambda>t\<in>T\<^sub>\<tau>. u\<^sub>\<tau> t)\<in>TR" and spaceTR_1: "trunc u u\<^sub>\<tau> U U\<^sub>\<tau>\<Longrightarrow> u\<^sub>\<tau>\<in>TR \<Longrightarrow> U\<^sub>\<tau> \<inter> U = u\<^sub>\<tau> ` T\<^sub>\<tau>" and spaceTR_2[iff]: "trunc u\<^sub>1 u\<^sub>1\<^sub>\<tau> U\<^sub>1 U\<^sub>1\<^sub>\<tau>\<Longrightarrow>trunc u\<^sub>2 u\<^sub>2\<^sub>\<tau> U\<^sub>2 U\<^sub>2\<^sub>\<tau>\<Longrightarrow> e\<^sub>1\<^sub>\<tau>= u\<^sub>1\<^sub>\<tau> - (H\<^sub>2 e\<^sub>2\<^sub>\<tau>) \<Longrightarrow> e\<^sub>2\<^sub>\<tau>= u\<^sub>2\<^sub>\<tau> + (H\<^sub>1 e\<^sub>1\<^sub>\<tau>) \<Longrightarrow>u\<^sub>1\<^sub>\<tau>\<in>TR\<Longrightarrow>u\<^sub>2\<^sub>\<tau>\<in>TR\<Longrightarrow>e\<^sub>1\<^sub>\<tau>\<in>TR" and spaceTR_3[iff]: "trunc u\<^sub>1 u\<^sub>1\<^sub>\<tau> U\<^sub>1 U\<^sub>1\<^sub>\<tau>\<Longrightarrow>trunc u\<^sub>2 u\<^sub>2\<^sub>\<tau> U\<^sub>2 U\<^sub>2\<^sub>\<tau>\<Longrightarrow> e\<^sub>1\<^sub>\<tau>= u\<^sub>1\<^sub>\<tau> - (H\<^sub>2 e\<^sub>2\<^sub>\<tau>) \<Longrightarrow> e\<^sub>2\<^sub>\<tau>= u\<^sub>2\<^sub>\<tau> + (H\<^sub>1 e\<^sub>1\<^sub>\<tau>) \<Longrightarrow>u\<^sub>1\<^sub>\<tau>\<in>TR\<Longrightarrow>u\<^sub>2\<^sub>\<tau>\<in>TR\<Longrightarrow>e\<^sub>2\<^sub>\<tau>\<in>TR" and spaceTR_4[iff]: "trunc u\<^sub>1 u\<^sub>1\<^sub>\<tau> U\<^sub>1 U\<^sub>1\<^sub>\<tau>\<Longrightarrow>trunc u\<^sub>2 u\<^sub>2\<^sub>\<tau> U\<^sub>2 U\<^sub>2\<^sub>\<tau>\<Longrightarrow> e\<^sub>1\<^sub>\<tau>= u\<^sub>1\<^sub>\<tau> - (H\<^sub>2 e\<^sub>2\<^sub>\<tau>) \<Longrightarrow> e\<^sub>2\<^sub>\<tau>= u\<^sub>2\<^sub>\<tau> + (H\<^sub>1 e\<^sub>1\<^sub>\<tau>) \<Longrightarrow> Signal_Y y\<^sub>1\<^sub>\<tau> H\<^sub>1 e\<^sub>1\<^sub>\<tau> OP \<Longrightarrow>u\<^sub>1\<^sub>\<tau>\<in>TR\<Longrightarrow>u\<^sub>2\<^sub>\<tau>\<in>TR\<Longrightarrow>e\<^sub>1\<^sub>\<tau>\<in>TR\<Longrightarrow> e\<^sub>2\<^sub>\<tau>\<in>TR \<Longrightarrow> y\<^sub>1\<^sub>\<tau>\<in>TR " and spaceTR_5[iff]: "trunc u\<^sub>1 u\<^sub>1\<^sub>\<tau> U\<^sub>1 U\<^sub>1\<^sub>\<tau>\<Longrightarrow>trunc u\<^sub>2 u\<^sub>2\<^sub>\<tau> U\<^sub>2 U\<^sub>2\<^sub>\<tau>\<Longrightarrow> e\<^sub>1\<^sub>\<tau>= u\<^sub>1\<^sub>\<tau> - (H\<^sub>2 e\<^sub>2\<^sub>\<tau>) \<Longrightarrow> e\<^sub>2\<^sub>\<tau>= u\<^sub>2\<^sub>\<tau> + (H\<^sub>1 e\<^sub>1\<^sub>\<tau>) \<Longrightarrow> Signal_Y y\<^sub>2\<^sub>\<tau> H\<^sub>2 e\<^sub>2\<^sub>\<tau> OP \<Longrightarrow>u\<^sub>1\<^sub>\<tau>\<in>TR\<Longrightarrow>u\<^sub>2\<^sub>\<tau>\<in>TR\<Longrightarrow>e\<^sub>1\<^sub>\<tau>\<in>TR\<Longrightarrow> e\<^sub>2\<^sub>\<tau>\<in>TR \<Longrightarrow> y\<^sub>2\<^sub>\<tau>\<in>TR " and spaceTR_6 : "trunc u u\<^sub>\<tau> U U\<^sub>\<tau>\<Longrightarrow>Signal_Y y H e OP\<Longrightarrow> Signal_Y y\<^sub>\<tau> H e\<^sub>\<tau> OP\<Longrightarrow> e\<^sub>\<tau>\<in>TR \<Longrightarrow> y\<^sub>\<tau>\<in>TR \<Longrightarrow> y\<^sub>\<tau> ` T\<^sub>\<tau> \<subseteq> range y\<^sub>\<tau> \<inter> range y" (* Some lemmas for truncation definition *) lemma tr1:"trunc u u\<^sub>\<tau> U U\<^sub>\<tau> \<Longrightarrow> \<exists>t\<in>T. u\<^sub>\<tau> t\<in>U\<^sub>\<tau> " unfolding trunc_def using T_def by force lemma tr1a:"trunc u u\<^sub>\<tau> U U\<^sub>\<tau> \<Longrightarrow> \<forall>t\<in>T\<^sub>\<tau>. u\<^sub>\<tau> t\<in>U\<^sub>\<tau> " unfolding trunc_def using T\<^sub>\<tau>_subset_T subset_eq by fastforce lemma tr1b:" trunc u u\<^sub>\<tau> U U\<^sub>\<tau> \<Longrightarrow>\<forall>\<tau>\<in>T. \<forall>t\<in>T. t>\<tau> \<longrightarrow> 0\<in>U\<^sub>\<tau> " unfolding trunc_def using T_def by force lemma tr1c:" trunc u u\<^sub>\<tau> U U\<^sub>\<tau> \<Longrightarrow>\<forall>\<tau>\<in>T. \<forall>t\<in>T. t>\<tau> \<and> t\<notin>T\<^sub>\<tau> \<longrightarrow> 0\<in>U\<^sub>\<tau> " unfolding trunc_def using T_def by fastforce lemma tr1d:"trunc u u\<^sub>\<tau> U U\<^sub>\<tau> \<Longrightarrow> u\<^sub>\<tau> ` T\<^sub>\<tau> \<subseteq> U\<^sub>\<tau>" unfolding trunc_def using T\<^sub>\<tau>_subset_T by force lemma tr1e:"trunc u u\<^sub>\<tau> U U\<^sub>\<tau> \<Longrightarrow> u\<^sub>\<tau> ` T\<^sub>\<tau> \<subseteq> U" unfolding trunc_def using T\<^sub>\<tau>_subset_T by force lemma tr1f:"trunc u u\<^sub>\<tau> U U\<^sub>\<tau> \<Longrightarrow> u\<^sub>\<tau> ` T\<^sub>\<tau> \<subseteq> u ` T" unfolding trunc_def using T\<^sub>\<tau>_subset_T image_iff image_subsetI subsetCE by fastforce lemma tr1g:"trunc u u\<^sub>\<tau> U U\<^sub>\<tau> \<Longrightarrow> u ` T\<^sub>\<tau> = u\<^sub>\<tau> ` T\<^sub>\<tau>" unfolding trunc_def using T\<^sub>\<tau>_subset_T by force lemma tr3:"trunc u u\<^sub>\<tau> U U\<^sub>\<tau> \<Longrightarrow>\<forall>\<tau>\<in>T. \<forall>t\<in>T. t>\<tau> \<longrightarrow> u\<^sub>\<tau> t\<in>U\<^sub>\<tau> \<and> u\<^sub>\<tau> t=0 " unfolding trunc_def by force lemma tr6:"trunc u u\<^sub>\<tau> U U\<^sub>\<tau> \<Longrightarrow> \<forall>\<tau>\<in>T. \<forall>t\<in>T. t>\<tau> \<Longrightarrow> \<forall>t\<in>T\<^sub>\<tau>. \<not>(u\<^sub>\<tau> ` T\<^sub>\<tau> \<subseteq> U) " using T\<^sub>\<tau>_subset_T by fast lemma tr7:"trunc u u\<^sub>\<tau> U U\<^sub>\<tau> \<Longrightarrow> T = T\<^sub>\<tau> \<Longrightarrow> u ` T = u\<^sub>\<tau> ` T\<^sub>\<tau> " using trunc_def by (metis tr1g) lemma tr8:"trunc u u\<^sub>\<tau> U U\<^sub>\<tau> \<Longrightarrow> (\<lambda>t\<in>T\<^sub>\<tau>. u t) = (\<lambda>t\<in>T\<^sub>\<tau>. u\<^sub>\<tau> t) " using trunc_def T\<^sub>\<tau>_def T\<^sub>\<tau>_subset_T by force lemma tr9:"trunc u u\<^sub>\<tau> U U\<^sub>\<tau> \<Longrightarrow> u\<^sub>\<tau> ` T\<^sub>\<tau> \<subseteq> U\<^sub>\<tau> \<inter> U " by (simp add: tr1d tr1e) lemma tr10:" trunc u u\<^sub>\<tau> U U\<^sub>\<tau> \<Longrightarrow>\<forall>\<tau>\<in>T. \<forall>t\<in>T. t\<le>\<tau> \<longrightarrow> u t\<in>U\<^sub>\<tau> " unfolding trunc_def by fastforce lemma tr11:" trunc u u\<^sub>\<tau> U U\<^sub>\<tau> \<Longrightarrow>\<forall>\<tau>\<in>T. \<forall>t\<in>T. t\<le>\<tau> \<longrightarrow> u\<^sub>\<tau> t\<in>U\<^sub>\<tau> " unfolding trunc_def by fastforce lemma tr12:" trunc u u\<^sub>\<tau> U U\<^sub>\<tau> \<Longrightarrow>\<forall>\<tau>\<in>T. \<forall>t\<in>T. t\<le>\<tau> \<longrightarrow> u\<^sub>\<tau> t \<in> U\<^sub>\<tau> \<inter> U " unfolding trunc_def by force (*some lemmas for output signal y*) lemma sig_Y1: "Signal_Y y H e OP \<Longrightarrow> (\<lambda>t\<in>T. y t) = H (\<lambda>t\<in>T. e t)" using Signal_Y_def by metis lemma sig_Y3: "trunc u u\<^sub>\<tau> U U\<^sub>\<tau> \<Longrightarrow> Signal_Y y\<^sub>\<tau> H e\<^sub>\<tau> OP\<Longrightarrow> (\<lambda>t\<in>T\<^sub>\<tau>. y\<^sub>\<tau> t) = H(\<lambda>t\<in>T\<^sub>\<tau>. e\<^sub>\<tau> t) " using Signal_Y_def by metis definition Causality :: "(real \<Rightarrow> real)\<Rightarrow> (real \<Rightarrow> real)\<Rightarrow> (real \<Rightarrow> real) \<Rightarrow> (real \<Rightarrow> real) \<Rightarrow> real set \<Rightarrow> real set \<Rightarrow> ((real \<Rightarrow> real) \<Rightarrow> real \<Rightarrow> real) \<Rightarrow> ((real \<Rightarrow> real) \<Rightarrow> real \<Rightarrow> real) set \<Rightarrow> (real \<Rightarrow> real) set \<Rightarrow> bool" where "Causality u u\<^sub>\<tau> e e\<^sub>\<tau> U U\<^sub>\<tau> H OP TR = ((Operator_Space OP \<and> H\<in>OP \<and> trunc u u\<^sub>\<tau> U U\<^sub>\<tau> \<and> TR_Space TR \<and> u\<^sub>\<tau>\<in>TR \<and> e\<^sub>\<tau>\<in>TR) \<longrightarrow> H (\<lambda>t\<in>T\<^sub>\<tau>. e t) = H (\<lambda>t\<in>T\<^sub>\<tau>. e\<^sub>\<tau> t))" lemma Caus1: "Operator_Space OP \<Longrightarrow>H\<in>OP \<Longrightarrow>TR_Space TR\<Longrightarrow>u\<^sub>\<tau>\<in>TR \<and> e\<^sub>\<tau>\<in>TR\<Longrightarrow>trunc u u\<^sub>\<tau> U U\<^sub>\<tau> \<Longrightarrow>Causality u u\<^sub>\<tau> e e\<^sub>\<tau> U U\<^sub>\<tau> H OP TR \<Longrightarrow> H (\<lambda>t\<in>T\<^sub>\<tau>. e t) = H (\<lambda>t\<in>T\<^sub>\<tau>. e\<^sub>\<tau> t)" using Causality_def by blast lemma sig_Y_tr:"Signal_Y y H e OP\<Longrightarrow> Causality u u\<^sub>\<tau> e e\<^sub>\<tau> U U\<^sub>\<tau> H OP TR \<Longrightarrow> (\<lambda>t\<in>T\<^sub>\<tau>. y t) = H(\<lambda>t\<in>T\<^sub>\<tau>. e\<^sub>\<tau> t)" using Signal_Y_def by metis lemma sig_Y_tr1:"Signal_Y y H e OP\<Longrightarrow> Causality u u\<^sub>\<tau> e e\<^sub>\<tau> U U\<^sub>\<tau> H OP TR \<Longrightarrow> (\<lambda>t\<in>T\<^sub>\<tau>. y\<^sub>\<tau> t) = H(\<lambda>t\<in>T\<^sub>\<tau>. e\<^sub>\<tau> t)" using Signal_Y_def by metis definition Stability :: "(real \<Rightarrow> real) \<Rightarrow> (real \<Rightarrow> real) \<Rightarrow> (real \<Rightarrow> real)\<Rightarrow> (real \<Rightarrow> real) \<Rightarrow> real set \<Rightarrow> real set \<Rightarrow> real \<Rightarrow> real \<Rightarrow> ((real \<Rightarrow> real) \<Rightarrow> real \<Rightarrow> real) \<Rightarrow> real measure \<Rightarrow> ((real \<Rightarrow> real) \<Rightarrow> real \<Rightarrow> real) set \<Rightarrow> (real \<Rightarrow> real) set \<Rightarrow> bool" where "Stability u u\<^sub>\<tau> e e\<^sub>\<tau> U U\<^sub>\<tau> \<gamma> \<beta> H M OP TR = ((Causality u u\<^sub>\<tau> e e\<^sub>\<tau> U U\<^sub>\<tau> H OP TR) \<longrightarrow> (\<exists>a. \<exists>b. a\<in>T \<and> b\<in>T \<and> \<gamma>=a \<and> \<beta>=b \<and> ((L2norm M (\<lambda>t. (H e) t) T\<^sub>\<tau>) \<le> \<gamma> * (L2norm M (\<lambda>t. e\<^sub>\<tau> t) T\<^sub>\<tau>) + \<beta>)))" lemma stb1: "Causality u u\<^sub>\<tau> e e\<^sub>\<tau> U U\<^sub>\<tau> H OP TR \<Longrightarrow> Stability u u\<^sub>\<tau> e e\<^sub>\<tau> U U\<^sub>\<tau> \<gamma> \<beta> H M OP TR \<Longrightarrow>(\<exists>\<gamma>. \<gamma>\<in>T) \<Longrightarrow> (\<exists>\<beta>. \<beta>\<in>T) \<Longrightarrow> (L2norm M (\<lambda>t. (H e) t) T\<^sub>\<tau> \<le> \<gamma> * (L2norm M (\<lambda>t. e\<^sub>\<tau> t) T\<^sub>\<tau>) + \<beta>)" using Stability_def by blast lemma stb2: "Signal_Y y H e OP\<Longrightarrow>Stability u u\<^sub>\<tau> e e\<^sub>\<tau> U U\<^sub>\<tau> \<gamma> \<beta> H M OP TR\<Longrightarrow>(\<exists>\<gamma>. \<gamma>\<in>T) \<Longrightarrow> (\<exists>\<beta>. \<beta>\<in>T) \<Longrightarrow> (L2norm M (\<lambda>t. y t) T\<^sub>\<tau> \<le> \<gamma> * (L2norm M (\<lambda>t. e\<^sub>\<tau> t) T\<^sub>\<tau>) + \<beta>)" using Stability_def Signal_Y_def by (metis (mono_tags, hide_lams) add_le_imp_le_right order_refl) section \<open>\<open>Small-Gain Theorem Definitions\<close>\<close> text \<open>Closed feedback loop interconnection\<close> lemma e1: assumes "Signal u\<^sub>1" and "Signal u\<^sub>2" and "Operator_Space OP" and "H\<^sub>1\<in>OP" and "H\<^sub>2\<in>OP" and "Domain_Space D" and "Range_Space G" and "u\<^sub>1\<in>D \<and> e\<^sub>1\<in>D \<and> H\<^sub>2 e\<^sub>2\<in>D" and "u\<^sub>2\<in>G \<and> e\<^sub>2\<in>G \<and> H\<^sub>1 e\<^sub>1\<in>G" and "e\<^sub>2 = u\<^sub>2 + (H\<^sub>1 e\<^sub>1)" shows "e\<^sub>1 = u\<^sub>1 - (H\<^sub>2 e\<^sub>2)" using assms Operator_Space.asm_op6 Operator_Space.spaceG_mem eq_iff_diff_eq_0 by fastforce lemma e2: assumes "Signal u\<^sub>1" and "Signal u\<^sub>2" and "Operator_Space OP" and "H\<^sub>1\<in>OP" and "H\<^sub>2\<in>OP" and "Domain_Space D" and "Range_Space G" and "u\<^sub>1\<in>D \<and> e\<^sub>1\<in>D \<and> H\<^sub>2 e\<^sub>2\<in>D" and "u\<^sub>2\<in>G \<and> e\<^sub>2\<in>G \<and> H\<^sub>1 e\<^sub>1\<in>G" and "e\<^sub>1 = u\<^sub>1 - (H\<^sub>2 e\<^sub>2)" shows "e\<^sub>2 = u\<^sub>2 + (H\<^sub>1 e\<^sub>1)" using assms Operator_Space.asm_op6 Operator_Space.spaceG_mem eq_iff_diff_eq_0 by fastforce lemma e1_1: assumes "Signal u\<^sub>1" and "Signal u\<^sub>2" and "Operator_Space OP" and "H\<^sub>1\<in>OP" and "H\<^sub>2\<in>OP" and "Domain_Space D" and "Range_Space G" and "Signal_Y y\<^sub>1 H\<^sub>1 e\<^sub>1 OP" and "Signal_Y y\<^sub>2 H\<^sub>2 e\<^sub>2 OP" and "u\<^sub>1\<in>D \<and> e\<^sub>1\<in>D \<and> y\<^sub>2\<in>D" and "u\<^sub>2\<in>G \<and> e\<^sub>2\<in>G \<and> y\<^sub>1\<in>G" and "e\<^sub>2 = u\<^sub>2 + y\<^sub>1" shows "e\<^sub>1 = u\<^sub>1 - y\<^sub>2" using assms by (metis Signal_Y_def) lemma e2_2: assumes "Signal u\<^sub>1" and "Signal u\<^sub>2" and "Operator_Space OP" and "H\<^sub>1\<in>OP" and "H\<^sub>2\<in>OP" and "Domain_Space D" and "Range_Space G" and "Signal_Y y\<^sub>1 H\<^sub>1 e\<^sub>1 OP" and "Signal_Y y\<^sub>2 H\<^sub>2 e\<^sub>2 OP" and "u\<^sub>1\<in>D \<and> e\<^sub>1\<in>D \<and> y\<^sub>2\<in>D" and "u\<^sub>2\<in>G \<and> e\<^sub>2\<in>G \<and> y\<^sub>1\<in>G" and "e\<^sub>1 = u\<^sub>1 - y\<^sub>2" shows "e\<^sub>2 = u\<^sub>2 + y\<^sub>1" using assms by (metis Signal_Y_def) lemma e1_11: assumes "Signal u\<^sub>1" and "Signal u\<^sub>2" and "Operator_Space OP" and "H\<^sub>1\<in>OP" and "H\<^sub>2\<in>OP" and "Domain_Space D" and "Range_Space G" and "Signal_Y y\<^sub>1 H\<^sub>1 e\<^sub>1 OP" and "Signal_Y y\<^sub>2 H\<^sub>2 e\<^sub>2 OP" and "u\<^sub>1\<in>D \<and> e\<^sub>1\<in>D \<and> y\<^sub>2\<in>D \<and> H\<^sub>2 e\<^sub>2\<in>D" and "u\<^sub>2\<in>G \<and> e\<^sub>2\<in>G \<and> y\<^sub>1\<in>G \<and> H\<^sub>1 e\<^sub>1\<in>G" and "(e\<^sub>2 = u\<^sub>2 + y\<^sub>1) " and "(e\<^sub>2 = u\<^sub>2 + (H\<^sub>1 e\<^sub>1))" shows "(e\<^sub>1 = u\<^sub>1 - y\<^sub>2) \<longleftrightarrow> (e\<^sub>1 = u\<^sub>1 - (H\<^sub>2 e\<^sub>2))" using assms by (metis (full_types) Signal_Y_def) lemma e2_22: assumes "Signal u\<^sub>1" and "Signal u\<^sub>2" and "Operator_Space OP" and "H\<^sub>1\<in>OP" and "H\<^sub>2\<in>OP" and "Domain_Space D" and "Range_Space G" and "Signal_Y y\<^sub>1 H\<^sub>1 e\<^sub>1 OP" and "Signal_Y y\<^sub>2 H\<^sub>2 e\<^sub>2 OP" and "u\<^sub>1\<in>D \<and> e\<^sub>1\<in>D \<and> y\<^sub>2\<in>D \<and> H\<^sub>2 e\<^sub>2\<in>D" and "u\<^sub>2\<in>G \<and> e\<^sub>2\<in>G \<and> y\<^sub>1\<in>G \<and> H\<^sub>1 e\<^sub>1\<in>G" and "e\<^sub>1 = u\<^sub>1 - y\<^sub>2" and "e\<^sub>1 = u\<^sub>1 - (H\<^sub>2 e\<^sub>2) " shows "(e\<^sub>2 = u\<^sub>2 + y\<^sub>1) \<longleftrightarrow> (e\<^sub>2 = u\<^sub>2 + (H\<^sub>1 e\<^sub>1))" using assms by (metis (full_types) Signal_Y_def) (* With truncation*) lemma tr_e1: assumes "Signal u\<^sub>1" and "Signal u\<^sub>2" and "trunc u\<^sub>1 u\<^sub>1\<^sub>\<tau> U\<^sub>1 U\<^sub>1\<^sub>\<tau>" and "trunc u\<^sub>2 u\<^sub>2\<^sub>\<tau> U\<^sub>2 U\<^sub>2\<^sub>\<tau>" and "Operator_Space OP" and "H\<^sub>1\<in>OP" and "H\<^sub>2\<in>OP" and "TR_Space TR" and "u\<^sub>1\<^sub>\<tau>\<in>TR \<and> u\<^sub>2\<^sub>\<tau>\<in>TR \<and> e\<^sub>1\<^sub>\<tau>\<in>TR \<and> e\<^sub>2\<^sub>\<tau>\<in>TR \<and> y\<^sub>1\<^sub>\<tau>\<in>TR \<and> y\<^sub>2\<^sub>\<tau>\<in>TR" and "Domain_Space D" and "Range_Space G" and "Causality u\<^sub>1 u\<^sub>1\<^sub>\<tau> e\<^sub>1 e\<^sub>1\<^sub>\<tau> U\<^sub>1 U\<^sub>1\<^sub>\<tau> H\<^sub>1 OP TR" and "Causality u\<^sub>2 u\<^sub>2\<^sub>\<tau> e\<^sub>2 e\<^sub>2\<^sub>\<tau> U\<^sub>2 U\<^sub>2\<^sub>\<tau> H\<^sub>2 OP TR" and "Signal_Y y\<^sub>1 H\<^sub>1 e\<^sub>1 OP" and "Signal_Y y\<^sub>2 H\<^sub>2 e\<^sub>2 OP" and "u\<^sub>1\<in>D \<and> e\<^sub>1\<in>D \<and> y\<^sub>2\<in>D \<and> H\<^sub>2 e\<^sub>2\<in>D" and "u\<^sub>2\<in>G \<and> e\<^sub>2\<in>G \<and> y\<^sub>1\<in>G \<and> H\<^sub>1 e\<^sub>1\<in>G" and "(e\<^sub>2\<^sub>\<tau> = u\<^sub>2\<^sub>\<tau> + (\<lambda>t\<in>T\<^sub>\<tau>. (H\<^sub>1 e\<^sub>1)t))" shows "e\<^sub>1\<^sub>\<tau> = u\<^sub>1\<^sub>\<tau> - (\<lambda>t\<in>T\<^sub>\<tau>. (H\<^sub>2 e\<^sub>2)t)" using assms by (metis Signal_Y_def) lemma tr_e2: assumes "Signal u\<^sub>1" and "Signal u\<^sub>2" and "trunc u\<^sub>1 u\<^sub>1\<^sub>\<tau> U\<^sub>1 U\<^sub>1\<^sub>\<tau>" and "trunc u\<^sub>2 u\<^sub>2\<^sub>\<tau> U\<^sub>2 U\<^sub>2\<^sub>\<tau>" and "Operator_Space OP" and "H\<^sub>1\<in>OP" and "H\<^sub>2\<in>OP" and "TR_Space TR" and "u\<^sub>1\<^sub>\<tau>\<in>TR \<and> u\<^sub>2\<^sub>\<tau>\<in>TR \<and> e\<^sub>1\<^sub>\<tau>\<in>TR \<and> e\<^sub>2\<^sub>\<tau>\<in>TR \<and> y\<^sub>1\<^sub>\<tau>\<in>TR \<and> y\<^sub>2\<^sub>\<tau>\<in>TR" and "Domain_Space D" and "Range_Space G" and "Causality u\<^sub>1 u\<^sub>1\<^sub>\<tau> e\<^sub>1 e\<^sub>1\<^sub>\<tau> U\<^sub>1 U\<^sub>1\<^sub>\<tau> H\<^sub>1 OP TR" and "Causality u\<^sub>2 u\<^sub>2\<^sub>\<tau> e\<^sub>2 e\<^sub>2\<^sub>\<tau> U\<^sub>2 U\<^sub>2\<^sub>\<tau> H\<^sub>2 OP TR" and "Signal_Y y\<^sub>1 H\<^sub>1 e\<^sub>1 OP" and "Signal_Y y\<^sub>2 H\<^sub>2 e\<^sub>2 OP" and "u\<^sub>1\<in>D \<and> e\<^sub>1\<in>D \<and> y\<^sub>2\<in>D \<and> H\<^sub>2 e\<^sub>2\<in>D" and "u\<^sub>2\<in>G \<and> e\<^sub>2\<in>G \<and> y\<^sub>1\<in>G \<and> H\<^sub>1 e\<^sub>1\<in>G" and "e\<^sub>1\<^sub>\<tau> = u\<^sub>1\<^sub>\<tau> - (\<lambda>t\<in>T\<^sub>\<tau>. (H\<^sub>2 e\<^sub>2)t)" shows "e\<^sub>2\<^sub>\<tau> = u\<^sub>2\<^sub>\<tau> + (\<lambda>t\<in>T\<^sub>\<tau>. (H\<^sub>1 e\<^sub>1)t)" using assms by (metis Signal_Y_def) lemma tr_e1_11: assumes "Signal u\<^sub>1" and "Signal u\<^sub>2" and "trunc u\<^sub>1 u\<^sub>1\<^sub>\<tau> U\<^sub>1 U\<^sub>1\<^sub>\<tau>" and "trunc u\<^sub>2 u\<^sub>2\<^sub>\<tau> U\<^sub>2 U\<^sub>2\<^sub>\<tau>" and "Operator_Space OP" and "H\<^sub>1\<in>OP" and "H\<^sub>2\<in>OP" and "TR_Space TR" and "u\<^sub>1\<^sub>\<tau>\<in>TR \<and> u\<^sub>2\<^sub>\<tau>\<in>TR \<and> e\<^sub>1\<^sub>\<tau>\<in>TR \<and> e\<^sub>2\<^sub>\<tau>\<in>TR \<and> y\<^sub>1\<^sub>\<tau>\<in>TR \<and> y\<^sub>2\<^sub>\<tau>\<in>TR" and "Domain_Space D" and "Range_Space G" and "Causality u\<^sub>1 u\<^sub>1\<^sub>\<tau> e\<^sub>1 e\<^sub>1\<^sub>\<tau> U\<^sub>1 U\<^sub>1\<^sub>\<tau> H\<^sub>1 OP TR" and "Causality u\<^sub>2 u\<^sub>2\<^sub>\<tau> e\<^sub>2 e\<^sub>2\<^sub>\<tau> U\<^sub>2 U\<^sub>2\<^sub>\<tau> H\<^sub>2 OP TR" and "Signal_Y y\<^sub>1 H\<^sub>1 e\<^sub>1 OP" and "Signal_Y y\<^sub>2 H\<^sub>2 e\<^sub>2 OP" and "u\<^sub>1\<in>D \<and> e\<^sub>1\<in>D \<and> y\<^sub>2\<in>D \<and> H\<^sub>2 e\<^sub>2\<in>D" and "u\<^sub>2\<in>G \<and> e\<^sub>2\<in>G \<and> y\<^sub>1\<in>G \<and> H\<^sub>1 e\<^sub>1\<in>G" and "(e\<^sub>2\<^sub>\<tau> = u\<^sub>2\<^sub>\<tau> + (\<lambda>t\<in>T\<^sub>\<tau>. y\<^sub>1 t)) " and "(e\<^sub>2\<^sub>\<tau> = u\<^sub>2\<^sub>\<tau> + (\<lambda>t\<in>T\<^sub>\<tau>. (H\<^sub>1 e\<^sub>1)t))" shows "(e\<^sub>1\<^sub>\<tau> = u\<^sub>1\<^sub>\<tau> - (\<lambda>t\<in>T\<^sub>\<tau>. y\<^sub>2 t)) \<longleftrightarrow> (e\<^sub>1\<^sub>\<tau> = u\<^sub>1\<^sub>\<tau> - (\<lambda>t\<in>T\<^sub>\<tau>. (H\<^sub>2 e\<^sub>2)t))" using assms by (metis (full_types) sig_Y_tr1) lemma tr_e2_22: assumes "Signal u\<^sub>1" and "Signal u\<^sub>2" and "trunc u\<^sub>1 u\<^sub>1\<^sub>\<tau> U\<^sub>1 U\<^sub>1\<^sub>\<tau>" and "trunc u\<^sub>2 u\<^sub>2\<^sub>\<tau> U\<^sub>2 U\<^sub>2\<^sub>\<tau>" and "Operator_Space OP" and "H\<^sub>1\<in>OP" and "H\<^sub>2\<in>OP" and "TR_Space TR" and "u\<^sub>1\<^sub>\<tau>\<in>TR \<and> u\<^sub>2\<^sub>\<tau>\<in>TR \<and> e\<^sub>1\<^sub>\<tau>\<in>TR \<and> e\<^sub>2\<^sub>\<tau>\<in>TR \<and> y\<^sub>1\<^sub>\<tau>\<in>TR \<and> y\<^sub>2\<^sub>\<tau>\<in>TR" and "Domain_Space D" and "Range_Space G" and "Causality u\<^sub>1 u\<^sub>1\<^sub>\<tau> e\<^sub>1 e\<^sub>1\<^sub>\<tau> U\<^sub>1 U\<^sub>1\<^sub>\<tau> H\<^sub>1 OP TR" and "Causality u\<^sub>2 u\<^sub>2\<^sub>\<tau> e\<^sub>2 e\<^sub>2\<^sub>\<tau> U\<^sub>2 U\<^sub>2\<^sub>\<tau> H\<^sub>2 OP TR" and "Signal_Y y\<^sub>1 H\<^sub>1 e\<^sub>1 OP" and "Signal_Y y\<^sub>2 H\<^sub>2 e\<^sub>2 OP" and "u\<^sub>1\<in>D \<and> e\<^sub>1\<in>D \<and> y\<^sub>2\<in>D \<and> H\<^sub>2 e\<^sub>2\<in>D" and "u\<^sub>2\<in>G \<and> e\<^sub>2\<in>G \<and> y\<^sub>1\<in>G \<and> H\<^sub>1 e\<^sub>1\<in>G" and "e\<^sub>1\<^sub>\<tau> = u\<^sub>1\<^sub>\<tau> - (\<lambda>t\<in>T\<^sub>\<tau>. y\<^sub>2 t)" and "e\<^sub>1\<^sub>\<tau> = u\<^sub>1\<^sub>\<tau> - (\<lambda>t\<in>T\<^sub>\<tau>. (H\<^sub>2 e\<^sub>2)t)" shows "(e\<^sub>2\<^sub>\<tau> = u\<^sub>2\<^sub>\<tau> + (\<lambda>t\<in>T\<^sub>\<tau>. y\<^sub>1 t)) \<longleftrightarrow> (e\<^sub>2\<^sub>\<tau> = u\<^sub>2\<^sub>\<tau> + (\<lambda>t\<in>T\<^sub>\<tau>. (H\<^sub>1 e\<^sub>1)t))" using assms by (metis sig_Y_tr1) theorem Small_Gain_Theorem: assumes "\<And>\<tau>. \<tau>\<in>T" and "\<And>t. t\<in>T\<^sub>\<tau>" and "Signal u\<^sub>1 \<and> Signal u\<^sub>2" and "trunc u\<^sub>1 u\<^sub>1\<^sub>\<tau> U\<^sub>1 U\<^sub>1\<^sub>\<tau> \<and> trunc u\<^sub>2 u\<^sub>2\<^sub>\<tau> U\<^sub>2 U\<^sub>2\<^sub>\<tau>"and "Operator_Space OP \<Longrightarrow>H\<^sub>1:D\<rightarrow>G \<and> H\<^sub>1\<in>OP \<and> H\<^sub>2:G\<rightarrow>D \<and>H\<^sub>2\<in>OP" and "Domain_Space D \<Longrightarrow> u\<^sub>1\<in>D \<and> e\<^sub>1\<in>D \<and> y\<^sub>2\<in>D \<and> H\<^sub>2 e\<^sub>2\<in>D \<and> u\<^sub>1\<^sub>\<tau>\<in>D \<and> e\<^sub>1\<^sub>\<tau>\<in>D \<and> y\<^sub>2\<^sub>\<tau>\<in>D" and "Range_Space G \<Longrightarrow> u\<^sub>2\<in>G \<and> e\<^sub>2\<in>G \<and> y\<^sub>1\<in>G \<and> H\<^sub>1 e\<^sub>1\<in>G \<and> u\<^sub>2\<^sub>\<tau>\<in>G \<and> e\<^sub>2\<^sub>\<tau>\<in>G \<and> y\<^sub>1\<^sub>\<tau>\<in>G" and "Causality u\<^sub>1 u\<^sub>1\<^sub>\<tau> e\<^sub>1 e\<^sub>1\<^sub>\<tau> U\<^sub>1 U\<^sub>1\<^sub>\<tau> H\<^sub>1 OP TR " and " Causality u\<^sub>2 u\<^sub>2\<^sub>\<tau> e\<^sub>2 e\<^sub>2\<^sub>\<tau> U\<^sub>2 U\<^sub>2\<^sub>\<tau> H\<^sub>2 OP TR" and "TR_Space TR \<Longrightarrow> u\<^sub>1\<^sub>\<tau>\<in>TR \<and> e\<^sub>1\<^sub>\<tau>\<in>TR \<and> y\<^sub>2\<^sub>\<tau>\<in>TR \<and> u\<^sub>2\<^sub>\<tau>\<in>TR \<and> e\<^sub>2\<^sub>\<tau>\<in>TR \<and> y\<^sub>1\<^sub>\<tau>\<in>TR" and "e\<^sub>1 = u\<^sub>1 - y\<^sub>2" and "e\<^sub>1 = u\<^sub>1 - (H\<^sub>2 e\<^sub>2)"and "e\<^sub>2 = u\<^sub>2 + y\<^sub>1" and "e\<^sub>2 = u\<^sub>2 + (H\<^sub>1 e\<^sub>1)" and "\<And>t. t\<in>T\<^sub>\<tau> \<Longrightarrow>e\<^sub>1\<^sub>\<tau> = u\<^sub>1\<^sub>\<tau> - (\<lambda>t. y\<^sub>2 t)" and "\<And>t. t\<in>T\<^sub>\<tau> \<Longrightarrow>e\<^sub>1\<^sub>\<tau> = u\<^sub>1\<^sub>\<tau> - (\<lambda>t. (H\<^sub>2 e\<^sub>2)t)" and "\<And>t. t\<in>T\<^sub>\<tau> \<Longrightarrow>e\<^sub>2\<^sub>\<tau> = u\<^sub>2\<^sub>\<tau> + (\<lambda>t. y\<^sub>1 t)" and "\<And>t. t\<in>T\<^sub>\<tau> \<Longrightarrow>e\<^sub>2\<^sub>\<tau> = u\<^sub>2\<^sub>\<tau> + (\<lambda>t. (H\<^sub>1 e\<^sub>1)t)" and "Stability u\<^sub>1 u\<^sub>1\<^sub>\<tau> e\<^sub>1 e\<^sub>1\<^sub>\<tau> U\<^sub>1 U\<^sub>1\<^sub>\<tau> \<gamma>\<^sub>1 \<beta>\<^sub>1 H\<^sub>1 M OP TR" and "Stability u\<^sub>2 u\<^sub>2\<^sub>\<tau> e\<^sub>2 e\<^sub>2\<^sub>\<tau> U\<^sub>2 U\<^sub>2\<^sub>\<tau> \<gamma>\<^sub>2 \<beta>\<^sub>2 H\<^sub>2 M OP TR" and "set_integrable M T\<^sub>\<tau> u\<^sub>1\<^sub>\<tau>" "set_integrable M T\<^sub>\<tau> u\<^sub>2\<^sub>\<tau>" "set_integrable M T\<^sub>\<tau> e\<^sub>1\<^sub>\<tau>" "set_integrable M T\<^sub>\<tau> e\<^sub>2\<^sub>\<tau>" and "set_integrable M T\<^sub>\<tau> y\<^sub>1\<^sub>\<tau>" "set_integrable M T\<^sub>\<tau> y\<^sub>2\<^sub>\<tau>" "set_integrable M T\<^sub>\<tau> (\<lambda>t. (H\<^sub>1 e\<^sub>1)t)" and "set_integrable M T\<^sub>\<tau> (\<lambda>t. (H\<^sub>2 e\<^sub>2)t)" and "set_integrable M T\<^sub>\<tau> (\<lambda>t. (u\<^sub>1\<^sub>\<tau> t)\<^sup>2)" and "set_integrable M T\<^sub>\<tau> (\<lambda>t. ((H\<^sub>2 e\<^sub>2)t)\<^sup>2)"and "set_integrable M T\<^sub>\<tau> (\<lambda>t. u\<^sub>1\<^sub>\<tau> t * (H\<^sub>2 e\<^sub>2)t )" and "set_integrable M T\<^sub>\<tau> (\<lambda>t. (u\<^sub>2\<^sub>\<tau> t)\<^sup>2)" and "set_integrable M T\<^sub>\<tau> (\<lambda>t. ((H\<^sub>1 e\<^sub>1)t)\<^sup>2)" and "set_integrable M T\<^sub>\<tau> (\<lambda>t. u\<^sub>2\<^sub>\<tau> t *(H\<^sub>1 e\<^sub>1)t)" and "set_integrable M T\<^sub>\<tau> (\<lambda>t. (e\<^sub>1\<^sub>\<tau> t)\<^sup>2)" and "set_integrable M T\<^sub>\<tau> (\<lambda>t. (e\<^sub>2\<^sub>\<tau> t)\<^sup>2)" and "set_integrable M T\<^sub>\<tau> (\<lambda>t. e\<^sub>1\<^sub>\<tau> t * e\<^sub>2\<^sub>\<tau> t )" and "(LINT t:T\<^sub>\<tau>|M. (( H\<^sub>2 e\<^sub>2 )t)\<^sup>2 )>0" and "(LINT t:T\<^sub>\<tau>|M. (( H\<^sub>1 e\<^sub>1 )t)\<^sup>2 )>0" and "(LINT t:T\<^sub>\<tau>|M. (e\<^sub>2\<^sub>\<tau> t)\<^sup>2 )>0" and " \<gamma>\<^sub>1 * \<gamma>\<^sub>2 <1" shows "(L2norm M e\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) \<le> ((L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + \<gamma>\<^sub>2 *(L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + \<beta>\<^sub>2 + \<gamma>\<^sub>2 * \<beta>\<^sub>1 )/(1 - \<gamma>\<^sub>1 * \<gamma>\<^sub>2)" and "(L2norm M e\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) \<le> ((L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + \<gamma>\<^sub>1 *(L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + \<beta>\<^sub>1 + \<gamma>\<^sub>1 * \<beta>\<^sub>2 )/(1 - \<gamma>\<^sub>1 * \<gamma>\<^sub>2)" and "(L2norm M (\<lambda>t. e\<^sub>1 t + e\<^sub>2 t) T\<^sub>\<tau>) \<le> (L2norm M e\<^sub>1 T\<^sub>\<tau>) + (L2norm M e\<^sub>2 T\<^sub>\<tau>)" proof - from assms have asm_e1_1:"(L2norm M e\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) = (L2norm M (\<lambda>t. u\<^sub>1\<^sub>\<tau> t + - (H\<^sub>2 e\<^sub>2)t) T\<^sub>\<tau>)" by (metis minus_apply minus_real_def) then have asm_e1_2:"(L2norm M (\<lambda>t. u\<^sub>1\<^sub>\<tau> t + -( H\<^sub>2 e\<^sub>2 )t ) T\<^sub>\<tau>) \<le> (L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + (L2norm M (H\<^sub>2 e\<^sub>2) T\<^sub>\<tau>)" using assms L2norm_triangle_ineq_nq by auto from asm_e1_1 asm_e1_2 have "(L2norm M e\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) \<le> (L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + (L2norm M (H\<^sub>2 e\<^sub>2) T\<^sub>\<tau>)" by presburger note step_e1_1 =this have "(L2norm M (\<lambda>t. (H\<^sub>2 e\<^sub>2) t) T\<^sub>\<tau> \<le> \<gamma>\<^sub>2 * (L2norm M (\<lambda>t. e\<^sub>2\<^sub>\<tau> t) T\<^sub>\<tau>) + \<beta>\<^sub>2)" using assms Stability_def by auto from this step_e1_1 have "(L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + (L2norm M (H\<^sub>2 e\<^sub>2) T\<^sub>\<tau>) \<le> ((L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + (\<gamma>\<^sub>2 * (L2norm M e\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + \<beta>\<^sub>2))" by simp from this step_e1_1 have e1:"(L2norm M e\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) \<le> ((L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + (\<gamma>\<^sub>2 * (L2norm M e\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + \<beta>\<^sub>2))" by force note step_e1_2 =this have e2_1:"(L2norm M e\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) = (L2norm M (\<lambda>t. u\<^sub>2\<^sub>\<tau> t + (H\<^sub>1 e\<^sub>1)t) T\<^sub>\<tau>)" using assms by (metis plus_fun_apply) then have e2_2:"(L2norm M (\<lambda>t. u\<^sub>2\<^sub>\<tau> t + ( H\<^sub>1 e\<^sub>1 )t ) T\<^sub>\<tau>) \<le> (L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + (L2norm M (H\<^sub>1 e\<^sub>1) T\<^sub>\<tau>)" using assms L2norm_triangle_ineq by meson have "(L2norm M (\<lambda>t. (H\<^sub>1 e\<^sub>1) t) T\<^sub>\<tau> \<le> \<gamma>\<^sub>1 * (L2norm M (\<lambda>t. e\<^sub>1\<^sub>\<tau> t) T\<^sub>\<tau>) + \<beta>\<^sub>1)" using assms Stability_def by auto from this e2_2 have e2_3:"(L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + (L2norm M (H\<^sub>1 e\<^sub>1) T\<^sub>\<tau>) \<le> (L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + (\<gamma>\<^sub>1 * (L2norm M e\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + \<beta>\<^sub>1)" by simp from this e2_1 e2_2 have e2_4:"(L2norm M e\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>)\<le> ((L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + (\<gamma>\<^sub>1 * (L2norm M e\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + \<beta>\<^sub>1))" by linarith from this step_e1_2 have "((L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + (\<gamma>\<^sub>2 * (L2norm M e\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + \<beta>\<^sub>2)) \<le> ((L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + (\<gamma>\<^sub>2 * ((L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + (\<gamma>\<^sub>1 * (L2norm M e\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + \<beta>\<^sub>1)) + \<beta>\<^sub>2))" using T\<^sub>\<tau>_def assms(1) assms(2) by fastforce note step_e1_3 =this then have asm_e1_3: "((L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + (\<gamma>\<^sub>2 * ((L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + (\<gamma>\<^sub>1 * (L2norm M e\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + \<beta>\<^sub>1)) + \<beta>\<^sub>2)) = ((L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + \<gamma>\<^sub>2 *(L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + \<gamma>\<^sub>1 * \<gamma>\<^sub>2 * (L2norm M e\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + \<gamma>\<^sub>2 * \<beta>\<^sub>1 + \<beta>\<^sub>2)" by algebra then have asm_e1_4:"((L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + \<gamma>\<^sub>2 *(L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + \<gamma>\<^sub>1 * \<gamma>\<^sub>2 * (L2norm M e\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + \<gamma>\<^sub>2 * \<beta>\<^sub>1 + \<beta>\<^sub>2) = \<gamma>\<^sub>1 * \<gamma>\<^sub>2 * (L2norm M e\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + ((L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + \<gamma>\<^sub>2 *(L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + \<beta>\<^sub>2 + \<gamma>\<^sub>2 * \<beta>\<^sub>1 )" by linarith then have "(L2norm M e\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) \<le> \<gamma>\<^sub>1 * \<gamma>\<^sub>2 * (L2norm M e\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + ((L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + \<gamma>\<^sub>2 *(L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + \<beta>\<^sub>2 + \<gamma>\<^sub>2 * \<beta>\<^sub>1 )" using step_e1_1 step_e1_2 step_e1_3 asm_e1_3 by linarith then have "(L2norm M e\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) - \<gamma>\<^sub>1 * \<gamma>\<^sub>2 * (L2norm M e\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) \<le> ((L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + \<gamma>\<^sub>2 *(L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + \<beta>\<^sub>2 + \<gamma>\<^sub>2 * \<beta>\<^sub>1 )" by force then have "(L2norm M e\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>)*(1 - \<gamma>\<^sub>1 * \<gamma>\<^sub>2 )\<le> ((L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + \<gamma>\<^sub>2 *(L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + \<beta>\<^sub>2 + \<gamma>\<^sub>2 * \<beta>\<^sub>1 )" by (metis linordered_field_class.sign_simps(24) real_scaleR_def real_vector.scale_right_diff_distrib semiring_normalization_rules(12)) with \<open>\<gamma>\<^sub>1 * \<gamma>\<^sub>2 <1\<close> this show "(L2norm M e\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>)\<le> ((L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + \<gamma>\<^sub>2 *(L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + \<beta>\<^sub>2 + \<gamma>\<^sub>2 * \<beta>\<^sub>1 )/(1 - \<gamma>\<^sub>1 * \<gamma>\<^sub>2 )" by (simp add: less_diff_eq pos_le_divide_eq) note sig_e1 =this (* For Signal e2 *) from e2_4 e1 have e2_5:"((L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + (\<gamma>\<^sub>1 * (L2norm M e\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + \<beta>\<^sub>1)) \<le> ((L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + (\<gamma>\<^sub>1 * ((L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + (\<gamma>\<^sub>2 * (L2norm M e\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + \<beta>\<^sub>2)) + \<beta>\<^sub>1))" using T\<^sub>\<tau>_def assms(1) assms(2) by fastforce then have "((L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + (\<gamma>\<^sub>1 * ((L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + (\<gamma>\<^sub>2 * (L2norm M e\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + \<beta>\<^sub>2)) + \<beta>\<^sub>1)) = \<gamma>\<^sub>1 * \<gamma>\<^sub>2 * (L2norm M e\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>)+((L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + (\<gamma>\<^sub>1 * (L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + \<beta>\<^sub>1 + \<gamma>\<^sub>1 *\<beta>\<^sub>2))" by algebra then have "(L2norm M e\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) \<le> \<gamma>\<^sub>1 * \<gamma>\<^sub>2 * (L2norm M e\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>)+((L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + (\<gamma>\<^sub>1 * (L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + \<beta>\<^sub>1 + \<gamma>\<^sub>1 *\<beta>\<^sub>2 ))" using e2_4 e2_5 by linarith then have "(L2norm M e\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) - \<gamma>\<^sub>1 * \<gamma>\<^sub>2 * (L2norm M e\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) \<le> ((L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + (\<gamma>\<^sub>1 * (L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + \<beta>\<^sub>1 + \<gamma>\<^sub>1 *\<beta>\<^sub>2 ))" by force then have "(L2norm M e\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>)*(1 - \<gamma>\<^sub>1 * \<gamma>\<^sub>2) \<le> ((L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + (\<gamma>\<^sub>1 * (L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + \<beta>\<^sub>1 + \<gamma>\<^sub>1 *\<beta>\<^sub>2 ))" by (metis linordered_field_class.sign_simps(24) real_scaleR_def real_vector.scale_right_diff_distrib semiring_normalization_rules(12)) with \<open>\<gamma>\<^sub>1 * \<gamma>\<^sub>2 <1\<close> this show "(L2norm M e\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) \<le> ((L2norm M u\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>) + \<gamma>\<^sub>1 * (L2norm M u\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + \<beta>\<^sub>1 + \<gamma>\<^sub>1 *\<beta>\<^sub>2 )/(1 - \<gamma>\<^sub>1 * \<gamma>\<^sub>2)" by (simp add: less_diff_eq pos_le_divide_eq) note sig_e2 =this from sig_e1 sig_e2 have "(L2norm M (\<lambda>t. e\<^sub>1\<^sub>\<tau> t + e\<^sub>2\<^sub>\<tau> t) T\<^sub>\<tau>) \<le> (L2norm M e\<^sub>1\<^sub>\<tau> T\<^sub>\<tau>) + (L2norm M e\<^sub>2\<^sub>\<tau> T\<^sub>\<tau>)" using assms L2norm_triangle_ineq by meson then show "(L2norm M (\<lambda>t. e\<^sub>1 t + e\<^sub>2 t) T\<^sub>\<tau>) \<le> (L2norm M e\<^sub>1 T\<^sub>\<tau>) + (L2norm M e\<^sub>2 T\<^sub>\<tau>)" using assms L2norm_triangle_ineq by (metis T_def diff_add_cancel le_add_same_cancel2 mem_Collect_eq) qed end
#include "cudaSirecon.h" #include "cudaSireconImpl.h" #include "SIM_reconstructor.hpp" #include "cudasireconConfig.h" #include <boost/filesystem.hpp> #ifdef MRC #include "mrc.h" #endif std::string version_number = std::to_string(cudasirecon_VERSION_MAJOR) + "." + std::to_string(cudasirecon_VERSION_MINOR) + "." + std::to_string(cudasirecon_VERSION_PATCH); void SetDefaultParams(ReconParams *pParams) { pParams->k0startangle = 1.57193; pParams->linespacing = 0.177; pParams->na = 1.36; pParams->nimm = 1.515; pParams->ndirs = 3; pParams->nphases = 3; pParams->phaseSteps = 0; pParams->norders_output = 0; pParams->bTwolens = 0; pParams->bFastSIM = 0; pParams->bBessel = 0; pParams->BesselNA = 0.45; pParams->zoomfact = 2; pParams->z_zoom = 1; pParams->nzPadTo = 0; pParams->explodefact= 1.0; pParams->bFilteroverlaps = 1; pParams->recalcarrays = 1; //! whether to calculate the overlaping regions between bands just once or always; used in fitk0andmodamps() pParams->napodize = 10; pParams->forceamp.assign(1, 0.f); // pParams->k0angles = NULL; pParams->bSearchforvector = 1; pParams->bUseTime0k0 = 1; /* default to use time 0's k0 fit for the rest in a time series data */ pParams->apodizeoutput = 0; /* 0-no apodize; 1-cosine apodize; 2-triangle apodize; used in filterbands() */ pParams->bSuppress_singularities = 1; /* whether to dampen the OTF values near band centers; used in filterbands() */ pParams->suppression_radius = 10; /* if suppress_singularities is 1, the range within which suppresion is applied; used in filterbands() */ pParams->bDampenOrder0 = 0; /* whether to dampen order 0 contribution; used in filterbands() */ pParams->bFitallphases = 1; pParams->do_rescale=1; /* fading correction method: 0-no correction; 1-with correction */ pParams->equalizez = 0; pParams->equalizet = 0; pParams->bNoKz0 = 0; pParams->bRadAvgOTF = 0; /* default to use non-radially averaged OTFs */ pParams->bOneOTFperAngle = 0; /* default to use one OTF for all SIM angles */ pParams->bFixdrift = 0; pParams->drift_filter_fact = 0.0; pParams->constbkgd = 0.0; pParams->bBgInExtHdr = 0; pParams->bUsecorr = 0; pParams->electrons_per_bit = 0.6528; pParams->readoutNoiseVar = 32.42; // electron^2 pParams->bMakemodel = 0; pParams->bSaveAlignedRaw = 0; pParams->bSaveSeparated = 0; pParams->bSaveOverlaps = 0; pParams->bWriteTitle = 0; pParams -> bTIFF = false; } // Functions for dealing with images bool notGoodDimension(unsigned num) // Good dimension is defined as one that can be fatorized into 2s, 3s, 5s, and 7s // According to CUFFT manual, such dimension would warranty fast FFT { if (num==2 || num==3 || num==5 || num==7) return false; else if (num % 2 == 0) return notGoodDimension(num / 2); else if (num % 3 == 0) return notGoodDimension(num / 3); else if (num % 5 == 0) return notGoodDimension(num / 5); else if (num % 7 == 0) return notGoodDimension(num / 7); else return true; } unsigned findOptimalDimension(unsigned inSize, int step=-1) { unsigned outSize = inSize; while (notGoodDimension(outSize)) outSize += step; return outSize; } void allocateOTFs(ReconParams* pParams, int sizeOTF, std::vector<std::vector<GPUBuffer> >& otfs) { otfs.clear(); unsigned short nDirsOTF = 1; if (pParams->bOneOTFperAngle) nDirsOTF = pParams->ndirs; otfs.resize(nDirsOTF); for (int dir = 0; dir< nDirsOTF; dir++) for (int i = 0; i < pParams->norders; ++i) { GPUBuffer buff; buff.resize(sizeOTF * sizeof(cuFloatComplex)); otfs[dir].push_back(buff); } } void allocateImageBuffers(const ReconParams& params, const ImageParams& imgParams, ReconData* data) { data->savedBands.clear(); data->savedBands.reserve(params.ndirs); for (int i = 0; i < params.ndirs; ++i) { data->savedBands.push_back(std::vector<GPUBuffer>()); data->savedBands[i].reserve(params.nphases); for (int j = 0; j < params.nphases; ++j) { data->savedBands[i].push_back(GPUBuffer( (imgParams.nx / 2 + 1) * imgParams.ny * imgParams.nz0 * sizeof(cuFloatComplex), 0)); } } for (int i = 0; i < params.ndirs; ++i) { for (int j = 0; j < params.nphases; ++j) { data->savedBands[i][j].setToZero(); } } } void bgAndSlope(const ReconParams& myParams, const ImageParams& imgParams, ReconData* reconData) { reconData->background.resize(sizeof(float) * imgParams.nx * imgParams.ny); reconData->slope.resize(sizeof(float) * imgParams.nx * imgParams.ny); if (myParams.bUsecorr) { // flatfield correction of measured data using calibration data printf("loading CCD calibration file\n"); getbg_and_slope(myParams.corrfiles.c_str(), (float*)reconData->background.getPtr(), (float*)reconData->slope.getPtr(), imgParams.nx, imgParams.ny); } else { for (int i = 0; i < imgParams.nx * imgParams.ny; i++) { /* use the constant background value given by user */ ((float*)(reconData->background.getPtr()))[i] = myParams.constbkgd; ((float*)(reconData->slope.getPtr()))[i] = 1.0; } } reconData->backgroundExtra = 0; } void getbg_and_slope(const char *corrfiles, float *background, float *slope, int nx, int ny) { int cstream_no=10; int ixyz[3], mxyz[3], pixeltype; /* variables for IMRdHdr call */ float min, max, mean; /* variables for IMRdHdr call */ #ifdef MRC IW_MRC_HEADER header; if (IMOpen(cstream_no, corrfiles, "ro")) { fprintf(stderr, "File %s does not exist\n", corrfiles); exit(-1); } IMRdHdr(cstream_no, ixyz, mxyz, &pixeltype, &min, &max, &mean); IMGetHdr(cstream_no, &header); if (header.nx != nx || header.ny != ny) { fprintf(stderr, "calibration file %s has different dimension than data file", corrfiles); exit(-1); } IMAlCon(cstream_no, 0); IMRdSec(cstream_no, background); IMRdSec(cstream_no, slope); IMClose(cstream_no); #endif } void findModulationVectorsAndPhasesForAllDirections( int zoffset, ReconParams* params, const ImageParams& imgParams, DriftParams* driftParams, ReconData* data) { // Apodize (or edge softening) every 2D slice: apodizationDriver(zoffset, params, imgParams, driftParams, data); // 2D FFT every 2D slice: transformXYSlice(zoffset, params, imgParams, driftParams, data); float dkx = 1./(imgParams.dxy * imgParams.nx); float dky = 1./(imgParams.dxy * imgParams.ny); float k0magguess = 1.0 / params->linespacing; for (int direction = 0; direction < params->ndirs; ++direction) { std::vector<GPUBuffer>* rawImages = &(data->savedBands[direction]); std::vector<GPUBuffer>* bands = &(data->savedBands[direction]); std::vector<float> phaseList(params->nphases); if (params->phaseSteps != 0) { // User specified the non-ideal (i.e., not 2pi/5) phase steps for // each orientation. Under this circumstance, calculate the // non-ideal sepMatrix: for (int i = 0; i < params->nphases; ++i) { phaseList[i] = i * params->phaseSteps[direction]; } makematrix(params->nphases, params->norders, direction, &(phaseList[0]), (&data->sepMatrix[0]), &(data->noiseVarFactors[0])); } // Unmixing info components in real or reciprocal space: separate(imgParams.nx, imgParams.ny, imgParams.nz, direction, params->nphases, params->norders, rawImages, &data->sepMatrix[0]); #ifndef NDEBUG for (int phase = 0; phase < params->nphases; ++phase) { assert(rawImages->at(phase).hasNaNs(true) == false); std::cout << "Phase " << phase << "ok." << std::endl; } #endif if (imgParams.nz > 1) { // 1D FFT of a stack of 2D FFTs to obtain equivalent of 3D FFT cufftHandle fftplan1D; int fftN[1] = {imgParams.nz0}; int stride = (imgParams.nx / 2 + 1) * imgParams.ny; int dist = 1; cufftResult cuFFTErr = cufftPlanMany(&fftplan1D, 1, fftN, fftN, stride, dist, fftN, stride, dist, CUFFT_C2C, (imgParams.nx / 2 + 1) * imgParams.ny); if (cuFFTErr != CUFFT_SUCCESS) { throw std::runtime_error("CUFFT plan creation failed"); } for (int i = 0; i < params->nphases; ++i) { cufftExecC2C(fftplan1D, (cuFloatComplex*)((*bands)[i]).getPtr(), (cuFloatComplex*)((*bands)[i]).getPtr(), CUFFT_FORWARD); } cufftDestroy(fftplan1D); } if (params->bMakemodel) { /* Use the OTF to simulate an ideal point source; replace bands * with simulated data * DM: k0 is not initialized but has memory allocate at this point. * k0 initialization code is near lines 430ff in sirecon.c */ makemodeldata(imgParams.nx, imgParams.ny, imgParams.nz0, bands, params->norders, data->k0[direction], imgParams.dxy, imgParams.dz, &data->otf[0], imgParams.wave[0], params); } /* save the separated raw if requested */ if (params->bTIFF && params->bSaveSeparated) { // TO-DO std::cout << "No unmixed raw images were saved in TIFF mode\n"; } #ifdef MRC else if (!params->bTIFF && params->bSaveSeparated) { CPUBuffer tmp((*rawImages)[0].getSize()); for (int phase = 0; phase < params->nphases; ++ phase) { (*rawImages)[phase].set(&tmp, 0, tmp.getSize(), 0); for (int z = 0; z < imgParams.nz; ++z) { float* imgPtr = (float*)tmp.getPtr(); IMWrSec(separated_stream_no, imgPtr + (z + zoffset) * (imgParams.nx/2 + 1)*2 * imgParams.ny); } } continue; // skip the k0 search and modamp fitting } #endif /* After separation and FFT, the std::vector rawImages, now referred to as * the std::vector bands, contains the center band (bands[0]) * , the real (bands[1], bands[3], etc.) and * imaginary part (bands[2], bands[4], etc.) bands * of the different orders */ if (! (imgParams.ntimes > 1 && imgParams.curTimeIdx > 0 && params->bUseTime0k0) ) { data->k0[direction] = data->k0guess[direction]; printf("k0guess[direction %d] = (%f, %f) pixels\n", direction, data->k0guess[direction].x/dkx, data->k0guess[direction].y/dky); } // Now to fix 3D drift between dirs estimated by determinedrift_3D() if (direction != 0 && params->bFixdrift) { fixdrift_bt_dirs(bands, params->norders, driftParams->drift_bt_dirs[direction], imgParams.nx, imgParams.ny, imgParams.nz0); } /* assume k0 vector not well known, so fit for it */ cuFloatComplex amp_inv; cuFloatComplex amp_combo; // dir_ is used in upcoming calls involving data->otf, to differentiate the cases // of common OTF and dir-specific OTF int dir_=0; if (params->bOneOTFperAngle) dir_ = direction; if (params->bSearchforvector && !(imgParams.ntimes > 1 && imgParams.curTimeIdx > 0 && params->bUseTime0k0)) { /* In time series, can choose to use the time 0 k0 fit for the * rest of the series. * Find initial estimate of modulation wave vector k0 by * cross-correlation. */ findk0(bands, &data->overlap0, &data->overlap1, imgParams.nx, imgParams.ny, imgParams.nz0, params->norders, &(data->k0[direction]), imgParams.dxy, imgParams.dz, &(data->otf[dir_]), imgParams.wave[0], params); if (params->bSaveOverlaps) { // output the overlaps if (params->bTIFF) { CPUBuffer tmp0(data->overlap0.getSize()*2); data->overlap0.set(&tmp0, 0, data->overlap0.getSize(), 0); data->overlap1.set(&tmp0, 0, data->overlap1.getSize(), data->overlap0.getSize()); CImg<> ovlp0((float* )tmp0.getPtr(), imgParams.nx*2, imgParams.ny, imgParams.nz*2, 1, true); // ovlp0 shares buffer with tmp0 (hence "true" in the final parameter) ovlp0.save_tiff(params->fileOverlaps.c_str()); } #ifdef MRC else { CPUBuffer tmp0(data->overlap0.getSize()); data->overlap0.set(&tmp0, 0, tmp0.getSize(), 0); CPUBuffer tmp1(data->overlap1.getSize()); data->overlap1.set(&tmp1, 0, tmp1.getSize(), 0); cuFloatComplex* ol0Ptr = (cuFloatComplex*)tmp0.getPtr(); cuFloatComplex* ol1Ptr = (cuFloatComplex*)tmp1.getPtr(); for (int z = 0; z < imgParams.nz0; ++z) { IMWrSec(overlaps_stream_no, ol0Ptr + z * imgParams.nx * imgParams.ny); IMWrSec(overlaps_stream_no, ol1Ptr + z * imgParams.nx * imgParams.ny); } } #endif } printf("Initial guess by findk0() of k0[direction %d] = (%f,%f) pixels\n", direction, data->k0[direction].x/dkx, data->k0[direction].y/dky); /* refine the cross-corr estimate of k0 by a search for best k0 * vector direction and magnitude using real space waves*/ printf("before fitk0andmodamp\n"); /* if (myParams.recalcarrays==0 && dist>1.0) */ params->recalcarrays = 1; /* if k0 is very close to the guess, we can save time by not * recalculating the overlap arrays */ fitk0andmodamps(bands, &data->overlap0, &data->overlap1, imgParams.nx, imgParams.ny, imgParams.nz0, params->norders, &(data->k0[direction]), imgParams.dxy, imgParams.dz, &(data->otf[dir_]), imgParams.wave[0], &data->amp[direction][0], params); if (imgParams.curTimeIdx == 0) { data->k0_time0[direction] = data->k0[direction]; } /* check if the k0 vector found is reasonably close to the guess */ vector deltak0; deltak0.x = data->k0[direction].x - data->k0guess[direction].x; deltak0.y = data->k0[direction].y - data->k0guess[direction].y; float dist = sqrt(deltak0.x * deltak0.x + deltak0.y * deltak0.y); if (dist/k0magguess > K0_WARNING_THRESH) { printf("WARNING: "); } printf("best fit for k0 is %.3f%% from expected value.\n", dist/k0magguess*100); if (imgParams.ntimes > 1 && imgParams.curTimeIdx > 0 && dist > 2*K0_WARNING_THRESH) { data->k0[direction] = data->k0_time0[direction]; printf("k0 estimate of time point 0 is used instead\n"); for (int order = 1; order < params->norders; ++order) { float corr_coeff; if (imgParams.nz0>1) corr_coeff = findrealspacemodamp(bands, &data->overlap0, &data->overlap1, imgParams.nx, imgParams.ny, imgParams.nz0, 0, order, data->k0[direction], imgParams.dxy, imgParams.dz, &(data->otf[dir_]), imgParams.wave[0], &data->amp[direction][order], &amp_inv, &amp_combo, 1, params); else corr_coeff = findrealspacemodamp(bands, &data->overlap0, &data->overlap1, imgParams.nx, imgParams.ny, imgParams.nz0, order-1, order, data->k0[direction], imgParams.dxy, imgParams.dz, &(data->otf[dir_]), imgParams.wave[0], &data->amp[direction][order], &amp_inv, &amp_combo, 1, params); printf("modamp mag=%f, phase=%f\n, correlation coeff=%f\n\n", cmag(data->amp[direction][order]), atan2(data->amp[direction][order].y, data->amp[direction][order].x), corr_coeff); } } } else { /* assume k0 vector known, so just fit for the modulation amplitude and phase */ printf("known k0 for direction %d = (%f, %f) pixels \n", direction, data->k0[direction].x/dkx, data->k0[direction].y/dky); for (int order = 1; order < params->norders; ++order) { float corr_coeff = findrealspacemodamp(bands, &data->overlap0, &data->overlap1, imgParams.nx, imgParams.ny, imgParams.nz0, 0, order, data->k0[direction], imgParams.dxy, imgParams.dz, &(data->otf[dir_]), imgParams.wave[0], &data->amp[direction][order], &amp_inv, &amp_combo, 1, params); printf("modamp mag=%f, phase=%f\n", cmag(data->amp[direction][order]), atan2(data->amp[direction][order].y, data->amp[direction][order].x)); printf("reverse modamp mag=%f, phase=%f\n", 1.0f / cmag(amp_inv), -atan2(amp_inv.y, amp_inv.x)); printf("combined modamp mag=%f, phase=%f\n", cmag(amp_combo), atan2(amp_combo.y, amp_combo.x)); printf("correlation coeff=%f\n\n", corr_coeff); if (params->bTIFF) { // To-DO std::cout << "No overlaps were saved in TIFF mode"; } #ifdef MRC else if (!params->bTIFF && order == 1 && params->bSaveOverlaps) {// output the overlaps // output the overlaps CPUBuffer tmp0(data->overlap0.getSize()); data->overlap0.set(&tmp0, 0, tmp0.getSize(), 0); CPUBuffer tmp1(data->overlap1.getSize()); data->overlap1.set(&tmp1, 0, tmp1.getSize(), 0); float* ol0Ptr = (float*)tmp0.getPtr(); float* ol1Ptr = (float*)tmp1.getPtr(); for (int z = 0; z < imgParams.nz0; ++z) { IMWrSec(overlaps_stream_no, ol0Ptr + z * imgParams.nx * imgParams.ny); IMWrSec(overlaps_stream_no, ol1Ptr + z * imgParams.nx * imgParams.ny); } } #endif } } /* if(searchforvector) ... else ... */ if (imgParams.nz == 1) { /* In 2D SIM, amp stores modamp's between each adjacent pair of * bands. We want to convert this to modamp w.r.t. order 0 */ for (int order = 2; order < params->norders; ++order) { data->amp[direction][order] = cmul(data->amp[direction][order], data->amp[direction][order - 1]); } } if (params->forceamp[0] > 0.0) { /* force modamp's amplitude to be a value user provided (ideally * should be 1) */ for (int order = 1; order < params->norders; ++order) { float a = cmag(data->amp[direction][order]); if (a < params->forceamp[order-1]) { float ampfact = params->forceamp[order-1] / a; data->amp[direction][order].x *= ampfact; data->amp[direction][order].y *= ampfact; printf("modamp mag=%f, phase=%f \n", cmag(data->amp[direction][order]), atan2(data->amp[direction][order].y, data->amp[direction][order].x)); } } } /* In 2D NLSIM, we often don't trust the modamp fit between neighboring high-order components; */ /* only if fitallphases is True do all fitted modamps get actually used; */ /* otherwise, order 2 and above's global phase is inferred from order 1's phase. */ if (!params->bFitallphases) { float base_phase = get_phase(data->amp[direction][1]); cuFloatComplex expiphi; cuFloatComplex amplitude; float phi; for (int order = 2; order < params->norders; ++order) { amplitude.x = cmag(data->amp[direction][order]); amplitude.y = 0; phi = order * base_phase /*+ M_PI*(order-1)*/; /* sign flip for every other order happens only in saturation case? */ expiphi.x = cos(phi); expiphi.y = sin(phi); data->amp[direction][order] = cmul(amplitude, expiphi); } } } /* end for (dir) */ /* done finding the modulation vectors and phases for all directions */ } void apodizationDriver(int zoffset, ReconParams* params, const ImageParams& imgParams, DriftParams* driftParams, ReconData* data) { for (int direction = 0; direction < params->ndirs; ++direction) { /* data assumed taken with z changing fast, direction changing * slowly */ std::vector<GPUBuffer>* rawImages = &(data->savedBands[direction]); std::vector<GPUBuffer>* bands = &(data->savedBands[direction]); for (int z = 0; z < imgParams.nz; ++z) { for (int phase = 0; phase < params->nphases; ++phase) { if (params->napodize >= 0) { // Goes through here apodize(params->napodize, imgParams.nx, imgParams.ny, &(rawImages->at(phase)), (z + zoffset) * (imgParams.nx/2 + 1)*2 * imgParams.ny); } else if (params->napodize == -1) { cosapodize(imgParams.nx, imgParams.ny, &(*rawImages)[phase], (z + zoffset) * imgParams.nx * imgParams.ny); } } /* end for (phase), loading, flatfielding, and apodizing raw images */ } } /* end for (dir) */ } void rescaleDriver(int it, int iw, int zoffset, ReconParams* params, const ImageParams& imgParams, DriftParams* driftParams, ReconData* data) { for (int direction = 0; direction < params->ndirs; ++direction) { /* data assumed taken with z changing fast, direction changing * slowly */ std::vector<GPUBuffer>* rawImages = &(data->savedBands[direction]); std::vector<GPUBuffer>* bands = &(data->savedBands[direction]); for (int z = 0; z < imgParams.nz; ++z) if (params->do_rescale) { // Goes through here rescale(imgParams.nx, imgParams.ny, imgParams.nz, z, zoffset, direction, iw, it, params->nphases, rawImages, params->equalizez, params->equalizet, &data->sum_dir0_phase0[0]); } #ifndef NDEBUG std::cout<< "rescaleDriver(): " << cudaGetErrorString(cudaGetLastError()) << std::endl; #endif } } void transformXYSlice(int zoffset, ReconParams* params, const ImageParams& imgParams, DriftParams* driftParams, ReconData* data) { cufftHandle rfftplanGPU; int fftN[2] = {imgParams.ny, imgParams.nx}; int inembed[2] = {imgParams.nx * imgParams.ny, (imgParams.nx/2 + 1)*2}; int istride = 1; int idist = (imgParams.nx/2 + 1)*2 * imgParams.ny; int onembed[2] = {imgParams.nx * imgParams.ny, imgParams.nx /2 +1}; int ostride = 1; int odist = (imgParams.nx / 2 + 1) * imgParams.ny; cufftResult cuFFTErr = cufftPlanMany(&rfftplanGPU, 2, &fftN[0], inembed, istride, idist, onembed, istride, odist, CUFFT_R2C, imgParams.nz); if (cuFFTErr != CUFFT_SUCCESS) { std::cout << "Error code: " << cuFFTErr << " at " __FILE__ << ":" << __LINE__ << std::endl; throw std::runtime_error("cufftPlanMany() failed."); } for (int direction = 0; direction < params->ndirs; ++direction) { for (int phase = 0; phase < params->nphases; ++phase) { cuFFTErr = cufftExecR2C(rfftplanGPU, (float*)data->savedBands[direction][phase].getPtr(), (cuFloatComplex*)data->savedBands[direction][phase].getPtr()); if (cuFFTErr != CUFFT_SUCCESS) { std::cout << "Line:" << __LINE__ ; throw std::runtime_error("cufft failed."); } } } cufftDestroy(rfftplanGPU); if (cuFFTErr != CUFFT_SUCCESS) { std::cout << "Error code: " << cuFFTErr << " at " __FILE__ << ":" << __LINE__<< std::endl; throw std::runtime_error("cufftDestroy() failed."); } } /***************************** makematrix ************************************/ /* generates the matrix that is to be used to separate the raw indata */ /* into the different bands of sample information. */ /* Two cases: 1. If arrPhases is NULL, we're certain that phases are equally spaced within 2Pi range; 2. Else, user supplies a list of phases actually used (e.g, when there is drift or non-ideal SLM patterns are used), and noise variance amplification factors for each order and direction is calculated based on the non-ideal separation matrix */ /*****************************************************************************/ void makematrix(int nphases, int norders, int dir, float *arrPhases, float *sepMatrix, float * noiseVarFactors) { std::cout << "In makematrix." << std::endl; /* norders is not necessarily nphases/2+1, in cases such as nonlinear SIM where the number of output orders can be smaller. */ int j, order; float phi, sqrt_nphases, sqrt_2; sqrt_nphases = sqrt((float)nphases); sqrt_2 = sqrt(2.); // norders could be less than (nphases+1)/2 if (arrPhases == 0) { /* phase values equally spaced between 0 and 2Pi */ phi = 2.0 * M_PI / nphases; for (j = 0; j < nphases; ++j) { sepMatrix[0 * nphases + j] = 1.0; for (order = 1; order < norders; ++order) { /* With this definition, bandplus = bandre + i bandim * has coefficient exp() with unit normalization */ sepMatrix[(2 * order - 1) * nphases + j] = cos(j * order * phi); sepMatrix[2 * order * nphases + j] = sin(j * order * phi); } } } else {/* User supplied phase values in arrPhases */ int *ipvt, info, i, nCols; float *workspace, *forwardM, *A_t_A, unit=1., zero=0.; /* Here we differentiate between 2 options: */ /* 1. use direct matrix inversion; */ /* 2. use least-square solution. */ nCols = 2 * norders - 1; if (nCols < nphases) { // use least-square ipvt = (int*)malloc(nCols * sizeof(int)); forwardM = (float*)malloc(nphases*nCols*sizeof(float)); A_t_A = (float*)malloc(nCols*nCols*sizeof(float)); /* First construct the forward matrix*/ for (i=0; i<nphases; i++) { forwardM[i] = 1.0 / nphases; for (order=1; order<norders; order++) { forwardM[i+(2*order-1)*nphases] = 2 * cos(order*arrPhases[i]) / nphases; forwardM[i+2*order*nphases] = 2 * sin(order*arrPhases[i]) / nphases; } } /* print_matrix("forward matrix:", nphases, nCols, forwardM, nphases); */ /* multiply transposed forward matrix with forward matrix */ sgemm_("T", "N", &nCols, &nCols, &nphases, &unit, forwardM, &nphases, forwardM, &nphases, &zero, A_t_A, &nCols); /* print_matrix("A transpose times A:", nCols, nCols, A_t_A, nCols); */ /* Then invert the forward matrix to form the sep matrix*/ sgetrf_(&nCols, &nCols, A_t_A, &nCols, ipvt, &info); if (info==0) { // successful factorization workspace = (float*)malloc(nCols*sizeof(float)); sgetri_(&nCols, A_t_A, &nCols, ipvt, workspace, &nCols, &info); free(workspace); } else printf("WARNING: sgetri() returns non 0.\n"); if (info!=0) printf("WARNING: sgetrf() returns non 0.\n"); // multiply inverse A_t_A with transposed forward matrix sgemm_("N", "T", &nCols, &nphases, &nCols, &unit, A_t_A, &nCols, forwardM, &nphases, &zero, sepMatrix, &nCols); /* print_matrix("Separation Matrix:", nCols, nphases, sepMatrix, nCols); */ /* transpose back to C-style matrix */ matrix_transpose(sepMatrix, nphases, nCols); free(ipvt); free(forwardM); free(A_t_A); } else { // use direct inversion ipvt = (int*)malloc(nphases*sizeof(int)); /* First construct the forward matrix (in C-style storage convention ) */ for (i=0; i<nphases; i++) { sepMatrix[i*nphases] = 1.0 / nphases; for (order=1; order<norders; order++) { sepMatrix[i*nphases+(2*order-1)] = 2 * cos(order*arrPhases[i]) / nphases; sepMatrix[i*nphases+2*order] = 2 * sin(order*arrPhases[i]) / nphases; } } /* Then invert the forward matrix to form the sep matrix*/ sgetrf_(&nphases, &nphases, sepMatrix, &nphases, ipvt, &info); if (info==0) { // successful factorization workspace = (float*)malloc(nphases*sizeof(float)); sgetri_(&nphases, sepMatrix, &nphases, ipvt, workspace, &nphases, &info); free(workspace); } else printf("WARNING: sgetri() returns non 0.\n"); if (info!=0) printf("WARNING: sgetrf() returns non 0.\n"); free(ipvt); } /* Report noise factors */ for (order=0;order<norders;order++) noiseVarFactors[dir*norders+order] = 0.0; for (j=0;j<nphases;j++) { noiseVarFactors[dir*norders+0] += pow(sepMatrix[0*nphases+j], 2); for (order=1;order<norders;order++) noiseVarFactors[dir*norders+order] += pow(sepMatrix[(2*order-1)*nphases+j], 2) + pow(sepMatrix[2*order*nphases+j], 2); } printf(" Separation noise factors: "); for (order=0;order<norders;order++) { noiseVarFactors[dir*norders+order] /= nphases; printf(" Order %d: %.3f,",order, sqrt(noiseVarFactors[dir*norders+order])); } printf("\n"); } printf("Separation matrix:\n"); for (j=0;j<norders*2-1;j++) { int i; for (i=0; i<nphases; i++) printf("%9.5f ", sepMatrix[j*nphases+i]); printf("\n"); } printf("\n"); } void allocSepMatrixAndNoiseVarFactors(const ReconParams& params, ReconData* reconData) { reconData->sepMatrix.resize(params.nphases * (params.norders * 2 - 1)); reconData->noiseVarFactors.resize(params.ndirs * params.norders, 1.0f); } void matrix_transpose(float* mat, int nRows, int nCols) { int i, j; float* tmpmat = (float*)malloc(nRows*nCols*sizeof(float)); for (i=0; i<nRows; i++) for (j=0; j<nCols; j++) tmpmat[j*nRows+i] = mat[i*nCols+j]; memcpy(mat, tmpmat, nRows*nCols*sizeof(float)); free(tmpmat); } float get_phase(cuFloatComplex b) { return atan2(b.y, b.x); } float cmag(cuFloatComplex a) { return (sqrt(a.x*a.x+a.y*a.y)); } cuFloatComplex cmul(cuFloatComplex a, cuFloatComplex b) { cuFloatComplex result; result.x = a.x * b.x - a.y * b.y; result.y = a.x * b.y + a.y * b.x; return result; } void dumpBands(std::vector<GPUBuffer>* bands, int nx, int ny, int nz0) { int n = 0; for (auto i = bands->begin(); i != bands->end(); ++i) { std::stringstream s; s << "band" << n << ".tif"; CPUBuffer buf(nx*ny*nz0*sizeof(float)); i->set(&buf, 0, buf.getSize(), 0); CImg<> band_tiff((float *) buf.getPtr(), nx, ny, nz0, 1, true); band_tiff.save_tiff(s.str().c_str()); std::stringstream ss; ss << "band" << n << ".dat"; std::ofstream os(ss.str().c_str()); i->dump(os, nx, 0, nx * ny * sizeof(float)); ++n; } } template<class T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, " ")); return os; } // IMPLEMENTATION OF CLASS SIM_RECONSTRUCTOR FOLLOWS: SIM_Reconstructor::SIM_Reconstructor(int argc, char **argv) { // Call this constructor from a command-line based program m_argc = argc; m_argv = argv; SetDefaultParams(&m_myParams); // define all the commandline and config file options setupProgramOptions(); po::positional_options_description p; p.add("input-file", 1); p.add("output-file", 1); p.add("otf-file", 1); // parse the commandline store(po::command_line_parser(argc, argv). options(m_progopts).positional(p).run(), m_varsmap); if (m_varsmap.count("help")) { std::cout << "cudasirecon v" + version_number + " -- Written by Lin Shao. All rights reserved.\n" << "\n"; std::cout << m_progopts << "\n"; exit(0); } if (m_varsmap.count("version")) { std::cout << "Version " << version_number << std::endl; exit(0); } notify(m_varsmap); if (m_config_file != "") { std::ifstream ifs(m_config_file.c_str()); if (!ifs) { std::cout << "can not open config file: " << m_config_file << "\n"; std::cout << "proceed without it\n"; } else { // parse config file store(parse_config_file(ifs, m_progopts), m_varsmap); notify(m_varsmap); } } // fill in m_myParams fields that have not been set yet setParams(); printf("nphases=%d, ndirs=%d\n", m_myParams.nphases, m_myParams.ndirs); // In TIFF mode, m_myParams.ifiles refers to the name of the folder raw data resides in; // and m_myParams.ofiles refers to a pattern in all the raw data file names. // To help decide if input is in TIFF or MRC format, gather all TIFF files with // matching names under the same folder: if (boost::filesystem::is_directory(m_myParams.ifiles)) { m_all_matching_files = gatherMatchingFiles(m_myParams.ifiles, m_myParams.ofiles); // If there is no name-matching TIFF files, then presumably input is MRC m_myParams.bTIFF = (m_all_matching_files.size() > 0); } if (m_myParams.bTIFF) { // Suppress "unknown field" warnings TIFFSetWarningHandler(NULL); m_imgParams.ntimes = m_all_matching_files.size(); } else { #ifndef MRC throw std::runtime_error("No tiff files found, and program was not compiled with MRC support."); #endif } m_OTFfile_valid = false; openFiles(); // deviceMemoryUsage(); setup(); #ifdef MRC if (!m_myParams.bTIFF) ::setOutputHeader(m_myParams, m_imgParams, m_in_out_header); #endif //! Load flat-field correction data bgAndSlope(m_myParams, m_imgParams, &m_reconData); } //! used by shared library SIM_Reconstructor::SIM_Reconstructor(int nx, int ny, int nimages, // number of raw images per volume std::string configFileName) { SetDefaultParams(&m_myParams); // define all the commandline and config file options setupProgramOptions(); std::ifstream ifs(configFileName.c_str()); if (ifs) { // parse config file store(parse_config_file(ifs, m_progopts), m_varsmap); notify(m_varsmap); } // fill in m_myParams fields that have not been set yet setParams(); // TODO: allow more direct access // will throw CImgIOException if file cannot be opened m_otf_tiff.assign(m_myParams.otffiles.c_str()); m_OTFfile_valid = true; m_myParams.bTIFF = true; // not really: but we don't want it to use MRC stuff std::cout << "zoomz: " << m_myParams.zoomfact << std::endl; setup(nx, ny, nimages, 1); bgAndSlope(m_myParams, m_imgParams, &m_reconData); } SIM_Reconstructor::~SIM_Reconstructor() { } int SIM_Reconstructor::setupProgramOptions() { // Declare a group of options that will be // allowed both on command line and in a config file m_progopts.add_options() ("input-file", po::value<std::string>(), "input file (or data folder in TIFF mode)") ("output-file", po::value<std::string>(), "output file (or filename pattern in TIFF mode)") ("otf-file", po::value<std::string>()->required(), "OTF file") ("usecorr", po::value<std::string>(), "use the flat-field correction file provided") ("ndirs", po::value<int>(&m_myParams.ndirs)->default_value(3), "number of directions") ("nphases", po::value<int>(&m_myParams.nphases)->default_value(5), "number of phases per direction") ("nordersout", po::value<int>(&m_myParams.norders_output)->default_value(0), "number of output orders; must be <= norders") ("angle0", po::value<float>(&m_myParams.k0startangle)->default_value(1.648), "angle of the first direction in radians") ("ls", po::value<float>(&m_myParams.linespacing)->default_value(0.172), "line spacing of SIM pattern in microns") ("na", po::value<float>(&m_myParams.na)->default_value(1.2), "Detection numerical aperture") ("nimm", po::value<float>(&m_myParams.nimm)->default_value(1.33), "refractive index of immersion medium") ("zoomfact", po::value<float>(&m_myParams.zoomfact)->default_value(2.), "lateral zoom factor") ("explodefact", po::value<float>(&m_myParams.explodefact)->default_value(1.), "artificially exploding the reciprocal-space distance between orders by this factor") ("zzoom", po::value<int>(&m_myParams.z_zoom)->default_value(1), "axial zoom factor") ("nofilteroverlaps", po::value<int>(&m_myParams.bFilteroverlaps)->implicit_value(false), "do not filter the overlaping region between bands usually used in trouble shooting") ("background", po::value<float>(&m_myParams.constbkgd)->default_value(0.), "camera readout background") ("wiener", po::value<float>(&m_myParams.wiener)->default_value(0.01), "Wiener constant") ("forcemodamp", po::value< std::vector<float> >()->multitoken(), "modamps forced to these values") ("k0angles", po::value< std::string >(), //po::value< std::vector<float> >()->multitoken(), "user given pattern vector k0 angles for all directions") ("otfRA", po::value<int>(&m_myParams.bRadAvgOTF)->implicit_value(true), "using rotationally averaged OTF") ("otfPerAngle", po::value<int>(&m_myParams.bOneOTFperAngle)->implicit_value(true), "using one OTF per SIM angle") ("fastSI", po::value<int>(&m_myParams.bFastSIM)->implicit_value(true), "SIM data is organized in Z->Angle->Phase order; default being Angle->Z->Phase") ("k0searchAll", po::value<int>(&m_myParams.bUseTime0k0)->implicit_value(false), "search for k0 at all time points") ("norescale", po::value<int>(&m_myParams.do_rescale)->implicit_value(false), "bleach correcting for z") ("equalizez", po::value<int>(&m_myParams.equalizez)->implicit_value(true), "bleach correcting for z") ("equalizet", po::value<int>(&m_myParams.equalizet)->implicit_value(true), "bleach correcting for time") ("dampenOrder0", po::value<int>(&m_myParams.bDampenOrder0)->implicit_value(true), "dampen order-0 in final assembly") ("nosuppress", po::value<int>(&m_myParams.bSuppress_singularities)->implicit_value(false), "do not suppress DC singularity in final assembly (good idea for 2D/TIRF data)") ("nokz0", po::value<int>(&m_myParams.bNoKz0)->implicit_value(true), "do not use kz=0 plane of the 0th order in the final assembly") ("gammaApo", po::value<float>(&m_myParams.apoGamma)->default_value(1.f), "output apodization gamma; 1.0 means triangular apo") ("saveprefiltered", po::value<std::string>(), "save separated bands (half Fourier space) into a file and exit") ("savealignedraw", po::value<std::string>(), "save drift-fixed raw data (half Fourier space) into a file and exit") ("saveoverlaps", po::value<std::string>(), "save overlap0 and overlap1 (real-space complex data) into a file and exit") ("config,c", po::value<std::string>(&m_config_file)->default_value(""), "name of a file of a configuration.") ("2lenses", po::value<int>(&m_myParams.bTwolens)->implicit_value(true), "I5S data") ("bessel", po::value<int>(&m_myParams.bBessel)->implicit_value(1), "bessel-SIM data") ("besselExWave", po::value<float>(&m_myParams.BesselLambdaEx)->default_value(0.488f), "Bessel SIM excitation wavelength in microns") ("besselNA", po::value<float>(&m_myParams.BesselNA)->default_value(0.144f), "Bessel SIM excitation NA)") ("deskew", po::value<float>(&m_myParams.deskewAngle)->default_value(0.0f), "Deskew angle; if not 0.0 then perform deskewing before processing") ("deskewshift", po::value<int>(&m_myParams.extraShift)->default_value(0), "If deskewed, the output image's extra shift in X (positive->left)") ("noRecon", po::bool_switch(&m_myParams.bNoRecon)->default_value(false), "No reconstruction will be performed; useful when combined with --deskew") ("cropXY", po::value<unsigned>(&m_myParams.cropXYto)->default_value(0), "Crop the X-Y dimension to this number; 0 means no cropping") ("xyres", po::value<float>(&m_imgParams.dxy)->default_value(0.1), "x-y pixel size (only used for TIFF files)") ("zres", po::value<float>(&m_imgParams.dz)->default_value(0.2), "z pixel size (only used for TIFF files)") ("zresPSF", po::value<float>(&m_myParams.dzPSF)->default_value(0.15), "z pixel size used in PSF TIFF files)") ("wavelength", po::value<short>(&m_imgParams.wave[0])->default_value(530), "emission wavelength (only used for TIFF files)") ("writeTitle", po::value<int>(&m_myParams.bWriteTitle)->implicit_value(true), "Write command line to image header (may cause issues with bioformats)") ("help,h", "produce help message") ("version", "show version") ; return 0; } int SIM_Reconstructor::setParams() { // "otf-file" is required argument if (m_varsmap.count("input-file")) { m_myParams.ifiles = m_varsmap["input-file"].as<std::string>(); } if (m_varsmap.count("output-file")) { m_myParams.ofiles = m_varsmap["output-file"].as<std::string>(); } if (m_varsmap.count("otf-file")) { m_myParams.otffiles = m_varsmap["otf-file"].as<std::string>(); } if (m_varsmap.count("usecorr")) { m_myParams.corrfiles = m_varsmap["usecorr"].as<std::string>(); m_myParams.bUsecorr = 1; } if (m_varsmap.count("forcemodamp")) { m_myParams.forceamp = m_varsmap["forcemodamp"].as< std::vector<float> >(); } if (m_varsmap.count("wiener")) { std::cout<< "wiener=" << m_myParams.wiener << std::endl; } if (m_varsmap.count("gammaApo")) { // because "gammaApo" has a default value set, this block is always entered; // and therefore, "apodizeoutput" is always 2 (triangular or gamma apo) m_myParams.apodizeoutput = 2; std::cout << "gamma = " << m_myParams.apoGamma << std::endl; } if (m_varsmap.count("saveprefiltered")) { m_myParams.fileSeparated = m_varsmap["saveprefiltered"].as<std::string>(); m_myParams.bSaveSeparated = 1; } if (m_varsmap.count("savealignedraw")) { m_myParams.fileRawAligned = m_varsmap["savealignedraw"].as<std::string>(); m_myParams.bSaveAlignedRaw = 1; } if (m_varsmap.count("saveoverlaps")) { m_myParams.fileOverlaps = m_varsmap["saveoverlaps"].as<std::string>(); m_myParams.bSaveOverlaps = 1; } if (m_varsmap.count("k0angles")) { boost::char_separator<char> sep(","); boost::tokenizer<boost::char_separator<char>> tokens(m_varsmap["k0angles"].as< std::string >(), sep); for ( auto it = tokens.begin(); it != tokens.end(); ++it) m_myParams.k0angles.push_back(strtod(it->c_str(), NULL)); // std::cout << m_myParams.k0angles << std::endl; } return 0; } void SIM_Reconstructor::openFiles() { if (!m_myParams.ifiles.size() || !m_myParams.ofiles.size()) throw std::runtime_error( "Calling openFiles() but no input or output files were specified"); #ifdef MRC if (!m_myParams.bTIFF && IMOpen(istream_no, m_myParams.ifiles.c_str(), "ro")) // TIFF files are not opened till loadAndRescaleImage() throw std::runtime_error("No matching input TIFF or MRC files not found"); // Create output file in MRC mode; // in TIFF mode, output files are not created until writeResult() is called if (!m_myParams.bTIFF) if (IMOpen(ostream_no, m_myParams.ofiles.c_str(), "new")) { std::cerr << "File " << m_myParams.ofiles << " can not be created.\n"; throw std::runtime_error("Error creating output file"); } #endif if (m_myParams.bTIFF) { // will throw CImgIOException if file cannot be opened m_otf_tiff.assign(m_myParams.otffiles.c_str()); m_OTFfile_valid = true; } #ifdef MRC else if (IMOpen(otfstream_no, m_myParams.otffiles.c_str(), "ro")) throw std::runtime_error("OTF file not found"); else m_OTFfile_valid = true; #endif } void SIM_Reconstructor::setup(unsigned nx, unsigned ny, unsigned nImages, unsigned nChannels) // for mem buffer inputs { m_imgParams.nx = nx; m_imgParams.nx_raw = nx; m_imgParams.ny = ny; m_imgParams.nz = nImages; m_imgParams.nwaves = nChannels; m_imgParams.nz /= m_imgParams.nwaves * m_myParams.nphases * m_myParams.ndirs; setup_common(); } //! Find out memory requirements and call setup_common allocate memory void SIM_Reconstructor::setup() { if (m_myParams.bTIFF) { CImg<> tiff0(m_all_matching_files[0].c_str()); m_imgParams.nx = 0; m_imgParams.nx_raw = tiff0.width(); m_imgParams.ny = tiff0.height(); m_imgParams.nz = tiff0.depth(); m_imgParams.nwaves = tiff0.spectrum(); // multi-color not supported yet m_imgParams.nz /= m_imgParams.nwaves * m_myParams.nphases * m_myParams.ndirs; } #ifdef MRC else ::loadHeader(m_myParams, &m_imgParams, m_in_out_header); #endif printf("nx_raw=%d, ny=%d, nz=%d\n", m_imgParams.nx_raw, m_imgParams.ny, m_imgParams.nz); setup_common(); } void SIM_Reconstructor::setup_common() { // Do we need to keep this?? -lin // if (m_myParams.bTIFF) // m_imgParams.nz0 = ::findOptimalDimension(m_imgParams.nz); m_zoffset = 0; if (m_myParams.nzPadTo) { // 'nzPadTo' ~never used m_imgParams.nz0 = m_myParams.nzPadTo; m_zoffset = (m_imgParams.nz0 - m_imgParams.nz) / 2; } else { m_imgParams.nz0 = m_imgParams.nz; } //! Deskewing, if requested, will be performed after this function returns; // "nx" is altered to be equal to "ny" and "dz" is multiplied by sin(deskewAngle) if (fabs(m_myParams.deskewAngle) > 0.) { if (m_myParams.deskewAngle <0) m_myParams.deskewAngle += 180.; m_imgParams.nx = findOptimalDimension(m_imgParams.nx_raw + m_imgParams.nz0 * fabs(cos(m_myParams.deskewAngle*M_PI/180.)) * m_imgParams.dz / m_imgParams.dxy); // m_imgParams.nx = m_imgParams.ny; m_imgParams.dz_raw = m_imgParams.dz; m_imgParams.dz *= fabs(sin(m_myParams.deskewAngle * M_PI/180.)); } else { m_imgParams.nx = m_imgParams.nx_raw; m_imgParams.dz_raw = 0; } //! If cropping is requested, change nx, ny accordingly: (does this work or make sense?) if (m_myParams.cropXYto > 0 && m_myParams.cropXYto < m_imgParams.nx) { m_imgParams.nx = m_myParams.cropXYto; // m_imgParams.ny = m_myParams.cropXYto; } printf("nx=%d, ny=%d, nz=%d, nz0 = %d, nwaves=%d\n", m_imgParams.nx, m_imgParams.ny, m_imgParams.nz, m_imgParams.nz0, m_imgParams.nwaves); printf("dxy=%f, dz=%f um\n", m_imgParams.dxy, m_imgParams.dz); #ifdef MRC // // Initialize headers for intermediate output files if requested if (!m_myParams.bTIFF) { if (m_myParams.bSaveAlignedRaw) { memcpy(&aligned_header, &m_in_out_header, sizeof(m_in_out_header)); IMOpen(aligned_stream_no, m_myParams.fileRawAligned.c_str(), "new"); aligned_header.mode = IW_FLOAT; aligned_header.nx = m_imgParams.nx; aligned_header.inbsym = 0; IMPutHdr(aligned_stream_no, &aligned_header); } if (m_myParams.bSaveSeparated) { memcpy(&sep_header, &m_in_out_header, sizeof(m_in_out_header)); IMOpen(separated_stream_no, m_myParams.fileSeparated.c_str(), "new"); sep_header.nx = m_imgParams.nx/2+1; // saved will be separated FFTs sep_header.mode = IW_COMPLEX; sep_header.inbsym = 0; IMPutHdr(separated_stream_no, &sep_header); } if (m_myParams.bSaveOverlaps) { memcpy(&overlaps_header, &m_in_out_header, sizeof(m_in_out_header)); IMOpen(overlaps_stream_no, m_myParams.fileOverlaps.c_str(), "new"); overlaps_header.nz = m_imgParams.nz*2*m_myParams.ndirs*m_imgParams.ntimes*m_imgParams.nwaves; overlaps_header.nx = m_imgParams.nx; overlaps_header.num_waves = 2; // save overlap 0 and 1 as wave 0 and 1 respectively overlaps_header.interleaved = WZT_SEQUENCE; overlaps_header.mode = IW_COMPLEX; // saved will be full-complex overlaps in real space overlaps_header.inbsym = 0; IMPutHdr(overlaps_stream_no, &overlaps_header); } } #endif m_myParams.norders = 0; if (m_myParams.norders_output != 0) { m_myParams.norders = m_myParams.norders_output; } else { m_myParams.norders = m_myParams.nphases / 2 + 1; } std::cout << "nphases=" << m_myParams.nphases << ", norders=" << m_myParams.norders << ", ndirs=" << m_myParams.ndirs << std::endl; if (m_OTFfile_valid) setupOTFsFromFile(); ::allocSepMatrixAndNoiseVarFactors(m_myParams, &m_reconData); ::makematrix(m_myParams.nphases, m_myParams.norders, 0, 0, &(m_reconData.sepMatrix[0]), &(m_reconData.noiseVarFactors[0])); ::allocateImageBuffers(m_myParams, m_imgParams, &m_reconData); m_imgParams.inscale = 1.0 / (m_imgParams.nx * m_imgParams.ny * m_imgParams.nz0 * m_myParams.zoomfact * m_myParams.zoomfact * m_myParams.z_zoom * m_myParams.ndirs); m_reconData.k0 = std::vector<vector>(m_myParams.ndirs); m_reconData.k0_time0 = std::vector<vector>(m_myParams.ndirs); m_reconData.k0guess = std::vector<vector>(m_myParams.ndirs); float delta_angle = M_PI / m_myParams.ndirs; float k0magguess = 1.0 / m_myParams.linespacing; // in 1/um, not assuming square images sizes if (m_imgParams.nz > 1) { int nordersIn = m_myParams.nphases / 2 + 1; k0magguess /= nordersIn - 1; } for (int i = 0; i < m_myParams.ndirs; ++i) { float k0angleguess; if (m_myParams.k0angles.size() < m_myParams.ndirs) { k0angleguess = m_myParams.k0startangle + i * delta_angle; } else { k0angleguess = m_myParams.k0angles[i]; } m_reconData.k0guess[i].x = k0magguess * cos(k0angleguess); // in 1/um m_reconData.k0guess[i].y = k0magguess * sin(k0angleguess); // in 1/um } m_reconData.sum_dir0_phase0 = std::vector<double>(m_imgParams.nz * m_imgParams.nwaves); m_reconData.amp = std::vector<std::vector<cuFloatComplex> >( m_myParams.ndirs, std::vector<cuFloatComplex>(m_myParams.norders)); for (int i = 0; i < m_myParams.ndirs; ++i) { m_reconData.amp[i][0].x = 1.0f; m_reconData.amp[i][0].y = 0.0f; } } int SIM_Reconstructor::processOneVolume() { // process one SIM volume (i.e., for the time point timeIdx) m_reconData.bigbuffer.resize(0); m_reconData.outbuffer.resize(0); m_reconData.overlap0.resize(m_imgParams.nx * m_imgParams.ny * m_imgParams.nz * sizeof(cuFloatComplex)); m_reconData.overlap0.setToZero(); m_reconData.overlap1.resize(m_imgParams.nx * m_imgParams.ny * m_imgParams.nz * sizeof(cuFloatComplex)); m_reconData.overlap1.setToZero(); findModulationVectorsAndPhasesForAllDirections(m_zoffset, &m_myParams, m_imgParams, &m_driftParams, &m_reconData); m_reconData.overlap0.resize(0); m_reconData.overlap1.resize(0); // deviceMemoryUsage(); #ifdef MRC if (saveIntermediateDataForDebugging(m_myParams)) return 0; #endif m_reconData.bigbuffer.resize((m_myParams.zoomfact * m_imgParams.nx) * (m_myParams.zoomfact * m_imgParams.ny) * (m_myParams.z_zoom * m_imgParams.nz0) * sizeof(cuFloatComplex)); m_reconData.bigbuffer.setToZero(); m_reconData.outbuffer.resize((m_myParams.zoomfact * m_imgParams.nx) * (m_myParams.zoomfact * m_imgParams.ny) * (m_myParams.z_zoom * m_imgParams.nz0) * sizeof(float)); m_reconData.outbuffer.setToZero(); // deviceMemoryUsage(); for (int direction = 0; direction < m_myParams.ndirs; ++direction) { // dir_ is used in upcoming calls involving otf, to differentiate the cases // of common OTF and dir-specific OTF int dir_ = 0; if (m_myParams.bOneOTFperAngle) dir_ = direction; filterbands(direction, &m_reconData.savedBands[direction], m_reconData.k0, m_myParams.ndirs, m_myParams.norders, m_reconData.otf[dir_], m_imgParams.dxy, m_imgParams.dz, m_reconData.amp, m_reconData.noiseVarFactors, m_imgParams.nx, m_imgParams.ny, m_imgParams.nz0, m_imgParams.wave[0], &m_myParams); assemblerealspacebands( direction, &m_reconData.outbuffer, &m_reconData.bigbuffer, &m_reconData.savedBands[direction], m_myParams.ndirs, m_myParams.norders, m_reconData.k0, m_imgParams.nx, m_imgParams.ny, m_imgParams.nz0, m_imgParams.dxy, m_myParams.zoomfact, m_myParams.z_zoom, m_myParams.explodefact); } return 1; } void SIM_Reconstructor::loadAndRescaleImage(int timeIdx, int waveIdx) { if (m_myParams.bBessel && m_myParams.bNoRecon) return; ::rescaleDriver(timeIdx, waveIdx, m_zoffset, &m_myParams, m_imgParams, &m_driftParams, &m_reconData); } void SIM_Reconstructor::setRaw(CImg<> &input, int it, int iw) { rawImage.assign(input); loadImageData(it, iw); } void SIM_Reconstructor::setFile(int it, int iw) { if (m_myParams.bTIFF) { rawImage.assign(m_all_matching_files[it].c_str()); } #ifdef MRC else { rawImage.assign(m_imgParams.nx_raw, m_imgParams.ny, m_imgParams.nz * m_myParams.nphases * m_myParams.ndirs); for (unsigned sec=0; sec<rawImage.depth(); sec++) { IMPosnZWT(istream_no, sec, iw, it); IMRdSec(istream_no, rawImage.data(0, 0, sec)); } } #endif loadImageData(it, iw); } void SIM_Reconstructor::loadImageData(int it, int iw) { float dskewA = m_myParams.deskewAngle; // if ( dskewA<0) dskewA += 180.; already done in setup_common() float deskewFactor = 0; if (fabs(dskewA) > 0.0) deskewFactor = cos(dskewA * M_PI / 180.) * m_imgParams.dz_raw / m_imgParams.dxy; for (int direction = 0; direction < m_myParams.ndirs; ++direction) { // What does "PinnedCPUBuffer" really do? Using it here messes things up. CPUBuffer nxExtendedBuff(sizeof(float) * (m_imgParams.nx / 2 + 1) * 2 * m_imgParams.ny); std::vector<GPUBuffer>* rawImages = &(m_reconData.savedBands[direction]); int z = 0; for (z = 0; z < m_imgParams.nz; ++z) { CImg<> rawSection(m_imgParams.nx_raw, m_imgParams.ny); int zsec; // First determine which section of the raw data to load if (m_myParams.bFastSIM) { // data organized into (nz, ndirs, nphases) zsec = (z * m_myParams.ndirs * m_myParams.nphases + direction * m_myParams.nphases); } else { // data organized into (ndirs, nz, nphases) zsec = direction * m_imgParams.nz * m_myParams.nphases + z * m_myParams.nphases; } for (int phase = 0; phase < m_myParams.nphases; ++phase) { #ifdef MRC if (m_myParams.bBgInExtHdr) { /* subtract the background value of each exposure stored in MRC files' extended header, indexed by the section number. */ int extInts; float extFloats[3]; IMRtExHdrZWT(istream_no, zsec, iw, it, &extInts, extFloats); m_reconData.backgroundExtra = extFloats[2]; } #endif load_and_flatfield(rawImage, zsec, rawSection.data(), (float*)m_reconData.background.getPtr(), m_reconData.backgroundExtra, (float*)m_reconData.slope.getPtr(), m_imgParams.inscale); // if deskewFactor > 0, then do deskew for current z; otherwise, simply // transfer from "rawSection" to "nxExtendedBuff". In either case, // "nxExtendedBuff" holds result of current z. deskewOneSection(rawSection, (float*)nxExtendedBuff.getPtr(), z, m_imgParams.nz, m_imgParams.nx, deskewFactor, m_myParams.extraShift); // Transfer the data from nxExtendedBuff to device buffer previously // allocated (see m_reconData.savedBands) std::cout << "z=" << z; nxExtendedBuff.set( &(rawImages->at(phase)), 0, (m_imgParams.nx / 2 + 1) * 2 * m_imgParams.ny * sizeof(float), (z + m_zoffset) * (m_imgParams.nx / 2 + 1) * 2 * m_imgParams.ny * sizeof(float)); // std::cout << ", phase=" << phase << std::endl; ++zsec; } // end for (phase) } // end for (z) #ifndef NDEBUG for (auto i = rawImages->begin(); i != rawImages->end(); ++i) assert(i->hasNaNs() == false); #endif //! if (fabs(m_myParams.deskewAngle) > 0. && m_myParams.bNoRecon) { // To-do: add code to off load rawImages into rawtiff_uint16 // if (m_myParams.bNoRecon) { // CImg<unsigned short> rawtiff_uint16; // rawtiff_uint16.save_tiff(makeOutputFilePath(m_all_matching_files[it], // std::string("_deskewed")).c_str()); // std::cout << "Deskewed images written\n"; // return; // } } } // end for (direction) } void SIM_Reconstructor::setupOTFsFromFile() { determine_otf_dimensions(); ::allocateOTFs(&m_myParams, m_reconData.sizeOTF, m_reconData.otf); loadOTFs(); } void SIM_Reconstructor::determine_otf_dimensions() { if (m_myParams.bTIFF) { uint32_t nxotf, nyotf, nzotf; nxotf = m_otf_tiff.width()/2; // "/2" because of real and imaginary parts nyotf = m_otf_tiff.height(); nzotf = m_otf_tiff.depth(); /* determine nzotf, nxotf, nyotf, dkrotf, dkzotf based on dataset being 2D/3D and flags bRadAvgOTF and bOneOTFperAngle */ if (m_imgParams.nz == 1) { // 2D m_myParams.nxotf = nxotf; if (m_myParams.bRadAvgOTF) m_myParams.nyotf = 1; else m_myParams.nyotf = nyotf; m_myParams.nzotf = 1; // m_myParams.dkrotf = xres; // dkrotf's unit is 1/micron m_myParams.dkrotf = 1/(m_imgParams.dxy * (nxotf-1)*2); // dkrotf's unit is 1/micron m_myParams.dkzotf = 1; } else { // 3D if (m_myParams.bRadAvgOTF) { m_myParams.nzotf = nxotf; m_myParams.nxotf = nyotf; m_myParams.nyotf = 1; m_myParams.dkzotf = 1/(m_myParams.dzPSF * m_myParams.nzotf); m_myParams.dkrotf = 1/(m_imgParams.dxy * (m_myParams.nxotf-1)*2); } else { m_myParams.nzotf = nzotf / m_myParams.norders; // each order has a 3D OTF stack (non-negative kx half of Fourier space) m_myParams.nxotf = nxotf; m_myParams.nyotf = nyotf; m_myParams.dkzotf = 1/(m_myParams.dzPSF * m_myParams.nzotf); m_myParams.dkrotf = 1/(m_imgParams.dxy * m_myParams.nxotf); } } } #ifdef MRC else { int ixyz[3], mxyz[3], pixeltype; float min, max, mean; IW_MRC_HEADER otfheader; /* Retrieve OTF file header info */ IMRdHdr(otfstream_no, ixyz, mxyz, &pixeltype, &min, &max, &mean); IMGetHdr(otfstream_no, &otfheader); IMAlCon(otfstream_no, 0); /* determine nzotf, nxotf, nyotf, dkrotf, dkzotf based on dataset * being 2D/3D and flags bRadAvgOTF and bOneOTFperAngle */ if (m_imgParams.nz == 1) { // 2D, ignore bOneOTFperAngle m_myParams.nxotf = otfheader.nx; if (m_myParams.bRadAvgOTF) m_myParams.nyotf = 1; else m_myParams.nyotf = otfheader.ny; m_myParams.nzotf = 1; m_myParams.dkrotf = otfheader.xlen; // dkrotf's unit is 1/micron m_myParams.dkzotf = 1; } else { // 3D, take into account bOneOTFperAngle if (m_myParams.bRadAvgOTF) { m_myParams.nzotf = otfheader.nx; m_myParams.nxotf = otfheader.ny; m_myParams.nyotf = 1; m_myParams.dkzotf = otfheader.xlen; m_myParams.dkrotf = otfheader.ylen; } else { // each order has a 3D OTF stack (non-negative kx half of Fourier // space) m_myParams.nzotf = otfheader.nz / m_myParams.norders; if (m_myParams.bOneOTFperAngle) m_myParams.nzotf /= m_myParams.ndirs; m_myParams.nxotf = otfheader.nx; m_myParams.nyotf = otfheader.ny; m_myParams.dkzotf = otfheader.zlen; m_myParams.dkrotf = otfheader.xlen; } } } #endif printf("nzotf=%d, dkzotf=%f, nxotf=%d, nyotf=%d, dkrotf=%f\n", m_myParams.nzotf, m_myParams.dkzotf, m_myParams.nxotf, m_myParams.nyotf, m_myParams.dkrotf); //! sizeOTF are determined so that correct memory can be allocated for otf m_reconData.sizeOTF = m_myParams.nzotf*m_myParams.nxotf*m_myParams.nyotf; } int SIM_Reconstructor::loadOTFs() { // If one OTF per direction is used, then load all dirs of OTF unsigned short nDirsOTF = 1; if (m_myParams.bOneOTFperAngle) nDirsOTF = m_myParams.ndirs; // Load OTF data, no matter 2D, 3D, radially averaged or not. if (m_myParams.bTIFF) { size_t nzotf = m_otf_tiff.depth(); cuFloatComplex * otfTmp; CPUBuffer otfTmpBuffer(m_reconData.sizeOTF * sizeof(cuFloatComplex)); for (int dir = 0; dir < nDirsOTF; dir++) { for (int i=0; i<m_myParams.norders; i++) { // If OTF file has multiple sections, then read them into otf[i] if (m_imgParams.nz == 1 || m_myParams.bRadAvgOTF) { if (nzotf > i + dir*m_myParams.norders) { // each section in OTF file is OTF of one order; so load that section into otf[dir][i] otfTmp = (cuFloatComplex *) m_otf_tiff.data(0, 0, i); otfTmpBuffer.setFrom((void*) otfTmp, 0, m_reconData.sizeOTF * sizeof(cuFloatComplex), 0); m_reconData.otf[dir][i].setFrom(otfTmpBuffer, 0, m_reconData.sizeOTF * sizeof(cuFloatComplex), 0); } else // If there's just 1 OTF image, do not read any more and just duplicate otf[0][0] into otf[*][i] m_reconData.otf[0][0].set(&(m_reconData.otf[dir][i]), 0, m_reconData.otf[0][0].getSize(), 0); } else { // non-radially averaged 3D OTF otfTmp = (cuFloatComplex *) m_otf_tiff.data(0, 0, i * m_myParams.nzotf); otfTmpBuffer.setFrom((void*) otfTmp, 0, m_reconData.sizeOTF * sizeof(cuFloatComplex), 0); m_reconData.otf[dir][i].setFrom(otfTmpBuffer, 0, m_reconData.sizeOTF * sizeof(cuFloatComplex), 0); } } } } #ifdef MRC else { int ixyz[3], mxyz[3], pixeltype; float min, max, mean; IW_MRC_HEADER otfheader; /* Retrieve OTF file header info */ IMRdHdr(otfstream_no, ixyz, mxyz, &pixeltype, &min, &max, &mean); IMGetHdr(otfstream_no, &otfheader); CPUBuffer otfTmp(m_reconData.sizeOTF * sizeof(cuFloatComplex)); for (int dir = 0; dir< nDirsOTF; dir++) { for (int i = 0; i < m_myParams.norders; i++) { /* If OTF file has multiple sections, then read them into otf[i]; */ if (m_imgParams.nz == 1 || m_myParams.bRadAvgOTF) { if (otfheader.nz > i + dir*m_myParams.norders) { // each section in OTF file is OTF of one order; so load that section into otf[dir][i] IMRdSec(otfstream_no, otfTmp.getPtr()); otfTmp.set(&(m_reconData.otf[dir][i]), 0, otfTmp.getSize(), 0); } else { /* If it's 2D image, do not read any more and just * duplicate otf[0][0] into otf[*][i] */ m_reconData.otf[0][0].set(&(m_reconData.otf[dir][i]), 0, m_reconData.otf[0][0].getSize(), 0); } } else { // non-radially averaged 3D OTF for (int z = 0; z < m_myParams.nzotf; ++z) { IMRdSec(otfstream_no, otfTmp.getPtr()); otfTmp.set(&(m_reconData.otf[dir][i]), 0, m_myParams.nxotf * m_myParams.nyotf * sizeof(cuFloatComplex), z * m_myParams.nxotf * m_myParams.nyotf * sizeof(cuFloatComplex)); } } } } IMClose(otfstream_no); } #endif #ifndef NDEBUG for (int dir = 0; dir < nDirsOTF; dir++) for (auto i = m_reconData.otf[dir].begin(); i != m_reconData.otf[dir].end(); ++i) assert(i->hasNaNs() == false); #endif return 1; } // Transfer m_reconData from GPU to result buffer void SIM_Reconstructor::getResult(float * result) { CPUBuffer outbufferHost((m_myParams.zoomfact * m_imgParams.nx) * (m_myParams.zoomfact * m_imgParams.ny) * (m_myParams.z_zoom * m_imgParams.nz0) * sizeof(float)); m_reconData.outbuffer.set(&outbufferHost, 0, outbufferHost.getSize(), 0); CImg<> outCimg( (float*)outbufferHost.getPtr(), m_myParams.zoomfact * m_imgParams.nx, m_myParams.zoomfact * m_imgParams.ny, m_myParams.z_zoom * m_imgParams.nz0, true); memcpy(result, outCimg.data(), outCimg.size() * sizeof(float)); } void SIM_Reconstructor::writeResult(int it, int iw) { CPUBuffer outbufferHost( (m_myParams.zoomfact * m_imgParams.nx) * (m_myParams.zoomfact * m_imgParams.ny) * (m_myParams.z_zoom * m_imgParams.nz0) * sizeof(float)); // if (it==0) // computeAminAmax(&reconData.outbuffer, m_myParams.zoomfact * m_imgParams.nx, // m_myParams.zoomfact * m_imgParams.ny, m_myParams.z_zoom * m_imgParams.nz, // &minval, &maxval); m_reconData.outbuffer.set(&outbufferHost, 0, outbufferHost.getSize(), 0); #ifndef __clang__ double t1 = omp_get_wtime(); #endif if (m_myParams.bTIFF) { CImg<> outCimg((float*) outbufferHost.getPtr(), m_myParams.zoomfact * m_imgParams.nx, m_myParams.zoomfact * m_imgParams.ny, m_myParams.z_zoom * m_imgParams.nz0, true); // "true" means outCimg does not allocate host memory outCimg.save(makeOutputFilePath(m_all_matching_files[it], std::string("_proc")).c_str()); } #ifdef MRC else { float maxval = -FLT_MAX; float minval = FLT_MAX; float* ptr = ((float*)outbufferHost.getPtr()) + (int)(m_zoffset * m_myParams.z_zoom * m_imgParams.nx * m_imgParams.ny * m_myParams.zoomfact * m_myParams.zoomfact); for (int i = 0; i < m_imgParams.nz * m_myParams.z_zoom; ++i) { IMWrSec(ostream_no, ptr); if (it == 0) { for (int j = 0; j < (int)(m_imgParams.nx * m_imgParams.ny * m_myParams.zoomfact * m_myParams.zoomfact); ++j) { if (ptr[j] > maxval) { maxval = ptr[j]; } else if (ptr[j] < minval) { minval = ptr[j]; } } } ptr += (int)(m_myParams.zoomfact * m_imgParams.nx * m_myParams.zoomfact * m_imgParams.ny); } if (it == 0 && iw == 0) { m_in_out_header.amin = minval; m_in_out_header.amax = maxval; } } #endif #ifndef __clang__ double t2 = omp_get_wtime(); printf("amin, amax took: %f s\n", t2 - t1); #endif printf("Time point %d, wave %d done\n", it, iw); } void SIM_Reconstructor::closeFiles() { if (m_myParams.bTIFF) {} else { #ifdef MRC ::IMClose(istream_no); ::saveCommandLineToHeader(m_argc, m_argv, m_in_out_header, m_myParams); ::IMClose(ostream_no); #endif } } void load_and_flatfield(CImg<> &cimg, int section_no, float *bufDestiny, float *background, float backgroundExtra, float *slope, float inscale) { float *buffer = cimg.data(0, 0, section_no); int nx = cimg.width(); int ny = cimg.height(); unsigned extraX = 0; #pragma omp parallel for for (int l=0; l<ny; l++) { for (int k=0; k<nx; k++) { bufDestiny[l*(nx+extraX) + k] = (buffer[l*nx+k] - background[l*nx+k] - backgroundExtra) * slope[l*nx+k] * inscale; } for(int k=nx; k<nx+extraX; k++) bufDestiny[l*(nx+extraX) + k] = 0.0; } } void deskewOneSection(CImg<> &rawSection, float* nxp2OutBuff, int z, int nz, int nx_out, float deskewFactor, int extraShift) { unsigned nx_in = rawSection.width(); unsigned ny_in = rawSection.height(); float *in = rawSection.data(); int nx_out_ext = (nx_out/2+1)*2; // std::cout << "In deskewOneSection, deskewFactor=" << deskewFactor << std::endl; #pragma omp parallel for for (auto xout=0; xout<nx_out_ext; xout++) { float xin = xout; if (fabs(deskewFactor) > 0) xin = xout - nx_out/2. + extraShift - deskewFactor*(z-nz/2.) + nx_in/2.; for (int y=0; y<ny_in; y++) { unsigned indout = y * nx_out_ext + xout; if (xin >= 0 && xin < nx_in-1) { unsigned indin = y * nx_in + (unsigned int) floor(xin); float offset = xin - floor(xin); nxp2OutBuff[indout] = (1-offset) * in[indin] + offset * in[indin+1]; } else nxp2OutBuff[indout] = 0.; } } }
[STATEMENT] lemma dropWhile_eq_drop: "dropWhile P xs = drop (length (takeWhile P xs)) xs" [PROOF STATE] proof (prove) goal (1 subgoal): 1. dropWhile P xs = drop (length (takeWhile P xs)) xs [PROOF STEP] by (induct xs) auto
-- import SciLean.Core.Data.Curry import SciLean.Mathlib.Convenient.Basic -- import SciLean.Core.New.IsSmooth import SciLean.Core.TensorProduct import SciLean.Core.FinVec import SciLean.Core.SmoothMap namespace SciLean --TODO: Question? -- Should linearity include smoothness? Are there usefull linear -- functions that are not smooth? -- In finite dimension every linear function is smooth but in infitite -- dimensional spaces it does not have to be the case. /-- Function `f : X₁ → ... Xₙ → Y'` is a linear as a function `X₁ × ... × Xₙ → Y'`. Where `X = X₁` and `Y = X₂ → ... → Xₙ → Y'` Transitive closure of `IsLinNT` -/ class IsLinNT {X Y : Type} {Xs Y' : Type} [Vec Xs] [Vec Y'] (n : Nat) (f : X → Y) [Prod.Uncurry n (X → Y) Xs Y'] : Prop where is_lin : TensorProduct.is_linear (uncurryN n f) is_smooth : IsSmoothT (uncurryN n f) /-- Function `f : X₁ → ... Xₙ → Y'` is a linear as a function `X₁ × ... × Xₙ → Y'`. Where `X = X₁` and `Y = X₂ → ... → Xₙ → Y'` -/ class IsLinN {X Y : Type} {Xs Y' : Type} [Vec Xs] [Vec Y'] (n : Nat) (f : X → Y) [Prod.Uncurry n (X → Y) Xs Y'] extends IsLinNT n f : Prop /-- `IsLin f` says that `f : X → Y` is linear. Abbreviation for `IsLinN 1 f` -/ abbrev IsLin {X Y} [Vec X] [Vec Y] (f : X → Y) : Prop := IsLinN 1 f /-- `IsLinT f` says that `f : X → Y` is linear. Abbreviation for `IsLinNT 1 f`. `IsLinT` is transitive closure of `IsLin`. -/ abbrev IsLinT {X Y} [Vec X] [Vec Y] (f : X → Y) : Prop := IsLinNT 1 f structure LinMap (X Y : Type) [Vec X] [Vec Y] where val : X → Y [property : IsLinT val] /-- `X --o Y` is the space of all linear maps between `X` and `Y`. The notation `X ⊸ Y` is prefered, but this fixes pure ASCII equivalent. -/ infixr:25 " --o " => LinMap /-- `X ⊸ Y` is the space of all linear maps between `X` and `Y` -/ infixr:25 " ⊸ " => LinMap -- Lambda notation open Lean.TSyntax.Compat in macro "λ" xs:Lean.explicitBinders " ⊸ " b:term : term => Lean.expandExplicitBinders `SciLean.LinMap.mk xs b variable {X Y Z W: Type} [Vec X] [Vec Y] [Vec Z] [Vec W] instance : CoeFun (X⊸Y) (λ _ => X→Y) := ⟨λ f => f.1⟩ instance LinMap.val.arg_x.isLin {X Y} [Vec X] [Vec Y] (f : X ⊸ Y) : IsLinT f.1 := f.2 abbrev LinMap.mk' {X Y} [Vec X] [Vec Y] (f : X → Y) (_ : IsLinT f) : X⊸Y := λ x ⊸ f x @[ext] theorem LinMap.ext {X Y} [Vec X] [Vec Y] (f g : X ⊸ Y) : (∀ x, f x = g x) → f = g := by sorry @[simp, diff_simp] theorem LinMap.eta_reduction {X Y} [Vec X] [Vec Y] (f : X ⊸ Y) : (λ (x : X) ⊸ f x) = f := by rfl; done theorem show_is_lin_via {X Y} [Vec X] [Vec Y] {f : X → Y} (g : X ⊸ Y) : (f = g) → IsLinT f := by intro p have q : f = g := by apply p rw[q]; infer_instance namespace Lin variable {Z : Type} [Vec Z] {α : Type} def comp' : (Y⊸Z) → (X⊸Y) → (X⊸Z) := λ f g => LinMap.mk' (λ x => f (g x)) sorry def prodMap' : (X⊸Y) → (X⊸Z) → (X ⊸ Y×Z) := λ f g => LinMap.mk' (λ x => (f x, g x)) sorry def zeroFun : Y⊸X := LinMap.mk' (λ y => (0 : X)) sorry def swap : X⊗Y → Y⊗X := (λ xy => xy.map' (λ (x : X) (y : Y) => y⊗x) sorry) @[simp] theorem comp'_eval (f : Y ⊸ Z) (g : X⊸Y) (x : X) : comp' f g x = f (g x) := by simp[comp'] @[simp] theorem prodMap'_eval (f : X ⊸ Y) (g : X⊸Z) (x : X) : prodMap' f g x = (f x, g x) := by simp[prodMap'] @[simp] theorem zeroFun_eval (y : Y) : zeroFun y = (0 : X) := by simp[zeroFun] def neg : X ⊸ X := LinMap.mk' (λ x => -x) sorry def add' : X×X ⊸ X := LinMap.mk' (λ (x,y) => x+y) sorry def sub' : X×X ⊸ X := LinMap.mk' (λ (x,y) => x-y) sorry def mul' : ℝ×ℝ ⊸ ℝ := LinMap.mk' (λ (x,y) => x*y) sorry -- def tassocl : -- def tassocr : def unit' : ℝ → X ⊸ ℝ⊗X := λ r => LinMap.mk' (λ x => r⊗x) sorry def counit : ℝ⊗X ⊸ X := LinMap.mk' ((λ rx => rx.map' (λ r x => r • x) sorry)) sorry @[simp] theorem unit'_eval (r : ℝ) (x : X) : unit' r x = r⊗x := by simp[unit'] @[simp] theorem counit_eval (r : ℝ) (x : X) : counit (r⊗x) = r•x := by simp[counit] instance : Neg (X⊸Y) := ⟨λ f => LinMap.mk' (λ x => -f x) (show_is_lin_via (comp' neg f) (by funext; simp[neg]))⟩ instance : Add (X⊸Y) := ⟨λ f g => LinMap.mk' (λ x => f x + g x) (show_is_lin_via (comp' add' (prodMap' f g)) (by funext; simp[add']))⟩ instance : Sub (X⊸Y) := ⟨λ f g => LinMap.mk' (λ x => f x - g x) (show_is_lin_via (comp' sub' (prodMap' f g)) (by funext; simp[sub']))⟩ instance : Mul (X⊸ℝ) := ⟨λ f g => LinMap.mk' (λ x => f x * g x) (show_is_lin_via (comp' mul' (prodMap' f g)) (by funext; simp[mul']))⟩ instance : SMul ℝ (X⊸Y) := ⟨λ r f => LinMap.mk' (λ x => r • f x) (show_is_lin_via (comp' counit (comp' (unit' r) f)) (by funext; simp))⟩ instance : Zero (X ⊸ Y) := ⟨zeroFun⟩ -- !!!THIS USES SORRY!!! instance : Vec (X ⊸ Y) := Vec.mkSorryProofs end Lin def TensorProduct.map (f : X ⊸ Y ⊸ Z) (xy : X⊗Y) : Z := xy.map' (λ x y => f x y) sorry_proof namespace Lin @[infer_tc_goals_rl] instance {X ι} [Enumtype ι] [FinVec X ι] [Hilbert Y] : Inner (X ⊸ Y) where -- This should be the correct version of the inner product -- It looks assymetrical but it is a consequence of `inner_proj_dualproj` -- ⟪x, y⟫ = ∑ i, 𝕡 i x * 𝕡' i y -- which also appears assymetrical inner f g := ∑ i, ⟪f (𝕖 i), g (𝕖' i)⟫ @[infer_tc_goals_rl] instance {X ι} [Enumtype ι] [FinVec X ι] [Hilbert Y] : TestFunctions (X ⊸ Y) where TestFun _ := True @[infer_tc_goals_rl] instance {X ι} [Enumtype ι] [FinVec X ι] [Hilbert Y] : SemiHilbert (X ⊸ Y) := SemiHilbert.mkSorryProofs @[infer_tc_goals_rl] instance {X ι} [Enumtype ι] [FinVec X ι] [Hilbert Y] : Hilbert (X ⊸ Y) := Hilbert.mkSorryProofs @[infer_tc_goals_rl] instance {X ι κ} [Enumtype ι] [Enumtype κ] [FinVec X ι] [FinVec Y κ] : Basis (X ⊸ Y) (ι×κ) ℝ where basis := λ (i,j) => LinMap.mk' (λ x => 𝕡 i x • 𝕖[Y] j) sorry_proof proj := λ (i,j) f => 𝕡 j (f (𝕖 i)) @[infer_tc_goals_rl] instance {X ι κ} [Enumtype ι] [Enumtype κ] [FinVec X ι] [FinVec Y κ] : DualBasis (X ⊸ Y) (ι×κ) ℝ where dualBasis := λ (i,j) => LinMap.mk' (λ x => 𝕡' i x • 𝕖'[Y] j) sorry_proof dualProj := λ (i,j) f => 𝕡' j (f (𝕖' i)) open BasisDuality in @[infer_tc_goals_rl] instance {X ι κ} [Enumtype ι] [Enumtype κ] [FinVec X ι] [FinVec Y κ] : BasisDuality (X ⊸ Y) where toDual := λ f => LinMap.mk' (λ x => toDual (f (fromDual x))) sorry_proof fromDual := λ f => LinMap.mk' (λ x => fromDual (f (toDual x))) sorry_proof @[infer_tc_goals_rl] instance {X ι κ} [Enumtype ι] [Enumtype κ] [FinVec X ι] [FinVec Y κ] : FinVec (X ⊸ Y) (ι×κ) where is_basis := sorry_proof duality := by intro (i,j) (i',j'); simp[Basis.basis, DualBasis.dualBasis, Inner.inner]; -- This should be: -- ∑ i_i, ⟪[[i=i_]] * 𝕖 j, [[i'=i_1]] 𝕖' j'⟫ -- [[i=i']] * ⟪𝕖 j, 𝕖' j'⟫ -- [[i=i']] * [[j=j']] sorry_proof to_dual := by simp [BasisDuality.toDual, Basis.proj, DualBasis.dualBasis] intro f; ext x; simp[FinVec.to_dual,FinVec.from_dual] -- Now the goal is: -- ∑ j, 𝕡 j (f (∑ i, 𝕡' i x * 𝕖 i)) * 𝕖' j -- = -- ∑ (i,j), 𝕡 j (f (𝕖 i)) * 𝕡' i x * 𝕖' j sorry_proof from_dual := by simp [BasisDuality.fromDual, DualBasis.dualProj, Basis.basis] intro f; ext x; simp[FinVec.to_dual,FinVec.from_dual] -- Now the goal is: -- ∑ j, 𝕡' j (f (∑ i, 𝕡 i x * 𝕖' i)) * 𝕖 j -- = -- ∑ (i,j), 𝕡' j (f (𝕖' i)) * 𝕡' i x * 𝕖 j sorry_proof -------------------------------------------------------------------- def curry' (f : X ⊗ Y ⊸ Z) : (X ⊸ Y ⊸ Z) := LinMap.mk' (λ x => LinMap.mk' (λ y => f (x ⊗ y)) sorry_proof) sorry_proof def uncurry' (f : X ⊸ Y ⊸ Z) : (X ⊗ Y ⊸ Z) := LinMap.mk' (λ xy => xy.map' (λ x y => f x y) sorry_proof) sorry_proof def id : X ⊸ X := LinMap.mk' (λ x => x) sorry_proof def fst : X×Y ⊸ X := LinMap.mk' (λ (x,_) => x) sorry_proof def snd : X×Y ⊸ Y := LinMap.mk' (λ (_,y) => y) sorry_proof @[simp] theorem curry'_eval (f : X⊗Y ⊸ Z) (x : X) (y : Y) : curry' f x y = f (x⊗y) := by simp[curry'] @[simp] theorem uncurry'_eval (f : X ⊸ Y ⊸ Z) (xy : X⊗Y) : uncurry' f xy = xy.map f := by simp[uncurry',TensorProduct.map] @[simp] theorem id_eval (x : X) : id x = x := by simp[id] @[simp] theorem fst_eval (xy : X×Y) : fst xy = xy.1 := by simp[fst] @[simp] theorem snd_eval (xy : X×Y) : snd xy = xy.2 := by simp[snd] def tprod : X ⊸ Y ⊸ X⊗Y := LinMap.mk' (λ x => LinMap.mk' (λ y => x⊗y) (show_is_lin_via (curry' id x) (by ext y; simp))) (show_is_lin_via (curry' id) (by ext x y; simp)) -- noncomputable -- def tpmap : (X⊸Y) ⊸ (X⊸Z) ⊸ (X⊸Y⊗Z) := ⟨λ f => ⟨λ g => ⟨λ x => (f x ⊗ g x), sorry_proof⟩, sorry_proof⟩, sorry_proof⟩ -- noncomputable -- def tfmap : (X⊸Z) ⊸ (Y⊸W) ⊸ (X⊗Y⊸Z⊗W) := ⟨λ f => ⟨λ g => ⟨λ xy => -- let ⟨_,x,y⟩ := xy.repr -- ∑ i, f (x i) ⊗ g (y i), sorry_proof⟩, sorry_proof⟩, sorry_proof⟩ -- def pmap : (X⊸Y) × (X⊸Z) ⊸ (X⊸Y×Z) := ⟨λ (f,g) => ⟨λ x => (f x, g x), sorry_proof⟩, sorry_proof⟩ -- def fmap : (X⊸Z) × (Y⊸W) ⊸ (X×Y⊸Z×W) := ⟨λ (f,g) =>⟨λ (x,y) => (f x, g y), sorry_proof⟩, sorry_proof⟩ -- def fmap' : (X→Z) × (Y→W) ⊸ (X×Y→Z×W) := ⟨λ (f,g) => λ (x,y) => (f x, g y), sorry_proof⟩ -- def pmap' : (X→Y) × (X→Z) ⊸ (X→Y×Z) := ⟨λ (f,g) => λ x => (f x, g x), sorry_proof⟩ -- -- I don't think this is a valid map -- -- noncomputable -- -- def tfmap' : (X→Z) ⊸ (Y→W) ⊸ (X⊗Y→Z⊗W) := ⟨λ f => ⟨ λ g => λ xy => -- -- let ⟨_,x,y⟩ := xy.repr -- -- ∑ i, f (x i) ⊗ g (y i), sorry_proof⟩, sorry_proof⟩ -- noncomputable -- def tpmap' : (X→Y) ⊸ (X→Z) ⊸ (X→Y⊗Z) := ⟨λ f => ⟨λ g => λ x => f x ⊗ g x, sorry_proof⟩, sorry_proof⟩ -- -- Does this one work? -- def comp'' : (Y ⊸ Z) ⊸ (X → Y) ⊸ (X → Z) := ⟨λ f => ⟨λ g => λ x => f (g x), sorry_proof⟩, sorry_proof⟩ -- noncomputable -- def teval : ((X⊸Y)⊗X) ⊸ Y := uncurry' id -- noncomputable -- def tpair : X⊸Y⊸X⊗Y := curry' id -- def assocl : X×(Y×Z) ⊸ (X×Y)×Z := -- let F : X×(Y×Z) ⊸ (X×Y)×Z := pmap ((pmap (fst, (comp' fst snd))), (comp' snd snd)) -- ⟨λ (x,(y,z)) => ((x,y),z), -- by -- have h : (λ (x,(y,z)) => ((x,y),z)) = F.1 := by simp[pmap, comp', fst, snd] -- rw[h] -- apply F.2⟩ -- def assocr : (X×Y)×Z ⊸ X×(Y×Z) := -- let F : (X×Y)×Z ⊸ X×(Y×Z) := pmap ((comp' fst fst), (pmap ((comp' snd fst), snd))) -- ⟨λ ((x,y),z) => (x,(y,z)), -- by -- have h : (λ ((x,y),z) => (x,(y,z))) = F.1 := by simp[pmap, comp', fst, snd] -- rw[h] -- apply F.2⟩ -- @[simp] -- theorem assocl_eval (xyz : X×(Y×Z)) : assocl xyz = ((xyz.1,xyz.2.1),xyz.2.2) := rfl -- @[simp] -- theorem assocr_eval (xyz : (X×Y)×Z) : assocr xyz = (xyz.1.1,(xyz.1.2,xyz.2)) := rfl -- noncomputable -- def tassocl : X⊗(Y⊗Z) ⊸ (X⊗Y)⊗Z := ⟨λ xyz => -- let ⟨_,x,yz⟩ := xyz.repr -- let y := λ i => (yz i).repr.snd.fst -- let z := λ i => (yz i).repr.snd.snd -- ∑ i j, (x i ⊗ y i j) ⊗ z i j, -- sorry_proof⟩ -- noncomputable -- def tassocr : (X⊗Y)⊗Z ⊸ X⊗(Y⊗Z) := ⟨λ xyz => -- let ⟨_,xy,z⟩ := xyz.repr -- let x := λ i => (xy i).repr.snd.fst -- let y := λ i => (xy i).repr.snd.snd -- ∑ i j, x i j ⊗ (y i j ⊗ z i), -- sorry_proof⟩ -- def swap : (X×Y) ⊸ (Y×X) := pmap (snd, fst) -- @[simp] -- theorem swap_eval (xy : (X×Y)) : swap xy = (xy.2, xy.1) := rfl -- noncomputable -- def tswap : (X⊗Y) ⊸ (Y⊗X) := ⟨λ xy => -- let ⟨_,x,y⟩ := xy.repr -- ∑ i, y i ⊗ x i, -- sorry_proof⟩ -- def rot132 : (X×Y)×Z ⊸ (X×Z)×Y := comp' assocl (comp' (fmap (id, swap)) assocr) -- @[simp] -- theorem rot132_eval (xyz : (X×Y)×Z) : rot132 xyz = ((xyz.1.1, xyz.2), xyz.1.2) := rfl -- noncomputable -- def trot132 : (X⊗Y)⊗Z ⊸ (X⊗Z)⊗Y := comp' tassocl (comp' (tfmap id tswap) tassocr) -- @[simp] -- theorem trot132_eval (x : X) (y : Y) (z : Z) : trot132 ((x⊗y)⊗z) = (x⊗z)⊗y := sorry_proof -- -- TODO: This function is perfectly computable, make it so -- -- only the proof of linearity goes via noncomputable tensor product -- noncomputable -- def comp : (Y ⊸ Z) ⊸ (X ⊸ Y) ⊸ (X ⊸ Z) := -- let F₁ : (Y⊸Z)⊗((X⊸Y)⊗X) ⊸ Z := comp' teval (tfmap id teval) -- curry' (curry' (comp' F₁ tassocr)) -- @[simp] -- theorem comp_eval (f : Y⊸Z) (g : X ⊸ Y) (x : X) : comp f g x = f (g x) := sorry_proof -- -- def const : X⊸Y⊸X := curry' fst -- -- @[simp] -- -- theorem const_eval (f : Y⊸Z) (g : X ⊸ Y) (x : X) : comp f g x = f (g x) := rfl -- noncomputable -- def uncurry : (X ⊸ Y ⊸ Z) ⊸ (X⊗Y ⊸ Z) := -- let F : ((X⊸Y⊸Z)⊗X)⊗Y ⊸ Z := comp teval (tfmap teval id) -- let G₁ : (X⊗Y ⊸ (X⊸Y⊸Z)⊗(X⊗Y)) ⊸ (X⊗Y ⊸ Z) := comp (comp' F tassocl) -- let G₂ : (X⊸Y⊸Z) ⊸ (X⊗Y ⊸ (X⊸Y⊸Z)⊗(X⊗Y)) := tpair -- comp' G₁ G₂ -- -- @[simp] -- -- theorem Smooth.uncurry_eval (f : X ⊸ Y ⊸ Z) (xy : X×Y) : Smooth.uncurry f xy = f xy.1 xy.2 := by rfl -- noncomputable -- def curry : (X ⊗ Y ⊸ Z) ⊸ (X ⊸ Y ⊸ Z) := -- let G : ((X⊗Y⊸Z)⊗Y)⊗X ⊸ Z := comp (comp (uncurry' id) (tfmap id tswap)) tassocr -- let H : (Y ⊸ (X⊗Y⊸Z)⊗Y)⊗X ⊸ (Y ⊸ ((X⊗Y⊸Z)⊗Y)⊗X) := curry' (comp (tfmap teval id) trot132) -- let F₁ : (X⊗Y⊸Z) ⊸ (Y ⊸ (X⊗Y⊸Z)⊗Y) := tpair -- let F₂ : (Y ⊸ (X⊗Y⊸Z)⊗Y) ⊸ (X ⊸ (Y ⊸ (X⊗Y⊸Z)⊗Y)⊗X) := tpair -- let F₃ : (X ⊸ (Y ⊸ (X⊗Y⊸Z)⊗Y)⊗X) ⊸ (X ⊸ (Y ⊸ ((X⊗Y⊸Z)⊗Y)⊗X)) := comp H -- comp (comp (comp G)) (comp F₃ (comp F₂ F₁)) -- -- @[simp] -- -- theorem Smooth.curry_eval (f : X×Y ⊸ Z) (x : X) (y : Y) : Smooth.curry f x y = f (x,y) := by rfl -- -- TODO: make it computable -- noncomputable -- def prod : (X → Y ⊸ Z) ⊸ (X→Y) ⊸ (X→Z) := -- let F : (X → Y ⊸ Z) ⊸ (X→Y) ⊸ (X → Y ⊸ Z)⊗(X→Y) := tpair -- let G₁ : (X → Y ⊸ Z)⊗(X→Y) ⊸ (X → (Y⊸Z)⊗Y) := uncurry tpmap' -- let G₂ : (X → (Y⊸Z)⊗Y) ⊸ (X→Z) := comp'' teval -- comp (comp (comp G₂ G₁)) F -- @[simp] -- theorem prod_eval (f : X → Y ⊸ Z) : prod f (λ _ => y) x = f x y := sorry_proof -- -- def scomb : (X⊸Y⊸Z) ⊸ (X⊸Y) ⊸ X ⊸ Z := -- -- let F₁ : (X⊸Y⊸Z)⊗(X⊸Y)⊗X ⊸ (X⊗Y⊸Z)⊗(X⊗Y) := tfmap uncurry (tpmap snd teval) -- -- comp (curry) (curry (comp eval F₁)) -- -- variable {ι κ : Type} {E F G : ι → Type} {E' : κ → Type} [∀ i, Vec (E i)] [∀ i, Vec (F i)] [∀ i, Vec (G i)] [∀ j, Vec (E' j)] -- -- instance [∀ i, Vec (F i)] : Vec ((i : ι) → (F i)) := sorry -- -- def Smooth.pmapDep : ((i : ι)→(E i)) ⊸ ((i : ι)→(F i)) ⊸ ((i : ι)→(E i)×(F i)) := ⟨λ f => ⟨λ g => λ x => (f x, g x), sorry⟩, sorry⟩ -- -- def Smooth.fmapDep : ((i : ι)→(E i)) ⊸ ((j : κ)→(E' j)) ⊸ ((ij : (ι×κ))→(E ij.1)×(E' ij.2)) := ⟨λ f => ⟨λ g => λ (i,j) => (f i, g j), sorry⟩, sorry⟩ -- -- def Smooth.prodDep : ((i : ι) → E i ⊸ F i) ⊸ ((i : ι) → E i) ⊸ ((i : ι) → F i) := sorry -- end Linear
-- | authors: Connor Ford, Jake Hauser module Persistence where import Data.List (intercalate) import Numeric.LinearAlgebra import Data.List.HT (mapAdjacent) import ExplicitSimplexStream -- Betti Vector -- This data type is equivalent to a list of Ints. It represents the betti vector. -- For a betti vector of length n, all betti numbers b_i such that i >= n are assumed to be 0. data BettiVector = BettiVector [Int] deriving (Eq) instance Show BettiVector where show (BettiVector []) = "()" show (BettiVector vs) = "(" ++ intercalate ", " (map show vs) ++ ")" -- getBoundaryMapHelper (see: getBoundaryMap) -- First argument is SimplexListByDegree representing C_k -- Second argument is SimplexListByDegree representing C_k+1 -- Third argument should initially be the length of the x in (x:xs) for C_k+1. It it a counter for removing elements from x. -- Fourth argument should initially be zero. It is a counter for the index of x in (x:xs). -- Fifth argument should be the zero matrix for _correct_ boundary map calculations. getBoundaryMapHelper :: (Ord a) => SimplexListByDegree a -> SimplexListByDegree a -> Int -> Int -> Matrix Double -> Matrix Double getBoundaryMapHelper _ (SimplexListByDegree _ []) _ _ mat = mat getBoundaryMapHelper list1 (SimplexListByDegree n (_:xs)) 0 k mat = getBoundaryMapHelper list1 (SimplexListByDegree n (xs)) n (k+1) mat getBoundaryMapHelper list1 (SimplexListByDegree n (x:xs)) m k mat = let x_dim = indexOfSimplex (Simplex (removeSimplexElement x (m-1))) list1 y_dim = k val = (-1)^(m-1) updatedMatrix = accum mat (\a _ -> a) [((x_dim,y_dim), val)] -- use accumulator to change values of matrix in getBoundaryMapHelper list1 (SimplexListByDegree n (x:xs)) (m-1) k updatedMatrix -- getBoundaryMap -- First argument C_k -- Second argument C_k+1 -- return matrix dimensions: len(C_k) = num rows, len(C_k+1) = num cols -- algorithm: -- Given element of C_k+1, y, remove i'th element from y (starting with index zero) to get element in C_k called x. -- Then the value in the matrix at row idxOf(x) and column idxOf(y) is (-1)^i. getBoundaryMap :: (Ord a) => SimplexListByDegree a -> SimplexListByDegree a -> Matrix Double getBoundaryMap list1@(SimplexListByDegree _ simps1) list2@(SimplexListByDegree n simps2) = let zero_matrix = matrix (length simps2) (replicate ((length simps1)*(length simps2)) 0) in getBoundaryMapHelper list1 list2 n 0 zero_matrix -- getHomologyDimension -- first arg is D_i+1 -- second arg is D_i -- third argument k (or i in the below illustration) -- want to find: dim ker D_i - dim im D_i+1 -- algorithm to find ker and im: -- (i) rref matrix -- (ii) # of non-zero rows correspond to rnk of original matrix. -- (iii) # of columns with leading 1’s correspond to the columns of original matrix that span image. -- (iv) dim ker = (ii) - (iii) getHomologyDimension :: Matrix Double -> Matrix Double -> Int -> Int getHomologyDimension m1 m2 k = let m1_rank = rank m1 m2_columns = cols m2 m2_rank = rank m2 m2_nullity = m2_columns - m2_rank in if k > 0 then m2_nullity - m1_rank else m2_columns - m1_rank -- persistenceHelper (see: persistence) -- First argument is a list of matrices representing a sequence of boundary maps. -- Second argument is k representing the k'th homology. persistenceHelper :: [Matrix Double] -> Int -> [Int] persistenceHelper [] _ = [] persistenceHelper [x] k = [getHomologyDimension ((ident 1) - (ident 1)) x k] -- base case for last boundary map persistenceHelper (x:y:xs) k = (getHomologyDimension y x k):(persistenceHelper (y:xs) (k+1)) -- persistence -- The persistence algorithm computes the BettiVector for s simplex stream. The algorithm is as follows: -- Given a simplex stream, and a field coefficient p corresponding to Z/pZ we will return betti numbers (b_0, b_1, ..., b_n) where n+1 equals the degree of the highest order simplex in the stream. -- (1) Get simplex lists ordered by the degree of simplices -- (2) Get boundary maps D_0, ..., D_{n-1} such that: -- 0 <-- C_0 <-- C_1 <-- ... <-- C_{n-1} <-- C_n <-- 0 -- D_{-1} D_0 D_1 D_{n-1} -- (3) Compute dimensions of the Homologies: -- dim H_0 = dim Ker 0 - dim Im D_0 -- dim H_1 = dim Ker D_0 - dim Im D_1 -- ... -- dim H_n = dim Ker D_{n-1} - dim Im 0 -- (4) return betti profile (dim H_0, dim H_1, ..., dim H_n) -- TODO: implement with rref mod p where Field = Z/pZ. persistence :: (Ord a) => Stream a -> Int -> BettiVector persistence stream field = let (OrderedSimplexList l) = streamToOrderedSimplexList stream in BettiVector $ persistenceHelper (mapAdjacent getBoundaryMap l) 0
theory Values imports Main Archi AST BinNums Integers Floats begin (** This module defines the type of values that is used in the dynamic semantics of all our intermediate languages. *) type_synonym block = positive (** A value is either: - a machine integer; - a floating-point number; - a pointer: a pair of a memory address and an integer offset with respect to this address; - the [Vundef] value denoting an arbitrary bit pattern, such as the value of an uninitialized variable. *) datatype val = Vundef | Vint m_int | Vlong m_int64 | Vfloat float64 | Vsingle float32 | Vptr block m_ptrofs definition "Vtrue \<equiv> Vint 1" definition "Vfalse \<equiv> Vint 0" definition "Vnullptr \<equiv> Vlong 0" (* only valid on 64-bit arch *) definition Vptrofs :: "m_ptrofs \<Rightarrow> val" where "Vptrofs n \<equiv> Vlong n" (* only valid on 64-bit arch *) lemma vptrofs_equ[iff]: "Vptrofs n = Vptrofs n' \<longleftrightarrow> n = n'" unfolding Vptrofs_def by simp section \<open>Operations over values\<close> (** The module [Val] defines a number of arithmetic and logical operations over type [val]. Most of these operations are straightforward extensions of the corresponding integer or floating-point operations. *) locale Val' begin fun has_type :: "val \<Rightarrow> type \<Rightarrow> bool" where "has_type v t = (case (v, t) of (Vundef, _) \<Rightarrow> True | (Vint _, Tint) \<Rightarrow> True | (Vlong _, Tlong) \<Rightarrow> True | (Vfloat _, Tfloat) \<Rightarrow> True | (Vsingle _, Tsingle) \<Rightarrow> True | (Vptr _ _, Tint) \<Rightarrow> Archi.ptr64 = False | (Vptr _ _, Tlong) \<Rightarrow> Archi.ptr64 = True | (Vint _, Tany32) \<Rightarrow> True | (Vsingle _, Tany32) \<Rightarrow> True | (Vptr _ _, Tany32) \<Rightarrow> Archi.ptr64 = False | (_, Tany64) \<Rightarrow> True | (_, _) \<Rightarrow> False )" fun has_rettype :: "val \<Rightarrow> rettype \<Rightarrow> bool" where "has_rettype v (Tret t) = has_type v t" | "has_rettype (Vint n) Tint8signed = (n = Int.sign_ext TYPE(8) n)" | "has_rettype (Vint n) Tint8unsigned = (n = Int.zero_ext TYPE(8) n)" | "has_rettype (Vint n) Tint16signed = (n = Int.sign_ext TYPE(16) n)" | "has_rettype (Vint n) Tint16unsigned = (n = Int.zero_ext TYPE(16) n)" | "has_rettype Vundef _ = True" | "has_rettype _ _ = False" (** Truth values. Non-zero integers are treated as [True]. The integer 0 (also used to represent the null pointer) is [False]. Other values are neither true nor false. *) fun bool_to_val where "bool_to_val False = Vfalse" | "bool_to_val True = Vtrue" inductive bool_of_val :: "val \<Rightarrow> bool \<Rightarrow> bool" where bool_of_val_int: "(n \<noteq> 0) = b \<Longrightarrow> bool_of_val (Vint n) b" lemma bool_of_val_one: "bool_of_val v False \<Longrightarrow> bool_of_val v True \<Longrightarrow> P" by (metis bool_of_val.cases val.inject(1)) fun bool_of_val_func :: "val \<Rightarrow> bool option" where "bool_of_val_func (Vint n) = (if n = 0 then Some False else Some True)" | "bool_of_val_func _ = None" (** Arithmetic operations *) fun neg :: "val \<Rightarrow> val" where "neg (Vint n) = Vint (- n)" | "neg _ = Vundef" fun negf :: "val \<Rightarrow> val" where "negf (Vfloat f) = Vfloat (- f)" | "negf _ = Vundef" fun absf :: "val \<Rightarrow> val" where "absf (Vfloat f) = Vfloat (abs f)" | "absf _ = Vundef" fun negfs :: "val \<Rightarrow> val" where "negfs (Vsingle f) = Vsingle (- f)" | "negfs _ = Vundef" fun absfs :: "val \<Rightarrow> val" where "absfs (Vsingle f) = Vsingle (abs f)" | "absfs _ = Vundef" (* fun intoffloat :: "val \<Rightarrow> (val option)" where "intoffloat (Vfloat f) = map_option Vint (Float.to_int f)" | "intoffloat _ = None" fun intuoffloat :: "val \<Rightarrow> (val option)" where "intuoffloat (Vfloat f) = map_option Vint (Float.to_intu f)" | "intuoffloat _ = None" fun floatofint :: "val \<Rightarrow> (val option)" where "floatofint (Vint n) = Some (Vfloat (Float.of_int n))" | "floatofint _ = None" fun floatofintu :: "val \<Rightarrow> (val option)" where "floatofintu (Vint n) = Some (Vfloat (Float.of_intu n))" | "floatofintu _ = None" fun intofsingle :: "val \<Rightarrow> (val option)" where "intofsingle (Vsingle f) = map_option Vint (Float32.to_int f)" | "intofsingle _ = None" fun intuofsingle :: "val \<Rightarrow> (val option)" where "intuofsingle (Vsingle f) = map_option Vint (Float32.to_intu f)" | "intuofsingle _ = None" fun singleofint :: "val \<Rightarrow> (val option)" where "singleofint (Vint n) = Some (Vsingle (Float32.of_int n))" | "singleofint _ = None" fun singleofintu :: "val \<Rightarrow> (val option)" where "singleofintu (Vint n) = Some (Vsingle (Float32.of_intu n))" | "singleofintu _ = None" *) fun negint :: "val \<Rightarrow> val" where "negint (Vint n) = Vint (- n)" | "negint _ = Vundef" fun notint :: "val \<Rightarrow> val" where "notint (Vint n) = Vint (not n)" | "notint _ = Vundef" fun of_bool :: "bool \<Rightarrow> val" where "of_bool True = Vtrue" | "of_bool False = Vfalse" fun boolval :: "val \<Rightarrow> val" where "boolval (Vint n) = of_bool (n \<noteq> 0)" | "boolval (Vptr b ofs) = Vtrue" | "boolval _ = Vundef" fun notbool :: "val \<Rightarrow> val" where "notbool (Vint n) = of_bool (n = 0)" | "notbool (Vptr b ofs) = Vfalse" | "notbool _ = Vundef" fun zero_ext :: "'l::len itself \<Rightarrow> val \<Rightarrow> val" where "zero_ext nbits (Vint n) = Vint(Int.zero_ext nbits n)" | "zero_ext nbits _ = Vundef" fun sign_ext :: "'l::len itself \<Rightarrow> val \<Rightarrow> val" where "sign_ext nbits (Vint n) = Vint(Int.sign_ext nbits n)" | "sign_ext nbits _ = Vundef" (* fun singleoffloat :: "val \<Rightarrow> val" where "singleoffloat (Vfloat f) = Vsingle (Float.to_single f)" | "singleoffloat _ = Vundef" fun floatofsingle :: "val \<Rightarrow> val" where "floatofsingle (Vsingle f) = Vfloat (Float.of_single f)" | "floatofsingle _ = Vundef" *) fun add :: "val \<Rightarrow> val \<Rightarrow> val" where "add (Vint n1) (Vint n2) = Vint(Int.add n1 n2)" | "add (Vptr b1 ofs1) (Vint n2) = (if Archi.ptr64 then Vundef else Vptr b1 (Ptrofs.add ofs1 (Ptrofs.of_int n2)))" | "add (Vint n1) (Vptr b2 ofs2) = (if Archi.ptr64 then Vundef else Vptr b2 (Ptrofs.add ofs2 (Ptrofs.of_int n1)))" | "add _ _ = Vundef" fun sub :: "val \<Rightarrow> val \<Rightarrow> val" where "sub v1 v2 = (case (v1, v2) of (Vint n1, Vint n2) \<Rightarrow> Vint (Int.sub n1 n2) | (Vptr b1 ofs1, Vint n2) \<Rightarrow> if Archi.ptr64 then Vundef else Vptr b1 (Ptrofs.sub ofs1 (Ptrofs.of_int n2)) | (Vptr b1 ofs1, Vptr b2 ofs2) \<Rightarrow> if Archi.ptr64 then Vundef else if b1 = b2 then Vint(Ptrofs.to_int (Ptrofs.sub ofs1 ofs2)) else Vundef | (_, _) \<Rightarrow> Vundef )" fun mul :: "val \<Rightarrow> val \<Rightarrow> val" where "mul (Vint n1) (Vint n2) = Vint(Int.mul n1 n2)" | "mul _ _ = Vundef" (* fun mulhs :: "val \<Rightarrow> val \<Rightarrow> val" where "mulhs (Vint n1) (Vint n2) = Vint(Int.mulhs n1 n2)" | "mulhs _ _ = Vundef" fun mulhu :: "val \<Rightarrow> val \<Rightarrow> val" where "mulhu (Vint n1) (Vint n2) = Vint(Int.mulhu n1 n2)" | "mulhu _ _ = Vundef" *) fun divs :: "val \<Rightarrow> val \<Rightarrow> (val option)" where "divs v1 v2 = (case (v1, v2) of (Vint n1, Vint n2) \<Rightarrow> if n2 = 0 \<or> n1 = (Int.repr Int.min_signed) \<and> n2 = Int.mone then None else Some(Vint(Int.divs n1 n2)) | (_, _) \<Rightarrow> None )" fun mods :: "val \<Rightarrow> val \<Rightarrow> (val option)" where "mods v1 v2 = (case (v1, v2) of (Vint n1, Vint n2) \<Rightarrow> if n2 = 0 \<or> n1 = (Int.repr Int.min_signed) \<and> n2 = Int.mone then None else Some(Vint(Int.mods n1 n2)) | (_, _) \<Rightarrow> None )" fun divu :: "val \<Rightarrow> val \<Rightarrow> (val option)" where "divu (Vint n1) (Vint n2) = (if n2 = 0 then None else Some(Vint(Int.divu n1 n2)))" | "divu _ _ = None" fun modu :: "val \<Rightarrow> val \<Rightarrow> (val option)" where "modu (Vint n1) (Vint n2) = (if n2 = 0 then None else Some(Vint(Int.modu n1 n2)))" | "modu _ _ = None" (* fun add_carry :: "val \<Rightarrow> val \<Rightarrow> val \<Rightarrow> val" where "add_carry (Vint n1) (Vint n2) (Vint c) = Vint(Int.add_carry n1 n2 c)" | "add_carry _ _ _ = Vundef" fun sub_overflow :: "val \<Rightarrow> val \<Rightarrow> val" where "sub_overflow (Vint n1) (Vint n2) = Vint(Int.sub_overflow n1 n2 Int.zero)" | "sub_overflow _ _ = Vundef" fun negative :: "val \<Rightarrow> val" where "negative (Vint n) = Vint (Int.negative n)" | "negative _ = Vundef" *) fun and' :: "val \<Rightarrow> val \<Rightarrow> val" where "and' (Vint n1) (Vint n2) = Vint(Int.and' n1 n2)" | "and' _ _ = Vundef" fun or :: "val \<Rightarrow> val \<Rightarrow> val" where "or (Vint n1) (Vint n2) = Vint(Int.or n1 n2)" | "or _ _ = Vundef" fun xor' :: "val \<Rightarrow> val \<Rightarrow> val" where "xor' (Vint n1) (Vint n2) = Vint(Int.xor n1 n2)" | "xor' _ _ = Vundef" fun shl :: "val \<Rightarrow> val \<Rightarrow> val" where "shl v1 v2 = (case (v1, v2) of (Vint n1, Vint n2) \<Rightarrow> if Int.ltu n2 Int.iwordsize then Vint(Int.shl n1 n2) else Vundef | (_, _) \<Rightarrow> Vundef )" fun shr :: "val \<Rightarrow> val \<Rightarrow> val" where "shr v1 v2 = (case (v1, v2) of (Vint n1, Vint n2) \<Rightarrow> if Int.ltu n2 Int.iwordsize then Vint(Int.shr n1 n2) else Vundef | (_, _) \<Rightarrow> Vundef )" (* fun shr_carry :: "val \<Rightarrow> val \<Rightarrow> val" where "shr_carry v1 v2 = (case v1, v2 of Vint n1, Vint n2 \<Rightarrow> if Int.ltu n2 Int.iwordsize then Vint(Int.shr_carry n1 n2) else Vundef | _, _ \<Rightarrow> Vundef )" *) (* fun shrx :: "val \<Rightarrow> val \<Rightarrow> (val option)" where "shrx v1 v2 = (case v1, v2 of Vint n1, Vint n2 \<Rightarrow> if Int.ltu n2 (Int.repr 31) then Some(Vint(Int.shrx n1 n2)) else None | _, _ \<Rightarrow> None )" *) fun shru :: "val \<Rightarrow> val \<Rightarrow> val" where "shru v1 v2 = (case (v1, v2) of (Vint n1, Vint n2) \<Rightarrow> if Int.ltu n2 Int.iwordsize then Vint(Int.shru n1 n2) else Vundef | (_, _) \<Rightarrow> Vundef )" fun rol :: "val \<Rightarrow> val \<Rightarrow> val" where "rol (Vint n1) (Vint n2) = Vint(Int.rol n1 n2)" | "rol _ _ = Vundef" (* fun rolm :: "val \<Rightarrow> int \<Rightarrow> int \<Rightarrow> val" where "rolm (Vint n) amount mask = Vint(Int.rolm n amount mask)" | "rolm _ amount mask = Vundef" *) fun ror :: "val \<Rightarrow> val \<Rightarrow> val" where "ror (Vint n1) (Vint n2) = Vint(Int.ror n1 n2)" | "ror _ _ = Vundef" fun addf :: "val \<Rightarrow> val \<Rightarrow> val" where "addf (Vfloat f1) (Vfloat f2) = Vfloat(Float.add f1 f2)" | "addf _ _ = Vundef" fun subf :: "val \<Rightarrow> val \<Rightarrow> val" where "subf (Vfloat f1) (Vfloat f2) = Vfloat(Float.sub f1 f2)" | "subf _ _ = Vundef" fun mulf :: "val \<Rightarrow> val \<Rightarrow> val" where "mulf (Vfloat f1) (Vfloat f2) = Vfloat(Float.mul f1 f2)" | "mulf _ _ = Vundef" fun divf :: "val \<Rightarrow> val \<Rightarrow> val" where "divf (Vfloat f1) (Vfloat f2) = Vfloat(Float.div' f1 f2)" | "divf _ _ = Vundef" (* fun floatofwords :: "val \<Rightarrow> val \<Rightarrow> val" where "floatofwords (Vint n1) (Vint n2) = Vfloat (Float.from_words n1 n2)" | "floatofwords _ _ = Vundef" *) fun addfs :: "val \<Rightarrow> val \<Rightarrow> val" where "addfs (Vsingle f1) (Vsingle f2) = Vsingle(Float32.add f1 f2)" | "addfs _ _ = Vundef" fun subfs :: "val \<Rightarrow> val \<Rightarrow> val" where "subfs (Vsingle f1) (Vsingle f2) = Vsingle(Float32.sub f1 f2)" | "subfs _ _ = Vundef" fun mulfs :: "val \<Rightarrow> val \<Rightarrow> val" where "mulfs (Vsingle f1) (Vsingle f2) = Vsingle(Float32.mul f1 f2)" | "mulfs _ _ = Vundef" fun divfs :: "val \<Rightarrow> val \<Rightarrow> val" where "divfs (Vsingle f1) (Vsingle f2) = Vsingle(Float32.div' f1 f2)" | "divfs _ _ = Vundef" (** Operations on 64-bit integers *) fun longofwords :: "val \<Rightarrow> val \<Rightarrow> val" where "longofwords (Vint n1) (Vint n2) = Vlong (Int64.ofwords n1 n2)" | "longofwords _ _ = Vundef" fun loword :: "val \<Rightarrow> val" where "loword (Vlong n) = Vint (Int64.loword n)" | "loword _ = Vundef" fun hiword :: "val \<Rightarrow> val" where "hiword (Vlong n) = Vint (Int64.hiword n)" | "hiword _ = Vundef" fun negl :: "val \<Rightarrow> val" where "negl (Vlong n) = Vlong (Int64.neg n)" | "negl _ = Vundef" fun notl :: "val \<Rightarrow> val" where "notl (Vlong n) = Vlong (Int64.not n)" | "notl _ = Vundef" fun longofint :: "val \<Rightarrow> val" where "longofint (Vint n) = Vlong (Int64.repr (Int.signed n))" | "longofint _ = Vundef" fun longofintu :: "val \<Rightarrow> val" where "longofintu (Vint n) = Vlong (Int64.repr (Int.unsigned n))" | "longofintu _ = Vundef" (* fun longoffloat :: "val \<Rightarrow> (val option)" where "longoffloat (Vfloat f) = map_option Vlong (Float.to_long f)" | "longoffloat _ = None" fun longuoffloat :: "val \<Rightarrow> (val option)" where "longuoffloat (Vfloat f) = map_option Vlong (Float.to_longu f)" | "longuoffloat _ = None" fun longofsingle :: "val \<Rightarrow> (val option)" where "longofsingle (Vsingle f) = map_option Vlong (Float32.to_long f)" | "longofsingle _ = None" fun longuofsingle :: "val \<Rightarrow> (val option)" where "longuofsingle (Vsingle f) = map_option Vlong (Float32.to_longu f)" | "longuofsingle _ = None" fun floatoflong :: "val \<Rightarrow> (val option)" where "floatoflong (Vlong n) = Some (Vfloat (Float.of_long n))" | "floatoflong _ = None" fun floatoflongu :: "val \<Rightarrow> (val option)" where "floatoflongu (Vlong n) = Some (Vfloat (Float.of_longu n))" | "floatoflongu _ = None" fun singleoflong :: "val \<Rightarrow> (val option)" where "singleoflong (Vlong n) = Some (Vsingle (Float32.of_long n))" | "singleoflong _ = None" fun singleoflongu :: "val \<Rightarrow> (val option)" where "singleoflongu (Vlong n) = Some (Vsingle (Float32.of_longu n))" | "singleoflongu _ = None" *) fun addl :: "val \<Rightarrow> val \<Rightarrow> val" where "addl (Vlong n1) (Vlong n2) = Vlong(Int64.add n1 n2)" | "addl (Vptr b1 ofs1) (Vlong n2) = (if Archi.ptr64 then Vptr b1 (Ptrofs.add ofs1 (Ptrofs.of_int64 n2)) else Vundef)" | "addl (Vlong n1) (Vptr b2 ofs2) = (if Archi.ptr64 then Vptr b2 (Ptrofs.add ofs2 (Ptrofs.of_int64 n1)) else Vundef)" | "addl _ _ = Vundef" fun subl :: "val \<Rightarrow> val \<Rightarrow> val" where "subl v1 v2 = (case (v1, v2) of (Vlong n1, Vlong n2) \<Rightarrow> Vlong(Int64.sub n1 n2) | (Vptr b1 ofs1, Vlong n2) \<Rightarrow> if Archi.ptr64 then Vptr b1 (Ptrofs.sub ofs1 (Ptrofs.of_int64 n2)) else Vundef | (Vptr b1 ofs1, Vptr b2 ofs2) \<Rightarrow> if \<not>Archi.ptr64 then Vundef else if b1 = b2 then Vlong(Ptrofs.to_int64 (Ptrofs.sub ofs1 ofs2)) else Vundef | (_, _) \<Rightarrow> Vundef )" fun mull :: "val \<Rightarrow> val \<Rightarrow> val" where "mull (Vlong n1) (Vlong n2) = Vlong(Int64.mul n1 n2)" | "mull _ _ = Vundef" (* fun mull' :: "val \<Rightarrow> val \<Rightarrow> val" where "mull' (Vint n1) (Vint n2) = Vlong(Int64.mul' n1 n2)" | "mull' _ _ = Vundef" fun mullhs :: "val \<Rightarrow> val \<Rightarrow> val" where "mullhs (Vlong n1) (Vlong n2) = Vlong(Int64.mulhs n1 n2)" | "mullhs _ _ = Vundef" fun mullhu :: "val \<Rightarrow> val \<Rightarrow> val" where "mullhu (Vlong n1) (Vlong n2) = Vlong(Int64.mulhu n1 n2)" | "mullhu _ _ = Vundef" *) fun divls :: "val \<Rightarrow> val \<Rightarrow> (val option)" where "divls v1 v2 = (case (v1, v2) of (Vlong n1, Vlong n2) \<Rightarrow> if Int64.eq n2 Int64.zero \<or> Int64.eq n1 (Int64.repr Int64.min_signed) \<and> Int64.eq n2 Int64.mone then None else Some(Vlong(Int64.divs n1 n2)) | (_, _) \<Rightarrow> None )" fun modls :: "val \<Rightarrow> val \<Rightarrow> (val option)" where "modls v1 v2 = (case (v1, v2) of (Vlong n1, Vlong n2) \<Rightarrow> if Int64.eq n2 Int64.zero \<or> Int64.eq n1 (Int64.repr Int64.min_signed) \<and> Int64.eq n2 Int64.mone then None else Some(Vlong(Int64.mods n1 n2)) | (_, _) \<Rightarrow> None )" fun divlu :: "val \<Rightarrow> val \<Rightarrow> (val option)" where "divlu (Vlong n1) (Vlong n2) = (if Int64.eq n2 Int64.zero then None else Some(Vlong(Int64.divu n1 n2)))" | "divlu _ _ = None" fun modlu :: "val \<Rightarrow> val \<Rightarrow> (val option)" where "modlu (Vlong n1) (Vlong n2) = (if Int64.eq n2 Int64.zero then None else Some(Vlong(Int64.modu n1 n2)))" | "modlu _ _ = None" (* fun addl_carry :: "val \<Rightarrow> val \<Rightarrow> val \<Rightarrow> val" where "addl_carry (Vlong n1) (Vlong n2) (Vlong c) = Vlong(Int64.add_carry n1 n2 c)" | "addl_carry _ _ _ = Vundef" fun subl_overflow :: "val \<Rightarrow> val \<Rightarrow> val" where "subl_overflow (Vlong n1) (Vlong n2) = Vint (Int.repr (Int64.unsigned (Int64.sub_overflow n1 n2 Int64.zero)))" | "subl_overflow _ _ = Vundef" fun negativel :: "val \<Rightarrow> val" where "negativel (Vlong n) = Vint (Int.repr (Int64.unsigned (Int64.negative n)))" | "negativel _ = Vundef" *) fun andl :: "val \<Rightarrow> val \<Rightarrow> val" where "andl (Vlong n1) (Vlong n2) = Vlong(Int64.and' n1 n2)" | "andl _ _ = Vundef" fun orl :: "val \<Rightarrow> val \<Rightarrow> val" where "orl (Vlong n1) (Vlong n2) = Vlong(Int64.or n1 n2)" | "orl _ _ = Vundef" fun xorl :: "val \<Rightarrow> val \<Rightarrow> val" where "xorl (Vlong n1) (Vlong n2) = Vlong(Int64.xor n1 n2)" | "xorl _ _ = Vundef" fun shll :: "val \<Rightarrow> val \<Rightarrow> val" where "shll v1 v2 = (case (v1, v2) of (Vlong n1, Vint n2) \<Rightarrow> if Int.ltu n2 Int64.iwordsize' then Vlong(Int64.shl' n1 n2) else Vundef | (_, _) \<Rightarrow> Vundef )" fun shrl :: "val \<Rightarrow> val \<Rightarrow> val" where "shrl v1 v2 = (case (v1, v2) of (Vlong n1, Vint n2) \<Rightarrow> if Int.ltu n2 Int64.iwordsize' then Vlong(Int64.shr' n1 n2) else Vundef | (_, _) \<Rightarrow> Vundef )" fun shrlu :: "val \<Rightarrow> val \<Rightarrow> val" where "shrlu v1 v2 = (case (v1, v2) of (Vlong n1, Vint n2) \<Rightarrow> if Int.ltu n2 Int64.iwordsize' then Vlong(Int64.shru' n1 n2) else Vundef | (_, _) \<Rightarrow> Vundef )" (* fun shrxl :: "val \<Rightarrow> val \<Rightarrow> (val option)" where "shrxl v1 v2 = (case v1, v2 of Vlong n1, Vint n2 \<Rightarrow> if Int.ltu n2 (Int.repr 63) then Some(Vlong(Int64.shrx' n1 n2)) else None | _, _ \<Rightarrow> None )" fun shrl_carry :: "val \<Rightarrow> val \<Rightarrow> val" where "shrl_carry v1 v2 = (case v1, v2 of Vlong n1, Vint n2 \<Rightarrow> if Int.ltu n2 Int64.iwordsize' then Vlong(Int64.shr_carry' n1 n2) else Vundef | _, _ \<Rightarrow> Vundef )" *) fun roll :: "val \<Rightarrow> val \<Rightarrow> val" where "roll (Vlong n1) (Vint n2) = Vlong(Int64.rol n1 (Int64.repr (Int.unsigned n2)))" | "roll _ _ = Vundef" fun rorl :: "val \<Rightarrow> val \<Rightarrow> val" where "rorl (Vlong n1) (Vint n2) = Vlong(Int64.ror n1 (Int64.repr (Int.unsigned n2)))" | "rorl _ _ = Vundef" (* fun rolml :: "val \<Rightarrow> int \<Rightarrow> int64 \<Rightarrow> val" where "rolml (Vlong n) amount mask = Vlong(Int64.rolm n (Int64.repr (Int.unsigned amount)) mask)" | "rolml _ amount mask = Vundef" *) fun zero_ext_l :: "'l::len itself \<Rightarrow> val \<Rightarrow> val" where "zero_ext_l nbits (Vlong n) = Vlong(Int64.zero_ext nbits n)" | "zero_ext_l nbits _ = Vundef" fun sign_ext_l :: "'l::len itself \<Rightarrow> val \<Rightarrow> val" where "sign_ext_l nbits (Vlong n) = Vlong(Int64.sign_ext nbits n)" | "sign_ext_l nbits _ = Vundef" section \<open>Comparisons\<close> fun cmp_bool :: "comparison \<Rightarrow> val \<Rightarrow> val \<Rightarrow> (bool option)" where "cmp_bool c (Vint n1) (Vint n2) = Some (Int.cmp c n1 n2)" | "cmp_bool c _ _ = None" fun cmp_different_blocks :: "comparison \<Rightarrow> (bool option)" where "cmp_different_blocks Ceq = Some False" | "cmp_different_blocks Cne = Some True" | "cmp_different_blocks _ = None" fun cmpf_bool :: "comparison \<Rightarrow> val \<Rightarrow> val \<Rightarrow> (bool option)" where "cmpf_bool c (Vfloat f1) (Vfloat f2) = Some (Float.cmp c f1 f2)" | "cmpf_bool c _ _ = None" fun cmpfs_bool :: "comparison \<Rightarrow> val \<Rightarrow> val \<Rightarrow> (bool option)" where "cmpfs_bool c (Vsingle f1) (Vsingle f2) = Some (Float32.cmp c f1 f2)" | "cmpfs_bool c _ _ = None" fun cmpl_bool :: "comparison \<Rightarrow> val \<Rightarrow> val \<Rightarrow> (bool option)" where "cmpl_bool c (Vlong n1) (Vlong n2) = Some (Int64.cmp c n1 n2)" | "cmpl_bool c _ _ = None" fun of_optbool :: "(bool option) \<Rightarrow> val" where "of_optbool (Some True) = Vtrue" | "of_optbool (Some False) = Vfalse" | "of_optbool None = Vundef" fun cmp :: "comparison \<Rightarrow> val \<Rightarrow> val \<Rightarrow> val" where "cmp c v1 v2 = of_optbool (cmp_bool c v1 v2)" fun cmpf :: "comparison \<Rightarrow> val \<Rightarrow> val \<Rightarrow> val" where "cmpf c v1 v2 = of_optbool (cmpf_bool c v1 v2)" fun cmpfs :: "comparison \<Rightarrow> val \<Rightarrow> val \<Rightarrow> val" where "cmpfs c v1 v2 = of_optbool (cmpfs_bool c v1 v2)" fun cmpl :: "comparison \<Rightarrow> val \<Rightarrow> val \<Rightarrow> (val option)" where "cmpl c v1 v2 = map_option of_bool (cmpl_bool c v1 v2)" context fixes valid_ptr :: "block \<Rightarrow> Z \<Rightarrow> bool" begin definition "weak_valid_ptr b ofs \<equiv> valid_ptr b ofs \<or> valid_ptr b (ofs - 1)" fun cmpu_bool :: "comparison \<Rightarrow> val \<Rightarrow> val \<Rightarrow> (bool option)" where "cmpu_bool c v1 v2 = (case (v1, v2) of (Vint n1, Vint n2) \<Rightarrow> Some (Int.cmpu c n1 n2) | (Vint n1, Vptr b2 ofs2) \<Rightarrow> if Archi.ptr64 then None else if Int.eq n1 Int.zero \<and> weak_valid_ptr b2 (Ptrofs.unsigned ofs2) then cmp_different_blocks c else None | (Vptr b1 ofs1, Vptr b2 ofs2) \<Rightarrow> if Archi.ptr64 then None else if b1 = b2 then if weak_valid_ptr b1 (Ptrofs.unsigned ofs1) \<and> weak_valid_ptr b2 (Ptrofs.unsigned ofs2) then Some (Ptrofs.cmpu c ofs1 ofs2) else None else if valid_ptr b1 (Ptrofs.unsigned ofs1) \<and> valid_ptr b2 (Ptrofs.unsigned ofs2) then cmp_different_blocks c else None | (Vptr b1 ofs1, Vint n2) \<Rightarrow> if Archi.ptr64 then None else if Int.eq n2 Int.zero \<and> weak_valid_ptr b1 (Ptrofs.unsigned ofs1) then cmp_different_blocks c else None | (_, _) \<Rightarrow> None )" fun cmpu :: "comparison \<Rightarrow> val \<Rightarrow> val \<Rightarrow> val" where "cmpu c v1 v2 = of_optbool (cmpu_bool c v1 v2)" fun cmplu_bool :: "comparison \<Rightarrow> val \<Rightarrow> val \<Rightarrow> (bool option)" where "cmplu_bool c v1 v2 = (case (v1, v2) of (Vlong n1, Vlong n2) \<Rightarrow> Some (Int64.cmpu c n1 n2) | (Vlong n1, Vptr b2 ofs2) \<Rightarrow> if \<not>Archi.ptr64 then None else if Int64.eq n1 Int64.zero \<and> weak_valid_ptr b2 (Ptrofs.unsigned ofs2) then cmp_different_blocks c else None | (Vptr b1 ofs1, Vptr b2 ofs2) \<Rightarrow> if \<not>Archi.ptr64 then None else if b1 = b2 then if weak_valid_ptr b1 (Ptrofs.unsigned ofs1) \<and> weak_valid_ptr b2 (Ptrofs.unsigned ofs2) then Some (Ptrofs.cmpu c ofs1 ofs2) else None else if valid_ptr b1 (Ptrofs.unsigned ofs1) \<and> valid_ptr b2 (Ptrofs.unsigned ofs2) then cmp_different_blocks c else None | (Vptr b1 ofs1, Vlong n2) \<Rightarrow> if \<not>Archi.ptr64 then None else if Int64.eq n2 Int64.zero \<and> weak_valid_ptr b1 (Ptrofs.unsigned ofs1) then cmp_different_blocks c else None | (_, _) \<Rightarrow> None )" fun cmplu :: "comparison \<Rightarrow> val \<Rightarrow> val \<Rightarrow> (val option)" where "cmplu c v1 v2 = map_option of_bool (cmplu_bool c v1 v2)" end (** Add the given offset to the given pointer. *) fun offset_ptr :: "val \<Rightarrow> m_ptrofs \<Rightarrow> val" where "offset_ptr (Vptr b ofs) delta = Vptr b (ofs + delta)" | "offset_ptr _ delta = Vundef" (** [load_result] reflects the effect of storing a value with a given memory chunk, then reading it back with the same chunk. Depending on the chunk and the type of the value, some normalization occurs. For instance, consider storing the integer value [0xFFF] on 1 byte at a given address, and reading it back. If it is read back with chunk [Mint8unsigned], zero-extension must be performed, resulting in [0xFF]. If it is read back as a [Mint8signed], sign-extension is performed and [0xFFFFFFFF] is returned. *) fun load_result :: "memory_chunk \<Rightarrow> val \<Rightarrow> val" where "load_result Mint8signed (Vint n) = Vint (Int.sign_ext TYPE(8) n)" | "load_result Mint8unsigned (Vint n) = Vint (Int.zero_ext TYPE(8) n)" | "load_result Mint16signed (Vint n) = Vint (Int.sign_ext TYPE(16) n)" | "load_result Mint16unsigned (Vint n) = Vint (Int.zero_ext TYPE(16) n)" | "load_result Mint32 (Vint n) = Vint n" | "load_result Mint32 (Vptr b ofs) = (if Archi.ptr64 then Vundef else Vptr b ofs)" | "load_result Mint64 (Vlong n) = Vlong n" | "load_result Mint64 (Vptr b ofs) = (if Archi.ptr64 then Vptr b ofs else Vundef)" | "load_result Mfloat32 (Vsingle f) = Vsingle f" | "load_result Mfloat64 (Vfloat f) = Vfloat f" | "load_result Many32 (Vint n) = Vint n" | "load_result Many32 (Vsingle f) = Vsingle f" | "load_result Many32 (Vptr b ofs) = (if Archi.ptr64 then Vundef else Vptr b ofs)" | "load_result Many64 v = v" | "load_result _ _ = Vundef" (** The ``is less defined'' relation between values. A value is less defined than itself, and [Vundef] is less defined than any value. *) inductive lessdef :: "val \<Rightarrow> val \<Rightarrow> bool" where lessdef_refl: "lessdef v v" | lessdef_undef: "lessdef Vundef v" inductive lessdef_list :: "val list \<Rightarrow> val list \<Rightarrow> bool" where lessdef_list_nil: "lessdef_list [] []" | lessdef_list_cons: "lessdef v1 v2 \<Longrightarrow> lessdef_list vl1 vl2 \<Longrightarrow> lessdef_list (v1 # vl1) (v2 # vl2)" section \<open>Values and memory injections\<close> (** A memory injection [f] is a function from addresses to either [None] or [Some] of an address and an offset. It defines a correspondence between the blocks of two memory states [m1] and [m2]: - if [f b = None], the block [b] of [m1] has no equivalent in [m2]; - if [f b = Some(b', ofs)], the block [b] of [m2] corresponds to a sub-block at offset [ofs] of the block [b'] in [m2]. *) type_synonym meminj = "block \<Rightarrow> (block * Z) option" (** A memory injection defines a relation between values that is the identity relation, except for pointer values which are shifted as prescribed by the memory injection. Moreover, [Vundef] values inject into any other value. *) inductive inject :: "meminj \<Rightarrow> val \<Rightarrow> val \<Rightarrow> bool" where inject_int: "inject mi (Vint i) (Vint i)" | inject_long: "inject mi (Vlong i) (Vlong i)" | inject_float: "inject mi (Vfloat f) (Vfloat f)" | inject_single: "inject mi (Vsingle f) (Vsingle f)" | inject_ptr: "mi b1 = Some (b2, delta) \<Longrightarrow> ofs2 = ofs1 + (Int64.repr delta) \<Longrightarrow> inject mi (Vptr b1 ofs1) (Vptr b2 ofs2)" | val_inject_undef: "inject mi Vundef v" inductive inject_list :: "meminj \<Rightarrow> val list \<Rightarrow> val list \<Rightarrow> bool" where inject_list_nil: "inject_list mi [] []" | inject_list_cons: "inject mi v v' \<Longrightarrow> inject_list mi vl vl' \<Longrightarrow> inject_list mi (v # vl) (v' # vl')" end (* locale Val' *) interpretation Val: Val' . type_synonym meminj = Val.meminj (** Monotone evolution of a memory injection. *) definition inject_incr :: "meminj \<Rightarrow> meminj \<Rightarrow> bool" where "inject_incr f1 f2 \<equiv> \<forall> b b' delta. f1 b = Some(b', delta) \<longrightarrow> f2 b = Some(b', delta)" (** The identity injection gives rise to the "less defined than" relation. *) definition inject_id :: meminj where "inject_id b \<equiv> Some (b, 0)" end
\section{Single determinant wavefunctions} \label{sec:singledeterminant} Placing a single determinant for each spin is the most used ansatz for the antisymmetric part of a trial wavefunction. The input xml block for \texttt{slaterdeterminant} is give in Listing~\ref{listing:singledet}. A list of options is given in Table~\ref{table:singledet} \begin{table}[h] \begin{center} \begin{tabularx}{\textwidth}{l l l l l l } \hline \multicolumn{6}{l}{\texttt{slaterdeterminant} element} \\ \hline \multicolumn{2}{l}{parent elements:} & \multicolumn{4}{l}{\texttt{determinantset}}\\ \multicolumn{2}{l}{child elements:} & \multicolumn{4}{l}{\texttt{determinant}}\\ \multicolumn{2}{l}{attribute :} & \multicolumn{4}{l}{}\\ & \bfseries name & \bfseries datatype & \bfseries values & \bfseries default & \bfseries description \\ & \texttt{delay\_rank} & integer & >0 & 1 & The number of delayed updates. \\ & \texttt{optimize} & text & yes/no & yes & Enable orbital optimization. \\ \hline \end{tabularx} \end{center} \caption{Options for the \texttt{slaterdeterminant} xml-block.} \label{table:singledet} \end{table} \begin{lstlisting}[style=XML,caption=slaterdeterminant set XML element.\label{listing:singledet}] <slaterdeterminant delay_rank="32"> <determinant id="updet" size="208"> <occupation mode="ground" spindataset="0"> </occupation> </determinant> <determinant id="downdet" size="208"> <occupation mode="ground" spindataset="0"> </occupation> </determinant> </slaterdeterminant> \end{lstlisting} Additional information: \begin{itemize} \item \texttt{delay\_rank}. This option enables the delayed updates of Slater matrix inverse when particle-by-particle move is used. By default, \texttt{delay\_rank=1} uses the Fahy's variant~\cite{Fahy1990} of the Sherman-Morrison rank-1 update which is mostly using memory bandwidth bound BLAS-2 calls. With \texttt{delay\_rank>1}, the delayed update algorithm~\cite{Luo2018delayedupdate,McDaniel2017} turns most of the computation to compute bound BLAS-3 calls. Tuning this parameter is highly recommended to gain the best performance on medium to large problem sizes ($>200$ electrons). We have seen up to an order of magnitude speed-up on large problem sizes. When studying the performance of QMCPACK, a scan of this parameter is required and we recommend to start from 32. The best \texttt{delay\_rank} giving the maximal speed-up depends the problem size. Usually the larger \texttt{delay\_rank} corresponds to a larger problem size. On CPUs, \texttt{delay\_rank} must be chosen a multiple of SIMD vector length for good performance of BLAS libraries. The best \texttt{delay\_rank} depends on the processor micro architecture. The GPU support is currently under development. \end{itemize}
-- Andreas, 2011-10-02 {-# OPTIONS --show-implicit #-} module Issue483a where data _≡_ {A : Set}(a : A) : A → Set where refl : a ≡ a data Empty : Set where postulate A : Set abort : .Empty → A abort () test : let X : .Set1 → A X = _ in (x : Empty) → X Set ≡ abort x test x = refl -- this should fail with message like -- -- Cannot instantiate the metavariable _16 to abort x since it -- contains the variable x which is not in scope of the metavariable -- when checking that the expression refl has type _16 _ ≡ abort x -- -- a solution like X = λ _ → abort x : Set1 → A -- would be invalid even though x is irrelevant, because there is no -- term of type Set1 → A
theory Chapter08_2_Typechecking imports Chapter08_1_Language begin inductive typecheck :: "type env => expr => type => bool" where tc_var [simp]: "lookup gam x = Some t ==> typecheck gam (Var x) t" | tc_str [simp]: "typecheck gam (Str s) StrType" | tc_num [simp]: "typecheck gam (Num n) NumType" | tc_plus [simp]: "typecheck gam e1 NumType ==> typecheck gam e2 NumType ==> typecheck gam (Plus e1 e2) NumType" | tc_times [simp]: "typecheck gam e1 NumType ==> typecheck gam e2 NumType ==> typecheck gam (Times e1 e2) NumType" | tc_cat [simp]: "typecheck gam e1 StrType ==> typecheck gam e2 StrType ==> typecheck gam (Cat e1 e2) StrType" | tc_len [simp]: "typecheck gam e StrType ==> typecheck gam (Len e) NumType" | tc_let [simp]: "typecheck gam e1 t1 ==> typecheck (extend gam t1) e2 t2 ==> typecheck gam (Let e1 e2) t2" | tc_lam [simp]: "typecheck (extend gam t1) e t2 ==> typecheck gam (Lam t1 e) (Arrow t1 t2)" | tc_appl [simp]: "typecheck gam e1 (Arrow t2 t) ==> typecheck gam e2 t2 ==> typecheck gam (Appl e1 e2) t" inductive_cases [elim!]: "typecheck gam (Var x) t" inductive_cases [elim!]: "typecheck gam (Str s) t" inductive_cases [elim!]: "typecheck gam (Num n) t" inductive_cases [elim!]: "typecheck gam (Plus e1 e2) t" inductive_cases [elim!]: "typecheck gam (Times e1 e2) t" inductive_cases [elim!]: "typecheck gam (Cat e1 e2) t" inductive_cases [elim!]: "typecheck gam (Len e) t" inductive_cases [elim!]: "typecheck gam (Let e1 e2) t" inductive_cases [elim!]: "typecheck gam (Lam t1 e) t" inductive_cases [elim!]: "typecheck gam (Appl e1 e2) t" lemma [simp]: "typecheck (extend_at n gam t') e t ==> n in gam ==> typecheck gam e' t' ==> typecheck gam (subst e' n e) t" by (induction "extend_at n gam t'" e t arbitrary: n gam t' e' rule: typecheck.induct, fastforce+) end
[GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a b : G hb : b ∈ doset a ↑H ↑K ⊢ doset b ↑H ↑K = doset a ↑H ↑K [PROOFSTEP] obtain ⟨_, k, ⟨h, a, hh, rfl : _ = _, rfl⟩, hk, rfl⟩ := hb [GOAL] case intro.intro.intro.intro.intro.intro.intro.intro G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G k h a : G hh : h ∈ ↑H hk : k ∈ ↑K ⊢ doset ((fun x x_1 => x * x_1) ((fun x x_1 => x * x_1) h a) k) ↑H ↑K = doset a ↑H ↑K [PROOFSTEP] rw [doset, doset, ← Set.singleton_mul_singleton, ← Set.singleton_mul_singleton, mul_assoc, mul_assoc, Subgroup.singleton_mul_subgroup hk, ← mul_assoc, ← mul_assoc, Subgroup.subgroup_mul_singleton hh] [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a b : G h : ¬Disjoint (doset a ↑H ↑K) (doset b ↑H ↑K) ⊢ b ∈ doset a ↑H ↑K [PROOFSTEP] rw [Set.not_disjoint_iff] at h [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a b : G h : ∃ x, x ∈ doset a ↑H ↑K ∧ x ∈ doset b ↑H ↑K ⊢ b ∈ doset a ↑H ↑K [PROOFSTEP] simp only [mem_doset] at * [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a b : G h : ∃ x, (∃ x_1, x_1 ∈ ↑H ∧ ∃ y, y ∈ ↑K ∧ x = x_1 * a * y) ∧ ∃ x_1, x_1 ∈ ↑H ∧ ∃ y, y ∈ ↑K ∧ x = x_1 * b * y ⊢ ∃ x, x ∈ ↑H ∧ ∃ y, y ∈ ↑K ∧ b = x * a * y [PROOFSTEP] obtain ⟨x, ⟨l, hl, r, hr, hrx⟩, y, hy, ⟨r', hr', rfl⟩⟩ := h [GOAL] case intro.intro.intro.intro.intro.intro.intro.intro.intro.intro G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a b l : G hl : l ∈ ↑H r : G hr : r ∈ ↑K y : G hy : y ∈ ↑H r' : G hr' : r' ∈ ↑K hrx : y * b * r' = l * a * r ⊢ ∃ x, x ∈ ↑H ∧ ∃ y, y ∈ ↑K ∧ b = x * a * y [PROOFSTEP] refine' ⟨y⁻¹ * l, H.mul_mem (H.inv_mem hy) hl, r * r'⁻¹, K.mul_mem hr (K.inv_mem hr'), _⟩ [GOAL] case intro.intro.intro.intro.intro.intro.intro.intro.intro.intro G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a b l : G hl : l ∈ ↑H r : G hr : r ∈ ↑K y : G hy : y ∈ ↑H r' : G hr' : r' ∈ ↑K hrx : y * b * r' = l * a * r ⊢ b = y⁻¹ * l * a * (r * r'⁻¹) [PROOFSTEP] rwa [mul_assoc, mul_assoc, eq_inv_mul_iff_mul_eq, ← mul_assoc, ← mul_assoc, eq_mul_inv_iff_mul_eq] [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a b : G h : ¬Disjoint (doset a ↑H ↑K) (doset b ↑H ↑K) ⊢ doset a ↑H ↑K = doset b ↑H ↑K [PROOFSTEP] rw [disjoint_comm] at h [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a b : G h : ¬Disjoint (doset b ↑H ↑K) (doset a ↑H ↑K) ⊢ doset a ↑H ↑K = doset b ↑H ↑K [PROOFSTEP] have ha : a ∈ doset b H K := mem_doset_of_not_disjoint h [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a b : G h : ¬Disjoint (doset b ↑H ↑K) (doset a ↑H ↑K) ha : a ∈ doset b ↑H ↑K ⊢ doset a ↑H ↑K = doset b ↑H ↑K [PROOFSTEP] apply doset_eq_of_mem ha [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G ⊢ Setoid.Rel (setoid ↑⊥ ↑H) = Setoid.Rel (QuotientGroup.leftRel H) [PROOFSTEP] ext a b [GOAL] case h.h.a G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G a b : G ⊢ Setoid.Rel (setoid ↑⊥ ↑H) a b ↔ Setoid.Rel (QuotientGroup.leftRel H) a b [PROOFSTEP] rw [rel_iff, Setoid.Rel, QuotientGroup.leftRel_apply] [GOAL] case h.h.a G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G a b : G ⊢ (∃ a_1, a_1 ∈ ⊥ ∧ ∃ b_1, b_1 ∈ H ∧ b = a_1 * a * b_1) ↔ a⁻¹ * b ∈ H [PROOFSTEP] constructor [GOAL] case h.h.a.mp G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G a b : G ⊢ (∃ a_1, a_1 ∈ ⊥ ∧ ∃ b_1, b_1 ∈ H ∧ b = a_1 * a * b_1) → a⁻¹ * b ∈ H [PROOFSTEP] rintro ⟨a, rfl : a = 1, b, hb, rfl⟩ [GOAL] case h.h.a.mp.intro.intro.intro.intro G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G a b : G hb : b ∈ H ⊢ a⁻¹ * (1 * a * b) ∈ H [PROOFSTEP] change a⁻¹ * (1 * a * b) ∈ H [GOAL] case h.h.a.mp.intro.intro.intro.intro G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G a b : G hb : b ∈ H ⊢ a⁻¹ * (1 * a * b) ∈ H [PROOFSTEP] rwa [one_mul, inv_mul_cancel_left] [GOAL] case h.h.a.mpr G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G a b : G ⊢ a⁻¹ * b ∈ H → ∃ a_2, a_2 ∈ ⊥ ∧ ∃ b_1, b_1 ∈ H ∧ b = a_2 * a * b_1 [PROOFSTEP] rintro (h : a⁻¹ * b ∈ H) [GOAL] case h.h.a.mpr G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G a b : G h : a⁻¹ * b ∈ H ⊢ ∃ a_1, a_1 ∈ ⊥ ∧ ∃ b_1, b_1 ∈ H ∧ b = a_1 * a * b_1 [PROOFSTEP] exact ⟨1, rfl, a⁻¹ * b, h, by rw [one_mul, mul_inv_cancel_left]⟩ [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G a b : G h : a⁻¹ * b ∈ H ⊢ b = 1 * a * (a⁻¹ * b) [PROOFSTEP] rw [one_mul, mul_inv_cancel_left] [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G ⊢ Setoid.Rel (setoid ↑H ↑⊥) = Setoid.Rel (QuotientGroup.rightRel H) [PROOFSTEP] ext a b [GOAL] case h.h.a G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G a b : G ⊢ Setoid.Rel (setoid ↑H ↑⊥) a b ↔ Setoid.Rel (QuotientGroup.rightRel H) a b [PROOFSTEP] rw [rel_iff, Setoid.Rel, QuotientGroup.rightRel_apply] [GOAL] case h.h.a G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G a b : G ⊢ (∃ a_1, a_1 ∈ H ∧ ∃ b_1, b_1 ∈ ⊥ ∧ b = a_1 * a * b_1) ↔ b * a⁻¹ ∈ H [PROOFSTEP] constructor [GOAL] case h.h.a.mp G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G a b : G ⊢ (∃ a_1, a_1 ∈ H ∧ ∃ b_1, b_1 ∈ ⊥ ∧ b = a_1 * a * b_1) → b * a⁻¹ ∈ H [PROOFSTEP] rintro ⟨b, hb, a, rfl : a = 1, rfl⟩ [GOAL] case h.h.a.mp.intro.intro.intro.intro G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G a b : G hb : b ∈ H ⊢ b * a * 1 * a⁻¹ ∈ H [PROOFSTEP] change b * a * 1 * a⁻¹ ∈ H [GOAL] case h.h.a.mp.intro.intro.intro.intro G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G a b : G hb : b ∈ H ⊢ b * a * 1 * a⁻¹ ∈ H [PROOFSTEP] rwa [mul_one, mul_inv_cancel_right] [GOAL] case h.h.a.mpr G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G a b : G ⊢ b * a⁻¹ ∈ H → ∃ a_2, a_2 ∈ H ∧ ∃ b_1, b_1 ∈ ⊥ ∧ b = a_2 * a * b_1 [PROOFSTEP] rintro (h : b * a⁻¹ ∈ H) [GOAL] case h.h.a.mpr G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G a b : G h : b * a⁻¹ ∈ H ⊢ ∃ a_1, a_1 ∈ H ∧ ∃ b_1, b_1 ∈ ⊥ ∧ b = a_1 * a * b_1 [PROOFSTEP] exact ⟨b * a⁻¹, h, 1, rfl, by rw [mul_one, inv_mul_cancel_right]⟩ [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G a b : G h : b * a⁻¹ ∈ H ⊢ b = b * a⁻¹ * a * 1 [PROOFSTEP] rw [mul_one, inv_mul_cancel_right] [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a b : G ⊢ mk H K a = mk H K b ↔ ∃ h, h ∈ H ∧ ∃ k, k ∈ K ∧ b = h * a * k [PROOFSTEP] rw [Quotient.eq''] [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a b : G ⊢ Setoid.r a b ↔ ∃ h, h ∈ H ∧ ∃ k, k ∈ K ∧ b = h * a * k [PROOFSTEP] apply rel_iff [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g✝ : G H K : Subgroup G g : G ⊢ ∃ h k, h ∈ H ∧ k ∈ K ∧ Quotient.out' (mk H K g) = h * g * k [PROOFSTEP] have := eq H K (mk H K g : Quotient ↑H ↑K).out' g [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g✝ : G H K : Subgroup G g : G this : mk H K (Quotient.out' (mk H K g)) = mk H K g ↔ ∃ h, h ∈ H ∧ ∃ k, k ∈ K ∧ g = h * Quotient.out' (mk H K g) * k ⊢ ∃ h k, h ∈ H ∧ k ∈ K ∧ Quotient.out' (mk H K g) = h * g * k [PROOFSTEP] rw [out_eq'] at this [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g✝ : G H K : Subgroup G g : G this : mk H K g = mk H K g ↔ ∃ h, h ∈ H ∧ ∃ k, k ∈ K ∧ g = h * Quotient.out' (mk H K g) * k ⊢ ∃ h k, h ∈ H ∧ k ∈ K ∧ Quotient.out' (mk H K g) = h * g * k [PROOFSTEP] obtain ⟨h, h_h, k, hk, T⟩ := this.1 rfl [GOAL] case intro.intro.intro.intro G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g✝ : G H K : Subgroup G g : G this : mk H K g = mk H K g ↔ ∃ h, h ∈ H ∧ ∃ k, k ∈ K ∧ g = h * Quotient.out' (mk H K g) * k h : G h_h : h ∈ H k : G hk : k ∈ K T : g = h * Quotient.out' (mk H K g) * k ⊢ ∃ h k, h ∈ H ∧ k ∈ K ∧ Quotient.out' (mk H K g) = h * g * k [PROOFSTEP] refine' ⟨h⁻¹, k⁻¹, H.inv_mem h_h, K.inv_mem hk, eq_mul_inv_of_mul_eq (eq_inv_mul_of_mul_eq _)⟩ [GOAL] case intro.intro.intro.intro G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g✝ : G H K : Subgroup G g : G this : mk H K g = mk H K g ↔ ∃ h, h ∈ H ∧ ∃ k, k ∈ K ∧ g = h * Quotient.out' (mk H K g) * k h : G h_h : h ∈ H k : G hk : k ∈ K T : g = h * Quotient.out' (mk H K g) * k ⊢ h * (Quotient.out' (mk H K g) * k) = g [PROOFSTEP] rw [← mul_assoc, ← T] [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a b : G h : doset a ↑H ↑K = doset b ↑H ↑K ⊢ mk H K a = mk H K b [PROOFSTEP] rw [eq] [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a b : G h : doset a ↑H ↑K = doset b ↑H ↑K ⊢ ∃ h, h ∈ H ∧ ∃ k, k ∈ K ∧ b = h * a * k [PROOFSTEP] exact mem_doset.mp (h.symm ▸ mem_doset_self H K b) [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a b : Quotient ↑H.toSubmonoid ↑K ⊢ a ≠ b → Disjoint (doset (Quotient.out' a) ↑H ↑K) (doset (Quotient.out' b) ↑H ↑K) [PROOFSTEP] contrapose! [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a b : Quotient ↑H.toSubmonoid ↑K ⊢ ¬Disjoint (doset (Quotient.out' a) ↑H ↑K) (doset (Quotient.out' b) ↑H ↑K) → a = b [PROOFSTEP] intro h [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a b : Quotient ↑H.toSubmonoid ↑K h : ¬Disjoint (doset (Quotient.out' a) ↑H ↑K) (doset (Quotient.out' b) ↑H ↑K) ⊢ a = b [PROOFSTEP] simpa [out_eq'] using mk_eq_of_doset_eq (eq_of_not_disjoint h) [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G ⊢ ⋃ (q : Quotient ↑H ↑K), quotToDoset H K q = Set.univ [PROOFSTEP] ext x [GOAL] case h G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G x : G ⊢ x ∈ ⋃ (q : Quotient ↑H ↑K), quotToDoset H K q ↔ x ∈ Set.univ [PROOFSTEP] simp only [Set.mem_iUnion, quotToDoset, mem_doset, SetLike.mem_coe, exists_prop, Set.mem_univ, iff_true_iff] [GOAL] case h G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G x : G ⊢ ∃ i x_1, x_1 ∈ H ∧ ∃ y, y ∈ K ∧ x = x_1 * Quotient.out' i * y [PROOFSTEP] use mk H K x [GOAL] case h G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G x : G ⊢ ∃ x_1, x_1 ∈ H ∧ ∃ y, y ∈ K ∧ x = x_1 * Quotient.out' (mk H K x) * y [PROOFSTEP] obtain ⟨h, k, h3, h4, h5⟩ := mk_out'_eq_mul H K x [GOAL] case h.intro.intro.intro.intro G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G x h k : G h3 : h ∈ H h4 : k ∈ K h5 : Quotient.out' (mk H K x) = h * x * k ⊢ ∃ x_1, x_1 ∈ H ∧ ∃ y, y ∈ K ∧ x = x_1 * Quotient.out' (mk H K x) * y [PROOFSTEP] refine' ⟨h⁻¹, H.inv_mem h3, k⁻¹, K.inv_mem h4, _⟩ [GOAL] case h.intro.intro.intro.intro G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G x h k : G h3 : h ∈ H h4 : k ∈ K h5 : Quotient.out' (mk H K x) = h * x * k ⊢ x = h⁻¹ * Quotient.out' (mk H K x) * k⁻¹ [PROOFSTEP] simp only [h5, Subgroup.coe_mk, ← mul_assoc, one_mul, mul_left_inv, mul_inv_cancel_right] [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a : G ⊢ ⋃ (k : { x // x ∈ K }), rightCoset (↑H) (a * ↑k) = doset a ↑H ↑K [PROOFSTEP] ext x [GOAL] case h G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a x : G ⊢ x ∈ ⋃ (k : { x // x ∈ K }), rightCoset (↑H) (a * ↑k) ↔ x ∈ doset a ↑H ↑K [PROOFSTEP] simp only [mem_rightCoset_iff, exists_prop, mul_inv_rev, Set.mem_iUnion, mem_doset, Subgroup.mem_carrier, SetLike.mem_coe] [GOAL] case h G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a x : G ⊢ (∃ i, x * ((↑i)⁻¹ * a⁻¹) ∈ H) ↔ ∃ x_1, x_1 ∈ H ∧ ∃ y, y ∈ K ∧ x = x_1 * a * y [PROOFSTEP] constructor [GOAL] case h.mp G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a x : G ⊢ (∃ i, x * ((↑i)⁻¹ * a⁻¹) ∈ H) → ∃ x_1, x_1 ∈ H ∧ ∃ y, y ∈ K ∧ x = x_1 * a * y [PROOFSTEP] rintro ⟨y, h_h⟩ [GOAL] case h.mp.intro G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a x : G y : { x // x ∈ K } h_h : x * ((↑y)⁻¹ * a⁻¹) ∈ H ⊢ ∃ x_1, x_1 ∈ H ∧ ∃ y, y ∈ K ∧ x = x_1 * a * y [PROOFSTEP] refine' ⟨x * (y⁻¹ * a⁻¹), h_h, y, y.2, _⟩ [GOAL] case h.mp.intro G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a x : G y : { x // x ∈ K } h_h : x * ((↑y)⁻¹ * a⁻¹) ∈ H ⊢ x = x * (↑y⁻¹ * a⁻¹) * a * ↑y [PROOFSTEP] simp only [← mul_assoc, Subgroup.coe_mk, inv_mul_cancel_right, SubgroupClass.coe_inv] [GOAL] case h.mpr G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a x : G ⊢ (∃ x_1, x_1 ∈ H ∧ ∃ y, y ∈ K ∧ x = x_1 * a * y) → ∃ i, x * ((↑i)⁻¹ * a⁻¹) ∈ H [PROOFSTEP] rintro ⟨x, hx, y, hy, hxy⟩ [GOAL] case h.mpr.intro.intro.intro.intro G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a x✝ x : G hx : x ∈ H y : G hy : y ∈ K hxy : x✝ = x * a * y ⊢ ∃ i, x✝ * ((↑i)⁻¹ * a⁻¹) ∈ H [PROOFSTEP] refine' ⟨⟨y, hy⟩, _⟩ [GOAL] case h.mpr.intro.intro.intro.intro G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a x✝ x : G hx : x ∈ H y : G hy : y ∈ K hxy : x✝ = x * a * y ⊢ x✝ * ((↑{ val := y, property := hy })⁻¹ * a⁻¹) ∈ H [PROOFSTEP] simp only [hxy, ← mul_assoc, hx, mul_inv_cancel_right, Subgroup.coe_mk] [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a : G ⊢ ⋃ (h : { x // x ∈ H }), leftCoset (↑h * a) ↑K = doset a ↑H ↑K [PROOFSTEP] ext x [GOAL] case h G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a x : G ⊢ x ∈ ⋃ (h : { x // x ∈ H }), leftCoset (↑h * a) ↑K ↔ x ∈ doset a ↑H ↑K [PROOFSTEP] simp only [mem_leftCoset_iff, mul_inv_rev, Set.mem_iUnion, mem_doset] [GOAL] case h G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a x : G ⊢ (∃ i, a⁻¹ * (↑i)⁻¹ * x ∈ ↑K) ↔ ∃ x_1, x_1 ∈ ↑H ∧ ∃ y, y ∈ ↑K ∧ x = x_1 * a * y [PROOFSTEP] constructor [GOAL] case h.mp G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a x : G ⊢ (∃ i, a⁻¹ * (↑i)⁻¹ * x ∈ ↑K) → ∃ x_1, x_1 ∈ ↑H ∧ ∃ y, y ∈ ↑K ∧ x = x_1 * a * y [PROOFSTEP] rintro ⟨y, h_h⟩ [GOAL] case h.mp.intro G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a x : G y : { x // x ∈ H } h_h : a⁻¹ * (↑y)⁻¹ * x ∈ ↑K ⊢ ∃ x_1, x_1 ∈ ↑H ∧ ∃ y, y ∈ ↑K ∧ x = x_1 * a * y [PROOFSTEP] refine' ⟨y, y.2, a⁻¹ * y⁻¹ * x, h_h, _⟩ [GOAL] case h.mp.intro G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a x : G y : { x // x ∈ H } h_h : a⁻¹ * (↑y)⁻¹ * x ∈ ↑K ⊢ x = ↑y * a * (a⁻¹ * ↑y⁻¹ * x) [PROOFSTEP] simp only [← mul_assoc, one_mul, mul_right_inv, mul_inv_cancel_right, SubgroupClass.coe_inv] [GOAL] case h.mpr G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a x : G ⊢ (∃ x_1, x_1 ∈ ↑H ∧ ∃ y, y ∈ ↑K ∧ x = x_1 * a * y) → ∃ i, a⁻¹ * (↑i)⁻¹ * x ∈ ↑K [PROOFSTEP] rintro ⟨x, hx, y, hy, hxy⟩ [GOAL] case h.mpr.intro.intro.intro.intro G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a x✝ x : G hx : x ∈ ↑H y : G hy : y ∈ ↑K hxy : x✝ = x * a * y ⊢ ∃ i, a⁻¹ * (↑i)⁻¹ * x✝ ∈ ↑K [PROOFSTEP] refine' ⟨⟨x, hx⟩, _⟩ [GOAL] case h.mpr.intro.intro.intro.intro G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H K : Subgroup G a x✝ x : G hx : x ∈ ↑H y : G hy : y ∈ ↑K hxy : x✝ = x * a * y ⊢ a⁻¹ * (↑{ val := x, property := hx })⁻¹ * x✝ ∈ ↑K [PROOFSTEP] simp only [hxy, ← mul_assoc, hy, one_mul, mul_left_inv, Subgroup.coe_mk, inv_mul_cancel_right] [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G ⊢ Quotient ↑⊥.toSubmonoid ↑H = (G ⧸ H) [PROOFSTEP] unfold Quotient [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G ⊢ _root_.Quotient (setoid ↑⊥.toSubmonoid ↑H) = (G ⧸ H) [PROOFSTEP] congr [GOAL] case e_s G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G ⊢ setoid ↑⊥.toSubmonoid ↑H = QuotientGroup.leftRel H [PROOFSTEP] ext [GOAL] case e_s.H G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G a✝ b✝ : G ⊢ Setoid.Rel (setoid ↑⊥.toSubmonoid ↑H) a✝ b✝ ↔ Setoid.Rel (QuotientGroup.leftRel H) a✝ b✝ [PROOFSTEP] simp_rw [← bot_rel_eq_leftRel H] [GOAL] case e_s.H G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G a✝ b✝ : G ⊢ Setoid.Rel (setoid ↑⊥.toSubmonoid ↑H) a✝ b✝ ↔ Setoid.Rel (setoid ↑⊥ ↑H) a✝ b✝ [PROOFSTEP] rfl [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G ⊢ Quotient ↑H.toSubmonoid ↑⊥ = _root_.Quotient (QuotientGroup.rightRel H) [PROOFSTEP] unfold Quotient [GOAL] G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G ⊢ _root_.Quotient (setoid ↑H.toSubmonoid ↑⊥) = _root_.Quotient (QuotientGroup.rightRel H) [PROOFSTEP] congr [GOAL] case e_s G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G ⊢ setoid ↑H.toSubmonoid ↑⊥ = QuotientGroup.rightRel H [PROOFSTEP] ext [GOAL] case e_s.H G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G a✝ b✝ : G ⊢ Setoid.Rel (setoid ↑H.toSubmonoid ↑⊥) a✝ b✝ ↔ Setoid.Rel (QuotientGroup.rightRel H) a✝ b✝ [PROOFSTEP] simp_rw [← rel_bot_eq_right_group_rel H] [GOAL] case e_s.H G : Type u_1 inst✝¹ : Group G α : Type u_2 inst✝ : Mul α J : Subgroup G g : G H : Subgroup G a✝ b✝ : G ⊢ Setoid.Rel (setoid ↑H.toSubmonoid ↑⊥) a✝ b✝ ↔ Setoid.Rel (setoid ↑H ↑⊥) a✝ b✝ [PROOFSTEP] rfl
State Before: α : Type u β : Type v γ : Type w δ : Type ?u.255463 ι : Sort x f f₁ f₂ : Filter α g g₁ g₂ : Filter β m✝ : α → β m' : β → γ s✝ : Set α t : Set β s : Set (Filter β) m : α → β ⊢ comap m (sSup s) = ⨆ (f : Filter β) (_ : f ∈ s), comap m f State After: no goals Tactic: simp only [sSup_eq_iSup, comap_iSup, eq_self_iff_true]
[STATEMENT] lemma lookup_functional: assumes "lookup l f = o1" and "lookup l f = o2" shows "o1 = o2" [PROOF STATE] proof (prove) goal (1 subgoal): 1. o1 = o2 [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: lookup l f = o1 lookup l f = o2 goal (1 subgoal): 1. o1 = o2 [PROOF STEP] by (induct l) auto
[STATEMENT] lemma product_language[simp]: "c.language (product A B) = a.language A \<inter> b.language B" [PROOF STATE] proof (prove) goal (1 subgoal): 1. c.language (product A B) = a.language A \<inter> b.language B [PROOF STEP] by force
[STATEMENT] lemma poly_of_pm_sum: "poly_of_pm x (sum f I) = (\<Sum>i\<in>I. poly_of_pm x (f i))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. poly_of_pm x (sum f I) = (\<Sum>i\<in>I. poly_of_pm x (f i)) [PROOF STEP] by (induct I rule: infinite_finite_induct) (simp_all add: poly_of_pm_plus)
#ifndef TEST_PERIOR_TREE_AABB_TYPE_HPP #define TEST_PERIOR_TREE_AABB_TYPE_HPP #include <periortree/aabb_traits.hpp> #include <test/point_type.hpp> #include <boost/array.hpp> #include <boost/mpl/int.hpp> namespace perior { namespace test { struct aabb { aabb(const xyz& lw, const xyz& up) : lower(lw), upper(up) {} aabb() {} ~aabb(){} aabb(const aabb& rhs) : lower(rhs.lower), upper(rhs.upper){} aabb& operator=(const aabb& rhs) { upper = rhs.upper; lower = rhs.lower; return *this; } xyz lower, upper; }; }// test }// perior namespace perior { namespace traits { template<> struct tag<perior::test::aabb> {typedef aabb_tag type;}; template<> struct dimension_of<perior::test::aabb>: boost::mpl::int_<3>{}; template<> struct point_type_of<perior::test::aabb>{typedef perior::test::xyz type;}; template<> struct coordinate_type_of<perior::test::aabb>{typedef double type;}; template<std::size_t D> struct box_access<perior::test::aabb, max_corner, D> { typedef perior::test::aabb box_type; typedef typename point_type_of<box_type>::type point_type; typedef typename coordinate_type_of<box_type>::type coordinate_type; BOOST_FORCEINLINE static coordinate_type get(const box_type& b) BOOST_NOEXCEPT_IF( noexcept(point_access<point_type, D>::get(b.upper)) ) { return point_access<point_type, D>::get(b.upper); } BOOST_FORCEINLINE static void set(box_type& b, coordinate_type x) BOOST_NOEXCEPT_IF( noexcept(point_access<point_type, D>::set(b.upper, x)) ) { return point_access<point_type, D>::set(b.upper, x); } }; template<std::size_t D> struct box_access<perior::test::aabb, min_corner, D> { typedef perior::test::aabb box_type; typedef typename point_type_of<box_type>::type point_type; typedef typename coordinate_type_of<box_type>::type coordinate_type; BOOST_FORCEINLINE static coordinate_type get(const box_type& b) BOOST_NOEXCEPT_IF( noexcept(point_access<point_type, D>::get(b.lower)) ) { return point_access<point_type, D>::get(b.lower); } BOOST_FORCEINLINE static void set(box_type& b, coordinate_type x) BOOST_NOEXCEPT_IF( noexcept(point_access<point_type, D>::set(b.lower, x)) ) { return point_access<point_type, D>::set(b.lower, x); } }; template<std::size_t D> struct box_range_access<perior::test::aabb, D> { typedef perior::test::aabb box_type; typedef typename point_type_of<box_type>::type point_type; typedef typename coordinate_type_of<box_type>::type coordinate_type; BOOST_FORCEINLINE static coordinate_type get(const box_type& b) BOOST_NOEXCEPT_IF( noexcept(point_access<point_type, D>::get(b.lower)) ) { return point_access<point_type, D>::get(b.upper) - point_access<point_type, D>::get(b.lower); } }; }// traits }// perior #endif//TEST_PERIOR_TREE_AABB_TYPE_HPP
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # 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. """BERT finetuning runner.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function ##set random seed import numpy as np np.random.seed(26) import tensorflow as tf tf.set_random_seed(26) import collections import csv import pandas as pd import os,sys import modeling from tensorflow.contrib.layers.python.layers import initializers import optimization # import optimization_layerwise as optimization # import accoptimization as optimization import tokenization import pickle import codecs from sklearn import metrics from sklearn.externals import joblib flags = tf.flags FLAGS = flags.FLAGS ## Required parameters flags.DEFINE_string( "data_dir", None, "The input data dir. Should contain the .tsv files (or other data files) " "for the task.") flags.DEFINE_string( "bert_config_file", None, "The config json file corresponding to the pre-trained BERT model. " "This specifies the model architecture.") flags.DEFINE_string("task_name", None, "The name of the task to train.") flags.DEFINE_string("vocab_file", None, "The vocabulary file that the BERT model was trained on.") flags.DEFINE_string( "output_dir", None, "The output directory where the model checkpoints will be written.") ## Other parameters flags.DEFINE_string( "init_checkpoint", None, "Initial checkpoint (usually from a pre-trained BERT model).") flags.DEFINE_bool( "do_lower_case", False, "Whether to lower case the input text. Should be True for uncased " "models and False for cased models.") flags.DEFINE_integer( "max_seq_length", 128, "The maximum total input sequence length after WordPiece tokenization. " "Sequences longer than this will be truncated, and sequences shorter " "than this will be padded.") flags.DEFINE_bool("do_train", False, "Whether to run training.") flags.DEFINE_bool("do_eval", False, "Whether to run eval on the dev set.") flags.DEFINE_bool( "do_predict", False, "Whether to run the model in inference mode on the test set.") flags.DEFINE_bool("clean", True, "Whether to clean last training files.") flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.") flags.DEFINE_integer("eval_batch_size", 8, "Total batch size for eval.") flags.DEFINE_integer("predict_batch_size", 8, "Total batch size for predict.") flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.") flags.DEFINE_float("num_train_epochs", 3.0, "Total number of training epochs to perform.") flags.DEFINE_float( "warmup_proportion", 0.1, "Proportion of training to perform linear learning rate warmup for. " "E.g., 0.1 = 10% of training.") flags.DEFINE_integer("save_checkpoints_steps", 1000, "How often to save the model checkpoint.") flags.DEFINE_integer("iterations_per_loop", 1000, "How many steps to make in each estimator call.") flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.") tf.flags.DEFINE_string( "tpu_name", None, "The Cloud TPU to use for training. This should be either the name " "used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 " "url.") tf.flags.DEFINE_string( "tpu_zone", None, "[Optional] GCE zone where the Cloud TPU is located in. If not " "specified, we will attempt to automatically detect the GCE project from " "metadata.") tf.flags.DEFINE_string( "gcp_project", None, "[Optional] Project name for the Cloud TPU-enabled project. If not " "specified, we will attempt to automatically detect the GCE project from " "metadata.") tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.") flags.DEFINE_integer( "num_tpu_cores", 8, "Only used if `use_tpu` is True. Total number of TPU cores to use.") class InputExample(object): """A single training/test example for simple sequence classification.""" def __init__(self, guid, text_a, text_b=None, start_labels=None, end_labels=None): """Constructs a InputExample. Args: guid: Unique id for the example. text_a: string. The untokenized text of the first sequence. For single sequence tasks, only this sequence must be specified. text_b: (Optional) string. The untokenized text of the second sequence. Only must be specified for sequence pair tasks. label: (Optional) string. The label of the example. This should be specified for train and dev examples, but not for test examples. """ self.guid = guid self.text_a = text_a self.text_b = text_b self.start_labels = start_labels self.end_labels = end_labels class PaddingInputExample(object): """Fake example so the num input examples is a multiple of the batch size. When running eval/predict on the TPU, we need to pad the number of examples to be a multiple of the batch size, because the TPU requires a fixed batch size. The alternative is to drop the last batch, which is bad because it means the entire output data won't be generated. We use this class instead of `None` because treating `None` as padding battches could cause silent errors. """ class InputFeatures(object): """A single set of features of data.""" def __init__(self, input_ids, input_mask, segment_ids, start_labels_ids, end_labels_ids): self.input_ids = input_ids self.input_mask = input_mask self.segment_ids = segment_ids self.start_labels_ids = start_labels_ids self.end_labels_ids = end_labels_ids class DataProcessor(object): """Base class for data converters for sequence classification data sets.""" def get_train_examples(self, data_dir): """Gets a collection of `InputExample`s for the train set.""" raise NotImplementedError() def get_dev_examples(self, data_dir): """Gets a collection of `InputExample`s for the dev set.""" raise NotImplementedError() def get_test_examples(self, data_dir): """Gets a collection of `InputExample`s for prediction.""" raise NotImplementedError() def get_labels(self): """Gets the list of labels for this data set.""" raise NotImplementedError() @classmethod def _read_tsv(cls, input_file, quotechar=None): """Reads a tab separated value file.""" with tf.gfile.Open(input_file, "r") as f: reader = csv.reader(f, delimiter="\t", quotechar=quotechar) lines = [] for line in reader: lines.append(line) return lines class NerProcessor(DataProcessor): """Processor for the MRPC data set (GLUE version).""" def get_train_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "train_raw.out")), "train") def get_dev_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev_raw.out")), "dev") def get_test_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev_raw.out")), "test") def get_labels(self): """See base class.""" labels = ['0','1'] return labels def _create_examples(self, lines, set_type): """Creates examples for the training and dev sets.""" examples = [] for (i, line) in enumerate(lines): # if i == 0: # continue # if set_type == 'train': # if i > len(lines) * 0.01: # continue # if set_type == 'dev': # filter unclear class # if i > len(lines) * 0.01: # continue # if set_type == 'test': # filter unclear class # if i > len(lines) * 0.01: # continue ## xy:先pad句子,再pad query guid = "%s-%s" % (set_type, i) text_a = tokenization.convert_to_unicode(line[1].strip()) text_b = tokenization.convert_to_unicode(line[0].strip()) # start_labels = line[2].strip() # end_labels = line[3].strip() start_labels = tokenization.convert_to_unicode(line[2].strip()) end_labels = tokenization.convert_to_unicode(line[3].strip()) examples.append( InputExample(guid=guid, text_a=text_a, text_b=text_b, start_labels=start_labels, end_labels=end_labels)) return examples def convert_single_example(ex_index, example, label_map, max_seq_length, tokenizer): """Converts a single `InputExample` into a single `InputFeatures`.""" all_start_labels = [] all_end_labels = [] text_a = example.text_a.split(' ') text_b = example.text_b start_labels = example.start_labels.split(' ') end_labels = example.end_labels.split(' ') # text_a_start_labels = [] # text_a_end_labels = [] tokens = [] segment_ids = [] tokens.append("[CLS]") all_start_labels.append(0) all_end_labels.append(0) segment_ids.append(0) # print('**'*30) # print(len(text_a)) # print(len(text_b)) # print(len(start_labels)) # print(len(end_labels)) for i, word in enumerate(text_a): # 分词,如果是中文,就是分字,但是对于一些不在BERT的vocab.txt中得字符会被进行WordPice处理(例如中文的引号),可以将所有的分字操作替换为list(input) token = tokenizer.tokenize(word) tokens.extend(token) tmp_s_label = start_labels[i] tmp_e_label = end_labels[i] ## 熊英:?? 对每个token处理是否存在问题?不应该是还要判断start和end吗 ## xy revise for m in range(len(token)): if m == 0: all_start_labels.append(tmp_s_label) all_end_labels.append(0) # 不管怎样end都填0,如果是实体被token开,再最后判断把最后一个改成1 segment_ids.append(0) else: # 一般不会出现else all_start_labels.append(0) all_end_labels.append(0) segment_ids.append(0) if tmp_e_label == '1': # print('##################yyyyy################') all_end_labels[-1] = 1 tokens.append("[SEP]") all_start_labels.append(0) all_end_labels.append(0) segment_ids.append(0) tokens_b = tokenizer.tokenize(text_b) for token in tokens_b: tokens.append(token) all_start_labels.append(0) all_end_labels.append(0) segment_ids.append(1) # all_start_labels.extend(text_a_start_labels) # all_end_labels.extend(text_a_end_labels) # 序列截断 # 熊英:暴力截断会存在问题的吧?如果end_label为1,截断就没有对应的了?? if len(tokens) >= max_seq_length - 1: tokens = tokens[:(max_seq_length - 1)] # -2 的原因是因为序列需要加一个句首和句尾标志 all_start_labels = all_start_labels[:(max_seq_length - 1)] all_end_labels = all_end_labels[:(max_seq_length - 1)] segment_ids = segment_ids[:(max_seq_length - 1)] tokens.append("[SEP]") all_start_labels.append(0) all_end_labels.append(0) segment_ids.append(1) input_ids = tokenizer.convert_tokens_to_ids(tokens) input_mask = [1] * len(input_ids) # Zero-pad up to the sequence length. while len(input_ids) < max_seq_length: input_ids.append(0) input_mask.append(0) segment_ids.append(0) # we don't concerned about it! all_start_labels.append(0) all_end_labels.append(0) all_start_labels_ids = [label_map[str(i)] for i in all_start_labels] all_end_labels_ids = [label_map[str(i)] for i in all_end_labels] assert len(input_ids) == max_seq_length assert len(input_mask) == max_seq_length assert len(segment_ids) == max_seq_length assert len(all_start_labels_ids) == max_seq_length assert len(all_end_labels_ids) == max_seq_length if ex_index < 5: tf.logging.info("*** Example ***") tf.logging.info("guid: %s" % (example.guid)) tf.logging.info("tokens: %s" % " ".join( [tokenization.printable_text(x) for x in tokens])) tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids])) tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask])) tf.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids])) tf.logging.info("start_labels_ids: %s" % " ".join([str(x) for x in all_start_labels_ids])) tf.logging.info("end_labels_ids: %s" % " ".join([str(x) for x in all_end_labels_ids])) feature = InputFeatures( input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, start_labels_ids=all_start_labels_ids, end_labels_ids=all_end_labels_ids) return feature def file_based_convert_examples_to_features( examples, label_map, max_seq_length, tokenizer, output_file): """Convert a set of `InputExample`s to a TFRecord file.""" writer = tf.python_io.TFRecordWriter(output_file) for (ex_index, example) in enumerate(examples): if ex_index % 10000 == 0: tf.logging.info("Writing example %d of %d" % (ex_index, len(examples))) feature = convert_single_example(ex_index, example, label_map, max_seq_length, tokenizer) def create_int_feature(values): f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values))) return f features = collections.OrderedDict() features["input_ids"] = create_int_feature(feature.input_ids) features["input_mask"] = create_int_feature(feature.input_mask) features["segment_ids"] = create_int_feature(feature.segment_ids) features["start_labels_ids"] = create_int_feature(feature.start_labels_ids) features["end_labels_ids"] = create_int_feature(feature.end_labels_ids) tf_example = tf.train.Example(features=tf.train.Features(feature=features)) writer.write(tf_example.SerializeToString()) writer.close() def file_based_input_fn_builder(input_file, seq_length, is_training, drop_remainder): """Creates an `input_fn` closure to be passed to TPUEstimator.""" name_to_features = { "input_ids": tf.FixedLenFeature([seq_length], tf.int64), "input_mask": tf.FixedLenFeature([seq_length], tf.int64), "segment_ids": tf.FixedLenFeature([seq_length], tf.int64), "start_labels_ids": tf.FixedLenFeature([seq_length], tf.int64), "end_labels_ids": tf.FixedLenFeature([seq_length], tf.int64), } def _decode_record(record, name_to_features): """Decodes a record to a TensorFlow example.""" example = tf.parse_single_example(record, name_to_features) # tf.Example only supports tf.int64, but the TPU only supports tf.int32. # So cast all int64 to int32. for name in list(example.keys()): t = example[name] if t.dtype == tf.int64: t = tf.to_int32(t) example[name] = t return example def input_fn(params): """The actual input function.""" batch_size = params["batch_size"] # For training, we want a lot of parallel reading and shuffling. # For eval, we want no shuffling and parallel reading doesn't matter. d = tf.data.TFRecordDataset(input_file) if is_training: # d = d.repeat(1) d = d.shuffle(buffer_size=500) d = d.apply( tf.contrib.data.map_and_batch( lambda record: _decode_record(record, name_to_features), batch_size=batch_size, drop_remainder=drop_remainder)) return d return input_fn def focal_loss(logits,labels,mask,num_labels,one_hot=True,lambda_param=1.5): probs = tf.nn.softmax(logits,axis=-1) pos_probs = probs[:,:,1] prob_label_pos = tf.where(tf.equal(labels,1),pos_probs,tf.ones_like(pos_probs)) prob_label_neg = tf.where(tf.equal(labels,0),pos_probs,tf.zeros_like(pos_probs)) loss = tf.pow(1. - prob_label_pos,lambda_param)*tf.log(prob_label_pos + 1e-7) + \ tf.pow(prob_label_neg,lambda_param)*tf.log(1. - prob_label_neg + 1e-7) loss = -loss * tf.cast(mask,tf.float32) loss = tf.reduce_sum(loss,axis=-1,keepdims=True) # loss = loss/tf.cast(tf.reduce_sum(mask,axis=-1),tf.float32) loss = tf.reduce_mean(loss) return loss def create_model(bert_config, is_training, input_ids, input_mask, segment_ids, start_labels_ids, end_labels_ids, num_labels, use_one_hot_embeddings): """Creates a classification model.""" model = modeling.BertModel( config=bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings) output_layer = model.get_sequence_output() hidden_size = output_layer.shape[-1].value max_seq_length = output_layer.shape[1].value ##add CRF layer and biLSTM layer if is_training: output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) hidden = tf.reshape(output_layer, shape=[-1, hidden_size]) with tf.variable_scope("start_logits"): start_W = tf.get_variable("start_W", shape=[hidden_size, num_labels], dtype=tf.float32, initializer=initializers.xavier_initializer()) start_b = tf.get_variable("start_b", shape=[num_labels], dtype=tf.float32, initializer=tf.zeros_initializer()) start_pred = tf.nn.xw_plus_b(hidden, start_W, start_b) with tf.variable_scope("end_logits"): end_W = tf.get_variable("end_W", shape=[hidden_size, num_labels], dtype=tf.float32, initializer=initializers.xavier_initializer()) end_b = tf.get_variable("end_b", shape=[num_labels], dtype=tf.float32, initializer=tf.zeros_initializer()) end_pred = tf.nn.xw_plus_b(hidden, end_W, end_b) with tf.variable_scope("start_loss"): logits = tf.reshape(start_pred, [-1, max_seq_length, num_labels]) log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(start_labels_ids, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1) start_loss = tf.reduce_mean(per_example_loss) probabilities = tf.nn.softmax(logits, axis=-1) start_pred_ids = tf.argmax(probabilities,axis=-1) with tf.variable_scope("end_start_loss"): logits = tf.reshape(end_pred, [-1, max_seq_length, num_labels]) log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(end_labels_ids, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1) end_loss = tf.reduce_mean(per_example_loss) probabilities = tf.nn.softmax(logits, axis=-1) end_pred_ids = tf.argmax(probabilities,axis=-1) total_loss = start_loss + end_loss return (total_loss, logits, start_pred_ids, end_pred_ids) def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_tpu, use_one_hot_embeddings): """Returns `model_fn` closure for TPUEstimator.""" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument """The `model_fn` for TPUEstimator.""" tf.logging.info("*** Features ***") for name in sorted(features.keys()): tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape)) input_ids = features["input_ids"] input_mask = features["input_mask"] segment_ids = features["segment_ids"] start_labels_ids = features["start_labels_ids"] end_labels_ids = features["end_labels_ids"] is_training = (mode == tf.estimator.ModeKeys.TRAIN) # 使用参数构建模型,input_idx 就是输入的样本idx表示,label_ids 就是标签的idx表示 (total_loss, logits, start_pred_ids, end_pred_ids) = create_model( bert_config, is_training, input_ids, input_mask, segment_ids, start_labels_ids, end_labels_ids, num_labels, use_one_hot_embeddings) pred_ids = tf.stack([start_pred_ids,end_pred_ids],axis=1) print('-*'*30) print(pred_ids) tvars = tf.trainable_variables() scaffold_fn = None # 加载BERT模型 if init_checkpoint: (assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) if use_tpu: def tpu_scaffold(): tf.train.init_from_checkpoint(init_checkpoint, assignment_map) return tf.train.Scaffold() scaffold_fn = tpu_scaffold else: tf.train.init_from_checkpoint(init_checkpoint, assignment_map) ''' tf.logging.info("**** Trainable Variables ****") # 打印加载模型的参数 for var in tvars: init_string = "" if var.name in initialized_variable_names: init_string = ", *INIT_FROM_CKPT*" tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape, init_string) ''' output_spec = None if mode == tf.estimator.ModeKeys.TRAIN: train_op = optimization.create_optimizer( total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu) output_spec = tf.contrib.tpu.TPUEstimatorSpec( mode=mode, loss=total_loss, train_op=train_op, scaffold_fn=scaffold_fn) elif mode == tf.estimator.ModeKeys.EVAL: output_spec = tf.contrib.tpu.TPUEstimatorSpec( mode=mode, loss=total_loss, scaffold_fn=scaffold_fn) # else: output_spec = tf.contrib.tpu.TPUEstimatorSpec( mode=mode, predictions=pred_ids, scaffold_fn=scaffold_fn ) return output_spec return model_fn def labeltoid(label_list): label_map = {} # 1表示从1开始对label进行index化 for (i, label) in enumerate(label_list): label_map[label] = i # 保存label->index 的map with codecs.open(os.path.join(FLAGS.output_dir, 'label2id.pkl'), 'wb') as w: pickle.dump(label_map, w) return label_map def save_best_model(cur_ckpt_path,best_model_path): cmd1 = 'cp '+cur_ckpt_path+'.index '+best_model_path+'.index' cmd2 = 'cp '+cur_ckpt_path+'.meta '+best_model_path+'.meta' cmd3 = 'cp '+cur_ckpt_path+'.data-00000-of-00001 '+best_model_path+'.data-00000-of-00001' os.system(cmd1) os.system(cmd2) os.system(cmd3) def get_pred_metric(result, eval_input_ids, tokenizer): all_pred_ent = [] # print(len(result)) # print(len(eval_input_ids)) # print(result) for i in range(len(result)): # print(i) tmp_input_ids = eval_input_ids[i] start_preds = result[i][0] end_preds = result[i][1] start_inds = [] end_inds = [] # print(start_preds) # print(end_preds) for ind in range(len(start_preds)): if(start_preds[ind]==1): start_inds.append(ind) for ind in range(len(end_preds)): if(end_preds[ind]==1): end_inds.append(ind) if(len(start_inds)==0): all_pred_ent.append('') else: ans = [] def back(start_inds, end_inds): # global ans if(len(start_inds)==0 or len(end_inds)==0): return while(len(end_inds)>0 and end_inds[0]<start_inds[0]): end_inds = end_inds[1:] if(len(end_inds)>0): while(len(start_inds)>1 and (end_inds[0]-start_inds[1])>0 and ((end_inds[0]-start_inds[0])>(end_inds[0]-start_inds[1]))): start_inds = start_inds[1:] ans.append((start_inds[0],end_inds[0])) back(start_inds[1:],end_inds[1:]) back(start_inds, end_inds) if(len(ans)==0): all_pred_ent.append('') else: all_tmp_ent = [] for item in ans: s_ind = item[0] e_ind = item[1] # print(s_ind, e_ind) tmp_ent = ' '.join(tokenizer.convert_ids_to_tokens(tmp_input_ids[s_ind:e_ind+1])).replace(' ##','') end_str = '' e_ind += 1 while((e_ind<len(tmp_input_ids)-1) and ('##' in tokenizer.convert_ids_to_tokens([tmp_input_ids[e_ind]])[0])): end_str += tokenizer.convert_ids_to_tokens([tmp_input_ids[e_ind]])[0].replace('##','') e_ind += 1 tmp_ent += end_str all_tmp_ent.append(tmp_ent) # print(all_tmp_ent) all_pred_ent.append(all_tmp_ent) # print(' '.join(tokenizer.convert_ids_to_tokens(tmp_input_ids))) # print(all_tmp_ent) # print(all_pred_ent) # print(len(all_pred_ent)) ## save result in file with open(os.path.join(FLAGS.output_dir, 'dev_pred_answer.txt'), 'w') as f: for entities in all_pred_ent: if len(entities) == 0: f.write('\n') else: f.write('\t'.join(entities) + '\n') with open(os.path.join(FLAGS.data_dir, 'dev_answer.txt'), 'r') as f: gold = f.readlines() all_pred = 0 for item in all_pred_ent: if(item==''): continue else: for i in item: all_pred += 1 tp = 0 all_ann = 0 for i in range(len(gold)): if(len(gold[i].strip())!=0): # print(gold[i]) for k in gold[i].strip().split('\t'): all_ann += 1 for i in range(len(gold)): if(all_pred_ent[i]!=''): for j in all_pred_ent[i]: for e in gold[i].strip().split('\t'): if j.lower() == e.lower(): tp += 1 break p = tp/all_pred r = tp/all_ann f = (2*p*r)/(p+r) f1 = f print(tp,all_pred,all_ann) print(p,r,f) # print(all_pred_ent) return f1 def main(_): tf.logging.set_verbosity(tf.logging.INFO) processors = { "ner": NerProcessor, } tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case, FLAGS.init_checkpoint) if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict: raise ValueError( "At least one of `do_train`, `do_eval` or `do_predict' must be True.") bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length > bert_config.max_position_embeddings: raise ValueError( "Cannot use sequence length %d because the BERT model " "was only trained up to sequence length %d" % (FLAGS.max_seq_length, bert_config.max_position_embeddings)) ## del last training file if(FLAGS.do_train and FLAGS.clean): if os.path.exists(FLAGS.output_dir): def del_file(path): ls = os.listdir(path) for i in ls: c_path = os.path.join(path, i) if os.path.isdir(c_path): del_file(c_path) else: os.remove(c_path) try: del_file(FLAGS.output_dir) except Exception as e: print(e) print('pleace remove the files of output dir and data.conf') exit(-1) tf.gfile.MakeDirs(FLAGS.output_dir) task_name = FLAGS.task_name.lower() if task_name not in processors: raise ValueError("Task not found: %s" % (task_name)) processor = processors[task_name]() label_list = processor.get_labels() label_map = labeltoid(label_list) tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) print(tokenizer.convert_ids_to_tokens([101, 2424, 1996, 15316, 4668, 1997, 5423, 15660, 102 ])) # sys.exit(0) tpu_cluster_resolver = None if FLAGS.use_tpu and FLAGS.tpu_name: tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver( FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project) is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2 run_config = tf.contrib.tpu.RunConfig( cluster=tpu_cluster_resolver, master=FLAGS.master, model_dir=None, save_checkpoints_steps=FLAGS.save_checkpoints_steps, tpu_config=tf.contrib.tpu.TPUConfig( iterations_per_loop=FLAGS.iterations_per_loop, num_shards=FLAGS.num_tpu_cores, per_host_input_for_training=is_per_host)) train_examples = None num_train_steps = None num_warmup_steps = None if FLAGS.do_train: train_examples = processor.get_train_examples(FLAGS.data_dir) num_train_steps = int( len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs) num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion) model_fn = model_fn_builder( bert_config=bert_config, num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate, num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_tpu=FLAGS.use_tpu, use_one_hot_embeddings=FLAGS.use_tpu) # If TPU is not available, this will fall back to normal Estimator on CPU # or GPU. estimator = tf.contrib.tpu.TPUEstimator( use_tpu=FLAGS.use_tpu, model_fn=model_fn, config=run_config, model_dir=FLAGS.output_dir, train_batch_size=FLAGS.train_batch_size, eval_batch_size=FLAGS.eval_batch_size, predict_batch_size=FLAGS.predict_batch_size) if FLAGS.do_train: train_file = os.path.join(FLAGS.output_dir, "train.tf_record") file_based_convert_examples_to_features( train_examples, label_map, FLAGS.max_seq_length, tokenizer, train_file) tf.logging.info("***** Running training *****") tf.logging.info(" Num examples = %d", len(train_examples)) tf.logging.info(" Batch size = %d", FLAGS.train_batch_size) tf.logging.info(" Num steps = %d", num_train_steps) train_input_fn = file_based_input_fn_builder( input_file=train_file, seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True) if FLAGS.do_eval: eval_examples = processor.get_dev_examples(FLAGS.data_dir) eval_input_ids = [] for (ex_index, example) in enumerate(eval_examples): feature = convert_single_example(ex_index, example, label_map, FLAGS.max_seq_length, tokenizer) eval_input_ids.append(feature.input_ids) num_actual_eval_examples = len(eval_examples) eval_file = os.path.join(FLAGS.output_dir, "eval.tf_record") file_based_convert_examples_to_features( eval_examples, label_map, FLAGS.max_seq_length, tokenizer, eval_file) tf.logging.info("***** Running evaluation *****") tf.logging.info(" Num examples = %d (%d actual, %d padding)", len(eval_examples), num_actual_eval_examples, len(eval_examples) - num_actual_eval_examples) tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size) eval_input_fn = file_based_input_fn_builder( input_file=eval_file, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=False) ## Get id2label with codecs.open(os.path.join(FLAGS.output_dir, 'label2id.pkl'), 'rb') as rf: label2id = pickle.load(rf) id2label = {value: key for key, value in label2id.items()} best_result = 0 all_results = [] if FLAGS.do_train: for i in range(int(FLAGS.num_train_epochs)): print('**'*40) print('Train {} epoch'.format(i+1)) estimator.train(input_fn=train_input_fn) ## Do Dev # result = estimator.predict(input_fn=eval_input_fn) # result = list(result) # for i in range(len(result)): # tmp_input_ids = eval_input_ids[i] # start_preds = result[i][0] # end_preds = result[i][1] # start_ind = 0 # end_ind = 0 # for ind in range(len(start_preds)): # if(start_preds[ind]==1): # start_ind = ind # break # for ind in range(len(end_preds)): # if(end_preds[ind]==1): # end_ind = ind # break # pred_ids = tmp_input_ids[start_ind:end_ind+1] # print('-*-'*30) # print(pred_ids) # print(tokenizer.convert_ids_to_tokens(pred_ids)) # pred = np.array(pred) # output_dev_file = os.path.join(FLAGS.output_dir, "label_dev.txt") # tmp_result = report_metric(eval_examples, pred, output_dev_file, id2label, probs) # print('Tmp result (macro F1) : ',tmp_result) # all_results.append(tmp_result) # if(tmp_result>best_result): # print('**'*40) # print('Found better model, saved!') # best_result = tmp_result # cur_ckpt_path = estimator.latest_checkpoint() # best_model_path = '/'.join(cur_ckpt_path.split('/')[:-1]+['model.ckpt-best']) # save_best_model(cur_ckpt_path,best_model_path) # print('**'*40) # print('Training completed!') # print('all_results: ',all_results) # print('Best result: ',np.max(all_results)) # print('Avg result: ',np.mean(all_results)) # import sys # sys.exit(0) if FLAGS.do_predict: print('***********************Running Prediction************************') # print('Use model which perform best on dev data') cur_ckpt_path = estimator.latest_checkpoint() print('Use model which restore from last ckpt') estimator = tf.contrib.tpu.TPUEstimator( use_tpu=FLAGS.use_tpu, model_fn=model_fn, config=run_config, model_dir=None, train_batch_size=FLAGS.train_batch_size, eval_batch_size=FLAGS.eval_batch_size, predict_batch_size=FLAGS.predict_batch_size, warm_start_from=cur_ckpt_path) predict_examples = processor.get_test_examples(FLAGS.data_dir) num_actual_predict_examples = len(predict_examples) predict_file = os.path.join(FLAGS.output_dir, "predict.tf_record") file_based_convert_examples_to_features(predict_examples, label_map, FLAGS.max_seq_length, tokenizer, predict_file) tf.logging.info("***** Running prediction*****") tf.logging.info(" Num examples = %d (%d actual, %d padding)", len(predict_examples), num_actual_predict_examples, len(predict_examples) - num_actual_predict_examples) tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size) predict_input_fn = file_based_input_fn_builder( input_file=predict_file, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=False) result = estimator.predict(input_fn=predict_input_fn) result = list(result) print(get_pred_metric(result, eval_input_ids, tokenizer)) if __name__ == "__main__": flags.mark_flag_as_required("data_dir") flags.mark_flag_as_required("task_name") flags.mark_flag_as_required("vocab_file") flags.mark_flag_as_required("bert_config_file") flags.mark_flag_as_required("output_dir") tf.app.run()
(** * Functoriality of composition of natural transformations *) Require Import Category.Core Functor.Core NaturalTransformation.Core. Require Import FunctorCategory.Core Functor.Composition.Core NaturalTransformation.Composition.Core NaturalTransformation.Composition.Laws. Set Universe Polymorphism. Set Implicit Arguments. Generalizable All Variables. Set Asymmetric Patterns. Local Open Scope functor_scope. Section functorial_composition. Context `{Funext}. Variables C D E : PreCategory. Local Open Scope natural_transformation_scope. (** ** whiskering on the left is a functor *) Definition whiskerL_functor (F : (D -> E)%category) : ((C -> D) -> (C -> E))%category := Build_Functor (C -> D) (C -> E) (fun G => F o G)%functor (fun _ _ T => F oL T) (fun _ _ _ _ _ => composition_of_whisker_l _ _ _) (fun _ => whisker_l_right_identity _ _). (** ** whiskering on the right is a functor *) Definition whiskerR_functor (G : (C -> D)%category) : ((D -> E) -> (C -> E))%category := Build_Functor (D -> E) (C -> E) (fun F => F o G)%functor (fun _ _ T => T oR G) (fun _ _ _ _ _ => composition_of_whisker_r _ _ _) (fun _ => whisker_r_left_identity _ _). End functorial_composition.
using Test using CollectiveSpins.effective_interaction using CollectiveSpins.effective_interaction_simple @testset "effective-interaction" begin a = 0.3 b = 0.7 c = 0.4 eps = 1e-12 Ωeff0, Γeff0 = effective_interaction_simple.triangle_orthogonal(a) Ωeff1, Γeff1 = effective_interaction.triangle_orthogonal(a) @test abs(Ωeff0-Ωeff1)<eps @test abs(Γeff0-Γeff1)<eps Ωeff0, Γeff0 = effective_interaction_simple.square_orthogonal(a) Ωeff1, Γeff1 = effective_interaction.square_orthogonal(a) @test abs(Ωeff0-Ωeff1)<eps @test abs(Γeff0-Γeff1)<eps Ωeff0, Γeff0 = effective_interaction_simple.rectangle_orthogonal(a, b) Ωeff1, Γeff1 = effective_interaction.rectangle_orthogonal(a, b) @test abs(Ωeff0-Ωeff1)<eps @test abs(Γeff0-Γeff1)<eps Ωeff0, Γeff0 = effective_interaction_simple.cube_orthogonal(a) Ωeff1, Γeff1 = effective_interaction.cube_orthogonal(a) @test abs(Ωeff0-Ωeff1)<eps @test abs(Γeff0-Γeff1)<eps Ωeff0, Γeff0 = effective_interaction_simple.box_orthogonal(a, b, c) Ωeff1, Γeff1 = effective_interaction.box_orthogonal(a, b, c) @test abs(Ωeff0-Ωeff1)<eps @test abs(Γeff0-Γeff1)<eps Ωeff0, Γeff0 = effective_interaction_simple.chain(a, 0.21, 5) Ωeff1, Γeff1 = effective_interaction.chain(a, 0.21, 5) @test abs(Ωeff0-Ωeff1)<eps @test abs(Γeff0-Γeff1)<eps Ωeff0, Γeff0 = effective_interaction_simple.chain_orthogonal(a, 5) Ωeff1, Γeff1 = effective_interaction.chain_orthogonal(a, 5) @test abs(Ωeff0-Ωeff1)<eps @test abs(Γeff0-Γeff1)<eps Ωeff0, Γeff0 = effective_interaction_simple.squarelattice_orthogonal(a, 5) Ωeff1, Γeff1 = effective_interaction.squarelattice_orthogonal(a, 5) @test abs(Ωeff0-Ωeff1)<eps @test abs(Γeff0-Γeff1)<eps Ωeff0, Γeff0 = effective_interaction_simple.hexagonallattice_orthogonal(a, 5) Ωeff1, Γeff1 = effective_interaction.hexagonallattice_orthogonal(a, 5) @test abs(Ωeff0-Ωeff1)<eps @test abs(Γeff0-Γeff1)<eps Ωeff0, Γeff0 = effective_interaction_simple.cubiclattice_orthogonal(a, 3) Ωeff1, Γeff1 = effective_interaction.cubiclattice_orthogonal(a, 3) @test abs(Ωeff0-Ωeff1)<eps @test abs(Γeff0-Γeff1)<eps Ωeff0, Γeff0 = effective_interaction_simple.tetragonallattice_orthogonal(a, 1.2*a, 3) Ωeff1, Γeff1 = effective_interaction.tetragonallattice_orthogonal(a, 1.2*a, 3) @test abs(Ωeff0-Ωeff1)<eps @test abs(Γeff0-Γeff1)<eps Ωeff0, Γeff0 = effective_interaction_simple.hexagonallattice3d_orthogonal(a, b, 4) Ωeff1, Γeff1 = effective_interaction.hexagonallattice3d_orthogonal(a, b, 4) @test abs(Ωeff0-Ωeff1)<eps @test abs(Γeff0-Γeff1)<eps end # testset
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.analytic.basic /-! # Linear functions are analytic In this file we prove that a `continuous_linear_map` defines an analytic function with the formal power series `f x = f a + f (x - a)`. -/ variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] open_locale topological_space classical big_operators nnreal ennreal open set filter asymptotics noncomputable theory namespace continuous_linear_map /-- Formal power series of a continuous linear map `f : E →L[𝕜] F` at `x : E`: `f y = f x + f (y - x)`. -/ @[simp] def fpower_series (f : E →L[𝕜] F) (x : E) : formal_multilinear_series 𝕜 E F | 0 := continuous_multilinear_map.curry0 𝕜 _ (f x) | 1 := (continuous_multilinear_curry_fin1 𝕜 E F).symm f | _ := 0 @[simp] lemma fpower_series_apply_add_two (f : E →L[𝕜] F) (x : E) (n : ℕ) : f.fpower_series x (n + 2) = 0 := rfl @[simp] lemma fpower_series_radius (f : E →L[𝕜] F) (x : E) : (f.fpower_series x).radius = ∞ := (f.fpower_series x).radius_eq_top_of_forall_image_add_eq_zero 2 $ λ n, rfl protected theorem has_fpower_series_on_ball (f : E →L[𝕜] F) (x : E) : has_fpower_series_on_ball f (f.fpower_series x) x ∞ := { r_le := by simp, r_pos := ennreal.coe_lt_top, has_sum := λ y _, (has_sum_nat_add_iff' 2).1 $ by simp [finset.sum_range_succ, ← sub_sub, has_sum_zero] } protected theorem has_fpower_series_at (f : E →L[𝕜] F) (x : E) : has_fpower_series_at f (f.fpower_series x) x := ⟨∞, f.has_fpower_series_on_ball x⟩ protected theorem analytic_at (f : E →L[𝕜] F) (x : E) : analytic_at 𝕜 f x := (f.has_fpower_series_at x).analytic_at /-- Reinterpret a bilinear map `f : E →L[𝕜] F →L[𝕜] G` as a multilinear map `(E × F) [×2]→L[𝕜] G`. This multilinear map is the second term in the formal multilinear series expansion of `uncurry f`. It is given by `f.uncurry_bilinear ![(x, y), (x', y')] = f x y'`. -/ def uncurry_bilinear (f : E →L[𝕜] F →L[𝕜] G) : (E × F) [×2]→L[𝕜] G := @continuous_linear_map.uncurry_left 𝕜 1 (λ _, E × F) G _ _ _ _ _ $ (↑(continuous_multilinear_curry_fin1 𝕜 (E × F) G).symm : (E × F →L[𝕜] G) →L[𝕜] _).comp $ f.bilinear_comp (fst _ _ _) (snd _ _ _) @[simp] lemma uncurry_bilinear_apply (f : E →L[𝕜] F →L[𝕜] G) (m : fin 2 → E × F) : f.uncurry_bilinear m = f (m 0).1 (m 1).2 := rfl /-- Formal multilinear series expansion of a bilinear function `f : E →L[𝕜] F →L[𝕜] G`. -/ @[simp] def fpower_series_bilinear (f : E →L[𝕜] F →L[𝕜] G) (x : E × F) : formal_multilinear_series 𝕜 (E × F) G | 0 := continuous_multilinear_map.curry0 𝕜 _ (f x.1 x.2) | 1 := (continuous_multilinear_curry_fin1 𝕜 (E × F) G).symm (f.deriv₂ x) | 2 := f.uncurry_bilinear | _ := 0 @[simp] lemma fpower_series_bilinear_radius (f : E →L[𝕜] F →L[𝕜] G) (x : E × F) : (f.fpower_series_bilinear x).radius = ∞ := (f.fpower_series_bilinear x).radius_eq_top_of_forall_image_add_eq_zero 3 $ λ n, rfl protected protected theorem has_fpower_series_at_bilinear (f : E →L[𝕜] F →L[𝕜] G) (x : E × F) : has_fpower_series_at (λ x : E × F, f x.1 x.2) (f.fpower_series_bilinear x) x := ⟨∞, f.has_fpower_series_on_ball_bilinear x⟩ protected theorem analytic_at_bilinear (f : E →L[𝕜] F →L[𝕜] G) (x : E × F) : analytic_at 𝕜 (λ x : E × F, f x.1 x.2) x := (f.has_fpower_series_at_bilinear x).analytic_at end continuous_linear_map
############################################################################# ## #W utils.gi automgrp package Yevgen Muntyan ## Dmytro Savchuk ## #Y Copyright (C) 2003 - 2018 Yevgen Muntyan, Dmytro Savchuk ## ############################################################################# ## ## AG_PermFromTransformation( <tr> ) ## InstallGlobalFunction(AG_PermFromTransformation, function(tr) if IsPerm(tr) then return tr; elif tr^-1=fail then Error(tr, " is not invertible"); else return AsPermutation(tr); fi; end); ############################################################################# ## ## AG_PrintTransformation( <tr> ) ## InstallGlobalFunction(AG_PrintTransformation, function(tr) local list, i; if IsPerm(tr) then Print(tr); else list := ImageListOfTransformation(tr); Print("["); for i in [1..Length(list)] do if i <> 1 then Print(","); fi; Print(list[i]); od; Print("]"); fi; end); ############################################################################# ## ## AG_TransformationString( <tr> ) ## InstallGlobalFunction(AG_TransformationString, function(tr) local list, i, str; if IsPerm(tr) then return String(tr); else list := ImageListOfTransformation(tr); str:="["; for i in [1..Length(list)] do if i <> 1 then Append(str, ","); fi; Append(str, String(list[i])); od; Append(str, "]"); fi; return str; end); InstallGlobalFunction(AG_TrCmp, function(p1, p2, d) local l1, l2, getlist; if IsIdenticalObj(p1, p2) then return 0; fi; getlist := function(p) local l; if IsTransformation(p) then return ImageListOfTransformation(p); else return Permuted([1..d],p); fi; end; l1 := getlist(p1); l2 := getlist(p2); if l1 = l2 then return 0; elif l1 < l2 then return -1; else return 1; fi; end); ############################################################################# ## ## AG_CalculateWord(<word>, <list>) ## # XXX do not use this InstallMethod(AG_CalculateWord, [IsAssocWord, IsList], function(w, dom) local result, i; result := One(dom[1]); for i in [1..NumberSyllables(w)] do result := result * dom[GeneratorSyllable(w, i)]^ExponentSyllable(w, i); od; return result; end); ############################################################################# ## ## AG_CalculateWords(<words_list>, <list>) ## InstallMethod(AG_CalculateWords, [IsList, IsList], function(words, domain) local result, i; result := []; for i in [1..Length(words)] do result[i] := AG_CalculateWord(words[i], domain); od; return result; end); ############################################################################### ## ## AG_ReducedSphericalIndex(<ind>) ## InstallGlobalFunction("AG_ReducedSphericalIndex", function(M) local beg, per, beg_len, per_len, i; if IsEmpty(M.period) then return StructuralCopy(M); fi; beg := StructuralCopy(M.start); per := StructuralCopy(M.period); beg_len := Length(beg); per_len := Length(per); for i in Difference(DivisorsInt(per_len), [per_len]) do if per = Concatenation(List([1..per_len/i], j -> per{[1..i]})) then per := per{[1..i]}; per_len := i; break; fi; od; while Length(beg) <> 0 and beg[beg_len] = per[per_len] do per := Concatenation([per[per_len]], per{[1..per_len-1]}); beg := beg{[1..beg_len-1]}; beg_len := beg_len - 1; od; return rec(start := beg, period := per); end); ############################################################################### ## ## AG_IsEqualSphericalIndex(<ind1>, <ind2>) ## InstallGlobalFunction("AG_IsEqualSphericalIndex", function(M1, M2) return AG_ReducedSphericalIndex(M1) = AG_ReducedSphericalIndex(M2); end); ############################################################################### ## ## AG_TopDegreeInSphericalIndex(<ind>) ## InstallGlobalFunction("AG_TopDegreeInSphericalIndex", function(M) if not IsEmpty(M.start) then return M.start[1]; else return M.period[1]; fi; end); ############################################################################### ## ## AG_DegreeOfLevelInSphericalIndex(<ind>) ## InstallGlobalFunction("AG_DegreeOfLevelInSphericalIndex", function(M, k) local i; if Length(M.start) >= k then return M.start[k]; fi; i := RemInt(k-Length(M.start), Length(M.period)); if i = 0 then i := Length(M.period); fi; return M.period[i]; end); ############################################################################### ## ## AG_TreeLevelTuples(<ind>) ## AG_TreeLevelTuples(<ind>, <n>) ## AG_TreeLevelTuples(<start>, <period>, <n>) ## InstallGlobalFunction("AG_TreeLevelTuples", function(arg) local n, m, args, ind, start, period; if Length(arg) = 1 and IsList(arg[1]) then ind := arg[1]; n := Length(ind); args := List([1..n], i -> [1..ind[i]]); Add(args, function(arg) return arg; end); return CallFuncList(ListX, args); elif Length(arg) = 2 and IsRecord(arg[1]) and IsPosInt(arg[2]) then return AG_TreeLevelTuples(arg[1].start, arg[1].period, arg[2]); elif Length(arg) = 3 and IsList(arg[1]) and IsList(arg[2]) and IsPosInt(arg[3]) then start := arg[1]; period := arg[2]; n := arg[3]; m := n; ind := []; if Length(start) <> 0 then if n <= Length(start) then ind := start{[1..n]}; m := 0; else ind := start; m := n - Length(start); fi; fi; if m > 0 then # TODO: why Append doesn't work??? # Append(ind, Concatenation(List([1..Int(m/Length(period))], i -> period))); # Append(ind, period{[1..m-Int(m/Length(period))]}); ind := Concatenation(ind, Concatenation(List([1..Int(m/Length(period))], i -> period))); ind := Concatenation(ind, period{[1..m-Int(m/Length(period))]}); fi; args := List([1..n], i -> [1..ind[i]]); Add(args, function(arg) return arg; end); return CallFuncList(ListX, args); else Error("in AG_TreeLevelTuples\n", " usage: AG_TreeLevelTuples([n_1, n_2, ..., n_k])\n", " AG_TreeLevelTuples(<spher_ind>, k)\n", " AG_TreeLevelTuples(start, period, k)\n"); fi; end); ############################################################################# ## ## AG_AbelImageX ## AG_AbelImageSpherTrans ## InstallGlobalFunction(AG_AbelImageX, function() if not IsReadOnlyGlobal("AG_AbelImageXvar") then AG_AbelImageXvar := Indeterminate(GF(2),"x"); MakeReadOnlyGlobal("AG_AbelImageXvar"); fi; return AG_AbelImageXvar; end); InstallGlobalFunction(AG_AbelImageSpherTrans, function() return One(AG_AbelImageX())/ (One(AG_AbelImageX()) + AG_AbelImageX()); end); ############################################################################# ## ## AG_AbelImageAutomatonInList(<list>) ## InstallGlobalFunction(AG_AbelImageAutomatonInList, function(list) local zero, one, x, m, mk, e, n, d, s, i, k, det, detk, result; n := Length(list); d := Length(list[1]) - 1; x := AG_AbelImageX(); m := IdentityMat(n, x); e := []; zero := 0*x; one := x^0; for s in [1..n] do for i in [1..d] do # if the family is defined by wreath recursion if IsList(list[s][i]) then for k in [1..Length(list[s][i])] do m[s][AbsInt(list[s][i][k])] := m[s][AbsInt(list[s][i][k])] + x; od; # if the family is defined by automaton else m[s][list[s][i]] := m[s][list[s][i]] + x; fi; od; if SignPerm(list[s][d+1]) = 1 then e[s] := zero; else e[s] := one; fi; od; result := []; det := Determinant(m); for s in [1..n] do mk := StructuralCopy(m); for i in [1..n] do mk[i][s] := e[i]; od; detk := Determinant(mk); result[s] := detk / det; od; return result; end); #E
#' Standardized plotting function that can be passed to the plotfunction arguments in the \code{\link{createTopicBrowser}} function. #' #' One of the standardized plotting function used in the Topicbrowser package to manage how topics and additional information are visualized. #' This specific function plots a wordcloud below a graph showing the number of words assigned to the topic per time period #' #' @param info The output of the \code{\link{clusterinfo}} function #' @param topic_nr the index number of a topic #' @param date_interval if not NULL, a string indicating what interval to use for plotting the time/date graph. Can be 'year', 'month', 'week' and 'day'. If NULL, the date_interval will be chosen based on the number of days in the analysis. #' @param date_label a string indicating what the date object is in the meta data. #' @return nothing, only plots #' @export plot_wordcloud_time <- function(clusterinfo, topic_nr, ...) { par(mar = c(4.5, 3, 2, 1), cex.axis = 1.7) layout(matrix(c(1, 1, 2, 2), 2, 2, byrow = TRUE), widths = c(2.5, 1.5), heights = c(1, 2)) plot_time(clusterinfo=clusterinfo, topic_nr=topic_nr, ...) par(mar=c(0,0,0,0)) plot_wordcloud(clusterinfo=clusterinfo, topic_nr=topic_nr) par(mfrow = c(1, 1), mar=c(5,4,4,2) + 0.1) # reset to default } plot_topicdistribution <- function(clusterinfo, topic_nr, ...){ topic_pct_per_document = clusterinfo$topics_per_doc[topic_nr,] / colSums(clusterinfo$topics_per_doc) par(mar=c(5,6,1,4)) # Set the most suitable margins hist(topic_pct_per_document, main='', xlab='% of document assignments', ylab='Number of documents') par(mar=c(5,4,4,2) + 0.1) # reset to default } ## dependency based plotfunction defaults #' Standardized plotting function that can be passed to the plotfunction arguments in the \code{\link{createTopicBrowser}} function. #' #' One of the standardized plotting function used in the Topicbrowser package to manage how topics and additional information are visualized. #' This specific function plots a wordcloud below a graph showing the number of words assigned to the topic per time period #' #' @param info The output of the \code{\link{clusterinfo}} function #' @param topic_nr the index number of a topic #' @return nothing, only plots #' @export plot_semnet <- function(clusterinfo, topic_nr, backbone_alpha=0.01, nwords=100, wordsimilarity.measure='conprob', clustering_directed=F, ...) { require(semnet) dtm = createTopicDtm(clusterinfo$topics_per_term, clusterinfo$wordassignments, topic_nr, nwords) g = coOccurenceNetwork(dtm, measure=wordsimilarity.measure) g = getBackboneNetwork(g, alpha=backbone_alpha) if(vcount(g) > 0 & ecount(g) > 0){ V(g)$cluster = edge.betweenness.community(g, directed=clustering_directed)$membership g = setNetworkAttributes(g, V(g)$freq, V(g)$cluster) V(g)$label.cex = V(g)$label.cex * 1.5 par(mar=c(0,0,0,0)) plot(g) par(mar=c(5,4,4,2) + 0.1) # reset to default} } else plot(1, type="n", axes=F, xlab="", ylab="") } createTopicDtm <- function(topics_per_term, wordassignments, topic_nr, nwords){ wordfreq = topics_per_term[topic_nr,] wordfreq = wordfreq[order(-wordfreq)][1:nwords] words = names(wordfreq) wa = wordassignments[wordassignments$topic == topic_nr,] wa = wa[wa$term %in% words,] docs = unique(wa$aid) terms = unique(wa$term) dtm = spMatrix(nrow=length(docs), ncol=length(terms), i = match(wa$aid, docs), j = match(wa$term, terms), rep(1, nrow(wa))) colnames(dtm) = terms dtm } ### Basic plotting functions selectTimeInterval <- function(time_var){ ndays = abs(as.numeric(difftime(min(time_var), max(time_var), units='days'))) if(ndays < 20*30) return("month") if(ndays < 20*7) return('week') if(ndays < 20) return('day') "year" } prepare.time.var <- function(time_var, date_interval){ if(class(time_var) == 'Date'){ if(date_interval == 'day') time_var = as.Date(format(time_var, '%Y-%m-%d')) if(date_interval == 'month') time_var = as.Date(paste(format(time_var, '%Y-%m'),'-01',sep='')) if(date_interval == 'week') time_var = as.Date(paste(format(time_var, '%Y-%W'),1), '%Y-%W %u') if(date_interval == 'year') time_var = as.Date(paste(format(time_var, '%Y'),'-01-01',sep='')) } time_var } #' Add empty values for pretty plotting #' #' When plotting a timeline, gaps in date_intervals are ignored. For the attention for topics gaps should be considered as having value 0. #' #' @param d A data.frame with the columns 'time' (Date) and 'value' (numeric) #' @param date_interval The date_interval is required to know what the gaps are #' @return A data.frame with the columns 'time' (Date) and 'value' (numeric) #' @export fill.time.gaps <- function(d, time_interval){ if(class(d$time) == 'numeric') time_sequence = min(d$time):max(d$time) if(class(d$time) == 'Date') time_sequence = seq.Date(from=min(d$time), to=max(d$time), by=time_interval) emptytime = time_sequence[!time_sequence %in% d$time] if(length(emptytime) > 0) d = rbind(d, data.frame(time=emptytime, value=0)) d[order(d$time),] } prepare.plot.values <- function(document_topic_matrix, break_var, topic_nr, pct=F, value='total', filter=NULL){ hits = document_topic_matrix[topic_nr,] d = aggregate(hits, by=list(break_var=break_var), FUN='sum') if(value == 'relative'){ total_hits = colSums(document_topic_matrix) totals = aggregate(total_hits, by=list(break_var=break_var), FUN='sum') d$x = d$x / totals$x } if(pct == T) d$x = d$x / sum(d$x) d } #' Standardized plotting function that can be passed to the plotfunction arguments in the \code{\link{createTopicBrowser}} function. #' #' One of the standardized plotting function used in the Topicbrowser package to manage how topics and additional information are visualized. #' This specific function plots a graph showing the number of words assigned to the topic per time period #' #' @param info The output of the \code{\link{clusterinfo}} function #' @param topic_nr the index number of a topic #' @param time_interval a string indicating what interval to use for plotting the time/date graph. Can be 'year', 'month', 'week' and 'day'. If 'auto', the date_interval will be chosen based on the number of days in the analysis. #' @param time_var either a vector containing the date for each document, or the column name of the date variable in the metadata stored in the clusterinfo object #' @return nothing, only plots #' @export plot_time <- function(lda_model=NULL, document_topic_matrix=NULL, clusterinfo=NULL, topic_nr, time_var='date', time_interval='auto', pct=F, value='total', ...) { if (is.null(document_topic_matrix)) { if (is.null(clusterinfo)) { if (is.null(lda_model)) stop("Either lda_model, document_topic_matrix, or clusterinfo needs to be specified") clusterinfo = clusterinfo(lda_model) } document_topic_matrix = clusterinfo$topics_per_doc } if (is.character(time_var) & length(time_var) == 1) { if (is.null(clusterinfo)) stop("Time var is a column name, but clusterinfo not specified") if (is.null(clusterinfo$meta)) stop("Time var is a column name, but clusterinfo metadata is not specified") time_var = clusterinfo$meta[,time_var] } if (time_interval == 'auto') time_interval = selectTimeInterval(time_var) par(mar=c(3,3,3,1)) time_var = prepare.time.var(time_var, time_interval) d = prepare.plot.values(document_topic_matrix, break_var=time_var, topic_nr=topic_nr, pct=pct, value=value) colnames(d) = c('time','value') d = fill.time.gaps(d, time_interval) plot(d$time, d$value, type='l', xlab='', main='', ylab='', xlim=c(min(d$time), max(d$time)), ylim=c(0, max(d$value)), bty='L', lwd=5, col='darkgrey') par(mar=c(3,3,3,3)) invisible(d) } #' Function to plot a word cloud for a given topic #' #' Can be passed to the plotfunction arguments in the \code{\link{createTopicBrowser}} function. #' #' One of the standardized plotting function used in the Topicbrowser package to manage how topics and additional information are visualized. #' This specific function plots a wordcloud #' #' One of lda_model, topic_term_matrix, or topicinfo needs to be specified #' #' @param lda_model An lda model fitted using topicmodels::LDA #' @param topic_term_matrix a matrix of topics per term #' @param clusterinfo The output of the \code{\link{clusterinfo}} function #' @param topic_nr the index number of a topic #' @param wordsize_scale a scale for the word sizes #' @param relative_to_term_total make word sizes relative #' @return nothing, only plots #' @export plot_wordcloud <- function(lda_model=NULL, topic_term_matrix=NULL, clusterinfo=NULL, topic_nr, wordsize_scale=0.75, relative_to_term_total=F, ...){ if (is.null(topic_term_matrix)) { if (is.null(clusterinfo)) { if (is.null(lda_model)) stop("Either lda_model, topic_term_matrix, or topicinfo needs to be specified") clusterinfo = clusterinfo(lda_model) } topic_term_matrix = clusterinfo$topics_per_term } x = topic_term_matrix[topic_nr,] if(relative_to_term_total==T) { x = x / colSums(topic_term_matrix) x = x / sum(x) } x = sort(x, decreasing=T)[1:50] x = x[!is.na(x)] names = sub("/.*", "", names(x)) freqs = x^wordsize_scale pal <- brewer.pal(6,"YlGnBu") par(mar=c(0,0,0,0)) wordcloud(names, freqs, scale=c(3,.5), min.freq=1, max.words=50, random.order=FALSE, rot.per=.15, colors=pal) par(mar=c(5,4,4,2) + 0.1) # reset to default } plot_category <- function(document_sums, topic_nr, category_var, pct=T, value='relative', ...){ p = par(mar=c(3,3,3,1)) d = prepare.topics.plot.values(document_sums, break_var=as.character(category_var), topic_nr=topic_nr, pct=pct, value=value) colnames(d) = c('category','value') barplot(as.matrix(t(d[,c('value')])), main='', beside=TRUE,horiz=FALSE, density=NA, col='darkgrey', xlab='', ylab="", axes=T, names.arg=d$category, cex.names=1, cex.axis=0.7, adj=1, las=2) par(mar=c(5,4,4,2) + 0.1) # reset to default } plot_topics_network <- function(clusterinfo) { docs = clusterinfo$topics_per_doc t = terms(m, 2) labels = paste(t[1,], 1:nrow(docs), t[2,], sep='\n') g = semnet::adjacencyGraph(t(docs)) g = getBackboneNetwork(g, alpha=0.1, delete.isolates = F) E(g)$width = E(g)$weight*10 V(g)$size = rescale(V(g)$occurence, to = c(5,10)) V(g)$label.cex = rescale(V(g)$occurence, to = c(0.5,1)) V(g)$label = labels paste(1:nrow(docs), apply(terms(m, 3), 2, paste, collapse='\n'), sep=': ') V(g)$cluster = edge.betweenness.community(g, directed = F)$membership g = semnet:::setVertexColors(g, 'cluster') plot(g) }
If $0 \leq x \leq 1$, then the sequence $x^n$ is bounded.
\name{anno_enriched} \alias{anno_enriched} \title{ Annotation Function to Show the Enrichment } \description{ Annotation Function to Show the Enrichment } \usage{ anno_enriched(gp = gpar(col = "red"), pos_line = NULL, pos_line_gp = NULL, ylim = NULL, value = c("mean", "sum", "abs_mean", "abs_sum"), yaxis = TRUE, axis = yaxis, axis_param = list(side = "right"), show_error = FALSE, height = unit(2, "cm"), ...) } \arguments{ \item{gp}{Graphic parameters. There are two non-standard parameters: \code{neg_col} and \code{pos_col}. If these two parameters are defined, the positive signals and negatie signals are visualized separatedly. The graphic parameters can be set as vectors when the heatmap or heatmap list is split into several row clusters.} \item{pos_line}{Whether draw vertical lines which represent positions of \code{target}?} \item{pos_line_gp}{Graphic parameters for the position lines.} \item{ylim}{Ranges on y-axis. By default it is inferred from the data.} \item{value}{The method to summarize signals from columns of the normalized matrix.} \item{yaxis}{Deprecated, use \code{axis} instead.} \item{axis}{Whether show axis?} \item{axis_param}{parameters for controlling axis. See \code{\link[ComplexHeatmap]{default_axis_param}} for all possible settings and default parameters.} \item{show_error}{Whether show error regions which are one standard error to the mean value? Color of error area is same as the corresponding lines with 75 percent transparency.} \item{height}{Height of the annotation.} \item{...}{Other arguments.} } \details{ This annotation functions shows mean values (or depends on the method set in \code{value} argument) of columns in the normalized matrix which summarises the enrichment of the signals to the targets. If rows are splitted, the enriched lines are calculated for each row cluster and there will also be multiple lines in this annotation viewport. It should only be placed as column annotation of the enriched heatmap. } \value{ A column annotation function which should be set to \code{top_annotation} argument in \code{\link{EnrichedHeatmap}}. } \author{ Zuguang Gu <[email protected]> } \examples{ load(system.file("extdata", "chr21_test_data.RData", package = "EnrichedHeatmap")) tss = promoters(genes, upstream = 0, downstream = 1) mat1 = normalizeToMatrix(H3K4me3, tss, value_column = "coverage", extend = 5000, mean_mode = "w0", w = 50, keep = c(0, 0.99)) EnrichedHeatmap(mat1, col = c("white", "red"), name = "H3K4me3", top_annotation = HeatmapAnnotation(lines = anno_enriched(gp = gpar(col = 2:4))), km = 3, row_title_rot = 0) }
From Babel Require Import FQP.premises. From Babel Require Import TerminalDogma.Sequence. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Require ComplexTheories. Require VectorSpaceTheories. Module HilbertSpaceTheory. Export ComplexTheories.ComplexTheory. Export VectorSpaceTheories.VectorSpaceTheory. (** Definition 2.1.2 (complex inner product space) *) Record CIP_space := build_ipspace { Vs :> vspace ℂ_field; Vsdot : Vs -> Vs -> ℂ; (** dot non-negative *) Vsdot_realc : forall u : Vs, realc (Vsdot u u); Vsdot_pos_def : forall u : Vs, Vsdot_realc u >= 0; Vsdot_pos_0 : forall u : Vs, ((Vsdot_realc u) = 0%R :> R) <-> u = 𝟎; (** dot conjugate *) Vsdot_conj : forall u v : Vs, (Vsdot u v)^* = Vsdot v u; (** dot linearity *) Vsdot_linear : forall (c1 c2 : ℂ) (u v1 v2 : Vs), Vsdot u (Vadd (@Vscal _ Vs c1 v1) (@Vscal _ Vs c2 v2)) = (c1 * (Vsdot u v1) + c2 * (Vsdot u v2))%ℂ; }. (** Note : The level for a ∗ b is 30, and we want a ∗ u ∙ v to to mean a ∗ (u ∙ v), so level 35 is appropriate. *) Notation " u '∙' v " := (Vsdot u v) (at level 35) : Vspace_scope. (** Dirac Notation *) Notation " <[ u | v ]> " := (Vsdot u v) : Vspace_scope. (** orthogonal *) Definition orthogonal (CIPs : CIP_space) (u v : CIPs) := <[ u | v ]> = 0. Notation " u '⊥' v " := (orthogonal u v) (at level 20) : Vspace_scope. (** [] *) Definition f_norm (CIPs : CIP_space) (u : CIPs) := √ (Vsdot_realc u). Notation " |[ u ]| " := (f_norm u) : Vspace_scope. Definition unit_vector (CIPs : CIP_space) (u : CIPs) : Prop := |[ u ]| = 1%R. (** Definition 2.1.3 *) Record v_Cauchy_seq (H : CIP_space) := mk_v_Cauchy_seq { f_v_seq :> infSeq H; seq_conv_proof : forall e : { r : R | r > 0 }, exists N : nat, forall m n : { n : nat | (n > N)%nat }, |[ (f_v_seq (proj1_sig m)) + (- (f_v_seq (proj1_sig n))) ]| < proj1_sig e; }. Definition seq_lim (H : CIP_space) (f : infSeq H) (psi : H) := forall e : { r : R | r > 0 }, exists N : nat, forall n : { n : nat | (n > N)%nat }, |[ (f (proj1_sig n)) + (- psi) ]| < proj1_sig e. (** Definition 2.1.4 *) Record Hilbert_space := build_Hspace { H :> CIP_space; H_complete : forall s : v_Cauchy_seq H, exists psi, seq_lim s psi; }. (** Definition 2.1.5 *) Definition is_ortho_basis (H : Hilbert_space) (s : Seque H) : Prop := forall i j : index s, s i ⊥ s j. Record ortho_basis (H : Hilbert_space) := build_ortho_basis { ortho_basis_obj :> Seque H; ortho_basis_proof : is_ortho_basis ortho_basis_obj; }. Definition in_linear_comb (H : Hilbert_space) (s : Seque H) (psi : H) := exists End HilbertSpaceTheory.
If $x$ is an integer, then $x^n$ is an $n$th power.