Datasets:
AI4M
/

text
stringlengths
0
3.34M
Formal statement is: lemma monoseq_iff: "monoseq X \<longleftrightarrow> incseq X \<or> decseq X" Informal statement is: A sequence is monotonic if and only if it is either increasing or decreasing.
function K = lfmjXrbfKernCompute(lfmKern, rbfKern, t1, t2) % LFMJXRBFKERNCOMPUTE Compute cross kernel between the LFMJ and RBF kernels. % FORMAT % DESC computes cross kernel terms between LFMJ and RBF kernels for % the multiple output kernel. % ARG lfmKern : the kernel structure associated with the LFMJ % kernel. % ARG rbfKern : the kernel structure associated with the RBF % kernel. % ARG t : inputs for which kernel is to be computed. % RETURN K : block of values from kernel matrix. % % FORMAT % DESC computes cross kernel terms between LFMJ and RBF kernels for % the multiple output kernel. % ARG lfmKern : the kernel structure associated with the LFMJ % kernel. % ARG rbfKern : the kernel structure associated with the RBF % kernel. % ARG t1 : row inputs for which kernel is to be computed. % ARG t2 : column inputs for which kernel is to be computed. % RETURN K : block of values from kernel matrix. % % COPYRIGHT : Mauricio Alvarez, 2010 % KERN if nargin < 4 t2 = t1; end if size(t1, 2) > 1 || size(t2, 2) > 1 error('Input can only have one column'); end if lfmKern.inverseWidth ~= rbfKern.inverseWidth error('Kernels cannot be cross combined if they have different inverse widths.') end % Get length scale out. sigma2 = 2/lfmKern.inverseWidth; sigma = sqrt(sigma2); % Parameters of the kernel alpha = lfmKern.damper./(2*lfmKern.mass); omega = sqrt(lfmKern.spring./lfmKern.mass - alpha.*alpha); gamma1 = alpha + j*omega; gamma2 = alpha - j*omega; sK = lfmjpComputeUpsilonMatrix(gamma2,sigma2,t1, t2, 0) - ... lfmjpComputeUpsilonMatrix(gamma1,sigma2,t1, t2, 0); if lfmKern.isNormalised K0 = lfmKern.sensitivity/(j*4*sqrt(2)*lfmKern.mass*omega); else K0 = sqrt(pi)*sigma*lfmKern.sensitivity/(j*4*lfmKern.mass*omega); end K = K0*sK;
module LoggingFacilities using Logging using LoggingExtras using Dates using JSON using Logging: Info import Logging: shouldlog, min_enabled_level, catch_exceptions, handle_message export TimestampLoggingFormat, OneLineLoggingFormat, JSONLoggingFormat export logger export SimplestLogger export InjectByPrependingToMessage, InjectByAddingToKwargs include("formats.jl") include("simple.jl") end # module
# Unit Commitment _**[Power Systems Optimization](https://github.com/east-winds/power-systems-optimization)**_ _by Michael R. Davidson and Jesse D. Jenkins (last updated: August 31, 2021)_ This notebook will build on the economic dispatch (ED) model by introducing binary startup (called "commitment") decisions, constraints, and costs of thermal generators. Similar to ED, it minimizes the short-run production costs of meeting electricity demand, but these additions are necessary for operating systems with large amounts of (inflexible) thermal generation. They also entail significant computational trade-offs. **** We build up the model in several stages. We first start with the simplest model that incorporates unit commitment decisions in order to understand the logic of three-variable commitment formulations. Next, we introduce moderate complexity through the addition of ramp constraints&mdash;which we need to be modified from the ED to account for startups and shutdowns. Finally, we model a more realistic unit commitment that includes reserves&mdash;an important feature of day-ahead scheduling in power systems. ## Introduction to unit commitment Engineering considerations severely limit the possible output ranges of power plants. System operators need to be aware of these limitations when scheduling generation to meet demand. Thermal power plants, in particular, due to their complex designs, thermodynamic cycles, and material properties, can be particularly challenging. In practice, due to the times involved in bringing these power plants online, much of this scheduling is done day-ahead, which gives rise to the need for a day-ahead market. **Unit commitment** (UC) is the problem of minimizing short-run costs of production inclusive of production and startup costs, in order to meet a given demand and considering relevant engineering constraints of the generators. It is built on the ED model in that it typically considers all of the same variables in addition to the new startup-related variables and constraints&mdash;hence, it is also sometimes called unit commitment and economic dispatch (UCED). This notebook, for simplicity, only considers a single-bus case, while typical formulations usually include a simplified network representation. ## Simple unit commitment We start with the simplest case that incorporates unit commitment, building on the `economic_dispatch_multi` problem of the [Economic Dispatch notebook](04-Economic-Dispatch.ipynb). $$ \begin{align} \min \ & \sum_{g \in G, t \in T} VarCost_g \times GEN_{g,t} + \sum_{g \in G_{thermal}, t \in T} StartUpCost_g \times START_{g,t} \\ \end{align} $$ $$ \begin{align} \text{s.t.} & \\ & \sum_{g} GEN_{g,t} = Demand_t & \forall \quad t \in T \\ & GEN_{g,t} \leq Pmax_{g,t} & \forall \quad g \notin G_{thermal} , t \in T \\ & GEN_{g,t} \geq Pmin_{g,t} & \forall \quad g \notin G_{thermal} , t \in T \\ & GEN_{g,t} \leq Pmax_{g,t} \times COMMIT_{g,t} & \forall \quad g \in G_{thermal} , t \in T \\ & GEN_{g,t} \geq Pmin_{g,t} \times COMMIT_{g,t} & \forall \quad g \in G_{thermal} , t \in T \\ & COMMIT_{g,t} \geq \sum_{t'≥t-MinUp_g}^{t} START_{g,t} & \forall \quad g \in G_{thermal} , t \in T \\ & 1-COMMIT_{g,t} \geq \sum_{t'≥t-MinDown_g}^{t} SHUT_{g,t} &\forall \quad g \in G_{thermal} , t \in T \\ & COMMIT_{g,t+1} - COMMIT_{g,t} =&\\ & \quad START_{g,t+1} - SHUT_{g,t+1} &\forall \quad G_{thermal} \in G , t = 1..T-1 \end{align} $$ The **decision variables** in the above problem: - $GEN_{g}$, generation (in MW) produced by each generator, $g$ - $START_{g,t}$, startup decision (binary) of thermal generator $g$ at time $t$ - $SHUT_{g,t}$, shutdown decision (binary) of thermal generator $g$ at time $t$ - $COMMIT_{g,t}$, commitment status (binary) of generator $g$ at time $t$ The **parameters** are: - $Pmin_g$, the minimum operating bounds for generator $g$ (based on engineering or natural resource constraints) - $Pmax_g$, the maximum operating bounds for generator $g$ (based on engineering or natural resource constraints) - $Demand$, the demand (in MW) - $VarCost_g = VarOM_g + HeatRate_g \times FuelCost_g$, the variable cost of generator $g$ - $StartUpCost_g$, the startup cost of generator $g$ - $MinUp_g$, the minimum up time of generator $g$, or the minimum time after start-up before a unit can shut down - $MinDown_g$, the minimum down time of generator $g$, or the minimum time after shut-down before a unit can start again In addition, we introduce a few different sets: - $G$, the set of all generators - $G_{thermal} \subset G$, the subset of thermal generators for which commitment is necessary - $T$, the set of all time periods over which we are optimizing commitment and dispatch decisions Finally, the **three-variable commitment equations** capture the basic logic of commitment: - Units incur costs when they startup (not when they shutdown) - Units must stay on (and off) for a minimum period of time&mdash;in lieu of explicitly enforcing a startup trajectory - Some summations (simplified here) will need to be modified near the beginning of the time period There are some further resources at the bottom for alternative and/or more complex formulations of the UC. Now, let's implement UC. ### 1. Load packages ```julia using JuMP, GLPK using Plots; plotly(); using VegaLite # to make some nice plots using DataFrames, CSV, PrettyTables ENV["COLUMNS"]=120; # Set so all columns of DataFrames and Matrices are displayed ``` ┌ Info: For saving to png with the Plotly backend PlotlyBase has to be installed. └ @ Plots /Users/michd/.julia/packages/Plots/4UbNP/src/backends.jl:435 ### 2. Load and format data We will use data loosely based on San Diego Gas and Electric (SDG&E, via the [PowerGenome](https://github.com/gschivley/PowerGenome) data platform) including a few neighboring generators and adjustments to make the problem easy to solve, consisting of: - 33 generators (we added a few more to ensure we can provide enough reserves) - estimated hourly demand for 2020 (net load at the transmission substation level after subtracting 600MW of behind-the-meter solar from original demand) - variable generation capacity factors - estimated natural gas fuel costs In order to demonstrate the impacts of unit commitment, we will keep our high solar sensitivity case from the [Economic Dispatch notebook](04-Economic-Dispatch.ipynb) (with 3,500 MW of solar PV) to produce large variations in net load (demand less available renewable supply) required to meet demand (similar to [California's infamous "Duck Curve"](https://www.caiso.com/Documents/FlexibleResourcesHelpRenewables_FastFacts.pdf)). ```julia datadir = joinpath("uc_data") gen_info = CSV.read(joinpath(datadir,"Generators_data.csv"), DataFrame); fuels = CSV.read(joinpath(datadir,"Fuels_data.csv"), DataFrame); loads = CSV.read(joinpath(datadir,"Demand.csv"), DataFrame); gen_variable = CSV.read(joinpath(datadir,"Generators_variability.csv"), DataFrame); # Rename all columns to lowercase (by convention) for f in [gen_info, fuels, loads, gen_variable] rename!(f,lowercase.(names(f))) end ``` **Construct generator dataframe** ```julia # Keep columns relevant to our UC model select!(gen_info, 1:26) # columns 1:26 gen_df = outerjoin(gen_info, fuels, on = :fuel) # load in fuel costs and add to data frame rename!(gen_df, :cost_per_mmbtu => :fuel_cost) # rename column for fuel cost gen_df.fuel_cost[ismissing.(gen_df[:,:fuel_cost])] .= 0 # create "is_variable" column to indicate if this is a variable generation source (e.g. wind, solar): gen_df[!, :is_variable] .= false gen_df[in(["onshore_wind_turbine","small_hydroelectric","solar_photovoltaic"]).(gen_df.resource), :is_variable] .= true; # create full name of generator (including geographic location and cluster number) # for use with variable generation dataframe gen_df.gen_full = lowercase.(gen_df.region .* "_" .* gen_df.resource .* "_" .* string.(gen_df.cluster) .* ".0"); # remove generators with no capacity (e.g. new build options that we'd use if this was capacity expansion problem) gen_df = gen_df[gen_df.existing_cap_mw .> 0,:]; ``` **Modify load and variable generation dataframes** ```julia # 1. Convert from GMT to GMT-8 gen_variable.hour = mod.(gen_variable.hour .- 9, 8760) .+ 1 sort!(gen_variable, :hour) loads.hour = mod.(loads.hour .- 9, 8760) .+ 1 sort!(loads, :hour); # 2. Convert from "wide" to "long" format gen_variable_long = stack(gen_variable, Not(:hour), variable_name=:gen_full, value_name=:cf); # Now we have a "long" dataframe ``` ### 3. Create solver function As a utility function, since we do this alot, we'll create a function to convert JuMP AxisArray outputs with two indexes to DataFrames. ```julia #= Function to convert JuMP outputs (technically, AxisArrays) with two-indexes to a dataframe Inputs: var -- JuMP AxisArray (e.g., value.(GEN)) Reference: https://jump.dev/JuMP.jl/v0.19/containers/ =# function value_to_df_2dim(var) solution = DataFrame(var.data, :auto) ax1 = var.axes[1] ax2 = var.axes[2] cols = names(solution) insertcols!(solution, 1, :r_id => ax1) solution = stack(solution, Not(:r_id), variable_name=:hour) solution.hour = foldl(replace, [cols[i] => ax2[i] for i in 1:length(ax2)], init=solution.hour) rename!(solution, :value => :gen) solution.hour = convert.(Int64,solution.hour) return solution end ``` value_to_df_2dim (generic function with 1 method) Then we'll create a function to create and solve a simple unit commitment problem with specified input data. ```julia #= Function to solve simple unit commitment problem (commitment equations) Inputs: gen_df -- dataframe with generator info loads -- load by time gen_variable -- capacity factors of variable generators (in "long" format) =# function unit_commitment_simple(gen_df, loads, gen_variable) UC = Model(GLPK.Optimizer) # We reduce the MIP gap tolerance threshold here to increase tractability # Here we set it to a 1% gap, meaning that we will terminate once we have # a feasible integer solution guaranteed to be within 1% of the objective # function value of the optimal solution. # Note that GLPK's default MIP gap is 0.0, meaning that it tries to solve # the integer problem to optimality, which can take a LONG time for # any complex problem. So it is important to set this to a realistic value. set_optimizer_attribute(UC, "mip_gap", 0.01) # Define sets based on data # Note the creation of several different sets of generators for use in # different equations. # Thermal resources for which unit commitment constraints apply G_thermal = gen_df[gen_df[!,:up_time] .> 0,:r_id] # Non-thermal resources for which unit commitment constraints do NOT apply G_nonthermal = gen_df[gen_df[!,:up_time] .== 0,:r_id] # Variable renewable resources G_var = gen_df[gen_df[!,:is_variable] .== 1,:r_id] # Non-variable (dispatchable) resources G_nonvar = gen_df[gen_df[!,:is_variable] .== 0,:r_id] # Non-variable and non-thermal resources G_nt_nonvar = intersect(G_nonvar, G_nonthermal) # Set of all generators (above are all subsets of this) G = gen_df.r_id # All time periods (hours) over which we are optimizing T = loads.hour # A subset of time periods that excludes the last time period T_red = loads.hour[1:end-1] # reduced time periods without last one # Generator capacity factor time series for variable generators gen_var_cf = innerjoin(gen_variable, gen_df[gen_df.is_variable .== 1 , [:r_id, :gen_full, :existing_cap_mw]], on = :gen_full) # Decision variables @variables(UC, begin # Continuous decision variables GEN[G, T] >= 0 # generation # Bin = binary variables; # the following are all binary decisions that # can ONLY take the values 0 or 1 # The presence of these discrete decisions makes this an MILP COMMIT[G_thermal, T], Bin # commitment status (Bin=binary) START[G_thermal, T], Bin # startup decision SHUT[G_thermal, T], Bin # shutdown decision end) # Objective function # Sum of variable costs + start-up costs for all generators and time periods @objective(UC, Min, sum( (gen_df[gen_df.r_id .== i,:heat_rate_mmbtu_per_mwh][1] * gen_df[gen_df.r_id .== i,:fuel_cost][1] + gen_df[gen_df.r_id .== i,:var_om_cost_per_mwh][1]) * GEN[i,t] for i in G_nonvar for t in T) + sum(gen_df[gen_df.r_id .== i,:var_om_cost_per_mwh][1] * GEN[i,t] for i in G_var for t in T) + sum(gen_df[gen_df.r_id .== i,:start_cost_per_mw][1] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * START[i,t] for i in G_thermal for t in T) ) # Demand balance constraint (supply must = demand in all time periods) @constraint(UC, cDemand[t in T], sum(GEN[i,t] for i in G) == loads[loads.hour .== t,:demand][1]) # Capacity constraints # 1. thermal generators requiring commitment @constraint(UC, Cap_thermal_min[i in G_thermal, t in T], GEN[i,t] >= COMMIT[i, t] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:min_power][1]) @constraint(UC, Cap_thermal_max[i in G_thermal, t in T], GEN[i,t] <= COMMIT[i, t] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1]) # 2. non-variable generation not requiring commitment @constraint(UC, Cap_nt_nonvar[i in G_nt_nonvar, t in T], GEN[i,t] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1]) # 3. variable generation, accounting for hourly capacity factor @constraint(UC, Cap_var[i in 1:nrow(gen_var_cf)], GEN[gen_var_cf[i,:r_id], gen_var_cf[i,:hour] ] <= gen_var_cf[i,:cf] * gen_var_cf[i,:existing_cap_mw]) # Unit commitment constraints # 1. Minimum up time @constraint(UC, Startup[i in G_thermal, t in T], COMMIT[i, t] >= sum(START[i, tt] for tt in intersect(T, (t-gen_df[gen_df.r_id .== i,:up_time][1]):t))) # 2. Minimum down time @constraint(UC, Shutdown[i in G_thermal, t in T], 1-COMMIT[i, t] >= sum(SHUT[i, tt] for tt in intersect(T, (t-gen_df[gen_df.r_id .== i,:down_time][1]):t))) # 3. Commitment state @constraint(UC, CommitmentStatus[i in G_thermal, t in T_red], COMMIT[i,t+1] - COMMIT[i,t] == START[i,t+1] - SHUT[i,t+1]) # Solve statement (! indicates runs in place) optimize!(UC) # Generation solution and convert to data frame # with our helper function defined above gen = value_to_df_2dim(value.(GEN)) # Commitment status solution and convert to data frame commit = value_to_df_2dim(value.(COMMIT)) # Calculate curtailment = available wind and/or solar output that # had to be wasted due to operating constraints curtail = innerjoin(gen_var_cf, gen, on = [:r_id, :hour]) curtail.curt = curtail.cf .* curtail.existing_cap_mw - curtail.gen # Return the solution parameters and objective return ( gen, commit, curtail, cost = objective_value(UC), status = termination_status(UC) ) end ``` unit_commitment_simple (generic function with 1 method) ### 4. Solve a day's unit commitment ```julia # A spring day n=100 T_period = (n*24+1):((n+1)*24) # High solar case: 3,500 MW gen_df_sens = copy(gen_df) gen_df_sens[gen_df_sens.resource .== "solar_photovoltaic", :existing_cap_mw] .= 3500 loads_multi = loads[in.(loads.hour,Ref(T_period)),:] gen_variable_multi = gen_variable_long[in.(gen_variable_long.hour,Ref(T_period)),:] solution = unit_commitment_simple(gen_df_sens, loads_multi, gen_variable_multi); ``` ```julia # Add in BTM solar and curtailment and plot results sol_gen = innerjoin(solution.gen, gen_df[!, [:r_id, :resource]], on = :r_id) sol_gen = combine(groupby(sol_gen, [:resource, :hour]), :gen => sum) # Rename generators (for plotting purposes) sol_gen[sol_gen.resource .== "solar_photovoltaic", :resource] .= "_solar_photovoltaic" sol_gen[sol_gen.resource .== "onshore_wind_turbine", :resource] .= "_onshore_wind_turbine" sol_gen[sol_gen.resource .== "small_hydroelectric", :resource] .= "_small_hydroelectric" # BTM solar btm = DataFrame(resource = repeat(["_solar_photovoltaic_btm"]; outer=length(T_period)), hour = T_period, gen_sum = gen_variable_multi[gen_variable_multi.gen_full .== "wec_sdge_solar_photovoltaic_1.0",:cf] * 600) append!(sol_gen, btm) # Curtailment curtail = combine(groupby(solution.curtail, [:hour]), :curt => sum) curtail[!, :resource] .= "_curtailment" rename!(curtail, :curt_sum => :gen_sum) append!(sol_gen, curtail[:,[:resource, :hour, :gen_sum]]) # Rescale hours sol_gen.hour = sol_gen.hour .- T_period[1] sol_gen |> @vlplot(:area, x=:hour, y={:gen_sum, stack=:zero}, color={"resource:n", scale={scheme="category10"}}) ``` Notice that the combined cycle plants flatten out during the day, but don't shut down due to the need for ramping capabilities in the late afternoon/evening, when solar output falls off and evening demand remains strong. This leads to some curtailment of solar from 11:00 - 16:00, which was not present in the Economic Dispatch model. All curtailment is lumped together as the model does not accurately distinguish between whether wind, solar or hydro is curtailed, which in practice is up to the system operator and depends on a variety of factors such as location, interconnection voltage, etc. We can examine the commitment status of various units by examining the results in `solution.commit`. ```julia sol_commit = innerjoin(solution.commit, gen_df[!, [:r_id, :resource]], on = :r_id) sol_commit = combine(groupby(sol_commit, [:resource, :hour]), :gen => sum) sol_commit.hour = sol_commit.hour .- T_period[1] sol_commit |> @vlplot(:area, x=:hour, y={:gen_sum, stack=:zero}, color={"resource:n", scale={scheme="category10"}}) ``` Note that units shutdown during the solar period and startup for the evening peak. However, due to the commitment constraints, not all natural gas plants can be decommitted, resulting in the observed curtailment. A large number of combustion turbines turn on to meet the evening peak. ## Moderate complexity unit commitment We expand the above unit commitment with ramp equations. These must be modified to prevent ramp violations during the startup process. In order to accommodate this, we introduce an **auxiliary variable** $GENAUX_{g,t}$ defined as the generation above the minimum output (if committed). $GENAUX_{g,t} = GEN_{g,t} = 0$ if the unit is not committed. Auxiliary variables are for convenience (we could always write the whole problem in terms of the original decision variables), but they help de-clutter the model and in general won't add too much computational penalty. The following constraints are added: $$ \begin{align} & GENAUX_{g,t} = GEN_{g,t} - Pmin_{g,t}COMMIT_{g,t} & \forall \quad g \in G_{thermal} , t \in T \\ & GENAUX_{g,t+1} - GENAUX_{g,t} \leq RampUp_{g} & \forall \quad g \in G_{thermal} , t = 1..T-1 \\ & GENAUX_{g,t} - GENAUX_{g,t+1} \leq RampDn_{g} & \forall \quad g \in G_{thermal} , t = 1..T-1 \\ & GEN_{g,t+1} - GEN_{g,t} \leq RampUp_{g} & \forall \quad g \notin G_{thermal} , t = 1..T-1 \\ & GEN_{g,t} - GEN_{g,t+1} \leq RampDn_{g} & \forall \quad g \notin G_{thermal} , t = 1..T-1 \end{align} $$ The creation of this auxiliary variable $GENAUX$ helps us avoid violating ramping constraints when we start up our units and their generation immediately jumps up to their minium output level or during shut-down when a unit drops from minimum output (or above) to zero. Note you may encounter alternative formulations in the literature to address this start-up and shut-down that modify the right-hand side of the traditional ramping constraint on total generation to account for the additional step change in output during start-up or shut-down periods. The above formulation is conceptually simple and works well. ### 3. Create solver function (We reuse steps 1 and 2 above to load packages and data.) ```julia #= Function to solve moderate complexity unit commitment problem (commitment and ramp equations) Inputs: gen_df -- dataframe with generator info loads -- load by time gen_variable -- capacity factors of variable generators (in "long" format) =# function unit_commitment_ramp(gen_df, loads, gen_variable) UC = Model(GLPK.Optimizer) set_optimizer_attribute(UC, "mip_gap", 0.01) #1% MIP gap # Define sets based on data # Note the creation of several different sets of generators for use in # different equations. G_thermal = gen_df[gen_df[!,:up_time] .> 0,:r_id] G_nonthermal = gen_df[gen_df[!,:up_time] .== 0,:r_id] G_var = gen_df[gen_df[!,:is_variable] .== 1,:r_id] G_nonvar = gen_df[gen_df[!,:is_variable] .== 0,:r_id] G_nt_nonvar = intersect(G_nonvar, G_nonthermal) G = gen_df.r_id T = loads.hour T_red = loads.hour[1:end-1] # reduced time periods without last one # Generator capacity factor time series for variable generators gen_var_cf = innerjoin(gen_variable, gen_df[gen_df.is_variable .== 1 , [:r_id, :gen_full, :existing_cap_mw]], on = :gen_full) # Decision variables @variables(UC, begin GEN[G, T] >= 0 # generation GENAUX[G_thermal, T] >= 0 # auxiliary generation variable COMMIT[G_thermal, T], Bin # commitment status (Bin=binary) START[G_thermal, T], Bin # startup decision SHUT[G_thermal, T], Bin # shutdown decision end) # Objective function @objective(UC, Min, sum( (gen_df[gen_df.r_id .== i,:heat_rate_mmbtu_per_mwh][1] * gen_df[gen_df.r_id .== i,:fuel_cost][1] + gen_df[gen_df.r_id .== i,:var_om_cost_per_mwh][1]) * GEN[i,t] for i in G_nonvar for t in T) + sum(gen_df[gen_df.r_id .== i,:var_om_cost_per_mwh][1] * GEN[i,t] for i in G_var for t in T) + sum(gen_df[gen_df.r_id .== i,:start_cost_per_mw][1] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * START[i,t] for i in G_thermal for t in T) ) # Demand constraint @constraint(UC, cDemand[t in T], sum(GEN[i,t] for i in G) == loads[loads.hour .== t,:demand][1]) # Capacity constraints (thermal generators requiring commitment) @constraint(UC, Cap_thermal_min[i in G_thermal, t in T], GEN[i,t] >= COMMIT[i, t] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:min_power][1]) @constraint(UC, Cap_thermal_max[i in G_thermal, t in T], GEN[i,t] <= COMMIT[i, t] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1]) # Capacity constraints (non-variable generation not requiring commitment) @constraint(UC, Cap_nt_nonvar[i in G_nt_nonvar, t in T], GEN[i,t] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1]) # Capacity constraints (variable generation) @constraint(UC, Cap_var[i in 1:nrow(gen_var_cf)], GEN[gen_var_cf[i,:r_id], gen_var_cf[i,:hour] ] <= gen_var_cf[i,:cf] * gen_var_cf[i,:existing_cap_mw]) # Unit commitment constraints @constraint(UC, Startup[i in G_thermal, t in T], COMMIT[i, t] >= sum(START[i, tt] for tt in intersect(T, (t-gen_df[gen_df.r_id .== i,:up_time][1]):t))) @constraint(UC, Shutdown[i in G_thermal, t in T], 1-COMMIT[i, t] >= sum(SHUT[i, tt] for tt in intersect(T, (t-gen_df[gen_df.r_id .== i,:down_time][1]):t))) @constraint(UC, CommitmentStatus[i in G_thermal, t in T_red], COMMIT[i,t+1] - COMMIT[i,t] == START[i,t+1] - SHUT[i,t+1]) # New auxiliary variable GENAUX for generation above the minimum output level # for committed thermal units (only created for thermal generators) @constraint(UC, AuxGen[i in G_thermal, t in T], GENAUX[i,t] == GEN[i,t] - COMMIT[i, t] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:min_power][1]) # Ramp equations for thermal generators (constraining GENAUX) @constraint(UC, RampUp_thermal[i in G_thermal, t in T_red], GENAUX[i,t+1] - GENAUX[i,t] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:ramp_up_percentage][1] ) @constraint(UC, RampDn_thermal[i in G_thermal, t in T_red], GENAUX[i,t] - GENAUX[i,t+1] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:ramp_dn_percentage][1] ) # Ramp equations for non-thermal generators (constraining total generation GEN) @constraint(UC, RampUp_nonthermal[i in G_nonthermal, t in T_red], GEN[i,t+1] - GEN[i,t] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:ramp_up_percentage][1] ) @constraint(UC, RampDn[i in G, t in T_red], GEN[i,t] - GEN[i,t+1] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:ramp_dn_percentage][1] ) # Solve statement (! indicates runs in place) optimize!(UC) # Generation solution gen = value_to_df_2dim(value.(GEN)) # Commitment status solution commit = value_to_df_2dim(value.(COMMIT)) # Calculate curtailment curtail = innerjoin(gen_var_cf, gen, on = [:r_id, :hour]) curtail.curt = curtail.cf .* curtail.existing_cap_mw - curtail.gen # Return the solution and objective as named tuple return ( gen, commit, curtail, cost = objective_value(UC), status = termination_status(UC) ) end ``` unit_commitment_ramp (generic function with 1 method) ### 4. Solve a day's unit commitment ```julia solution = unit_commitment_ramp(gen_df_sens, loads_multi, gen_variable_multi); # Add in BTM solar and curtailment and plot results sol_gen = innerjoin(solution.gen, gen_df[!, [:r_id, :resource]], on = :r_id) sol_gen = combine(groupby(sol_gen, [:resource, :hour]), :gen => sum) # Rename generators (for plotting purposes) sol_gen[sol_gen.resource .== "solar_photovoltaic", :resource] .= "_solar_photovoltaic" sol_gen[sol_gen.resource .== "onshore_wind_turbine", :resource] .= "_onshore_wind_turbine" sol_gen[sol_gen.resource .== "small_hydroelectric", :resource] .= "_small_hydroelectric" # BTM solar btm = DataFrame(resource = repeat(["_solar_photovoltaic_btm"]; outer=length(T_period)), hour = T_period, gen_sum = gen_variable_multi[gen_variable_multi.gen_full .== "wec_sdge_solar_photovoltaic_1.0",:cf] * 600) append!(sol_gen, btm) # Curtailment curtail = combine(groupby(solution.curtail, [:hour]), :curt => sum) curtail[!, :resource] .= "_curtailment" rename!(curtail, :curt_sum => :gen_sum) append!(sol_gen, curtail[:,[:resource, :hour, :gen_sum]]) # Rescale hours sol_gen.hour = sol_gen.hour .- T_period[1] sol_gen |> @vlplot(:area, x=:hour, y={:gen_sum, stack=:zero}, color={"resource:n", scale={scheme="category10"}}) ``` In contrast to when we added ramp constraints to the Economic Dispatch problem, adding ramp constraints to our Unit Commitment formulation does not change the solution as much (at least in this case). Much of the inflexibility here arises from the unit commitment constraints, and once committed, there is ample ramping capability. We do however get relatively more combustion turbines running to meet the evening ramp, given their faster ramp rates. ```julia sol_commit = innerjoin(solution.commit, gen_df[!, [:r_id, :resource]], on = :r_id) sol_commit = combine(groupby(sol_commit, [:resource, :hour]), :gen => sum) sol_commit.hour = sol_commit.hour .- T_period[1] sol_commit |> @vlplot(:area, x=:hour, y={:gen_sum, stack=:zero}, color={"resource:n", scale={scheme="category10"}}) ``` A case involving more large coal or nuclear units with slower ramping limits than gas turbines or combined cycle plants might find ramp constraints more limiting. As in many cases, the impact of constraints is case dependent, and models must exercise some judicious application of domain knowledge (and experimentation with alternative formulations) to decide how complex your model should be to reflect important *binding* constraints that actually shape your outcomes of interest. Where constraints are non-binding or second order, it may be more practical to omit them entirely, reducing the computational intensity (solve time) of your model... ## Unit commitment with ramping and reserves We now add spinning reserve requirements to the model. Spinning reserves refer to generation capacity that is online and able to generate (e.g., within 10-30 minutes) if needed by the system operator. (Note: in Europe, these are referred to as tertiary reserves.) The SO will establish reserve requirements to maintain sufficient capacity to respond to demand or supply forecast errors or in case of "contingencies," such as the unplanned and sudden loss of a generating station or a transmission line. The SO then typically operates a reserve market to competitively procure this available capacity. Most SO's actually define several classes of reserve products defined by their response time and period over which they may be activated. Here we will focus on spinning reserve requirements and establish a simple set of reserve requirements for reserves up (ability to quickly increase output) and reserves down (ability to quickly reduce output): $$ \begin{align} & ResReqUp_t = 300 MW + 5\% \times Demand_t &\forall \quad t \in T \\ & ResReqDn_t = 5\% \times Demand_t & \forall \quad t \in T \end{align} $$ Here, $300 MW$ is our contigency reserves, meant to ensure we have sufficient upwards ramping capability online and available to cover the unexpected loss of 300 MW worth of generation. The 5% of demand term in the constraints above is meant to provide sufficient reserves in either upwards or downwards direction to cover errors in the demand forecast. For simplicity, we ignore solar PV and wind production in our reserve calculation, though in practice, we would want to consider solar and wind forecast errors in calculating up reserve requirements as well. In our simple system, only thermal generators provide reserves. (This can be easily adjusted by changing the sets and defining the potential reserve contributions for different sets of resources differently, such as storage or hydro resources). The contribution of each generators to meeting reserves and the overall reserve constraint are thus given by: $$ \begin{align} & RESUP_{g,t} \leq Pmax_{g,t}COMMIT_{g,t} - GEN_{g,t} & \forall \quad g \in G_{thermal} , t \in T \\ & RESDN_{g,t} \leq GEN_{g,t} - Pmin_{g,t}COMMIT_{g,t} & \forall \quad g \in G_{thermal} , t \in T \\ & RESUP_{g,t} \leq RampUp_{g} & \forall \quad g \in G_{thermal}, t \in T\\ & RESDN_{g,t} \leq RampDn_{g} & \forall \quad g \in G_{thermal}, t \in T \\ & \sum_{g \in G_{thermal}} RESUP_{g,t} \geq ResReqUp_t & \forall \quad t \in T \\ & \sum_{g \in G_{thermal}} RESDN_{g,t} \geq ResReqDn_t & \forall \quad t \in T \end{align} $$ We have added two new **decision variables**: - $RESUP_{g,t}$, up-reserve capacity (in MW) of generator $g$ at time $t$ - $RESDN_{g,t}$, down-reserve capacity (in MW) of generator $g$ at time $t$ Note that in this case, we constrain the reserve contribution for each thermal generator to be the same as their hourly ramp rates, $RampUp_{g}, RampDown_{g}$. In practice, reserve products typically require a faster response time, on the order of 10-30 minutes for "tertiary" reserves (aka spinning reserves or contingency reserves), and 5-15 minutes for "secondary" reserves (regulation reserves). Thus, depending on the reserve requirements being modeled, one might specify a distinct maximum reserve contribution for each unit that reflects their ramping capabilities over shorter time periods. ### 3. Create solver function (We reuse steps 1 and 2 above to load packages and data.) ```julia #= Function to solve full unit commitment problem (commitment, ramp, reserve equations) Inputs: gen_df -- dataframe with generator info loads -- load by time gen_variable -- capacity factors of variable generators (in "long" format) =# function unit_commitment_full(gen_df, loads, gen_variable) UC = Model(GLPK.Optimizer) # To keep solve times to a few minutes, we increase the MIP gap tolerance # in this more complex case to 2%. You can play with this setting to see # how the MIP gap affects solve times on your computer. set_optimizer_attribute(UC, "mip_gap", 0.02) # Define sets based on data # Note the creation of several different sets of generators for use in # different equations. G_thermal = gen_df[gen_df[!,:up_time] .> 0,:r_id] G_nonthermal = gen_df[gen_df[!,:up_time] .== 0,:r_id] G_var = gen_df[gen_df[!,:is_variable] .== 1,:r_id] G_nonvar = gen_df[gen_df[!,:is_variable] .== 0,:r_id] G_nt_nonvar = intersect(G_nonvar, G_nonthermal) G = gen_df.r_id T = loads.hour T_red = loads.hour[1:end-1] # reduced time periods without last one # Generator capacity factor time series for variable generators gen_var_cf = innerjoin(gen_variable, gen_df[gen_df.is_variable .== 1 , [:r_id, :gen_full, :existing_cap_mw, :resource]], on = :gen_full) gen_var_cf.max_gen = gen_var_cf.cf .* gen_var_cf.existing_cap_mw # Compute reserve requirements ResReqUp = Dict(T[i] => 300 + 0.05 * loads[loads.hour .== T[i],:demand][1] for i in 1:length(T)) ResReqDn = Dict(T[i] => 0 + 0.05 * loads[loads.hour .== T[i],:demand][1] for i in 1:length(T)) # Decision variables @variables(UC, begin GEN[G, T] >= 0 # generation GENAUX[G_thermal, T] >= 0 # auxiliary generation variable COMMIT[G_thermal, T], Bin # commitment status (Bin=binary) START[G_thermal, T], Bin # startup decision SHUT[G_thermal, T], Bin # shutdown decision RESUP[G_thermal, T] # up reserve capacity RESDN[G_thermal, T] # down reserve capacity end) # Objective function @objective(UC, Min, sum( (gen_df[gen_df.r_id .== i,:heat_rate_mmbtu_per_mwh][1] * gen_df[gen_df.r_id .== i,:fuel_cost][1] + gen_df[gen_df.r_id .== i,:var_om_cost_per_mwh][1]) * GEN[i,t] for i in G_nonvar for t in T) + sum(gen_df[gen_df.r_id .== i,:var_om_cost_per_mwh][1] * GEN[i,t] for i in G_var for t in T) + sum(gen_df[gen_df.r_id .== i,:start_cost_per_mw][1] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * START[i,t] for i in G_thermal for t in T) ) # Demand constraint @constraint(UC, cDemand[t in T], sum(GEN[i,t] for i in G) == loads[loads.hour .== t,:demand][1]) # Capacity constraints (thermal generators requiring commitment) @constraint(UC, Cap_thermal_min[i in G_thermal, t in T], GEN[i,t] >= COMMIT[i, t] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:min_power][1]) @constraint(UC, Cap_thermal_max[i in G_thermal, t in T], GEN[i,t] <= COMMIT[i, t] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1]) # Capacity constraints (non-variable generation not requiring commitment) @constraint(UC, Cap_nt_nonvar[i in G_nt_nonvar, t in T], GEN[i,t] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1]) # Capacity constraints (variable generation) @constraint(UC, Cap_var[i in 1:nrow(gen_var_cf)], GEN[gen_var_cf[i,:r_id], gen_var_cf[i,:hour] ] <= gen_var_cf[i,:max_gen]) # Unit commitment constraints @constraint(UC, Startup[i in G_thermal, t in T], COMMIT[i, t] >= sum(START[i, tt] for tt in intersect(T, (t-gen_df[gen_df.r_id .== i,:up_time][1]):t))) @constraint(UC, Shutdown[i in G_thermal, t in T], 1-COMMIT[i, t] >= sum(SHUT[i, tt] for tt in intersect(T, (t-gen_df[gen_df.r_id .== i,:down_time][1]):t))) @constraint(UC, CommitmentStatus[i in G_thermal, t in T_red], COMMIT[i,t+1] - COMMIT[i,t] == START[i,t+1] - SHUT[i,t+1]) # Auxiliary variable @constraint(UC, AuxGen[i in G_thermal, t in T], GENAUX[i,t] == GEN[i,t] - COMMIT[i, t] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:min_power][1]) # Ramp equations (thermal generators) @constraint(UC, RampUp_thermal[i in G_thermal, t in T_red], GENAUX[i,t+1] - GENAUX[i,t] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:ramp_up_percentage][1] ) @constraint(UC, RampDn_thermal[i in G_thermal, t in T_red], GENAUX[i,t] - GENAUX[i,t+1] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:ramp_dn_percentage][1] ) # Ramp equations (non-thermal generators) @constraint(UC, RampUp_nonthermal[i in G_nonthermal, t in T_red], GEN[i,t+1] - GEN[i,t] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:ramp_up_percentage][1] ) @constraint(UC, RampDn[i in G, t in T_red], GEN[i,t] - GEN[i,t+1] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:ramp_dn_percentage][1] ) # Reserve equations # (1) Reserves limited by committed capacity of generator @constraint(UC, ResUpCap[i in G_thermal, t in T], RESUP[i,t] <= COMMIT[i, t] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1] - GEN[i,t]) @constraint(UC, ResDnCap[i in G_thermal, t in T], RESDN[i,t] <= GEN[i,t] - COMMIT[i, t] * gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:min_power][1]) # (2) Reserves limited by ramp rates @constraint(UC, ResUpRamp[i in G_thermal, t in T], RESUP[i,t] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:ramp_up_percentage][1]) @constraint(UC, ResDnRamp[i in G_thermal, t in T], RESDN[i,t] <= gen_df[gen_df.r_id .== i,:existing_cap_mw][1] * gen_df[gen_df.r_id .== i,:ramp_dn_percentage][1]) # (3) Overall reserve requirements @constraint(UC, ResUpRequirement[t in T], sum(RESUP[i,t] for i in G_thermal) >= ResReqUp[t]) @constraint(UC, ResDnRequirement[t in T], sum(RESDN[i,t] for i in G_thermal) >= ResReqDn[t]) # Solve statement (! indicates runs in place) optimize!(UC) # Generation solution gen = value_to_df_2dim(value.(GEN)) # Commitment status solution commit = value_to_df_2dim(value.(COMMIT)) # Calculate curtailment curtail = innerjoin(gen_var_cf, gen, on = [:r_id, :hour]) curtail.curt = curtail.cf .* curtail.existing_cap_mw - curtail.gen # Return the solution and objective as named tuple return ( gen, commit, curtail, cost = objective_value(UC), status = termination_status(UC) ) end ``` unit_commitment_full (generic function with 1 method) ### 4. Solve the model and plot results **Note: this might take a little while depending on your machine.** ```julia solution = unit_commitment_full(gen_df_sens, loads_multi, gen_variable_multi); # Add in BTM solar and curtailment and plot results sol_gen = innerjoin(solution.gen, gen_df[!, [:r_id, :resource]], on = :r_id) sol_gen = combine(groupby(sol_gen, [:resource, :hour]), :gen => sum) # Rename generators (for plotting purposes) sol_gen[sol_gen.resource .== "solar_photovoltaic", :resource] .= "_solar_photovoltaic" sol_gen[sol_gen.resource .== "onshore_wind_turbine", :resource] .= "_onshore_wind_turbine" sol_gen[sol_gen.resource .== "small_hydroelectric", :resource] .= "_small_hydroelectric" # BTM solar btm = DataFrame(resource = repeat(["_solar_photovoltaic_btm"]; outer=length(T_period)), hour = T_period, gen_sum = gen_variable_multi[gen_variable_multi.gen_full .== "wec_sdge_solar_photovoltaic_1.0",:cf] * 600) append!(sol_gen, btm) # Curtailment curtail = combine(groupby(solution.curtail, [:hour]), :curt => sum) curtail[!, :resource] .= "_curtailment" rename!(curtail, :curt_sum => :gen_sum) append!(sol_gen, curtail[:,[:resource, :hour, :gen_sum]]) # Rescale hours sol_gen.hour = sol_gen.hour .- T_period[1] sol_gen |> @vlplot(:area, x=:hour, y={:gen_sum, stack=:zero}, color={"resource:n", scale={scheme="category10"}}) ``` We can now see that the need to maintain reserve requirements leads to greater commitment of natural gas units throughout the day. The addition of CCGTs and GTs to meet reserve requirements leads to greater curtailment of wind and solar in the afternoon hours. We also see more CT units committed during the morning ramp as well as the afternoon hours to help provide reserves. ```julia sol_commit = innerjoin(solution.commit, gen_df[!, [:r_id, :resource]], on = :r_id) sol_commit = combine(groupby(sol_commit, [:resource, :hour]), :gen => sum) sol_commit.hour = sol_commit.hour .- T_period[1] sol_commit |> @vlplot(:area, x=:hour, y={:gen_sum, stack=:zero}, color={"resource:n", scale={scheme="category10"}}) ``` ### Further resources Knueven, B., Ostrowski, J., & Watson, J.-P. (2019). On Mixed Integer Programming Formulations for the Unit Commitment Problem. Optimization Online, 91. http://www.optimization-online.org/DB_FILE/2018/11/6930.pdf Morales-Espana, G., Latorre, J. M., & Ramos, A. (2013). Tight and Compact MILP Formulation of Start-Up and Shut-Down Ramping in Unit Commitment. IEEE Transactions on Power Systems, 28(2), 1288–1296. https://doi.org/10.1109/TPWRS.2012.2222938 Morales-España, G., Ramírez-Elizondo, L., & Hobbs, B. F. (2017). Hidden power system inflexibilities imposed by traditional unit commitment formulations. Applied Energy, 191, 223–238. https://doi.org/10.1016/j.apenergy.2017.01.089 Ostrowski, J., Anjos, M. F., & Vannelli, A. (2012). Tight Mixed Integer Linear Programming Formulations for the Unit Commitment Problem. IEEE Transactions on Power Systems, 27(1), 39–46. https://doi.org/10.1109/TPWRS.2011.2162008
Public transportation within the City of Sarnia , including conventional bus transit , transportation of people with disabilities , transportation support for major events , and charter services , is provided by Sarnia Transit . From the city 's local airport , Sarnia Chris Hadfield Airport , Air Georgian operates services to and from Toronto Pearson International Airport on behalf of Air Canada Express . For rail travel , Sarnia is one of the two western termini , along with Windsor , of the Via Rail Quebec City – Windsor Corridor , over which a service departs Sarnia station in the morning and arrives in the evening .
[STATEMENT] lemma zero_on_circline: "on_circline H 0\<^sub>h \<longleftrightarrow> circline_D0 H" [PROOF STATE] proof (prove) goal (1 subgoal): 1. on_circline H 0\<^sub>h = circline_D0 H [PROOF STEP] by (transfer, transfer, auto simp add: vec_cnj_def)
On Monday, May 8, 2017, the construction of the new Amethyst Radiotherapy Center in Austria has begun. According to the estimations the treatment of the first patients will be possible in the end of 2017. Since the Centre Charlebourg-La Defense joined in 2015 Amethyst Radiotherapy group, it had benefited from a major investment plan: 2 additional bunkers are build and a new accelerator will be installed current 2017 year. Patients from Małopolska have now access to stereotactic therapy in Amethyst’s Krakow center. As of June 2015, Amethyst Radiotherapy finalized the acquisition of another clinic in France, reaching a network of three clinics in this country and six in total, across Europe. Amethyst Radiotherapy attracts an institutional shareholder. Starting with April 2015, the investment fund Accession Mezzanine Capital III, managed by Mezzanine Management, became a shareholder in the company through capital increase. Opened in May 2015, Amethyst Bucharest Fundeni is our newest clinic. It is conveniently located just across the Bucharest Oncological Institute and is designed to serve the oncology patients in need for fast and accurate diagnosis and treatment.
import .myRing import tactic.basic -- import tactic open myRing variables {R : Type} [myRing R] variables {O : Type} [ordered_ring O ] -- variable is_positive : O → Prop /- P1. Suppose a, z ∈ ℤ. If a+z=a then z=0. So "zero" is uniquely defined. Similarly, "one" is uniquely defined. -/ theorem zero_is_unique: ∀( z : R), (∀ (a : R), a + z = a) → (z = 0) := begin intros z a, have x: z + 0 = z := add_zero z, have y: z + 0 = 0 := begin rw add_comm, rw a, end, rw ← x, rw y, end theorem one_is_unique: ∀( o : R), (∀(a : R), a*o = a) → o = 1 := begin intros o a, have q : o * 1 = o := mul_one o, have r : 1 * o = 1 := a 1, rw mul_comm at r, rw q at r, exact r, end /- P3. Suppose a,b, b' ∈ ℤ. The a+b=a+b' → b=b' -/ theorem left_cancel: ∀ {a b c : R}, a+b=a+c → b=c := begin intros a b c eq, rw [ ← add_zero b], cases has_inv a , rw [← h,← add_assoc,add_comm b a,eq,add_comm a c,add_assoc,h,add_zero], end /- similarly, you can cancel on the right-/ -- @[simp] lemma right_cancel: ∀ {a b c : R}, b+a=c+a → b=c := begin intros a b c eq, rw add_comm at eq, have : c + a = a+c := begin rw add_comm, end, rw this at eq, have : b=c := begin exact left_cancel eq, end, exact this, end @[simp] lemma right_cancel_simp: ∀ {a b c : R}, b+a=c+a ↔ b=c := begin intros a b c, split,{ exact right_cancel, }, intro bc, rw bc, end /- anything times zero is zero -/ @[simp] lemma mul_zero : ∀{a : R}, a * 0 = 0 := begin intro a, have : a * (1 + 0) = a + 0, { rw add_zero, rw mul_one, rw add_zero, }, rw mul_add at this, rw mul_one at this, exact left_cancel this, end /- P2. Use P1 to deduce that 0 ≠ 1 False. 0 = 1 in the trivial myRing.` P2 SALVAGE. Zero is only one in the trivial myRing. -/ theorem zero_is_one_implies_trivial : ((0: R) = 1) → (∀(a : R), a = 0) := begin intros h a, have q : a * 1 = a := mul_one a, rw ← h at q, rw mul_zero at q, symmetry, exact q, end /- P4. Gvien a ∈ ℤ, let -a be the unique solution x to a+x=0 (why is it unique?) Then : -(-a) = a and -(ab)=(-a)b = a(-b). Moreover (-a)(-b) = ab and -a = (-1)*a -/ @[simp] theorem neg_neg_a : ∀ {a : R}, -(-a)=a := begin intro a, have na := add_neg a, have nna := add_neg (-a), rw add_comm at nna, rw ← na at nna, exact right_cancel nna, end @[simp] theorem dist_neg_right : ∀ (a b : R), (a)*(-b)=-(a*b) := begin intros a b, have x: 0 = a*0 := begin rw mul_zero, end, rw ← add_neg b at x, rw mul_add at x, rw add_neg b at x, have y: a*b + (-(a*b)) = 0 := begin rw add_neg (a*b), end, rw ← y at x, have := left_cancel x, symmetry, exact this, end @[simp] theorem mul_neg_one : ∀ (a : R), (-1)*a=-a := begin intro a, have x: a*0=0 := begin exact mul_zero, end, rw ← add_neg (1:R) at x, rw mul_add at x, rw mul_one at x, rw add_neg at x, have z: a + -a = 0 := begin rw add_neg, end, rw ← z at x, have z : a*(-1) = -a := begin exact left_cancel x, end, rw mul_comm, exact z, end @[simp] theorem dist_neg_left : ∀ (a b : R), (-a)*(b)=-(a*b) := begin intros a b, rw ← mul_neg_one a, rw mul_comm (-1:R) a, rw mul_assoc, rw mul_neg_one b, exact dist_neg_right a b, end @[simp] theorem dist_neg_both : ∀ (a b : R), (-a)*(-b)=(a*b) := begin intros a b, rw dist_neg_left (a) (-b), rw dist_neg_right (a) (b), rw neg_neg_a, end theorem neg1_times_neg1 : (-(1 :R))*(-1) = 1 := begin have x: (-1:R)*(0:R)=0 := begin exact mul_zero, end, rw ← add_neg (1 :R ) at x, rw mul_add at x, rw mul_one at x, rw add_comm at x, have : (-1 :R)* (-1) = 1 := begin rw right_cancel x, end, exact this, end /- P7 1 ∈ P and -1 ∉ P -/ /- lemma: if a is positive and b is not positive then a is not b -/ lemma pos_diff : ∀ (a b : O), is_positive (a) ∧ ¬ is_positive (b) → ¬ a=b := begin intros a b c, cases c with d e, by_contradiction, rw h at d, apply e, exact d, end /- lemma: if a is positive then a is not 0 -/ lemma pos_not_z : ∀ (a : O), is_positive (a) → ¬ a=0 := begin intros a b c, have nontriv := nontriviality, apply nontriv, rw c at b, exact b, end /- -1 ∉ P : in other words, -1 is not positive -/ theorem not_neg_one_pos : ¬ is_positive(-1:O) := begin intros a, have notz := pos_not_z (-1:O), have xf := notz a, have trich := trichotomy (-1:O), have ewf := pos_times_pos a a, rw neg1_times_neg1 at ewf, cases trich with f g, { cases f with d n, cases n with d s, rw neg_neg_a at s, apply s, exact ewf, }, cases g with fn dw,{ cases fn with dj dw, cases dw with dn fh, rw neg_neg_a at fh, apply fh, exact ewf, }, cases dw with fs wh, cases wh with od wx, apply fs, exact a, end /- 1 ∈ P : in other words 1 is positive -/ theorem one_pos : is_positive(1:O) := begin have ed : ¬is_positive(-1:O) := not_neg_one_pos, cases trichotomy (1:O), { cases h with h1 h2, exact h1, }, { cases h, cases h with h1 h2, cases h2 with h2 h3, have h4 : 0 = (1 : O), { symmetry, exact h2, }, { have allzero := zero_is_one_implies_trivial h4, have zeronotpos : ∃(a : O), is_positive a := nonempty_pos, rw h2 at h1, cases zeronotpos with a q, have azero := allzero a, rw ← h2 at azero, rw azero at q, exact q, }, { cases h with h1 h2, cases h2 with h2 h3, exfalso, apply ed, exact h3, }, } end theorem trans_lt : ∀{a b c : O}, a < b → b < c → a < c := begin intros a b c a_le_b b_le_c, rw less_than at a_le_b, rw less_than at b_le_c, rcases a_le_b with ⟨p1, p1pos, eq1⟩ , rcases b_le_c with ⟨p2, p2pos, eq2⟩ , rw less_than, use p1 + p2, split, exact pos_plus_pos p1pos p2pos, rw ← eq1 at eq2, rw add_assoc at eq2, exact eq2, end /- P8 Prove the transitivity of ≤ -/ theorem trans_le : ∀{a b c : O}, a ≤ b → b ≤ c → a ≤ c := begin intros a b c ab bc, rw less_eq at ab, rw less_eq at bc, rw less_eq, cases ab, { cases bc, { rw less_than at ab, rw less_than at bc, cases bc with Pbc bc, cases ab with Pab ab, cases bc with Pbc bc, cases ab with Pab ab, rw ← ab at bc, rw add_assoc at bc, have := pos_plus_pos Pab Pbc, have alc : a < c, { rw less_than, split, exact ⟨this, bc⟩, }, left, exact alc, }, { left, rw ← bc, exact ab, }, }, { cases bc, { left, rw ab, exact bc, }, { right, rw ab, exact bc, } }, end @[simp] /- 0 + something = something -/ lemma zero_add : ∀{a : R}, 0 + a = a := begin intro a, rw add_comm, rw add_zero, end /- move stuff across the equal sign-/ lemma move : ∀{a b c: R}, a + b = c → a = c + (-b) := begin intros a b c h, rw ← h, rw add_assoc, rw add_neg, rw add_zero, end /- you can multiply by stuff on the right-/ lemma mul_right : ∀{a b : R}, ∀(c : R), a = b → a * c = b * c := begin intros a b c h, rw h, end lemma mul_left : ∀{a b : R}, ∀(c : R), a = b → c*a = c*b := begin intros a b c h, rw h, end /- P9 ∀a, b ∈ ℤ, exactly one of the following is true: a < b or a = b or a > b in other words, the integers are a total order. -/ theorem trichotomy_lt : ∀(a b : O), (a < b ∧ a ≠ b ∧ ¬(b < a)) ∨ (¬(a < b) ∧ a = b ∧ ¬(b < a)) ∨ (¬(a < b) ∧ a ≠ b ∧ (b < a)) := begin intros a b, have : a + (b + (-a)) = b, { rw add_comm, rw add_assoc, rw add_comm (-a) a, rw add_neg, rw add_zero, }, cases trichotomy (b + (-a)), { cases h with h1 h2, cases h2 with h2 h3, left, split, { rw less_than, split, exact ⟨h1, this⟩, }, split, { by_contra, rw h at h1, rw add_neg at h1, exact nontriviality h1, }, { by_contra, rw less_than at h, cases h with P h, cases h with h4 h5, rw ← this at h5, rw ← add_zero a at h5, rw add_assoc a 0 at h5, rw zero_add at h5, rw add_assoc at h5, have q := left_cancel h5, rw add_zero at q, rw add_comm at q, have q2 := move q, rw zero_add at q2, rw q2 at h4, apply h3, exact h4, }, }, cases h, { right, left, cases h with h1 h2, cases h2 with h2 h3, have h4 := move h2, rw neg_neg_a at h4, rw zero_add at h4, split, { by_contra, rw less_than at h, cases h with P h, cases h with h5 h6, rw h4 at h6, rw ← add_zero a at h6, rw add_assoc at h6, have q := left_cancel h6, rw zero_add at q, rw q at h5, exact nontriviality h5, }, split, { symmetry, exact h4, }, { by_contra, rw less_than at h, cases h with P h, cases h with h5 h6, rw h4 at h6, rw ← add_zero a at h6, rw add_assoc at h6, have q := left_cancel h6, rw zero_add at q, rw q at h5, exact nontriviality h5, }, }, { right, right, cases h with h1 h2, cases h2 with h2 h3, split, { by_contra, rw less_than at h, cases h with P h4, cases h4 with h4 h5, rw ← this at h5, have q := left_cancel h5, rw ← q at h1, apply h1, exact h4, }, split, { by_contra, apply h2, rw h, rw add_neg, }, { rw less_than, have that := move this, split, split, exact h3, symmetry, exact that, }, }, end /- P10 ∀a, b, x, y ∈ ℤ, a ≤ b and x ≤ y → a + x ≤ b + y and SALVAGE a ≤ b and x ≤ y and a, x ∈ P implies a * x ≤ b * y -/ theorem add_le_add: ∀{a b x y : O}, a ≤ b → x ≤ y → a + x ≤ b + y := begin intros a b x y ab xy, rw less_eq, rw less_eq at ab, rw less_eq at xy, rw less_than at ab, rw less_than at xy, rw less_than, cases ab, { cases xy, { left, cases ab with P1 ab, cases xy with P2 xy, cases ab with P1pos ab, cases xy with P2pos xy, have : a + x + (P1 + P2) = b + y, { rw add_assoc, rw ← add_assoc x, rw add_comm x, rw add_assoc, rw xy, rw ← add_assoc, rw ab, }, have that := pos_plus_pos P1pos P2pos, split, split, exact that, exact this, }, { left, cases ab with P ab, cases ab with Ppos ab, split, split, exact Ppos, rw xy, rw add_assoc, rw add_comm y, rw ← add_assoc, rw ab, }, }, { cases xy, { left, cases xy with P xy, cases xy with Ppos xy, split, split, exact Ppos, rw add_assoc, rw xy, rw ab, }, { right, rw xy, rw ab, }, }, end @[simp] theorem one_mul: ∀ (a :R), 1*a=a := begin intro a, rw mul_comm, exact mul_one a, end theorem no_lt_self: ∀ (a:O), ¬ (a <a) := begin intros a b, rw less_than at b, cases b, cases b_h, rw ← add_zero (a) at b_h_right, rw add_assoc at b_h_right, have := left_cancel b_h_right, rw zero_add at this, rw this at b_h_left, have := nontriviality, apply this, exact b_h_left, end theorem mul_le :∀ (a b c :O), is_positive c → a < b → a*c < b*c := begin intros a b c pc alb , rw less_than, rw less_than at alb, cases alb, cases alb_h, have := mul_right c alb_h_right, rw mul_comm at this, rw mul_add at this, split, { split, { -- cases alb_h, -- -- -- split, { exact pos_times_pos pc alb_h_left, -- -- }, -- sorry, }, rw mul_comm at this, exact this, -- cases alb_h, }, -- sorry, end theorem mul_le_mul : ∀{a b x y : O}, is_positive a → is_positive x → a ≤ b → x ≤ y → a * x ≤ b * y := begin intros a b x y ap xp ab xy, rw less_eq, rw less_eq at ab, rw less_eq at xy, rw less_than at ab, rw less_than at xy, rw less_than, cases ab, { cases xy, { left, cases ab with P1 ab, cases xy with P2 xy, cases ab with P1pos ab, cases xy with P2pos xy, have : x*a + x*P1+ (P2*a + P2*P1) = b*y, { rw ← ab, rw ← xy, rw mul_add, rw mul_comm (a + P1) x, rw mul_add, rw mul_comm (a + P1) P2, rw mul_add, }, have pp: is_positive (x*P1+ (P2*a + P2*P1)), { have q := pos_times_pos P2pos P1pos, have q2 := pos_times_pos P2pos ap, have q3 := pos_times_pos xp P1pos, have q4 := pos_plus_pos q2 q, exact pos_plus_pos q3 q4, }, split, split, exact pp, rw ← add_assoc, rw mul_comm a x, exact this, }, { left, cases ab with P ab, cases ab with Ppos ab, have := mul_right x ab, rw mul_comm at this, rw mul_add at this, have xppos := pos_times_pos xp Ppos, split, split, exact xppos, rw xy, rw xy at this, rw mul_comm, exact this, }, }, { cases xy, { left, cases xy with P xy, cases xy with Ppos xy, have := mul_right a xy, rw mul_comm at this, rw mul_add at this, have appos := pos_times_pos ap Ppos, split, split, exact appos, rw ← ab, rw mul_comm a y, exact this, }, { right, rw ab, rw xy, }, }, end theorem le_all: ∀(a :O), a ≤ a := begin intro a, rw less_eq, right, refl, end theorem mul_lt_mul : ∀{a b x y : O}, is_positive a → is_positive x → a < b → x < y → a * x < b * y := begin intros a b x y a_pos x_pos aleb xley, rw less_than at aleb, rw less_than at xley, rw less_than, rcases aleb with ⟨p1,p1pos, eq1 ⟩, rcases xley with ⟨p2,p2pos, eq2 ⟩, have eq3 : (a + p1)*(x+p2) = b*y := begin rw eq2, rw eq1, end, rw mul_add at eq3, rw mul_comm at eq3, rw mul_comm (a+p1) p2 at eq3, rw mul_add at eq3, rw mul_add at eq3, rw add_assoc at eq3, use x * p1 + p2 * a + p2 * p1, split, exact (pos_plus_pos (pos_plus_pos (pos_times_pos x_pos p1pos) (pos_times_pos p2pos a_pos)) (pos_times_pos p2pos p1pos)), rw mul_comm a x, rw add_assoc, exact eq3, end @[simp] theorem add_lt_add : ∀(a b x : O), a+x < b+x ↔ a < b := begin intros a b c, split,{ intro eq, rw less_than at eq, rcases eq with ⟨ w,x,y⟩, rw add_comm at y, rw ← add_assoc at y, simp at y, rw less_than, use w, rw add_comm, rw y, exact ⟨ x,refl b⟩, }, intro x, rw less_than, rw less_than at x, rcases x with ⟨f,g,h ⟩, use f, rw ← h, rw add_assoc a f c, rw add_comm f c, rw ← add_assoc, exact ⟨g, refl (a+c+f) ⟩, end /- If a is positive then it isn't zero -/ lemma pos_not_zero: ∀ {a : O}, is_positive a → a ≠ 0 := begin intros a b, by_contradiction, rw h at b, have := nontriviality, apply this, exact b, end /- modus tollens + demorgans law-/ lemma thing : ∀ {P Q R : Prop}, (¬ P ∧ ¬ Q → ¬ R) → (R → P ∨ Q) := begin intros P Q R pqr r, by_cases P, --classical logic left, exact h, by_cases Q, right, exact h, have : ¬P ∧ ¬Q, split ; assumption, have that := pqr this, exfalso, apply that, exact r, end @[simp] /- -0 = 0-/ lemma neg_zero : -(0 : R) = 0 := begin rw ← mul_neg_one, rw mul_zero, end @[simp] lemma sub_zero: ∀{a:R}, a-0=a := begin intros a, rw subtr a (0:R), rw neg_zero, rw add_zero, end @[simp] lemma sub_self: ∀{a:R}, a-a=0 := begin intros a, rw subtr a (a), exact add_neg a, end /- P6: SALVAGE: In an ordered myRing: ab = 0 → a = 0 or b = 0 we proved the contrapositive because it was easier and a constructive proof the lemma "thing" was used to recover the original version -/ lemma zero_or' : ∀(a b : O), a ≠ 0 ∧ b ≠ 0 → a *b ≠ (0:O) := begin intros a b c, cases c with d e, have ta := trichotomy a, have tb := trichotomy b, cases ta with s f, { cases tb with d g, { cases s with asd fsa, cases d with sdd asd, cases asd with fds awe, cases fsa with sdad qwe, exact pos_not_zero (pos_times_pos asd sdd), }, cases s with asd fdj, cases g with daskd weq, { cases daskd with das qwem, cases fdj with as xz, cases qwem with oasd we, exfalso, rw oasd at e, apply e, refl, }, { cases fdj with asds wqer, cases weq with asdd tewoirm, cases tewoirm with gfs qowi, have := pos_not_zero (pos_times_pos asd qowi), rw dist_neg_right at this, intro h, apply this, have that := mul_right (-1 : O) h, rw mul_comm at that, rw mul_neg_one at that, rw mul_comm (0 : O) (-1) at that, rw mul_zero at that, exact that, }, }, { cases f with w q, { cases w with junk w, cases w with w junk2, exfalso, apply d, exact w, }, { cases tb with tb1 tb2, { cases q with junk q, cases q with junk2 negapos, cases tb1 with bpos junk3, have := pos_not_zero (pos_times_pos negapos bpos), intro h, apply this, rw dist_neg_left, rw h, simp, }, cases tb2 with tb2 tb3, { cases tb2 with junk3 tb2, cases tb2 with tb2 junk4, exfalso, apply e, exact tb2, }, { cases q with junk q, cases q with junk2 negapos, cases tb3 with junk3 tb3, cases tb3 with junk4 negbpos, have := pos_not_zero (pos_times_pos negapos negbpos), rw dist_neg_both at this, exact this, }, }, }, end /- The actually useful version of the lemma -/ lemma zero_or : ∀{a b : O}, a *b= (0:O) → a=0 ∨ b=0:= begin intros a b, have x1:= zero_or' a b, have x2 := thing x1, exact x2, end /- P6: SALVAGE : In an ordered myRing you can cancel multiplication, in other words: if c ≠ 0 and a * c = b * c, then a = b -/ theorem mul_cancel : ∀{a b c : O}, a * c = b * c → c ≠ 0 → a = b:= begin intros a b c d cnotzero, have start : a * 0 = 0 := by exact mul_zero, rw ← add_neg c at start, rw mul_add at start, rw d at start, rw add_neg at start, rw dist_neg_right at start, rw ← dist_neg_left at start, rw mul_comm at start, rw mul_comm (-a) c at start, rw ← mul_add at start, have := zero_or start, cases this, { exfalso, apply cnotzero, exact this, }, { have that := move this, simp at that, symmetry, exact that, } end theorem pos_div_pos: ∀ (a b p: O ), is_positive a → is_positive b → a*p=b → is_positive p := begin intros a b p a_pos b_pos equ, -- rw divs at a_divs_b, -- cases a_divs_b with p equ, have p_pos : is_positive p, { by_contradiction, have trich := trichotomy p, cases trich, { cases trich,{ apply h, exact trich_left, }, }, cases trich, { cases trich, { cases trich_right, { rw trich_right_left at equ, rw mul_zero at equ, have x:=pos_not_zero b_pos, apply x, symmetry, exact equ, }, }, }, cases trich,{ cases trich_right,{ have pp := pos_times_pos a_pos trich_right_right, rw dist_neg_right at pp, rw equ at pp, have trichb := trichotomy b, cases trichb, { cases trichb, { cases trichb_right, { apply trichb_right_right, exact pp, }, }, }, cases trichb, { cases trichb, { apply trichb_left, exact b_pos, }, }, cases trichb ,{ apply trichb_left, exact b_pos, }, }, }, }, exact p_pos, end /- P5: Subtraction is associative: WRONG and UNSALVAGEABLE -/
/* multifit_nlinear/nielsen.c * * Copyright (C) 2016 Patrick Alken * * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * This module contains routines for updating the Levenberg-Marquardt * damping parameter on each iteration using Nielsen's method: * * [1] H. B. Nielsen, K. Madsen, Introduction to Optimization and * Data Fitting, Informatics and Mathematical Modeling, * Technical University of Denmark (DTU), 2010. * * 5 routines are needed to implement the update procedure: * * 1. accept - update parameter after a step has been accepted * 2. reject - update parameter after a step has been rejected * 3. free - free workspace state */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_multifit_nlinear.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_blas.h> #define LM_ONE_THIRD (0.333333333333333) static int nielsen_init(const gsl_matrix * J, const gsl_vector * diag, double * mu, long * nu); static int nielsen_accept(const double rho, double * mu, long * nu); static int nielsen_reject(double * mu, long * nu); static int nielsen_init(const gsl_matrix * J, const gsl_vector * diag, double * mu, long * nu) { const double mu0 = 1.0e-3; const size_t p = J->size2; size_t j; double max = -1.0; *nu = 2; /* set mu = mu0 * max(diag(J~^T J~)), with J~ = J D^{-1} */ for (j = 0; j < p; ++j) { gsl_vector_const_view v = gsl_matrix_const_column(J, j); double dj = gsl_vector_get(diag, j); double norm = gsl_blas_dnrm2(&v.vector) / dj; max = GSL_MAX(max, norm); } *mu = mu0 * max * max; return GSL_SUCCESS; } static int nielsen_accept(const double rho, double * mu, long * nu) { double b; /* reset nu */ *nu = 2; b = 2.0 * rho - 1.0; b = 1.0 - b*b*b; *mu *= GSL_MAX(LM_ONE_THIRD, b); return GSL_SUCCESS; } static int nielsen_reject(double * mu, long * nu) { *mu *= (double) *nu; /* nu := 2*nu */ *nu <<= 1; return GSL_SUCCESS; }
Require Import CodeProofDeps. Require Import Ident. Require Import Constants. Require Import RData. Require Import EventReplay. Require Import MoverTypes. Require Import CommonLib. Require Import AbsAccessor.Spec. Require Import RmiAux.Layer. Require Import RmiAux2.Code.rec_granule_measure. Require Import RmiAux2.LowSpecs.rec_granule_measure. Local Open Scope Z_scope. Section CodeProof. Context `{real_params: RealParams}. Context {memb} `{Hmemx: Mem.MemoryModelX memb}. Context `{Hmwd: UseMemWithData memb}. Let mem := mwd (cdata RData). Context `{Hstencil: Stencil}. Context `{make_program_ops: !MakeProgramOps Clight.function type Clight.fundef type}. Context `{Hmake_program: !MakeProgram Clight.function type Clight.fundef type}. Let L : compatlayer (cdata RData) := _measurement_extend_rec_header ↦ gensem measurement_extend_rec_header_spec ⊕ _measurement_extend_rec_regs ↦ gensem measurement_extend_rec_regs_spec ⊕ _measurement_extend_rec_pstate ↦ gensem measurement_extend_rec_pstate_spec ⊕ _measurement_extend_rec_sysregs ↦ gensem measurement_extend_rec_sysregs_spec . Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L. Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L. Section BodyProof. Context `{Hwb: WritableBlockOps}. Variable (sc: stencil). Variables (ge: genv) (STENCIL_MATCHES: stencil_matches sc ge). Variable b_measurement_extend_rec_header: block. Hypothesis h_measurement_extend_rec_header_s : Genv.find_symbol ge _measurement_extend_rec_header = Some b_measurement_extend_rec_header. Hypothesis h_measurement_extend_rec_header_p : Genv.find_funct_ptr ge b_measurement_extend_rec_header = Some (External (EF_external _measurement_extend_rec_header (signature_of_type (Tcons Tptr (Tcons Tptr Tnil)) tvoid cc_default)) (Tcons Tptr (Tcons Tptr Tnil)) tvoid cc_default). Local Opaque measurement_extend_rec_header_spec. Variable b_measurement_extend_rec_regs: block. Hypothesis h_measurement_extend_rec_regs_s : Genv.find_symbol ge _measurement_extend_rec_regs = Some b_measurement_extend_rec_regs. Hypothesis h_measurement_extend_rec_regs_p : Genv.find_funct_ptr ge b_measurement_extend_rec_regs = Some (External (EF_external _measurement_extend_rec_regs (signature_of_type (Tcons Tptr (Tcons Tptr Tnil)) tvoid cc_default)) (Tcons Tptr (Tcons Tptr Tnil)) tvoid cc_default). Local Opaque measurement_extend_rec_regs_spec. Variable b_measurement_extend_rec_pstate: block. Hypothesis h_measurement_extend_rec_pstate_s : Genv.find_symbol ge _measurement_extend_rec_pstate = Some b_measurement_extend_rec_pstate. Hypothesis h_measurement_extend_rec_pstate_p : Genv.find_funct_ptr ge b_measurement_extend_rec_pstate = Some (External (EF_external _measurement_extend_rec_pstate (signature_of_type (Tcons Tptr (Tcons Tptr Tnil)) tvoid cc_default)) (Tcons Tptr (Tcons Tptr Tnil)) tvoid cc_default). Local Opaque measurement_extend_rec_pstate_spec. Variable b_measurement_extend_rec_sysregs: block. Hypothesis h_measurement_extend_rec_sysregs_s : Genv.find_symbol ge _measurement_extend_rec_sysregs = Some b_measurement_extend_rec_sysregs. Hypothesis h_measurement_extend_rec_sysregs_p : Genv.find_funct_ptr ge b_measurement_extend_rec_sysregs = Some (External (EF_external _measurement_extend_rec_sysregs (signature_of_type (Tcons Tptr (Tcons Tptr Tnil)) tvoid cc_default)) (Tcons Tptr (Tcons Tptr Tnil)) tvoid cc_default). Local Opaque measurement_extend_rec_sysregs_spec. Lemma rec_granule_measure_body_correct: forall m d d' env le rd_base rd_offset rec_base rec_offset data_size (Henv: env = PTree.empty _) (Hinv: high_level_invariant d) (HPTrd: PTree.get _rd le = Some (Vptr rd_base (Int.repr rd_offset))) (HPTrec: PTree.get _rec le = Some (Vptr rec_base (Int.repr rec_offset))) (HPTdata_size: PTree.get _data_size le = Some (Vlong data_size)) (Hspec: rec_granule_measure_spec0 (rd_base, rd_offset) (rec_base, rec_offset) (VZ64 (Int64.unsigned data_size)) d = Some d'), exists le', (exec_stmt ge env le ((m, d): mem) rec_granule_measure_body E0 le' (m, d') Out_normal). Proof. solve_code_proof Hspec rec_granule_measure_body; eexists; solve_proof_low. Qed. End BodyProof. End CodeProof.
#pragma once #include <Windows.h> #include <cstdint> #include <string> #include <vector> #include <gsl/span> #include "hid_handle.h" namespace hid { struct HidOpenFlags { enum T : uint32_t { none, exclusive = 1u << 0u, async = 1u << 1u }; }; using HidOpenFlags_t = uint32_t; struct HidCaps { uint16_t usage; uint16_t usagePage; uint16_t inputReportSize; uint16_t outputReportSize; uint16_t featureReportSize; uint16_t linkCollectionNodes; uint16_t inputButtonCaps; uint16_t inputValueCaps; uint16_t inputDataIndices; uint16_t outputButtonCaps; uint16_t outputValueCaps; uint16_t outputDataIndices; uint16_t featureButtonCaps; uint16_t featureValueCaps; uint16_t featureDataIndices; }; struct HidAttributes { uint16_t vendorId; uint16_t productId; uint16_t versionNumber; }; class HidInstance { HidOpenFlags_t flags = 0; Handle handle = Handle(nullptr, true); HidCaps caps_ {}; HidAttributes attributes_ {}; OVERLAPPED overlappedIn = {}; OVERLAPPED overlappedOut = {}; bool pendingRead_ = false; bool pendingWrite_ = false; size_t nativeError_ = 0; public: std::wstring path; std::wstring instanceId; std::wstring serialString; std::vector<uint8_t> inputBuffer; std::vector<uint8_t> outputBuffer; HidInstance(const HidInstance&) = delete; HidInstance& operator=(const HidInstance&) = delete; HidInstance() = default; HidInstance(std::wstring path, std::wstring instanceId); explicit HidInstance(std::wstring path); HidInstance(HidInstance&& other) noexcept; ~HidInstance(); HidInstance& operator=(HidInstance&& other) noexcept; bool isOpen() const; bool isExclusive() const; bool isAsync() const; const HidCaps& caps() const; const HidAttributes& attributes() const; bool readMetadata(); bool readCaps(); bool readSerial(); bool readAttributes(); bool getFeature(const gsl::span<uint8_t>& buffer) const; bool setFeature(const gsl::span<uint8_t>& buffer) const; bool open(HidOpenFlags_t openFlags); void close(); inline auto nativeError() const { return nativeError_; } bool read(void* buffer, size_t size) const; bool read(const gsl::span<uint8_t>& buffer) const; bool read(); bool readAsync(); bool write(const void* buffer, size_t size) const; bool write(const gsl::span<const uint8_t>& buffer) const; bool write() const; bool writeAsync(); bool asyncReadPending() const; bool asyncReadInProgress(); bool asyncWritePending() const; bool asyncWriteInProgress(); void cancelAsyncReadAndWait(); void cancelAsyncWriteAndWait(); bool setOutputReport(const gsl::span<uint8_t>& buffer) const; bool setOutputReport(); private: void cancelAsyncAndWait(OVERLAPPED* overlapped); bool asyncInProgress(OVERLAPPED* overlapped); bool readCaps(HANDLE h); bool readSerial(HANDLE h); bool readAttributes(HANDLE h); }; }
State Before: α : Type u β : Type ?u.60077 w x y z : α inst✝ : BooleanAlgebra α ⊢ Disjoint x (yᶜ) ↔ x ≤ y State After: no goals Tactic: rw [← le_compl_iff_disjoint_right, compl_compl]
Require Import AB.Imp9. Require Import Coq.ZArith.ZArith. Require Import Coq.Lists.List. Open Scope Z. Module Polynomial. Import Assertion_D. (** Definitions of poly *) Definition poly := list Z. (* The power increases as the index goes up *) Definition ZERO : poly := nil. Definition CONSTANT : poly := 1::nil. Definition LINEAR : poly := 0::1::nil. Definition QUADRATIC : poly := 0::0::1::nil. Definition CUBIC : poly := 0::0::0::1::nil. (** [] *) (** Evaluations of polynomial *) Fixpoint poly_eval (p : poly) : Z -> Z := fun z => match p with | nil => 0 | h :: t => h + z * (poly_eval t z) end. Open Scope term_scope. Print aexp'. Fixpoint TPower (v : logical_var) (n : nat) : term := match n with | O => 1 | S n' => v * (TPower v n') end. Fixpoint poly_eval_lv (p : poly) : logical_var -> term := fun v => match p with | nil => 0 | h :: t => h + v * (poly_eval_lv t v) end. Close Scope term_scope. (** [] *) (** Operations of polynomial *) Fixpoint poly_add (p1 p2 : poly) : poly := match p1, p2 with | nil, nil => nil | h::t, nil => h::t | nil, h::t => h::t | h::t, h'::t' => (h+h')::(poly_add t t') end. Fixpoint trim_0 (p : poly) : poly := match p with | nil => nil | h :: t => match trim_0 t with | nil => if Z.eq_dec h 0 then nil else h :: nil | _ => h :: trim_0 t end end. Fixpoint poly_scalar_mult (k : Z) (p : poly) : poly := match p with | nil => nil | h :: t => k * h :: poly_scalar_mult k t end. Fixpoint poly_mult (p1 p2 : poly) : poly := match p1, p2 with | nil, _ => nil | _, nil => nil | h :: t, _ => poly_add (poly_scalar_mult h p2) (0 :: (poly_mult t p2)) end. Notation "p '+++' q" := (poly_add p q) (at level 60). Notation "k ** p" := (poly_scalar_mult k p) (at level 60). Notation "p '***' q" := (poly_mult p q) (at level 60). Section Examples. Example poly_add_eg : poly_eval ((CONSTANT +++ LINEAR) +++ (CONSTANT +++ QUADRATIC)) 2 = 8. Proof. simpl. reflexivity. Qed. Example poly_mult_eg : poly_eval ((CONSTANT +++ LINEAR) *** (CONSTANT +++ QUADRATIC)) 2 = 15. Proof. simpl. reflexivity. Qed. End Examples. (** [] *) (** Properties of Shorthand Notations *) Fact CONSTANT_spec : forall z, poly_eval CONSTANT z = 1. Proof. intros. simpl. rewrite Z.mul_0_r. reflexivity. Qed. Fact LINEAR_spec : forall z, poly_eval LINEAR z = z. Proof. intros. simpl. rewrite Z.mul_0_r. omega. Qed. Fact QUADRATIC_spec : forall z, poly_eval QUADRATIC z = z*z. Proof. intros. simpl. rewrite Z.mul_0_r. ring. Qed. Fact CUBIC_spec : forall z, poly_eval CUBIC z = z*z*z. Proof. intros. simpl. rewrite Z.mul_0_r. ring. Qed. (** [] *) (** Properties of Polynomial Operations *) Lemma poly_add_nil_l : forall p, poly_add nil p = p. Proof. intros. destruct p. - auto. - simpl. reflexivity. Qed. Lemma poly_add_nil_r : forall p, poly_add p nil = p. Proof. intros. destruct p. - auto. - simpl. reflexivity. Qed. Lemma poly_mult_nil_l : forall p, poly_mult nil p = nil. Proof. intros. simpl. reflexivity. Qed. Lemma poly_mult_nil_r : forall p, poly_mult p nil = nil. Proof. intros. destruct p; auto. Qed. Lemma poly_eval_zero: forall n z, poly_eval (repeat 0 n) z = 0. Proof. intros. induction n. - simpl. reflexivity. - simpl. rewrite IHn. omega. Qed. Theorem poly_add_spec : forall (p1 p2 : poly) (z : Z), poly_eval (poly_add p1 p2) z = poly_eval p1 z + poly_eval p2 z. Proof. intro. induction p1; intros. - rewrite poly_add_nil_l. simpl. reflexivity. - destruct p2. + simpl. omega. + simpl. rewrite IHp1. rewrite Z.mul_add_distr_l. omega. Qed. Theorem poly_scalar_mult_spec : forall (k : Z) (p : poly) (z : Z), poly_eval (poly_scalar_mult k p) z = k * poly_eval p z. Proof. intros. induction p. - simpl. rewrite Z.mul_0_r. reflexivity. - simpl. rewrite IHp. ring. Qed. Theorem poly_mult_spec : forall (p1 p2 : poly) (z : Z), poly_eval (poly_mult p1 p2) z = poly_eval p1 z * poly_eval p2 z. Proof. intro. induction p1; intros. - auto. - destruct p2. + simpl. rewrite Z.mul_0_r. reflexivity. + simpl. rewrite poly_add_spec. rewrite IHp1. rewrite poly_scalar_mult_spec. simpl. ring. Qed. Theorem trim_invar: forall p z, poly_eval (trim_0 p) z = poly_eval p z. Proof. intro. induction p; intros. - auto. - simpl. destruct (trim_0 p) eqn:eqp. + destruct (Z.eq_dec a 0) eqn:eqa; rewrite <- IHp; simpl; omega. + rewrite <- eqp in *. simpl. rewrite IHp. reflexivity. Qed. Lemma poly_eval_cons : forall (p: poly) (a z : Z), poly_eval (a :: p) z = a + z * (poly_eval p z). Proof. simpl. reflexivity. Qed. Lemma poly_eval_nil : forall (z : Z), poly_eval nil z = 0. Proof. intros. simpl. reflexivity. Qed. Lemma poly_eval_app : forall (p1 p2 : poly) (z : Z), poly_eval (p1 ++ p2) z = poly_eval p1 z + (z^(Z.of_nat (length p1))) * (poly_eval p2 z). Proof. intros. induction p1. - assert (Z.of_nat (Datatypes.length (nil:poly)) = 0). auto. rewrite app_nil_l. rewrite H. rewrite Z.pow_0_r. pose proof poly_eval_nil z. rewrite H0. omega. - rewrite <- app_comm_cons. pose proof poly_eval_cons (p1 ++ p2) a z. rewrite H. clear H. rewrite IHp1. rewrite Z.mul_add_distr_l. assert (z * (z ^ Z.of_nat (Datatypes.length p1)) = z ^ Z.of_nat (Datatypes.length (a :: p1))). { pose proof Z.pow_1_r z. rewrite <- H at 1. pose proof Z.pow_add_r z 1 (Z.of_nat (Datatypes.length p1)). assert (0 <= 1). omega. assert (0 <= Z.of_nat (Datatypes.length p1)). { clear IHp1 H H0 H1. induction p1. - simpl. omega. - simpl. apply Zle_0_pos. } pose proof H0 H1 H2. rewrite <- H3. assert (1 + Z.of_nat (Datatypes.length p1) = Z.of_nat (Datatypes.length (a :: p1))). { clear IHp1 H H0 H1 H2 H3. pose proof Nat2Z.inj_add 1 (length p1). assert (Z.of_nat 1 = 1). auto. rewrite <- H0. rewrite <- H. pose proof inj_eq (1 + (length p1)) (length (a::p1)). assert ((1 + Datatypes.length p1)%nat = Datatypes.length (a :: p1)). auto. omega. } rewrite H4. omega. } rewrite <- H. pose proof poly_eval_cons p1 a z. rewrite H0. rewrite Z.mul_assoc. omega. Qed. Lemma poly_eval_add_zero_l: forall (p : poly) n z, poly_eval (poly_add (repeat 0 n) p) z = poly_eval p z. Proof. intros. rewrite poly_add_spec. rewrite poly_eval_zero. omega. Qed. Lemma poly_eval_add_zero_r: forall (p : poly) n z, poly_eval (poly_add p (repeat 0 n)) z = poly_eval p z. Proof. intros. rewrite poly_add_spec. rewrite poly_eval_zero. omega. Qed. Lemma poly_add_comm: forall p1 p2, poly_add p1 p2 = poly_add p2 p1. Proof. intro. induction p1; intros. - rewrite poly_add_nil_l, poly_add_nil_r. reflexivity. - destruct p2. + auto. + simpl. rewrite IHp1. rewrite Z.add_comm. reflexivity. Qed. (** [] *) (* Dealing with the coef *) Fixpoint poly_coef_sum (p : poly) : Z := match p with | nil => 0 | h::t => h + (poly_coef_sum t) end. End Polynomial. Module Polynomial'. Export Polynomial. Import Assertion_D. Definition poly' := list Z. (* The power decreases as the index goes up *) (** Evaluations of polynomial' *) Fixpoint poly'_eval (p : poly') : Z -> Z := fun z => match p with | nil => 0 | h :: t => h * (Z.pow z (Z.of_nat (length t))) + (poly'_eval t z) end. (** Operations of polynomial *) Fixpoint poly'_add_body (l1 l2 : list Z) : list Z := match l1, l2 with | nil, nil => l2 | h::t, nil => h::t | nil, h::t => h::t | h::t, h'::t' => (h+h')::(poly'_add_body t t') end. Definition poly'_add (p1 p2 : poly') : poly' := rev (poly'_add_body (rev p1) (rev p2)). (** Properties of Polynomial Operations *) Lemma poly'_add_body_empty_r : forall l, poly'_add_body l nil = l. Proof. intros. destruct l. - auto. - simpl. reflexivity. Qed. Lemma poly'_add_empty_r : forall p, poly'_add p nil = p. Proof. intros. destruct p. - auto. - unfold poly'_add. rewrite poly'_add_body_empty_r. apply rev_involutive. Qed. Lemma poly'_add_body_empty_l : forall l, poly'_add_body nil l = l. Proof. intros. destruct l. - auto. - simpl. reflexivity. Qed. Lemma poly'_add_empty_l : forall p, poly'_add nil p = p. Proof. intros. destruct p. - auto. - unfold poly'_add. rewrite poly'_add_body_empty_l. apply rev_involutive. Qed. Lemma poly'_eval_0s: forall times n, poly'_eval (repeat 0 times) n = 0. Proof. intros. induction times. - simpl. reflexivity. - simpl. omega. Qed. Lemma poly'_cons_eval_comm : forall p z n, poly'_eval (cons z p) n = poly'_eval (cons z (repeat 0 (length p))) n + poly'_eval p n. Proof. intros. simpl. assert (Datatypes.length (repeat 0 (Datatypes.length p)) = Datatypes.length p). { induction p. - simpl. reflexivity. - simpl. rewrite IHp. reflexivity. } rewrite H. pose proof poly'_eval_0s (Datatypes.length p) n. rewrite H0. omega. Qed. Lemma poly'_app_eval_comm: forall p1 p2 n, poly'_eval (p1 ++ p2) n = poly'_eval (p1 ++ (repeat 0 (length p2))) n + poly'_eval p2 n. Proof. intros. induction p1. - simpl. pose proof app_nil_l p2. rewrite <- H. simpl. pose proof poly'_eval_0s (Datatypes.length p2) n. rewrite H0. omega. - pose proof poly'_cons_eval_comm. simpl. assert (Datatypes.length (p1 ++ repeat 0 (Datatypes.length p2)) = Datatypes.length (p1 ++ p2)). { clear IHp1 H. Search (length (_ ++ _)). assert (Datatypes.length (repeat 0%Z (Datatypes.length p2)) = Datatypes.length p2). { induction p2. - simpl. reflexivity. - simpl. rewrite IHp2. reflexivity. } pose proof app_length p1 p2. rewrite H0. pose proof app_length p1 (repeat 0 (Datatypes.length p2)). rewrite H1. rewrite H. omega. } rewrite H0. rewrite IHp1. omega. Qed. Lemma poly'_eval_repeat_length_p: forall a (p : poly') z, poly'_eval (a :: repeat 0 (length p)) z = a * z ^ (Z.of_nat (length p)). Proof. intros. simpl. pose proof poly'_eval_0s (length p) z. rewrite H. pose proof repeat_length 0 (length p). rewrite H0. omega. Qed. Theorem poly'_eval_poly_eval: forall (p : poly') n, poly'_eval p n = poly_eval (rev p) n. Proof. intros. induction p. - simpl. reflexivity. - simpl. pose proof poly_eval_app (rev p) (a::nil) n. rewrite H. simpl. clear H. rewrite IHp. pose proof rev_length p. rewrite H. assert (a + n * 0 = a). { omega. } rewrite H0. rewrite Z.mul_comm. omega. Qed. Theorem poly_eval_poly'_eval: forall (p : poly) n, poly_eval p n = poly'_eval (rev p) n. Proof. intros. pose proof poly'_eval_poly_eval (rev p) n. rewrite rev_involutive in H. omega. Qed. End Polynomial'. Module WZY_Poly_Enhance. Export Polynomial. Inductive list_le : poly -> poly -> Prop := | nil_le : list_le nil nil | cons_le : forall p1 p2 a1 a2, length p1 = length p2 -> a1 <= a2 -> list_le p1 p2 -> list_le (a1 :: p1) (a2 :: p2). End WZY_Poly_Enhance. Module Monomial. Export Polynomial. Export Polynomial'. Export WZY_Poly_Enhance. Fixpoint poly_get_last (p : poly) : Z := match p with | nil => 0 | a::nil => a | h::t => poly_get_last t end. Fact poly_app_nonnil: forall (p : poly) a, (p ++ a::nil) <> nil. Proof. intros. unfold not. intros. induction p. - inversion H; subst. - inversion H; subst. Qed. Fact poly_get_last_app: forall (p : poly) a, poly_get_last (p ++ a::nil) = a. Proof. intros. induction p. - simpl. reflexivity. - pose proof poly_app_nonnil p a. simpl. destruct (p ++ a ::nil). + unfold not in H. assert ((nil:poly) = (nil:poly)). { reflexivity. } pose proof H H0. destruct H1. + tauto. Qed. Fact poly_get_last_cons: forall (a h: Z) (t : poly), poly_get_last (a::h::t) = poly_get_last (h::t). Proof. intros. simpl. reflexivity. Qed. Fixpoint poly'_get_first (p : poly) : Z := match p with | nil => 0 | h::t => h end. Definition poly_monomialize (p : poly) : poly := match p with | nil => nil | _ :: _ => (repeat 0 ((length p) - 1)) ++ (poly_get_last p)::nil end. Definition poly'_monomialize (p : poly') : poly' := match p with | nil => nil | h :: _ => h::nil ++ (repeat 0 ((length p) - 1)) end. Example poly_mono_1: poly_monomialize (3::2::1::nil) = 0::0::1::nil. Proof. simpl. reflexivity. Qed. Example poly'_mono_1: poly'_monomialize (1::2::3::nil) = 1::0::0::nil. Proof. simpl. reflexivity. Qed. Lemma poly'_eval_mono: forall (p : poly') (n : Z), poly'_eval (poly'_monomialize p) n = (poly'_get_first p) * n^(Z.of_nat (length p) - 1). Proof. intros. induction p. - simpl. reflexivity. - assert (Datatypes.length p - 0 = Datatypes.length p)%nat. { omega. } assert (poly'_eval (poly'_monomialize (a :: p)) n = a * n ^ Z.of_nat (Datatypes.length (repeat 0 (Datatypes.length p - 0))) + poly'_eval (repeat 0 (Datatypes.length p - 0)) n). { simpl. reflexivity. } rewrite H0. clear H0. rewrite H. assert (Datatypes.length (repeat 0 (Datatypes.length p)) = Datatypes.length p). { clear IHp H. induction p. - simpl. reflexivity. - simpl. rewrite IHp. reflexivity. } rewrite H0. pose proof poly'_eval_0s (Datatypes.length p) n. rewrite H1. assert (poly'_get_first (a :: p) = a). { simpl. reflexivity. } rewrite H2. assert (Z.of_nat (Datatypes.length (a :: p)) - 1 = Z.of_nat (Datatypes.length p)). { assert (Datatypes.length (a :: p) = Datatypes.length p + 1)%nat. { simpl. omega. } rewrite H3. rewrite Nat2Z.inj_add. simpl. omega. } rewrite H3. omega. Qed. Lemma poly_mono_app_1 : forall (p : poly) a, poly_monomialize (p ++ a::nil) = (repeat 0 (length p)) ++ a::nil. Proof. intros. pose proof poly_app_nonnil p a. pose proof poly_get_last_app p a. assert (length (p ++ a::nil) = length p + 1)%nat. { clear H H0. induction p. - simpl. reflexivity. - simpl. rewrite IHp. reflexivity. } unfold poly_monomialize. destruct (p ++ a::nil). { unfold not in H. assert ((nil:poly) = (nil:poly)). { reflexivity. } pose proof H H2. destruct H3. } { rewrite H0. rewrite H1. assert (Datatypes.length p + 1 - 1 = Datatypes.length p)%nat. { omega. } rewrite H2. reflexivity. } Qed. Lemma poly'_mono_poly_mono : forall (p : poly') n, poly_eval (poly_monomialize (rev p)) n = poly'_eval (poly'_monomialize p) n. Proof. intros. induction p. - simpl. reflexivity. - simpl. assert (Datatypes.length p - 0 = Datatypes.length p)%nat. { omega. } rewrite H. assert (Datatypes.length (repeat 0 (Datatypes.length p)) = Datatypes.length p). { clear IHp H. induction p. - simpl. reflexivity. - simpl. rewrite IHp. reflexivity. } rewrite H0. pose proof poly'_eval_0s (Datatypes.length p) n. rewrite H1. pose proof poly_mono_app_1 (rev p) a. rewrite H2. rewrite rev_length. { clear IHp H H0 H1 H2. induction p. - simpl. omega. - simpl. rewrite IHp. assert (n * (a * n ^ Z.of_nat (Datatypes.length p) + 0) = a * n * n ^ Z.of_nat (Datatypes.length p)). { simpl. ring. } rewrite H. pose proof Z.pow_1_r n. rewrite <- H0 at 1. clear H0. pose proof Z.pow_add_r n 1 (Z.of_nat (Datatypes.length p)). assert (0 <= 1). { omega. } assert ( 0 <= Z.of_nat (Datatypes.length p)). { omega. } pose proof H0 H1 H2. assert (a * n ^ 1 * n ^ Z.of_nat (Datatypes.length p) = a * n ^ (1 + Z.of_nat (Datatypes.length p))). { rewrite H3. rewrite Z.mul_assoc. reflexivity. } rewrite H4. clear H4. pose proof Zpos_P_of_succ_nat (Datatypes.length p). rewrite Z.pow_pos_fold. rewrite H4. assert (1 + Z.of_nat (Datatypes.length p) = Z.succ (Z.of_nat (Datatypes.length p))). { rewrite <- Z.add_1_r. rewrite Z.add_comm. reflexivity. } rewrite H5. omega. } Qed. Lemma poly_mono_poly'_mono : forall (p : poly) n, poly_eval (poly_monomialize p) n = poly'_eval (poly'_monomialize (rev p)) n. Proof. intros. pose proof poly'_mono_poly_mono (rev p) n. rewrite rev_involutive in H. tauto. Qed. Lemma poly'_last_poly_first: forall (p : poly'), poly_get_last (rev p) = poly'_get_first p. Proof. intros. induction p. - simpl. reflexivity. - simpl. pose proof poly_get_last_app (rev p) a. tauto. Qed. Lemma poly_last_poly'_first: forall (p : poly), poly_get_last p = poly'_get_first (rev p). Proof. intros. pose proof poly'_last_poly_first (rev p). rewrite rev_involutive in H. tauto. Qed. Lemma poly_eval_mono: forall (p : poly) (n : Z), poly_eval (poly_monomialize p) n = (poly_get_last p) * n^(Z.of_nat (length p) - 1). Proof. intros. pose proof poly_mono_poly'_mono p n. rewrite H. pose proof poly_last_poly'_first p. rewrite H0. rewrite <- rev_length. pose proof poly'_eval_mono (rev p) n. tauto. Qed. Fixpoint poly_get_max (p : poly) (d : Z) : Z := match p with | nil => d | b::t => poly_get_max t (Z.max b d) end. Lemma poly_get_max1: forall (p : poly), forall z, z <= poly_get_max p z. Proof. induction p; intros. - simpl. reflexivity. - simpl. specialize (IHp (Z.max a z)). assert (z <= Z.max a z). { apply Z.le_max_r. } pose proof Z.le_trans _ _ _ H IHp. tauto. Qed. Lemma poly_get_max2: forall (p : poly) z1 z2, z1 <= z2 -> poly_get_max p z1 <= poly_get_max p z2. Proof. induction p; intros. - simpl. tauto. - simpl. assert ( a <= z1 \/ z1 < a). { omega. } destruct H0. + pose proof Z.max_l _ _ H0. rewrite Z.max_comm in H1. rewrite H1. pose proof Z.le_trans _ _ _ H0 H. pose proof Z.max_l _ _ H2. rewrite Z.max_comm in H3. rewrite H3. specialize (IHp z1 z2). tauto. + apply Z.lt_le_incl in H0. pose proof Z.max_l _ _ H0. rewrite H1. assert ( a <= z2 \/ z2 < a). { omega. } destruct H2. * pose proof Z.max_l _ _ H2. rewrite Z.max_comm in H3. rewrite H3. pose proof IHp a z2 H2. tauto. * apply Z.lt_le_incl in H2. pose proof Z.max_l _ _ H2. rewrite H3. pose proof IHp a a. pose proof Z.le_refl a. tauto. Qed. Lemma poly_get_max3: forall (p : poly), forall z, In z p -> z <= poly_get_max p 0. Proof. induction p; intros. - simpl. inversion H. - simpl. assert (z <= 0 \/ z > 0). { omega. } destruct H0. + pose proof poly_get_max1 p 0. pose proof poly_get_max2 p 0 (Z.max a 0). pose proof Z.le_max_r a 0. pose proof H2 H3. pose proof Z.le_trans _ _ _ H0 H1. pose proof Z.le_trans _ _ _ H5 H4. tauto. + inversion H; subst. * pose proof poly_get_max1 p z. pose proof poly_get_max2 p z (Z.max z 0). pose proof Z.le_max_l z 0. pose proof H2 H3. pose proof Z.le_trans _ _ _ H1 H4. tauto. * specialize (IHp z). pose proof IHp H1. pose proof poly_get_max2 p 0 (Z.max a 0). pose proof Z.le_max_r a 0. pose proof H3 H4. pose proof Z.le_trans _ _ _ H2 H5. tauto. Qed. Lemma rev_nil : forall (l : list Z), nil = rev l -> l = nil. Proof. intros. destruct l. - auto. - assert (length (rev (z :: l)) = length (rev (z :: l))). auto. rewrite <- H in H0 at 1. simpl in H0. rewrite app_length in H0. simpl in H0. rewrite Nat.add_1_r in H0. inversion H0. Qed. Lemma non_empty_list : forall (l : list Z), l <> nil -> exists l' a, l = l' ++ a :: nil. Proof. intros. remember (rev l) as rl. destruct rl. - apply rev_nil in Heqrl. congruence. - assert (rev (z :: rl) = rev (rev l)). rewrite Heqrl. reflexivity. simpl in H0. rewrite rev_involutive in H0. exists (rev rl), z. auto. Qed. Lemma poly_get_last_spec : forall l a, poly_get_last (l ++ a :: nil) = a. Proof. intros. induction l. - auto. - simpl. destruct (l ++ a :: nil) eqn:eq. + assert (length (l ++ a :: nil) = length (l ++ a :: nil)); auto. rewrite eq in H at 1. simpl in H. rewrite app_length in H. simpl in H. rewrite Nat.add_1_r in H. inversion H. + auto. Qed. Fact poly_get_last_in_poly: forall p, p <> nil -> In (poly_get_last p) p. Proof. intros. apply non_empty_list in H as [l' [a ?]]. rewrite H at 1. rewrite poly_get_last_spec, H. rewrite in_app_iff. right. simpl. left. auto. Qed. Lemma poly_distr_coef_compare: forall K (N : nat) n, K > 0 -> n > 0 -> poly_eval ((repeat 0 (Z.to_nat (Z.of_nat N-1))) ++ (K * Z.of_nat N)::nil) n >= poly_eval (repeat K N) n. Proof. assert (forall N:nat, (Datatypes.length (repeat 0 N)) = N) as lem_repeat. { intros. simpl. induction N. - simpl. reflexivity. - simpl. rewrite IHN. reflexivity. } intros. induction N. - simpl. omega. - pose proof poly_eval_app (repeat 0 (Z.to_nat (Z.of_nat (S N) - 1))) (K * Z.of_nat (S N) :: nil) n. rewrite H1. pose proof poly_eval_zero (Z.to_nat (Z.of_nat (S N) - 1)). rewrite H2. pose proof lem_repeat (Z.to_nat (Z.of_nat (S N) - 1))%nat. rewrite H3. pose proof Z2Nat.id (Z.of_nat (S N) - 1). assert (0 <= Z.of_nat (S N) - 1). { clear IHN H1 H2 H3 H4. induction N. - simpl. omega. - pose proof Nat2Z.inj_succ (S N). rewrite H1. pose proof Z.le_succ_diag_r (Z.of_nat (S N)). omega. } pose proof H4 H5. rewrite H6. assert (poly_eval (K * Z.of_nat (S N) :: nil) n = K * Z.of_nat (S N)). { simpl. omega. } rewrite H7. rewrite Z.add_0_l. assert (S N = N + 1)%nat. { omega. } rewrite H8. assert (Z.of_nat (N + 1) - 1 = Z.of_nat N). { pose proof Nat2Z.inj_sub (N+1) 1. assert (1 <= N + 1)%nat. omega. pose proof H9 H10. simpl in H11. assert (N+1-1=N)%nat. omega. rewrite H12 in H11. omega. } rewrite H9. clear H1 H2 H3 H4 H5 H6 H7 H8 H9. pose proof poly_eval_app (repeat 0 (Z.to_nat (Z.of_nat N - 1))) (K * Z.of_nat N :: nil) n. rewrite H1 in IHN. pose proof poly_eval_zero (Z.to_nat (Z.of_nat N - 1)) n. rewrite H2 in IHN. pose proof lem_repeat (Z.to_nat (Z.of_nat N - 1))%nat. rewrite H3 in IHN. assert (poly_eval (K * Z.of_nat N :: nil) n = K * Z.of_nat N). { simpl. omega. } rewrite H4 in IHN. rewrite Z.add_0_l in IHN. assert (Z.to_nat (Z.of_nat N - 1) = N - 1)%nat. { pose proof Nat2Z.id N. pose proof Z2Nat.inj_sub (Z.of_nat N) 1. assert (0<=1). omega. pose proof H6 H7. rewrite H5 in H8. assert (Z.to_nat 1 = 1)%nat. { simpl. apply Pos2Nat.inj_1. } rewrite H9 in H8. exact H8. } rewrite H5 in IHN. clear H1 H2 H3 H4 H5. assert (poly_eval (repeat K (N + 1)) n = K * n ^ (Z.of_nat N) + poly_eval (repeat K N) n). { clear IHN. induction N. - simpl. omega. - assert (poly_eval (repeat K (S N + 1)) n = K + n * poly_eval (repeat K (S N)) n). { clear IHN. simpl. induction N. - simpl. omega. - simpl. rewrite IHN. omega. } rewrite H1. assert (S N = N + 1)%nat. omega. rewrite <- H2 in IHN. rewrite IHN at 1. rewrite Z.mul_add_distr_l. assert (n * (K * n ^ Z.of_nat N) = K * n ^ (Z.of_nat (S N))). { rewrite Z.mul_assoc. rewrite Z.mul_shuffle0. pose proof Z.pow_1_r n. rewrite <- H3 at 1. pose proof Z.pow_add_r n 1 (Z.of_nat N). assert (0 <= 1). { omega. } assert (0 <= Z.of_nat N). { omega. } pose proof H4 H5 H6. rewrite <- H7. assert (Z.of_nat (S N) = 1 + Z.of_nat N). { pose proof Nat2Z.inj_add 1 N. assert (1 + N = S N)%nat. { omega. } assert (1 = Z.of_nat 1). { simpl. omega. } rewrite H9 in H8. rewrite <- H10 in H8. tauto. } rewrite <- H8. rewrite Z.mul_comm. omega. } rewrite H3. rewrite Z.add_assoc. assert (K + K * n ^ Z.of_nat (S N) + n * poly_eval (repeat K N) n = K * n ^ Z.of_nat (S N) + (K + n * poly_eval (repeat K N) n)). { omega. } rewrite H4. assert (K + n * poly_eval (repeat K N) n = poly_eval (repeat K (S N)) n). { simpl. omega. } rewrite H5. omega. } rewrite H1. assert (n ^ Z.of_nat N * (K * Z.of_nat (N + 1)) >= n ^ Z.of_nat (N - 1) * (K * Z.of_nat N) + K * n ^ Z.of_nat N). { clear H1. assert (Z.of_nat (N + 1) = Z.of_nat N + 1). { pose proof Nat2Z.inj_add N 1. simpl in H1. tauto. } rewrite H1. rewrite Z.mul_add_distr_l. rewrite Z.mul_add_distr_l. assert (n >= 1). { omega. } assert (n ^ Z.of_nat N >= n ^ Z.of_nat (N - 1)). { clear IHN H1. induction N. - simpl. omega. - assert (n ^ Z.of_nat (S N) = n * n ^ Z.of_nat N). { assert (S N = N + 1)%nat. omega. rewrite H1. clear H1. assert (Z.of_nat (N + 1) = Z.of_nat N + 1). { pose proof Nat2Z.inj_add N 1. simpl in H1. tauto. } rewrite H1. clear H1. pose proof Z.pow_add_r n (Z.of_nat N) 1. assert (0 <= Z.of_nat N). omega. assert (0 <= 1). omega. pose proof H1 H3 H4. rewrite H5. rewrite Z.pow_1_r. rewrite Z.mul_comm. reflexivity. } rewrite H1. assert (S N - 1 = N)%nat. omega. rewrite H3. pose proof Z.le_mul_diag_r (n ^ Z.of_nat N) n. assert (0 < n ^ Z.of_nat N). { apply Z.pow_pos_nonneg. omega. omega. } assert (1<=n). omega. pose proof H4 H5. apply H7 in H6. rewrite Z.mul_comm in H6. omega. } assert (n ^ Z.of_nat N * (K * 1) = K * n ^ Z.of_nat N). { ring. } rewrite H4. apply Z.le_ge. pose proof Zplus_le_compat_r (n ^ Z.of_nat (N - 1) * (K * Z.of_nat N)) (n ^ Z.of_nat N * (K * Z.of_nat N)) (K * n ^ Z.of_nat N). assert (n ^ Z.of_nat (N - 1) * (K * Z.of_nat N) <= n ^ Z.of_nat N * (K * Z.of_nat N)). { clear H5. pose proof Z.mul_le_mono_nonneg_r (n ^ Z.of_nat (N - 1)) (n ^ Z.of_nat N) (K * Z.of_nat N). assert (0 <= K * Z.of_nat N ). pose proof Z.mul_nonneg_nonneg K (Z.of_nat N). assert (0<=K). omega. pose proof H6 H7. assert (0<=Z.of_nat N). omega. pose proof H8 H9. exact H10. pose proof H5 H6. assert (n ^ Z.of_nat (N - 1) <= n ^ Z.of_nat N). omega. tauto. } pose proof H5 H6. tauto. } assert (n ^ Z.of_nat (N - 1) * (K * Z.of_nat N) + K * n ^ Z.of_nat N >= K * n ^ Z.of_nat N + poly_eval (repeat K N) n). { apply Z.le_ge. pose proof Zplus_le_compat_l (poly_eval (repeat K N) n) (n ^ Z.of_nat (N - 1) * (K * Z.of_nat N)) (K * n ^ Z.of_nat N). apply Z.ge_le in IHN. pose proof H3 IHN. omega. } omega. Qed. Fact poly_mono_cons: forall a h t, poly_monomialize (a :: h :: t) = 0 :: poly_monomialize (h :: t). Proof. intros. simpl. assert (Datatypes.length t - 0 = Datatypes.length t)%nat. omega. rewrite H. reflexivity. Qed. Fact poly_mono_length_invar: forall p : poly, length p = length (poly_monomialize p). Proof. intros. induction p. - simpl. omega. - destruct p. + simpl. reflexivity. + pose proof poly_mono_cons a z p. rewrite H. assert (Datatypes.length (a :: z :: p) = 1 + Datatypes.length (z :: p))%nat. { simpl. omega. } assert (Datatypes.length (0 :: poly_monomialize (z :: p)) = plus 1 (Datatypes.length (poly_monomialize (z :: p)))). { simpl. reflexivity. } rewrite H0. rewrite H1. f_equal. omega. Qed. Definition term_by_term_le := list_le. Lemma poly_each_coef_compare: forall p1 p2, length p1 = length p2 -> term_by_term_le p1 p2 -> forall n, 0 <= n -> poly_eval p1 n <= poly_eval p2 n. Proof. intros. induction H0. - omega. - simpl. pose proof IHlist_le H0. apply Z.add_le_mono; auto. apply Z.mul_le_mono_nonneg_l; auto. Qed. End Monomial. Module Polynomial_Asympotitic_Bound. Export Polynomial. Export Monomial. Import Assertion_D. Inductive AsymptoticBound : Type := | BigO : poly -> logical_var -> AsymptoticBound | BigOmega : poly -> logical_var -> AsymptoticBound | BigTheta : poly -> logical_var -> AsymptoticBound. (* Convert asymtotic bounds to corresponding inequalities. We do not consider input with nonpositive size *) Definition ab_eval (La : Lassn) (T : AsymptoticBound) (a1 a2 t : Z) : Prop := match T with | BigO p n => 0 < La n -> 0 <= t <= a2 * (poly_eval p (La n)) | BigOmega p n => 0 < La n -> 0 <= a1 * (poly_eval p (La n)) <= t | BigTheta p n => 0 < La n -> 0 <= a1 * (poly_eval p (La n)) <= t /\ t <= a2 * (poly_eval p (La n)) end. Reserved Notation "T1 '=<' T2" (at level 50, no associativity). (* loosen relationship defines equivalence between bounds *) Inductive loosen : AsymptoticBound -> AsymptoticBound -> Prop := (* If time is bounded by Theta, it is bounded by O and Omega *) | Theta2Omega : forall p n, 0 < poly_get_last p -> BigTheta p n =< BigOmega p n | Theta2O : forall p n, 0 < poly_get_last p -> BigTheta p n =< BigO p n (* We can relax the bound to a monomial with the same highest order term *) | O_Poly2Mono : forall p n, 0 < poly_get_last p -> BigO p n =< BigO (poly_monomialize p) n (* TODO: a monomial should also be able to be relaxed to polynomial with same highest order, but we did not have time to prove its soundness, thus it is not included yet *) (* Multiplying positive constant to a bound can obtain another valid bound *) | O_const : forall p a b n, 0 < a -> 0 < b -> 0 < poly_get_last p -> BigO (a ** p) n =< BigO (b ** p) n (* A polynomial can have different forms, if they always evaulate to the same value, then bounds defined by them are equivalent *) | O_id : forall p1 p2 n, (forall z, poly_eval p1 z = poly_eval p2 z) -> BigO p1 n =< BigO p2 n | Theta_id : forall p1 p2 n, (forall z, poly_eval p1 z = poly_eval p2 z) -> BigTheta p1 n =< BigTheta p2 n | Omega_id : forall p1 p2 n, (forall z, poly_eval p1 z = poly_eval p2 z) -> BigOmega p1 n =< BigOmega p2 n where "T1 '=<' T2" := (loosen T1 T2). End Polynomial_Asympotitic_Bound.
Formal statement is: lemma degree_mult_le: "degree (p * q) \<le> degree p + degree q" Informal statement is: The degree of a product of two polynomials is less than or equal to the sum of the degrees of the two polynomials.
[STATEMENT] lemma fbox_while_var2: "ad t \<cdot> |while t do x od] p \<le> d p" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ad t \<cdot> |while t do x od] p \<le> d p [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. ad t \<cdot> |while t do x od] p \<le> d p [PROOF STEP] have "ad t \<cdot> |while t do x od] p = ad t \<cdot> (d t + d p) \<cdot> (ad t + |x] |while t do x od] p)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ad t \<cdot> |while t do x od] p = ad t \<cdot> (d t + d p) \<cdot> (ad t + |x] |while t do x od] p) [PROOF STEP] by (metis fbox_while_unfold ds.ddual.mult_assoc) [PROOF STATE] proof (state) this: ad t \<cdot> |while t do x od] p = ad t \<cdot> (d t + d p) \<cdot> (ad t + |x] |while t do x od] p) goal (1 subgoal): 1. ad t \<cdot> |while t do x od] p \<le> d p [PROOF STEP] also [PROOF STATE] proof (state) this: ad t \<cdot> |while t do x od] p = ad t \<cdot> (d t + d p) \<cdot> (ad t + |x] |while t do x od] p) goal (1 subgoal): 1. ad t \<cdot> |while t do x od] p \<le> d p [PROOF STEP] have "... = ad t \<cdot> d p \<cdot> (ad t + |x] |while t do x od] p)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ad t \<cdot> (d t + d p) \<cdot> (ad t + |x] |while t do x od] p) = ad t \<cdot> d p \<cdot> (ad t + |x] |while t do x od] p) [PROOF STEP] by (metis a_de_morgan_var_3 addual.ars_r_def dka.dom_add_closed s4) [PROOF STATE] proof (state) this: ad t \<cdot> (d t + d p) \<cdot> (ad t + |x] |while t do x od] p) = ad t \<cdot> d p \<cdot> (ad t + |x] |while t do x od] p) goal (1 subgoal): 1. ad t \<cdot> |while t do x od] p \<le> d p [PROOF STEP] also [PROOF STATE] proof (state) this: ad t \<cdot> (d t + d p) \<cdot> (ad t + |x] |while t do x od] p) = ad t \<cdot> d p \<cdot> (ad t + |x] |while t do x od] p) goal (1 subgoal): 1. ad t \<cdot> |while t do x od] p \<le> d p [PROOF STEP] have "... \<le> d p \<cdot> (ad t + |x] |while t do x od] p)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ad t \<cdot> d p \<cdot> (ad t + |x] |while t do x od] p) \<le> d p \<cdot> (ad t + |x] |while t do x od] p) [PROOF STEP] using a_subid_aux1' mult_isor [PROOF STATE] proof (prove) using this: ad ?x \<cdot> ?y \<le> ?y ?x \<le> ?y \<Longrightarrow> ?x \<cdot> ?z \<le> ?y \<cdot> ?z goal (1 subgoal): 1. ad t \<cdot> d p \<cdot> (ad t + |x] |while t do x od] p) \<le> d p \<cdot> (ad t + |x] |while t do x od] p) [PROOF STEP] by blast [PROOF STATE] proof (state) this: ad t \<cdot> d p \<cdot> (ad t + |x] |while t do x od] p) \<le> d p \<cdot> (ad t + |x] |while t do x od] p) goal (1 subgoal): 1. ad t \<cdot> |while t do x od] p \<le> d p [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: ad t \<cdot> |while t do x od] p \<le> d p \<cdot> (ad t + |x] |while t do x od] p) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: ad t \<cdot> |while t do x od] p \<le> d p \<cdot> (ad t + |x] |while t do x od] p) goal (1 subgoal): 1. ad t \<cdot> |while t do x od] p \<le> d p [PROOF STEP] by (metis a_de_morgan_var_3 a_mult_idem addual.ars_r_def ans4 dka.dsr5 dpdz.domain_1'' dual_order.trans fbox_def) [PROOF STATE] proof (state) this: ad t \<cdot> |while t do x od] p \<le> d p goal: No subgoals! [PROOF STEP] qed
[STATEMENT] lemma term_to_nterm_mono: "mono_state (term_to_nterm \<Gamma> x)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. mono_state (term_to_nterm \<Gamma> x) [PROOF STEP] by (induction \<Gamma> x rule: term_to_nterm.induct) (auto intro: bind_mono_strong)
\documentclass[dvipdfmx,<%= documentoptions.join(',') %>]{<%= documentclass %>} \usepackage{graphicx} \usepackage{listings} \usepackage{datetime} % List \usepackage{enumitem} \renewcommand{\labelitemi}{$\bullet$} \renewcommand{\labelitemii}{$\circ$} \renewcommand{\labelitemiii}{$\bullet$} \renewcommand{\labelitemiv}{$\circ$} %% Font Config \usepackage[deluxe]{otf} \usepackage[noalphabet,<%= fontpreset %>]{pxchfon} \usepackage[prefernoncjk]{pxcjkcat} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{textcomp} \usepackage{lmodern} \usepackage{fix-cm} \cjkcategory{sym18}{cjk} \cjkcategory{sym19}{cjk} %% Cites \usepackage{cite} \makeatletter \def\NAT@parse{\typeout{}} \makeatother %% Margin Config \usepackage[dvipdfm,top=10zw,bottom=12zw,left=10zw,right=10zw]{geometry} \newcommand{\parasep}{\vspace*{3zh}} \setlength{\footskip}{30pt} \renewcommand{\baselinestretch}{1.25} \sloppy %% Link Config \PassOptionsToPackage{hyphens}{url} \usepackage[bookmarks=true,bookmarksnumbered=true,colorlinks=true,pdfusetitle=true]{hyperref} \usepackage{pxjahyper} \hypersetup{ linkcolor=black, citecolor=black, filecolor=black, urlcolor=black, anchorcolor=black } %% Header Config \usepackage{fancyhdr} \pagestyle{fancy} \lhead{\gtfamily\sffamily\bfseries\upshape \leftmark} \chead{} \rhead{\gtfamily\sffamily\bfseries\upshape \rightmark} \fancyfoot[CE,CO]{\thepage} \fancypagestyle{plainhead}{% \fancyhead{} \renewcommand{\headrulewidth}{0pt} \renewcommand{\footrulewidth}{0pt}} \renewcommand{\sfdefault}{phv} %% Set date \year<%= date.year %> \relax \month<%= date.month %> \relax %% Document Config \title{<%= title.en %>} \author{<%= authors.map((author) => author.en).join(' \\and ') %>} \date{\shortmonthname.~\the\year} \begin{document} \maketitle \chapter*{Abstract} \thispagestyle{empty} \input{dist/abstract} \newpage \frontmatter \setcounter{tocdepth}{2} \tableofcontents \mainmatter <%- body %> \backmatter %% Bibliography \bibliographystyle{junsrt} \bibliography{bibs/index} \end{document}
[STATEMENT] lemma tensor_mat_positive_le: assumes "m1 \<in> carrier_mat d1 d1" and "m2 \<in> carrier_mat d2 d2" and "positive m1" and "positive m2" and "m1 \<le>\<^sub>L A" and "m2 \<le>\<^sub>L B" shows "tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B" [PROOF STATE] proof (prove) goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] have dA: "A \<in> carrier_mat d1 d1" [PROOF STATE] proof (prove) goal (1 subgoal): 1. A \<in> carrier_mat d1 d1 [PROOF STEP] using assms lowner_le_def [PROOF STATE] proof (prove) using this: m1 \<in> carrier_mat d1 d1 m2 \<in> carrier_mat d2 d2 positive m1 positive m2 m1 \<le>\<^sub>L A m2 \<le>\<^sub>L B (?A \<le>\<^sub>L ?B) = (dim_row ?A = dim_row ?B \<and> dim_col ?A = dim_col ?B \<and> positive (?B - ?A)) goal (1 subgoal): 1. A \<in> carrier_mat d1 d1 [PROOF STEP] by auto [PROOF STATE] proof (state) this: A \<in> carrier_mat d1 d1 goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] have pA: "positive A" [PROOF STATE] proof (prove) goal (1 subgoal): 1. positive A [PROOF STEP] using assms dA lowner_le_trans_positiveI[of m1] [PROOF STATE] proof (prove) using this: m1 \<in> carrier_mat d1 d1 m2 \<in> carrier_mat d2 d2 positive m1 positive m2 m1 \<le>\<^sub>L A m2 \<le>\<^sub>L B A \<in> carrier_mat d1 d1 \<lbrakk>m1 \<in> carrier_mat ?n ?n; positive m1; m1 \<le>\<^sub>L ?B\<rbrakk> \<Longrightarrow> positive ?B goal (1 subgoal): 1. positive A [PROOF STEP] by auto [PROOF STATE] proof (state) this: positive A goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] have dB: "B \<in> carrier_mat d2 d2" [PROOF STATE] proof (prove) goal (1 subgoal): 1. B \<in> carrier_mat d2 d2 [PROOF STEP] using assms lowner_le_def [PROOF STATE] proof (prove) using this: m1 \<in> carrier_mat d1 d1 m2 \<in> carrier_mat d2 d2 positive m1 positive m2 m1 \<le>\<^sub>L A m2 \<le>\<^sub>L B (?A \<le>\<^sub>L ?B) = (dim_row ?A = dim_row ?B \<and> dim_col ?A = dim_col ?B \<and> positive (?B - ?A)) goal (1 subgoal): 1. B \<in> carrier_mat d2 d2 [PROOF STEP] by auto [PROOF STATE] proof (state) this: B \<in> carrier_mat d2 d2 goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] have pB: "positive B" [PROOF STATE] proof (prove) goal (1 subgoal): 1. positive B [PROOF STEP] using assms dB lowner_le_trans_positiveI[of m2] [PROOF STATE] proof (prove) using this: m1 \<in> carrier_mat d1 d1 m2 \<in> carrier_mat d2 d2 positive m1 positive m2 m1 \<le>\<^sub>L A m2 \<le>\<^sub>L B B \<in> carrier_mat d2 d2 \<lbrakk>m2 \<in> carrier_mat ?n ?n; positive m2; m2 \<le>\<^sub>L ?B\<rbrakk> \<Longrightarrow> positive ?B goal (1 subgoal): 1. positive B [PROOF STEP] by auto [PROOF STATE] proof (state) this: positive B goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] have "A - m1 = A + (- m1)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. A - m1 = A + - m1 [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: m1 \<in> carrier_mat d1 d1 m2 \<in> carrier_mat d2 d2 positive m1 positive m2 m1 \<le>\<^sub>L A m2 \<le>\<^sub>L B goal (1 subgoal): 1. A - m1 = A + - m1 [PROOF STEP] by (auto simp add: minus_add_uminus_mat) [PROOF STATE] proof (state) this: A - m1 = A + - m1 goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] then [PROOF STATE] proof (chain) picking this: A - m1 = A + - m1 [PROOF STEP] have "positive (A + (- m1))" [PROOF STATE] proof (prove) using this: A - m1 = A + - m1 goal (1 subgoal): 1. positive (A + - m1) [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: A - m1 = A + - m1 m1 \<in> carrier_mat d1 d1 m2 \<in> carrier_mat d2 d2 positive m1 positive m2 m1 \<le>\<^sub>L A m2 \<le>\<^sub>L B goal (1 subgoal): 1. positive (A + - m1) [PROOF STEP] unfolding lowner_le_def [PROOF STATE] proof (prove) using this: A - m1 = A + - m1 m1 \<in> carrier_mat d1 d1 m2 \<in> carrier_mat d2 d2 positive m1 positive m2 dim_row m1 = dim_row A \<and> dim_col m1 = dim_col A \<and> positive (A - m1) dim_row m2 = dim_row B \<and> dim_col m2 = dim_col B \<and> positive (B - m2) goal (1 subgoal): 1. positive (A + - m1) [PROOF STEP] by auto [PROOF STATE] proof (state) this: positive (A + - m1) goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] then [PROOF STATE] proof (chain) picking this: positive (A + - m1) [PROOF STEP] have p1: "positive (tensor_mat (A + (- m1)) m2)" [PROOF STATE] proof (prove) using this: positive (A + - m1) goal (1 subgoal): 1. positive (tensor_mat (A + - m1) m2) [PROOF STEP] using assms tensor_mat_positive [PROOF STATE] proof (prove) using this: positive (A + - m1) m1 \<in> carrier_mat d1 d1 m2 \<in> carrier_mat d2 d2 positive m1 positive m2 m1 \<le>\<^sub>L A m2 \<le>\<^sub>L B \<lbrakk>?m1.0 \<in> carrier_mat d1 d1; ?m2.0 \<in> carrier_mat d2 d2; positive ?m1.0; positive ?m2.0\<rbrakk> \<Longrightarrow> positive (tensor_mat ?m1.0 ?m2.0) goal (1 subgoal): 1. positive (tensor_mat (A + - m1) m2) [PROOF STEP] by auto [PROOF STATE] proof (state) this: positive (tensor_mat (A + - m1) m2) goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] moreover [PROOF STATE] proof (state) this: positive (tensor_mat (A + - m1) m2) goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] have "tensor_mat (- m1) m2 = - tensor_mat m1 m2" [PROOF STATE] proof (prove) goal (1 subgoal): 1. tensor_mat (- m1) m2 = - tensor_mat m1 m2 [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: m1 \<in> carrier_mat d1 d1 m2 \<in> carrier_mat d2 d2 positive m1 positive m2 m1 \<le>\<^sub>L A m2 \<le>\<^sub>L B goal (1 subgoal): 1. tensor_mat (- m1) m2 = - tensor_mat m1 m2 [PROOF STEP] apply (subgoal_tac "- m1 = -1 \<cdot>\<^sub>m m1") [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<lbrakk>m1 \<in> carrier_mat d1 d1; m2 \<in> carrier_mat d2 d2; positive m1; positive m2; m1 \<le>\<^sub>L A; m2 \<le>\<^sub>L B; - m1 = - 1 \<cdot>\<^sub>m m1\<rbrakk> \<Longrightarrow> tensor_mat (- m1) m2 = - tensor_mat m1 m2 2. \<lbrakk>m1 \<in> carrier_mat d1 d1; m2 \<in> carrier_mat d2 d2; positive m1; positive m2; m1 \<le>\<^sub>L A; m2 \<le>\<^sub>L B\<rbrakk> \<Longrightarrow> - m1 = - 1 \<cdot>\<^sub>m m1 [PROOF STEP] by (auto simp add: tensor_mat_scale1) [PROOF STATE] proof (state) this: tensor_mat (- m1) m2 = - tensor_mat m1 m2 goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] moreover [PROOF STATE] proof (state) this: tensor_mat (- m1) m2 = - tensor_mat m1 m2 goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] have "tensor_mat (A + (- m1)) m2 = tensor_mat A m2 + (tensor_mat (- m1) m2)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. tensor_mat (A + - m1) m2 = tensor_mat A m2 + tensor_mat (- m1) m2 [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: m1 \<in> carrier_mat d1 d1 m2 \<in> carrier_mat d2 d2 positive m1 positive m2 m1 \<le>\<^sub>L A m2 \<le>\<^sub>L B goal (1 subgoal): 1. tensor_mat (A + - m1) m2 = tensor_mat A m2 + tensor_mat (- m1) m2 [PROOF STEP] by (auto simp add: tensor_mat_add1 dA) [PROOF STATE] proof (state) this: tensor_mat (A + - m1) m2 = tensor_mat A m2 + tensor_mat (- m1) m2 goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: positive (tensor_mat (A + - m1) m2) tensor_mat (- m1) m2 = - tensor_mat m1 m2 tensor_mat (A + - m1) m2 = tensor_mat A m2 + tensor_mat (- m1) m2 [PROOF STEP] have "tensor_mat (A + (- m1)) m2 = tensor_mat A m2 - (tensor_mat m1 m2)" [PROOF STATE] proof (prove) using this: positive (tensor_mat (A + - m1) m2) tensor_mat (- m1) m2 = - tensor_mat m1 m2 tensor_mat (A + - m1) m2 = tensor_mat A m2 + tensor_mat (- m1) m2 goal (1 subgoal): 1. tensor_mat (A + - m1) m2 = tensor_mat A m2 - tensor_mat m1 m2 [PROOF STEP] by auto [PROOF STATE] proof (state) this: tensor_mat (A + - m1) m2 = tensor_mat A m2 - tensor_mat m1 m2 goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] with p1 [PROOF STATE] proof (chain) picking this: positive (tensor_mat (A + - m1) m2) tensor_mat (A + - m1) m2 = tensor_mat A m2 - tensor_mat m1 m2 [PROOF STEP] have le1: "tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A m2" [PROOF STATE] proof (prove) using this: positive (tensor_mat (A + - m1) m2) tensor_mat (A + - m1) m2 = tensor_mat A m2 - tensor_mat m1 m2 goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A m2 [PROOF STEP] unfolding lowner_le_def [PROOF STATE] proof (prove) using this: positive (tensor_mat (A + - m1) m2) tensor_mat (A + - m1) m2 = tensor_mat A m2 - tensor_mat m1 m2 goal (1 subgoal): 1. dim_row (tensor_mat m1 m2) = dim_row (tensor_mat A m2) \<and> dim_col (tensor_mat m1 m2) = dim_col (tensor_mat A m2) \<and> positive (tensor_mat A m2 - tensor_mat m1 m2) [PROOF STEP] by auto [PROOF STATE] proof (state) this: tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A m2 goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] have "B - m2 = B + (- m2)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. B - m2 = B + - m2 [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: m1 \<in> carrier_mat d1 d1 m2 \<in> carrier_mat d2 d2 positive m1 positive m2 m1 \<le>\<^sub>L A m2 \<le>\<^sub>L B goal (1 subgoal): 1. B - m2 = B + - m2 [PROOF STEP] by (auto simp add: minus_add_uminus_mat) [PROOF STATE] proof (state) this: B - m2 = B + - m2 goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] then [PROOF STATE] proof (chain) picking this: B - m2 = B + - m2 [PROOF STEP] have "positive (B + (- m2))" [PROOF STATE] proof (prove) using this: B - m2 = B + - m2 goal (1 subgoal): 1. positive (B + - m2) [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: B - m2 = B + - m2 m1 \<in> carrier_mat d1 d1 m2 \<in> carrier_mat d2 d2 positive m1 positive m2 m1 \<le>\<^sub>L A m2 \<le>\<^sub>L B goal (1 subgoal): 1. positive (B + - m2) [PROOF STEP] unfolding lowner_le_def [PROOF STATE] proof (prove) using this: B - m2 = B + - m2 m1 \<in> carrier_mat d1 d1 m2 \<in> carrier_mat d2 d2 positive m1 positive m2 dim_row m1 = dim_row A \<and> dim_col m1 = dim_col A \<and> positive (A - m1) dim_row m2 = dim_row B \<and> dim_col m2 = dim_col B \<and> positive (B - m2) goal (1 subgoal): 1. positive (B + - m2) [PROOF STEP] by auto [PROOF STATE] proof (state) this: positive (B + - m2) goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] then [PROOF STATE] proof (chain) picking this: positive (B + - m2) [PROOF STEP] have p2: "positive (tensor_mat A (B + (- m2)))" [PROOF STATE] proof (prove) using this: positive (B + - m2) goal (1 subgoal): 1. positive (tensor_mat A (B + - m2)) [PROOF STEP] using assms tensor_mat_positive positive_one dA dB pA [PROOF STATE] proof (prove) using this: positive (B + - m2) m1 \<in> carrier_mat d1 d1 m2 \<in> carrier_mat d2 d2 positive m1 positive m2 m1 \<le>\<^sub>L A m2 \<le>\<^sub>L B \<lbrakk>?m1.0 \<in> carrier_mat d1 d1; ?m2.0 \<in> carrier_mat d2 d2; positive ?m1.0; positive ?m2.0\<rbrakk> \<Longrightarrow> positive (tensor_mat ?m1.0 ?m2.0) positive (1\<^sub>m ?n) A \<in> carrier_mat d1 d1 B \<in> carrier_mat d2 d2 positive A goal (1 subgoal): 1. positive (tensor_mat A (B + - m2)) [PROOF STEP] by auto [PROOF STATE] proof (state) this: positive (tensor_mat A (B + - m2)) goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] moreover [PROOF STATE] proof (state) this: positive (tensor_mat A (B + - m2)) goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] have "tensor_mat A (-m2) = - tensor_mat A m2" [PROOF STATE] proof (prove) goal (1 subgoal): 1. tensor_mat A (- m2) = - tensor_mat A m2 [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: m1 \<in> carrier_mat d1 d1 m2 \<in> carrier_mat d2 d2 positive m1 positive m2 m1 \<le>\<^sub>L A m2 \<le>\<^sub>L B goal (1 subgoal): 1. tensor_mat A (- m2) = - tensor_mat A m2 [PROOF STEP] apply (subgoal_tac "- m2 = -1 \<cdot>\<^sub>m m2") [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<lbrakk>m1 \<in> carrier_mat d1 d1; m2 \<in> carrier_mat d2 d2; positive m1; positive m2; m1 \<le>\<^sub>L A; m2 \<le>\<^sub>L B; - m2 = - 1 \<cdot>\<^sub>m m2\<rbrakk> \<Longrightarrow> tensor_mat A (- m2) = - tensor_mat A m2 2. \<lbrakk>m1 \<in> carrier_mat d1 d1; m2 \<in> carrier_mat d2 d2; positive m1; positive m2; m1 \<le>\<^sub>L A; m2 \<le>\<^sub>L B\<rbrakk> \<Longrightarrow> - m2 = - 1 \<cdot>\<^sub>m m2 [PROOF STEP] by (auto simp add: tensor_mat_scale2 dA) [PROOF STATE] proof (state) this: tensor_mat A (- m2) = - tensor_mat A m2 goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] moreover [PROOF STATE] proof (state) this: tensor_mat A (- m2) = - tensor_mat A m2 goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] have "tensor_mat A (B + (- m2)) = tensor_mat A B + tensor_mat A (- m2)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. tensor_mat A (B + - m2) = tensor_mat A B + tensor_mat A (- m2) [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: m1 \<in> carrier_mat d1 d1 m2 \<in> carrier_mat d2 d2 positive m1 positive m2 m1 \<le>\<^sub>L A m2 \<le>\<^sub>L B goal (1 subgoal): 1. tensor_mat A (B + - m2) = tensor_mat A B + tensor_mat A (- m2) [PROOF STEP] by (auto simp add: tensor_mat_add2 dA dB) [PROOF STATE] proof (state) this: tensor_mat A (B + - m2) = tensor_mat A B + tensor_mat A (- m2) goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: positive (tensor_mat A (B + - m2)) tensor_mat A (- m2) = - tensor_mat A m2 tensor_mat A (B + - m2) = tensor_mat A B + tensor_mat A (- m2) [PROOF STEP] have "tensor_mat A (B + (- m2)) = tensor_mat A B - tensor_mat A m2" [PROOF STATE] proof (prove) using this: positive (tensor_mat A (B + - m2)) tensor_mat A (- m2) = - tensor_mat A m2 tensor_mat A (B + - m2) = tensor_mat A B + tensor_mat A (- m2) goal (1 subgoal): 1. tensor_mat A (B + - m2) = tensor_mat A B - tensor_mat A m2 [PROOF STEP] by auto [PROOF STATE] proof (state) this: tensor_mat A (B + - m2) = tensor_mat A B - tensor_mat A m2 goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] with p2 [PROOF STATE] proof (chain) picking this: positive (tensor_mat A (B + - m2)) tensor_mat A (B + - m2) = tensor_mat A B - tensor_mat A m2 [PROOF STEP] have le20: "tensor_mat A m2 \<le>\<^sub>L tensor_mat A B" [PROOF STATE] proof (prove) using this: positive (tensor_mat A (B + - m2)) tensor_mat A (B + - m2) = tensor_mat A B - tensor_mat A m2 goal (1 subgoal): 1. tensor_mat A m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] unfolding lowner_le_def [PROOF STATE] proof (prove) using this: positive (tensor_mat A (B + - m2)) tensor_mat A (B + - m2) = tensor_mat A B - tensor_mat A m2 goal (1 subgoal): 1. dim_row (tensor_mat A m2) = dim_row (tensor_mat A B) \<and> dim_col (tensor_mat A m2) = dim_col (tensor_mat A B) \<and> positive (tensor_mat A B - tensor_mat A m2) [PROOF STEP] by auto [PROOF STATE] proof (state) this: tensor_mat A m2 \<le>\<^sub>L tensor_mat A B goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B [PROOF STEP] apply (subst lowner_le_trans[of _ d "tensor_mat (A) m2"]) [PROOF STATE] proof (prove) goal (6 subgoals): 1. tensor_mat m1 m2 \<in> carrier_mat d d 2. tensor_mat A m2 \<in> carrier_mat d d 3. tensor_mat A B \<in> carrier_mat d d 4. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A m2 5. tensor_mat A m2 \<le>\<^sub>L tensor_mat A B 6. True [PROOF STEP] subgoal [PROOF STATE] proof (prove) goal (1 subgoal): 1. tensor_mat m1 m2 \<in> carrier_mat d d [PROOF STEP] using tensor_mat_carrier [PROOF STATE] proof (prove) using this: tensor_mat ?m1.0 ?m2.0 \<in> carrier_mat d d goal (1 subgoal): 1. tensor_mat m1 m2 \<in> carrier_mat d d [PROOF STEP] by auto [PROOF STATE] proof (prove) goal (5 subgoals): 1. tensor_mat A m2 \<in> carrier_mat d d 2. tensor_mat A B \<in> carrier_mat d d 3. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A m2 4. tensor_mat A m2 \<le>\<^sub>L tensor_mat A B 5. True [PROOF STEP] subgoal [PROOF STATE] proof (prove) goal (1 subgoal): 1. tensor_mat A m2 \<in> carrier_mat d d [PROOF STEP] using tensor_mat_carrier [PROOF STATE] proof (prove) using this: tensor_mat ?m1.0 ?m2.0 \<in> carrier_mat d d goal (1 subgoal): 1. tensor_mat A m2 \<in> carrier_mat d d [PROOF STEP] by auto [PROOF STATE] proof (prove) goal (4 subgoals): 1. tensor_mat A B \<in> carrier_mat d d 2. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A m2 3. tensor_mat A m2 \<le>\<^sub>L tensor_mat A B 4. True [PROOF STEP] using le1 le20 [PROOF STATE] proof (prove) using this: tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A m2 tensor_mat A m2 \<le>\<^sub>L tensor_mat A B goal (4 subgoals): 1. tensor_mat A B \<in> carrier_mat d d 2. tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A m2 3. tensor_mat A m2 \<le>\<^sub>L tensor_mat A B 4. True [PROOF STEP] by auto [PROOF STATE] proof (state) this: tensor_mat m1 m2 \<le>\<^sub>L tensor_mat A B goal: No subgoals! [PROOF STEP] qed
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.norm_num import tactic.linarith import tactic.omega import control.lawful_fix import order.category.omega_complete_partial_order import data.nat.basic universes u_1 u_2 namespace roption.examples open function has_fix omega_complete_partial_order /-! `easy` is a trivial, non-recursive example -/ def easy.intl (easy : ℕ → ℕ → roption ℕ) : ℕ → ℕ → roption ℕ | x y := pure x def easy := fix easy.intl -- automation coming soon theorem easy.cont : continuous' easy.intl := pi.omega_complete_partial_order.flip₂_continuous' easy.intl (λ x, pi.omega_complete_partial_order.flip₂_continuous' _ (λ x_1, const_continuous' (pure x))) -- automation coming soon theorem easy.equations.eqn_1 (x y : ℕ) : easy x y = pure x := by rw [easy, lawful_fix.fix_eq' easy.cont]; refl /-! division on natural numbers -/ def div.intl (div : ℕ → ℕ → roption ℕ) : ℕ → ℕ → roption ℕ | x y := if y ≤ x ∧ y > 0 then div (x - y) y else pure x def div : ℕ → ℕ → roption ℕ := fix div.intl -- automation coming soon theorem div.cont : continuous' div.intl := pi.omega_complete_partial_order.flip₂_continuous' div.intl (λ (x : ℕ), pi.omega_complete_partial_order.flip₂_continuous' (λ (g : ℕ → ℕ → roption ℕ), div.intl g x) (λ (x_1 : ℕ), (continuous_hom.ite_continuous' (λ (x_2 : ℕ → ℕ → roption ℕ), x_2 (x - x_1) x_1) (λ (x_1 : ℕ → ℕ → roption ℕ), pure x) (pi.omega_complete_partial_order.flip₁_continuous' (λ (v_1 : ℕ) (x_2 : ℕ → ℕ → roption ℕ), x_2 (x - x_1) v_1) _ $ pi.omega_complete_partial_order.flip₁_continuous' (λ (v : ℕ) (g : ℕ → ℕ → roption ℕ) (x : ℕ), g v x) _ id_continuous') (const_continuous' (pure x))))) -- automation coming soon theorem div.equations.eqn_1 (x y : ℕ) : div x y = if y ≤ x ∧ y > 0 then div (x - y) y else pure x := by conv_lhs { rw [div, lawful_fix.fix_eq' div.cont] }; refl inductive tree (α : Type*) | nil {} : tree | node (x : α) : tree → tree → tree open roption.examples.tree /-! `map` on a `tree` using monadic notation -/ def tree_map.intl {α β : Type*} (f : α → β) (tree_map : tree α → roption (tree β)) : tree α → roption (tree β) | nil := pure nil | (node x t₀ t₁) := do tt₀ ← tree_map t₀, tt₁ ← tree_map t₁, pure $ node (f x) tt₀ tt₁ -- automation coming soon def tree_map {α : Type u_1} {β : Type u_2} (f : α → β) : tree α → roption (tree β) := fix (tree_map.intl f) -- automation coming soon theorem tree_map.cont : ∀ {α : Type u_1} {β : Type u_2} (f : α → β), continuous' (tree_map.intl f) := λ {α : Type u_1} {β : Type u_2} (f : α → β), pi.omega_complete_partial_order.flip₂_continuous' (tree_map.intl f) (λ (x : tree α), tree.cases_on x (id (const_continuous' (pure nil))) (λ (x_x : α) (x_a x_a_1 : tree α), (continuous_hom.bind_continuous' (λ (x : tree α → roption (tree β)), x x_a) (λ (x : tree α → roption (tree β)) (tt₀ : tree β), x x_a_1 >>= λ (tt₁ : tree β), pure (node (f x_x) tt₀ tt₁)) (pi.omega_complete_partial_order.flip₁_continuous' (λ (v : tree α) (x : tree α → roption (tree β)), x v) x_a id_continuous') (pi.omega_complete_partial_order.flip₂_continuous' (λ (x : tree α → roption (tree β)) (tt₀ : tree β), x x_a_1 >>= λ (tt₁ : tree β), pure (node (f x_x) tt₀ tt₁)) (λ (x : tree β), continuous_hom.bind_continuous' (λ (x : tree α → roption (tree β)), x x_a_1) (λ (x_1 : tree α → roption (tree β)) (tt₁ : tree β), pure (node (f x_x) x tt₁)) (pi.omega_complete_partial_order.flip₁_continuous' (λ (v : tree α) (x : tree α → roption (tree β)), x v) x_a_1 id_continuous') (pi.omega_complete_partial_order.flip₂_continuous' (λ (x_1 : tree α → roption (tree β)) (tt₁ : tree β), pure (node (f x_x) x tt₁)) (λ (x_1 : tree β), const_continuous' (pure (node (f x_x) x x_1))))))))) -- automation coming soon theorem tree_map.equations.eqn_1 {α : Type u_1} {β : Type u_2} (f : α → β) : tree_map f nil = pure nil := by rw [tree_map,lawful_fix.fix_eq' (tree_map.cont f)]; refl -- automation coming soon theorem tree_map.equations.eqn_2 {α : Type u_1} {β : Type u_2} (f : α → β) (x : α) (t₀ t₁ : tree α) : tree_map f (node x t₀ t₁) = tree_map f t₀ >>= λ (tt₀ : tree β), tree_map f t₁ >>= λ (tt₁ : tree β), pure (node (f x) tt₀ tt₁) := by conv_lhs { rw [tree_map,lawful_fix.fix_eq' (tree_map.cont f)] }; refl /-! `map` on a `tree` using applicative notation -/ def tree_map'.intl {α β} (f : α → β) (tree_map : tree α → roption (tree β)) : tree α → roption (tree β) | nil := pure nil | (node x t₀ t₁) := node (f x) <$> tree_map t₀ <*> tree_map t₁ -- automation coming soon def tree_map' {α : Type u_1} {β : Type u_2} (f : α → β) : tree α → roption (tree β) := fix (tree_map'.intl f) -- automation coming soon theorem tree_map'.cont : ∀ {α : Type u_1} {β : Type u_2} (f : α → β), continuous' (tree_map'.intl f) := λ {α : Type u_1} {β : Type u_2} (f : α → β), pi.omega_complete_partial_order.flip₂_continuous' (tree_map'.intl f) (λ (x : tree α), tree.cases_on x (id (const_continuous' (pure nil))) (λ (x_x : α) (x_a x_a_1 : tree α), (continuous_hom.seq_continuous' (λ (x : tree α → roption (tree β)), node (f x_x) <$> x x_a) (λ (x : tree α → roption (tree β)), x x_a_1) (continuous_hom.map_continuous' (node (f x_x)) (λ (x : tree α → roption (tree β)), x x_a) (pi.omega_complete_partial_order.flip₁_continuous' (λ (v : tree α) (x : tree α → roption (tree β)), x v) x_a id_continuous')) (pi.omega_complete_partial_order.flip₁_continuous' (λ (v : tree α) (x : tree α → roption (tree β)), x v) x_a_1 id_continuous')))) -- automation coming soon theorem tree_map'.equations.eqn_1 {α : Type u_1} {β : Type u_2} (f : α → β) : tree_map' f nil = pure nil := by rw [tree_map',lawful_fix.fix_eq' (tree_map'.cont f)]; refl -- automation coming soon theorem tree_map'.equations.eqn_2 {α : Type u_1} {β : Type u_2} (f : α → β) (x : α) (t₀ t₁ : tree α) : tree_map' f (node x t₀ t₁) = node (f x) <$> tree_map' f t₀ <*> tree_map' f t₁ := by conv_lhs { rw [tree_map',lawful_fix.fix_eq' (tree_map'.cont f)] }; refl /-! f91 is a function whose proof of termination cannot rely on the structural ordering of its arguments and does not use the usual well-founded order on natural numbers. It is an interesting candidate to show that `fix` lets us disentangle the issue of termination from the definition of the function. -/ def f91.intl (f91 : ℕ → roption ℕ) (n : ℕ) : roption ℕ := if n > 100 then pure $ n - 10 else f91 (n + 11) >>= f91 -- automation coming soon def f91 : ℕ → roption ℕ := fix f91.intl -- automation coming soon lemma f91.cont : continuous' f91.intl := pi.omega_complete_partial_order.flip₂_continuous' f91.intl (λ (x : ℕ), id (continuous_hom.ite_continuous' (λ (x_1 : ℕ → roption ℕ), pure (x - 10)) (λ (x_1 : ℕ → roption ℕ), x_1 (x + 11) >>= x_1) (const_continuous' (pure (x - 10))) (continuous_hom.bind_continuous' (λ (x_1 : ℕ → roption ℕ), x_1 (x + 11)) (λ (x : ℕ → roption ℕ), x) (pi.omega_complete_partial_order.flip₁_continuous' (λ (v : ℕ) (x : ℕ → roption ℕ), x v) (x + 11) id_continuous') (pi.omega_complete_partial_order.flip₂_continuous' (λ (x : ℕ → roption ℕ), x) (λ (x_1 : ℕ), pi.omega_complete_partial_order.flip₁_continuous' (λ (v : ℕ) (g : ℕ → roption ℕ), g v) x_1 id_continuous'))))) . -- automation coming soon theorem f91.equations.eqn_1 (n : ℕ) : f91 n = ite (n > 100) (pure (n - 10)) (f91 (n + 11) >>= f91) := by conv_lhs { rw [f91, lawful_fix.fix_eq' f91.cont] }; refl lemma f91_spec (n : ℕ) : (∃ n', n < n' + 11 ∧ n' ∈ f91 n) := begin apply well_founded.induction (measure_wf $ λ n, 101 - n) n, clear n, dsimp [measure,inv_image], intros n ih, by_cases h' : n > 100, { rw [roption.examples.f91.equations.eqn_1,if_pos h'], existsi n - 10, rw nat.sub_add_eq_add_sub, norm_num [pure], apply le_of_lt, transitivity 100, norm_num, exact h' }, { rw [roption.examples.f91.equations.eqn_1,if_neg h'], simp, rcases ih (n + 11) _ with ⟨n',hn₀,hn₁⟩, rcases ih (n') _ with ⟨n'',hn'₀,hn'₁⟩, refine ⟨n'',_,_,hn₁,hn'₁⟩, { clear ih hn₁ hn'₁, omega }, { clear ih hn₁, omega }, { clear ih, omega } }, end lemma f91_dom (n : ℕ) : (f91 n).dom := by rw roption.dom_iff_mem; apply exists_imp_exists _ (f91_spec n); simp def f91' (n : ℕ) : ℕ := (f91 n).get (f91_dom n) run_cmd guard (f91' 109 = 99) lemma f91_spec' (n : ℕ) : f91' n = if n > 100 then n - 10 else 91 := begin suffices : (∃ n', n' ∈ f91 n ∧ n' = if n > 100 then n - 10 else 91), { dsimp [f91'], rw roption.get_eq_of_mem, rcases this with ⟨n,_,_⟩, subst n, assumption }, apply well_founded.induction (measure_wf $ λ n, 101 - n) n, clear n, dsimp [measure,inv_image], intros n ih, by_cases h' : n > 100, { rw [roption.examples.f91.equations.eqn_1,if_pos h',if_pos h'], simp [pure] }, { rw [roption.examples.f91.equations.eqn_1,if_neg h',if_neg h'], simp, rcases ih (n + 11) _ with ⟨n',hn'₀,hn'₁⟩, split_ifs at hn'₁, { subst hn'₁, norm_num at hn'₀, refine ⟨_,hn'₀,_⟩, rcases ih (n+1) _ with ⟨n',hn'₀,hn'₁⟩, split_ifs at hn'₁, { subst n', convert hn'₀, clear hn'₀ hn'₀ ih, omega }, { subst n', exact hn'₀ }, { clear ih hn'₀, omega } }, { refine ⟨_,hn'₀,_⟩, subst n', rcases ih 91 _ with ⟨n',hn'₀,hn'₁⟩, rw if_neg at hn'₁, subst n', exact hn'₀, { clear ih hn'₀ hn'₀, omega, }, { clear ih hn'₀, omega, } }, { clear ih, omega } } end end roption.examples
/- Copyright (c) 2023 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Kevin Buzzard -/ import field_theory.normal /- # Normal extensions Normal extensions are splitting fields. They play a role in Galois theory because they correspond to normal subgroups via the fundamental theorem. In Lean, normal implies algebraic. Say F/E is an extension of fields -/ variables (E F : Type) [field E] [field F] [algebra E F] section is_normal -- Say furthermore F/E is normal variable [normal E F] -- Then F/E is algebraic example (f : F) : is_algebraic E f := normal.is_algebraic infer_instance f -- and all min polys split open polynomial example (f : F) : splits (algebra_map E F) (minpoly E f) := normal.splits infer_instance f end is_normal -- A finite extension is normal iff it's the splitting field of a polynomial open_locale polynomial open polynomial example [finite_dimensional E F] : normal E F ↔ ∃ p : E[X], is_splitting_field E F p := ⟨λ h, by exactI normal.exists_is_splitting_field E F, λ ⟨p, hp⟩, by exactI normal.of_is_splitting_field p⟩ /- Note that in that proof I had to use `by exactI` which jumps into tactic mode, resets the instance cache (because I've just `intro`ed something which should be in it but isn't), and jumps back into term mode. PS the proof of `normal.of_is_splitting_field` is a 60 line monster. ## Normal closures Say E ⊆ F ⊆ Ω is a tower of field extensions. The normal closure of F/E in Ω is naturally a subfield of Ω containing `F`, and there's a special structure for this: `intermediate_field F Ω`, which we'll see in the fundamental theorem. -/ noncomputable theory -- Say E ⊆ F ⊆ Ω variables (Ω : Type) [field Ω] [algebra E Ω] [algebra F Ω] [is_scalar_tower E F Ω] example : intermediate_field F Ω := normal_closure E F Ω -- Note that `normal_closure E F Ω` is a term (of type `intermediate_field F Ω`) but it has a coercion -- to a type, and that type has a field structure and is normal over `E` if `Ω/E` is normal example [normal E Ω] : normal E (normal_closure E F Ω) := normal_closure.normal E F Ω
(* Title: HOL/Auth/n_german_lemma_on_inv__17.thy Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences *) header{*The n_german Protocol Case Study*} theory n_german_lemma_on_inv__17 imports n_german_base begin section{*All lemmas on causal relation between inv__17 and some rule r*} lemma n_SendInv__part__0Vsinv__17: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__17 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__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__17 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv2)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendInv__part__1Vsinv__17: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__17 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__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__17 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv2)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendInvAckVsinv__17: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__17 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__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__17 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv2)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendGntSVsinv__17: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__17 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__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__17 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv2)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendGntEVsinv__17: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__17 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__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__17 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Ident ''ExGntd'')) (Const false)) (eqn (IVar (Field (Para (Ident ''Cache'') p__Inv2) ''State'')) (Const E))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv2)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvGntSVsinv__17: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__17 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__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__17 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv2)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvGntEVsinv__17: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__17 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__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__17 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv2)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendReqE__part__1Vsinv__17: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__17 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_StoreVsinv__17: assumes a1: "\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__17 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_RecvInvAckVsinv__17: assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvInvAck i" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__17 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_RecvReqEVsinv__17: assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvReqE N i" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__17 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendReqE__part__0Vsinv__17: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__17 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendReqSVsinv__17: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqS i" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__17 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_RecvReqSVsinv__17: assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvReqS N i" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__17 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done end
(* Copyright (C) 2017 M.A.L. Marques This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. *) (* type: work_gga_x *) (* prefix: gga_x_vmt_params *params; assert(p->params != NULL); params = (gga_x_vmt_params * )(p->params); *) f0_vmt := s -> 1 + params_a_mu*s^2*exp(-params_a_alpha*s^2)/(1 + params_a_mu*s^2): f_vmt := x -> f0_vmt(X2S*x): f := x -> f_vmt(x):
[STATEMENT] lemma dom_subid_aux2'': "x \<cdot> d y \<le> x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. x \<cdot> d y \<le> x [PROOF STEP] using dpd3 mult_isol [PROOF STATE] proof (prove) using this: d ?x \<le> (1::'a) ?x \<le> ?y \<Longrightarrow> ?z \<cdot> ?x \<le> ?z \<cdot> ?y goal (1 subgoal): 1. x \<cdot> d y \<le> x [PROOF STEP] by fastforce
[STATEMENT] lemma (in vec_space) rank_0I: "rank (0\<^sub>m n nc) = 0" [PROOF STATE] proof (prove) goal (1 subgoal): 1. rank (0\<^sub>m n nc) = 0 [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. rank (0\<^sub>m n nc) = 0 [PROOF STEP] have "set (cols (0\<^sub>m n nc)) \<subseteq> {0\<^sub>v n}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. set (cols (0\<^sub>m n nc)) \<subseteq> {0\<^sub>v n} [PROOF STEP] by (metis col_zero cols_length cols_nth in_set_conv_nth insertCI index_zero_mat(3) subsetI) [PROOF STATE] proof (state) this: set (cols (0\<^sub>m n nc)) \<subseteq> {0\<^sub>v n} goal (1 subgoal): 1. rank (0\<^sub>m n nc) = 0 [PROOF STEP] have "set (cols (0\<^sub>m n nc::'a mat)) = {} \<or> set (cols (0\<^sub>m n nc)) = {0\<^sub>v n::'a vec}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. set (cols (0\<^sub>m n nc)) = {} \<or> set (cols (0\<^sub>m n nc)) = {0\<^sub>v n} [PROOF STEP] by (meson \<open>set (cols (0\<^sub>m n nc)) \<subseteq> {0\<^sub>v n}\<close> subset_singletonD) [PROOF STATE] proof (state) this: set (cols (0\<^sub>m n nc)) = {} \<or> set (cols (0\<^sub>m n nc)) = {0\<^sub>v n} goal (1 subgoal): 1. rank (0\<^sub>m n nc) = 0 [PROOF STEP] then [PROOF STATE] proof (chain) picking this: set (cols (0\<^sub>m n nc)) = {} \<or> set (cols (0\<^sub>m n nc)) = {0\<^sub>v n} [PROOF STEP] have "span (set (cols (0\<^sub>m n nc))) = {0\<^sub>v n}" [PROOF STATE] proof (prove) using this: set (cols (0\<^sub>m n nc)) = {} \<or> set (cols (0\<^sub>m n nc)) = {0\<^sub>v n} goal (1 subgoal): 1. local.span (set (cols (0\<^sub>m n nc))) = {0\<^sub>v n} [PROOF STEP] by (metis (no_types) span_empty span_zero vectorspace.span_empty vectorspace_axioms) [PROOF STATE] proof (state) this: local.span (set (cols (0\<^sub>m n nc))) = {0\<^sub>v n} goal (1 subgoal): 1. rank (0\<^sub>m n nc) = 0 [PROOF STEP] then [PROOF STATE] proof (chain) picking this: local.span (set (cols (0\<^sub>m n nc))) = {0\<^sub>v n} [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: local.span (set (cols (0\<^sub>m n nc))) = {0\<^sub>v n} goal (1 subgoal): 1. rank (0\<^sub>m n nc) = 0 [PROOF STEP] unfolding rank_def \<open>span (set (cols (0\<^sub>m n nc))) = {0\<^sub>v n}\<close> [PROOF STATE] proof (prove) using this: {0\<^sub>v n} = {0\<^sub>v n} goal (1 subgoal): 1. vectorspace.dim class_ring (vs {0\<^sub>v n}) = 0 [PROOF STEP] using span_empty dim_zero_vs [PROOF STATE] proof (prove) using this: {0\<^sub>v n} = {0\<^sub>v n} local.span {} = {0\<^sub>v n} vectorspace.dim class_ring (vs (local.span {})) = 0 goal (1 subgoal): 1. vectorspace.dim class_ring (vs {0\<^sub>v n}) = 0 [PROOF STEP] by simp [PROOF STATE] proof (state) this: rank (0\<^sub>m n nc) = 0 goal: No subgoals! [PROOF STEP] qed
Formal statement is: lemma null_set_Diff: assumes "B \<in> null_sets M" "A \<in> sets M" shows "B - A \<in> null_sets M" Informal statement is: If $B$ is a null set and $A$ is any set, then $B - A$ is a null set.
proposition path_connected_openin_diff_countable: fixes S :: "'a::euclidean_space set" assumes "connected S" and ope: "openin (top_of_set (affine hull S)) S" and "\<not> collinear S" "countable T" shows "path_connected(S - T)"
State Before: ι : Sort ?u.17353 α : Type u β : Type v inst✝¹ : PseudoEMetricSpace α inst✝ : PseudoEMetricSpace β x y : α s t : Set α Φ : α → β h : IsClosed s ⊢ x ∈ s ↔ infEdist x s = 0 State After: no goals Tactic: rw [← mem_closure_iff_infEdist_zero, h.closure_eq]
theory T119 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) " nitpick[card nat=4,timeout=86400] oops end
(** Each homotopy between functions give rise to a pseudotransformation *) Require Import UniMath.Foundations.All. Require Import UniMath.MoreFoundations.All. Require Import UniMath.CategoryTheory.Core.Categories. Require Import UniMath.CategoryTheory.Core.Functors. Require Import UniMath.CategoryTheory.PrecategoryBinProduct. Require Import UniMath.Bicategories.Core.Bicat. Import Bicat.Notations. Require Import UniMath.Bicategories.Core.Invertible_2cells. Require Import UniMath.Bicategories.Core.BicategoryLaws. Require Import UniMath.Bicategories.PseudoFunctors.Display.PseudoFunctorBicat. Require Import UniMath.Bicategories.PseudoFunctors.PseudoFunctor. Require Import UniMath.Bicategories.Transformations.PseudoTransformation. Import PseudoFunctor.Notations. Require Import UniMath.Bicategories.Core.Examples.TwoType. Require Import UniMath.Bicategories.PseudoFunctors.Examples.ApFunctor. Local Open Scope cat. Definition homotsec_natural {X Y : UU} {f g : X → Y} (e : f ~ g) {x y : X} (p : x = y) : e x @ maponpaths g p = maponpaths f p @ e y. Proof. induction p. apply pathscomp0rid. Defined. Definition homotsec_natural_natural {X Y : UU} {f g : X → Y} (e : f ~ g) {x y : X} {p q : x = y} (h : p = q) : maponpaths (λ s : g x = g y, e x @ s) (maponpaths (maponpaths g) h) @ homotsec_natural e q = homotsec_natural e p @ maponpaths (λ s : f x = f y, s @ e y) (maponpaths (maponpaths f) h). Proof. induction h. exact (!(pathscomp0rid _)). Defined. Section ApTrans. Context {X Y : UU} (HX : isofhlevel 4 X) (HY : isofhlevel 4 Y) {f g : X → Y} (e : f ~ g). Definition ap_pstrans_data : pstrans_data (ap_psfunctor HX HY f) (ap_psfunctor HX HY g). Proof. use make_pstrans_data. - exact e. - intros x y p. use make_invertible_2cell. + exact (homotsec_natural e p). + apply fundamental_groupoid_2cell_iso. Defined. Definition ap_pstrans_laws : is_pstrans ap_pstrans_data. Proof. repeat split. - simpl ; intros x y p q h ; cbn. exact (homotsec_natural_natural e h). - simpl ; intro x ; cbn. exact (!(pathscomp0rid _ @ pathscomp0rid _)). - simpl ; intros x y z p q ; cbn. induction p, q. cbn. induction (e x). apply idpath. Qed. Definition ap_pstrans : pstrans (ap_psfunctor HX HY f) (ap_psfunctor HX HY g). Proof. use make_pstrans. - exact ap_pstrans_data. - exact ap_pstrans_laws. Defined. End ApTrans.
function D = driving_function_mono_nfchoa_fs(x0,xs,f,N,conf) %DRIVING_FUNCTION_MONO_NFCHOA_FS driving signal for a focused source in NFC-HOA % % Usage: D = driving_function_mono_nfchoa_fs(x0,xs,f,N,conf) % % Input parameters: % x0 - position of the secondary sources / m [nx3] % xs - position of focused source / m [nx3] % f - frequency of the monochromatic source / Hz % N - maximum order of spherical harmonics % conf - configuration struct (see SFS_config) % % Output parameters: % D - driving function signal [nx1] % % See also: driving_function_mono_nfchoa, driving_function_imp_nfchoa_fs %***************************************************************************** % The MIT License (MIT) * % * % Copyright (c) 2010-2019 SFS Toolbox Developers * % * % 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. * % * % The SFS Toolbox allows to simulate and investigate sound field synthesis * % methods like wave field synthesis or higher order ambisonics. * % * % https://sfs.readthedocs.io [email protected] * %***************************************************************************** %% ===== Checking of input parameters ================================== nargmin = 5; nargmax = 5; narginchk(nargmin,nargmax); isargmatrix(x0,xs); isargpositivescalar(f,N); isargstruct(conf); %% ===== Configuration ================================================== xref = conf.xref; dimension = conf.dimension; driving_functions = conf.driving_functions; %% ===== Computation ==================================================== if strcmp('2D',dimension) % === 2-Dimensional ================================================== switch driving_functions case 'default' % --- SFS Toolbox ------------------------------------------------ to_be_implemented; otherwise error(['%s: %s, this type of driving function is not implemented ', ... 'for a 2D focused source.'],upper(mfilename),driving_functions); end elseif strcmp('2.5D',dimension) % === 2.5-Dimensional ================================================ % Reference point xref = repmat(xref,[size(x0,1) 1]); switch driving_functions case 'default' % --- SFS Toolbox ------------------------------------------------ to_be_implemented; otherwise error(['%s: %s, this type of driving function is not implemented ', ... 'for a 2.5D focused source.'],upper(mfilename),driving_functions); end elseif strcmp('3D',dimension) % === 3-Dimensional ================================================== switch driving_functions case 'default' % --- SFS Toolbox ------------------------------------------------ to_be_implemented; otherwise error(['%s: %s, this type of driving function is not implemented ', ... 'for a 3D focused source.'],upper(mfilename),driving_functions); end else error('%s: the dimension %s is unknown.',upper(mfilename),dimension); end
module Fractions %default total record Fraction : Type where F : (top : Nat) -> (bottom : Nat) -> Fraction corecord Tree : Type -> Type where value : Tree a -> a left : Tree a -> Tree a right : Tree a -> Tree a constructor MkTree fracSum : Fraction -> Nat fracSum (F top bottom) = top + bottom leftFrac : Fraction -> Fraction leftFrac f = F (top f) (fracSum f) rightFrac : Fraction -> Fraction rightFrac f = F (fracSum f) (bottom f) total causal flattenTree : Tree a -> Stream a flattenTree t = ft [] where total causal ft : List (Tree a) -> Stream a ft [] = (value t) :: (ft [left t, right t]) ft (tree :: xs) = (value tree) :: (ft (xs ++ [left tree, right tree])) total causal rationalTree : Tree Fraction rationalTree = rt $ F (S Z) (S Z) where total causal rt : Fraction -> Tree Fraction rt f = MkTree f (rt $ leftFrac f) (rt $ rightFrac f) --total causal rationals : Stream Fraction --rationals = flattenTree $ rationalTree
import tactic -- injective and surjective functions are already in Lean. -- They are called `function.injective` and `function.surjective`. -- It gets a bit boring typing `function.` a lot so we start -- by opening the `function` namespace open function -- We now move into the `xena` namespace namespace xena -- let X, Y, Z be "types", i.e. sets, and let `f : X → Y` and `g : Y → Z` -- be functions variables {X Y Z : Type} {f : X → Y} {g : Y → Z} -- let a,b,x be elements of X, let y be an element of Y and let z be an -- element of Z variables (a b x : X) (y : Y) (z : Z) /-! # Injective functions -/ -- let's start by checking the definition of injective is -- what we think it is. lemma injective_def : injective f ↔ ∀ a b : X, f a = f b → a = b := begin -- true by definition refl end -- You can now `rw injective_def` to change `injective f` into its definition. -- The identity function id : X → X is defined by id(x) = x. Let's check this lemma id_def : id x = x := begin -- true by definition refl end -- you can now `rw id_def` to change `id x` into `x` /-- The identity function is injective -/ lemma injective_id : injective (id : X → X) := begin -- these rewrites are not necessary, but I'll -- put them in just this once -- ⊢ injective id rw injective_def, -- ⊢ ∀ (a b : X), id a = id b → a = b intros a b hab, -- hab: id a = id b -- again another rewrite which isn't actually necessary rw id_def at hab, rw id_def at hab, -- hab : a = b exact hab, end -- function composition g ∘ f is satisfies (g ∘ f) (x) = g(f(x)). This -- is true by definition. Let's check this lemma comp_def : (g ∘ f) x = g (f x) := begin -- true by definition refl end /-- Composite of two injective functions is injective -/ lemma injective_comp (hf : injective f) (hg : injective g) : injective (g ∘ f) := begin -- I'll do this without any definitional rewrites -- ⊢ injective (g ∘ f) -- so goal is by definition "for all a, b, ..." and I can just intro intros a b h, -- `hf : injective f`, so `hf : ∀ a b : X, f a = f b → a = b` -- and my goal is `a = b` so this will work apply hf, apply hg, exact h, -- again `h` is not syntactically equal to the goal, -- but it is definitionally equal to the goal end /-! ### Surjective functions -/ -- Let's start by checking the definition of surjectivity is what we think it is lemma surjective_def : surjective f ↔ ∀ y : Y, ∃ x : X, f x = y := begin -- true by definition refl end /-- The identity function is surjective -/ lemma surjective_id : surjective (id : X → X) := begin -- you can start with `rw surjective_def` if you like. intro x, use x, refl, end -- If you started with `rw surjective_def` -- try deleting it. -- Probably your proof still works! This is because -- `surjective_def` is true *by definition*. The proof is `refl`. -- For this next one, the `have` tactic is helpful. /-- Composite of two surjective functions is surjective -/ lemma surjective_comp (hf : surjective f) (hg : surjective g) : surjective (g ∘ f) := begin intro z, cases hg z with y hy, cases hf y with x hx, use x, show g(f(x)) = z, rw hx, exact hy, end /-! ### Bijective functions In Lean a function is defined to be bijective if it is injective and surjective. Let's check this. -/ lemma bijective_def : bijective f ↔ injective f ∧ surjective f := begin -- true by definition refl end -- You can now use the lemmas you've proved already to make these -- proofs very short. /-- The identity function is bijective. -/ lemma bijective_id : bijective (id : X → X) := begin exact ⟨injective_id, surjective_id⟩, end /-- A composite of bijective functions is bijective. -/ lemma bijective_comp (hf : bijective f) (hg : bijective g) : bijective (g ∘ f) := begin cases hf with hf_inj hf_surj, cases hg with hg_inj hg_surj, exact ⟨injective_comp hf_inj hg_inj, surjective_comp hf_surj hg_surj⟩ end end xena
data Vect : Nat -> Type -> Type where Nil : Vect Z a (::) : a -> Vect k a -> Vect (S k) a Show a => Show (Vect n a) where show xs = "[" ++ showV xs ++ "]" where showV : forall n . Vect n a -> String showV [] = "" showV [x] = show x showV (x :: xs) = show x ++ ", " ++ showV xs filter : (a -> Bool) -> Vect n a -> (p ** Vect p a) filter pred [] = (_ ** []) filter pred (x :: xs) = let (n ** xs') = filter pred xs in if pred x then (_ ** x :: xs') else (_ ** xs') test : (x ** Vect x Nat) test = (_ ** [1,2]) foo : String foo = show test even : Nat -> Bool even Z = True even (S k) = not (even k) main : IO () main = printLn (filter even [S Z,2,3,4,5,6])
State Before: α : Type u_2 β : Type u_1 γ : Type ?u.839059 δ : Type ?u.839062 m : MeasurableSpace α μ ν : Measure α inst✝² : MeasurableSpace δ inst✝¹ : NormedAddCommGroup β inst✝ : NormedAddCommGroup γ f : α → β hμ : Integrable f hν : Integrable f ⊢ Integrable f State After: α : Type u_2 β : Type u_1 γ : Type ?u.839059 δ : Type ?u.839062 m : MeasurableSpace α μ ν : Measure α inst✝² : MeasurableSpace δ inst✝¹ : NormedAddCommGroup β inst✝ : NormedAddCommGroup γ f : α → β hμ : Memℒp f 1 hν : Memℒp f 1 ⊢ Memℒp f 1 Tactic: simp_rw [← memℒp_one_iff_integrable] at hμ hν⊢ State Before: α : Type u_2 β : Type u_1 γ : Type ?u.839059 δ : Type ?u.839062 m : MeasurableSpace α μ ν : Measure α inst✝² : MeasurableSpace δ inst✝¹ : NormedAddCommGroup β inst✝ : NormedAddCommGroup γ f : α → β hμ : Memℒp f 1 hν : Memℒp f 1 ⊢ Memℒp f 1 State After: α : Type u_2 β : Type u_1 γ : Type ?u.839059 δ : Type ?u.839062 m : MeasurableSpace α μ ν : Measure α inst✝² : MeasurableSpace δ inst✝¹ : NormedAddCommGroup β inst✝ : NormedAddCommGroup γ f : α → β hμ : Memℒp f 1 hν : Memℒp f 1 ⊢ snorm f 1 (μ + ν) < ⊤ Tactic: refine' ⟨hμ.aestronglyMeasurable.add_measure hν.aestronglyMeasurable, _⟩ State Before: α : Type u_2 β : Type u_1 γ : Type ?u.839059 δ : Type ?u.839062 m : MeasurableSpace α μ ν : Measure α inst✝² : MeasurableSpace δ inst✝¹ : NormedAddCommGroup β inst✝ : NormedAddCommGroup γ f : α → β hμ : Memℒp f 1 hν : Memℒp f 1 ⊢ snorm f 1 (μ + ν) < ⊤ State After: α : Type u_2 β : Type u_1 γ : Type ?u.839059 δ : Type ?u.839062 m : MeasurableSpace α μ ν : Measure α inst✝² : MeasurableSpace δ inst✝¹ : NormedAddCommGroup β inst✝ : NormedAddCommGroup γ f : α → β hμ : Memℒp f 1 hν : Memℒp f 1 ⊢ snorm f 1 μ < ⊤ ∧ snorm f 1 ν < ⊤ Tactic: rw [snorm_one_add_measure, ENNReal.add_lt_top] State Before: α : Type u_2 β : Type u_1 γ : Type ?u.839059 δ : Type ?u.839062 m : MeasurableSpace α μ ν : Measure α inst✝² : MeasurableSpace δ inst✝¹ : NormedAddCommGroup β inst✝ : NormedAddCommGroup γ f : α → β hμ : Memℒp f 1 hν : Memℒp f 1 ⊢ snorm f 1 μ < ⊤ ∧ snorm f 1 ν < ⊤ State After: no goals Tactic: exact ⟨hμ.snorm_lt_top, hν.snorm_lt_top⟩
(* Copyright (C) 2017 M.A.L. Marques This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. *) (* type: gga_exc *) cac := 1.467: mtau := 4.5: bcgp_pt := t -> t*sqrt((mtau + t)/(mtau + cac*t)): arg := 0.5: crg := 0.16667: drg := 0.29633: fbeta_modRasoltGeldart := rs -> (1.0 + arg*rs*(1+crg*rs)) / (1.0 + arg*rs*(1+drg*rs)): $define gga_c_pbe_params $include "gga_c_pbe.mpl" (* override definition of tp *) tp := (rs, z, xt) -> bcgp_pt(tt(rs, z, xt)): (* override definition of mbeta *) mbeta := (rs, t) -> params_a_beta*fbeta_modRasoltGeldart(rs):
# Кратчайшие пути Существуют вариации в зависимости от конкретного случая, но обычно базовой задачей о кратчайших путях считают следующую: дана вершина $s$, найти пути миниальной длины (длина пути -- сумма длин образующих его ребер) до всех остальных вершин. В случае, если длины всех ребер одинаковы, то эта задача решается с помощью базового обхода в ширину, в общем случае его недостаточно, одна есть похожий по простоте метод, на котором основано подавляющее большинство методов нахождения кратчайших путей. ### Обозначения \begin{align} u\rightarrow v~-~& ребро~из~u~в~v \\ u\rightsquigarrow v~-~& путь~из~u~в~v \\ u\rightsquigarrow z\rightsquigarrow v~-~& путь~из~u~в~v,~проходящий~через~z \\ u\rightsquigarrow z\rightarrow v~-~& путь~из~u~в~v,~в~котором~последнее~ребро~начинается~в~z \\ u\rightarrow z\rightsquigarrow v~-~& путь~из~u~в~v,~в~котором~первое~ребро~ведет~в~z \\ u_i\rightsquigarrow_{i=1}^{n-1} u_{i+1}=u_1\rightarrow\ldots\rightarrow u_n ~-~& путь,~состоящий~из~ребер~u_1\rightarrow u_2,~u_2\rightarrow u_3,\ldots,~u_{n-1}\rightarrow~u_n. \\ \omega(u\rightarrow v)~-~ & длина~ребра~u\rightarrow v. \\ \omega(u_i\rightsquigarrow_{i=1}^{n-1} u_{i+1})=\sum_{i=1}^{n-1}\omega(u_i\rightarrow u_{i+1})~-~& длина~пути, состоящего~из~ребер~u_1\rightarrow u_2,~u_2\rightarrow u_3,\ldots,~u_{n-1}\rightarrow~u_n. \\ d(u, v)~-~& минимальная~длина~пути~из~u~в~v. \end{align} Так как путей из одной вершины в другую может быть много, то обозначение $u\rightsquigarrow v$ предполагает какой-то путь. Если нужно будет уточнить промежуточные вершины в этом пути, то будут использованы правила конкатенации, указанные выше. Длина пути определяется как сумма длин ребер и, соответственно, используется только для путей с явным указанием последовательности ребер. ## Дерево кратчайших путей и динамическое программирование У кратчайших путей есть одно чрезвычайно важное свойство: если $u_1\rightarrow\ldots\rightarrow u_n$ -- кратчайший путь из $u_1$ в $u_n$, то для всех $1\leq i<j\leq n$: $u_i\rightarrow\ldots\rightarrow u_j$ -- кратчайший путь из $u_i$ в $u_j$, иначе говоря любой кусок оптимального пути также является оптимальным, это свойство обычно называют оптимальной подструктурой. Для решений задач с подобным свойством оказался очень успешным метод динамического программирования, который в целом можно описать следующими принципами: * Вместе с $d(u, v)$ вычисляем еще какие-то вспомагательные величины, также обозначающие кратчайшие пути, но обычно дополнительно чем-то ограниченые. * Последовательно вычислять вспомагательные величины начиная с коротких путей постепенно переходя к более длинным. Подробней уже в конкретных алгоритмах. Теперь предположим, что мы каким-то образом научились вычислять $d$ для одной пары вершин или нескольких, обычно нам не только интересно само расстояние, но и сам путь. Возникает следующая проблема: $d(u, v)$ -- это одно число, а вот путь -- это уже последовательность. Вопрос в том, можно компактно представить себе этот набор оптимальных путей? В случае, если нас интересуют оптимальные пути от одной вершины до всех остальных, то это удается сделать довольно изящно, очень сильно помагает оптимальная подструктура: если $$ d(u_1, u_n)=\omega(u_1\rightarrow\ldots\rightarrow u_n), $$ то \begin{align} d(u_1, u_n)=\omega(u_1\rightarrow\ldots\rightarrow u_n)=\omega(u_1\rightarrow\ldots\rightarrow u_{n-1})+\omega(u_{n-1}\rightarrow u_n)=d(u_1, u_{n-1})+\omega(u_{n-1}\rightarrow u_n) \end{align} По сути мы просто выделили последнее ребро на оптимальном пути. Предположим, что мы как-то умеем выделять оптимальный путь $u_1\rightsquigarrow u_{n-1}$, тогда чтобы выделить оптимальный путь $u_1\rightsquigarrow u_{n}$, то достаточно запомнить последнее ребро на этом оптимальном пути $u_{n-1}\rightarrow u_n$ и дописать его в конец оптимального пути $u_1\rightsquigarrow u_{n-1}$. Пример этой концепции покажу чуть позже ## Сканирующий метод Базовый метод для нахождения кратчайших путей заключается в следующем: \begin{align} &scan\_arc(v\rightarrow u): \\ &~ ~ ~ ~if (l(v) + \omega(v\rightarrow u) < l(u)) \\ &~ ~ ~ ~ ~ ~ ~ ~l(u)\leftarrow l(v)+\omega(v\rightarrow u) \\ &~ ~ ~ ~ ~ ~ ~ ~p(u)\leftarrow v \\ &~ ~ ~ ~ ~ ~ ~ ~mark(u)\leftarrow labelled \\ & \\ &scan\_vertex(v): \\ &~ ~ ~ ~for~u~such~that~v\rightarrow u~exists: \\ &~ ~ ~ ~~ ~ ~ ~scan\_arc(v\rightarrow u) \\ &~ ~ ~ ~mark(v)\leftarrow scanned \\ & \\ & l(s)\leftarrow 0,~mark(s)\leftarrow labelled \\ & while~exists~v~with~mark(v)=labelled:\\ &~ ~ ~ ~scan\_vertex(v) \end{align} Здесь $l(v)$ -- это некоторое расстояние до вершины $v$, которое изменяется по ходу работы алгоритма какждый раз немного улучшаясь, $p(v)$ обновляется вместе с $l$ и запоминает предыдущую вершиу на пути, который мы сейчас считаем минимальным, $mark(v)$ -- пометка вершины: labelled означает, что с момента последнего сканирования этой вершины расстояние до нее изменилось (т.е. уменьшилось), а значит нужно её отсканировать заново; scanned означает, что мы отсканировали вершину, попытались с помощью неё уменьшить расстояния до её соседей, и при этом после этого расстояние до этой вершины не изменялось. Большинство известных методов нахождения кратчайших путей являются частыми случаями сканирующего метода и отличаются только тем, как выбирать вершины для сканирования в цикле. ### Анализ сканирующего метода Основные два утверждения касательно сканирующего метода заключается в том, что * Вне зависимости от выбора вершина для сканирования алгоритм завершается тогда и только тогда, когда в графе нет отрицательных циклов. Это также является необходимым и достаточным условием корректности задачи о кратчайших путях. * По завершению алгоритма для всех $v$ выполняется $$ l(v)=d(s, v) $$ * По завершению $p(v)$ содежит последнее ребро на кратчайшем пути из $s$ в $v$, соответственно ребра $p(v)\rightarrow v$ образуют дерево кратчайших путей. Первый факт обосновывается следующим образом: если нет отрицательных циклов, значит минимальный путь существует и является простым (без повторений вершин); промежуточные пути в алгоритме являются простыми, вершина помечается $labelled$ только если путь до неё уменьшился, а значит количество раз, когда мы вызовем сканирование вершины конечно. Обоснования второго факта: для начала заметим, что сканирующий метод обязательно просмотрит все достижимые вершины, так как если запретить повторно сканировать вершину, то сканирущий метод вырождается в BFS. Для недостижимых вершин $l(v)=d(s, v)=+\infty$. Далее заметим, что так как $l(v)$ соответствует длине какого-то пути $s\rightsquigarrow v$, то по определению $d$ $$ l(v)\geq d(s, v). $$ Пусть оптимальный путь $s\rightsquigarrow$ состоит из вершин $s=u_1, \ldots, u_k=v$, каждая из этих вершин была просканирована хотя бы раз, а значит по завершению работы алгорима выполняется $$ l(u_i)-l(u_{i-1})\leq \omega(u_{i-1}\rightarrow u_i) $$ (так как $l(u_i)$ может только уменьшаться и при этом после последнего сканирования $u_{i-1}$ это неравенство выполнялось). Просуммировав эти неравенства получаем $$ l(v)=l(v)-l(s)\leq \sum_{i=1}^{n}\omega(u_{i-1}\rightarrow u_i)=d(s, v). $$ Третее утверждение вытекает из второго и того факта, что $p(v)$ всегда обновляется вместе с $l(v)$. ```python import random import graphviz from interactive_visualization.graph_utils import Graph, Arc, Node from interactive_visualization.animation_utils import animate_list ``` ```python def mark_labelled(node): node.SetColor('red') def mark_scanned(node): node.SetColor('green') def process_node(node): node.SetColor('blue') def set_previous(arc): arc.SetColor('green') def unset_previous(arc): arc.SetColor('black') def scan_arc(graph, arc, l, p, mark): if l[arc.end] > l[arc.beginning] + arc.weight: l[arc.end] = l[arc.beginning] + arc.weight if p[arc.end] is not None: unset_previous(p[arc.end]) # Сохраняем arc, а не arc.beginning, чтобы было больше информации p[arc.end] = arc set_previous(p[arc.end]) mark[arc.end] = True mark_labelled(graph.nodes[arc.end]) def scan_node(graph, node_id, l, p, mark): for arc in graph.nodes[node_id].arcs: scan_arc(graph, arc, l, p, mark) mark[node_id] = False mark_scanned(graph.nodes[node_id]) def random_choice(l, mark): labelled = [node_id for node_id, value in mark.items() if value == True] if len(labelled) == 0: return None return random.choice(labelled) def base_scanning_method(graph, s, choice_function): l = {key: float('Inf') for key in graph.nodes.keys()} p = {key: None for key in graph.nodes.keys()} mark = {key: False for key in graph.nodes.keys()} l[s] = 0 mark[s] = True mark_labelled(graph.nodes[s]) out_lst = [] while True: node_id = choice_function(l, mark) if node_id is None: break process_node(graph.nodes[node_id]) out_lst.append(graph.Visualize(l)) scan_node(graph, node_id, l, p, mark) out_lst.append(graph.Visualize(l)) return l, p, out_lst ``` ```python arcs = [ Arc(1, 3, 3), Arc(1, 4, 7), Arc(4, 3, 2), Arc(4, 5, 3), Arc(1, 5, 2), Arc(6, 4, 2), Arc(5, 6, 2), Arc(6, 7, 1), Arc(7, 2, 7), Arc(4, 2, 2), Arc(3, 2, 5) ] Graph(arcs).Visualize() ``` ```python graph = Graph(arcs) random_scanning_shortest_path_lst = [] l, p, random_scanning_shortest_path_lst = \ base_scanning_method(graph, 1, random_choice) ``` ```python animate_list(random_scanning_shortest_path_lst); ``` HBox(children=(Button(description='Prev', style=ButtonStyle()), Button(description='Next', style=ButtonStyle()… interactive(children=(IntSlider(value=0, description='step', max=15), Output()), _dom_classes=('widget-interac… ### Кратчайшие пути на ациклических графах В случае, если в графе нет не только отрицательных циклов, но вообще любых других, то возникает интересная ситуация: если обрабатывать вершины в топологическом порядке, то каждая вершина будет просканирована ровно один раз. Доказать это очень просто: если в графе допустим топологический порядок, то при сканировании вершины $v$ расстояние обновится только для тех вершин, которые в топологическом порядке идут позже $v$. Если вершины в графе пронумерованы в топологическом порядке, то в указанной выше процедуре для этого достаточно будет просто вместо случайной вершины выбирать наименьшую по номеру ```python def least_id_choice(l, mark): labelled = [node_id for node_id, value in mark.items() if value == True] if len(labelled) == 0: return None return min(labelled) ``` ```python graph = Graph([ Arc(0, 1, 4), Arc(0, 2, 2), Arc(1, 2, 5), Arc(2, 3, 3), Arc(1, 4, 10), Arc(3, 4, 4), Arc(4, 5, 11) ]) l, p, topological_scanning_shortest_path_lst = \ base_scanning_method(graph, 0, least_id_choice) animate_list(topological_scanning_shortest_path_lst); ``` HBox(children=(Button(description='Prev', style=ButtonStyle()), Button(description='Next', style=ButtonStyle()… interactive(children=(IntSlider(value=0, description='step', max=11), Output()), _dom_classes=('widget-interac… Это один из двух случаев, когда достигается асимптотическая оценка в $\mathcal{O}(E)$ ($E$ -- количество ребер): во-первых, топологическая сортировка осуществляется обходом в глубину за $\mathcal{O}(E)$; во-вторых каждая вершины сканируется ровно один раз, а значит какждое ребро также сканируется ровно один раз; в-третьих если вместо выбора минимальной вершины просто итерироваться в по всем вершинам в топологическом порядке пропуская недостижимые, то результат будет тот же, и при этом суммарно на это мы тратим $\mathcal{O}(V)$ ($V$ -- количество вершин). На практике ациклические графы часто возникают при моделировании каких-либо протекающих во времени событий. Например одним из промежуточных результатов распознавания речи называе "словные сетки" -- это граф, в котором вершины помечены временнОй меткой, а на ребрах написано слово и информация об акустическом/языковом правдоподобие; ребра всегда ведут из вершин с меньшей временной отметков в вершину с большей и означают, что на этом интервале с такой-то вероятностью было произнесено такое-то слово. Пути в этом графе соответствуют временному интервалу, начинающемуся от временной отметки первой вершины, заканчивающемуся во временной отметке последней вершины. Forward-backward алгоритмы по сути являются частными случаями нахождения кратчайших путей в ациклическом графа, в том числе и алгоритм Витерби для нахождения наиболее правдоподобной последовательности состояний в марковской цепи. ### Обход в ширину и алгоритм Дейкстры Второй случай, в котором оказывается возможной минимальная оценка для поиска кратчайших путей -- это случай единичных весов, т.е. когда длины всех ребер одинаковы. С точки зрения сканирующего метода в этом случае можно добиться того, чтобы каждая вершина сканировалась ровно один раз, все, что для этого нужно сделать, а это выбирать для очередного сканирования вершину с минимальным расстоянием. ```python def least_distance_choice(l, mark): labelled = [node_id for node_id, value in mark.items() if value == True] if len(labelled) == 0: return None return min(labelled, key=lambda x: l[x]) ``` ```python graph = Graph([ Arc(1, 3, 1), Arc(1, 4, 1), Arc(4, 3, 1), Arc(4, 5, 1), Arc(1, 5, 1), Arc(6, 4, 1), Arc(5, 6, 1), Arc(6, 7, 1), Arc(7, 2, 1), Arc(4, 2, 1), Arc(3, 2, 1) ]) l, p, bfs_shortest_path_lst = \ base_scanning_method(graph, 1, least_distance_choice) animate_list(bfs_shortest_path_lst); ``` HBox(children=(Button(description='Prev', style=ButtonStyle()), Button(description='Next', style=ButtonStyle()… interactive(children=(IntSlider(value=0, description='step', max=13), Output()), _dom_classes=('widget-interac… На самом деле для того, чтобы при выборе вершины с минимальным расстоянием каждая вершина сканировалась единожды, достаточно более слабого условия -- чтобы в графе не было ребер с отрицательным весом. Ключевое соображение: кратчайший путь до вершины $v$ может проходить по тем вершинам, которые ближе к $s$, чем $v$. Из этого утверждения следует другое, чуть менее очевидное: если мы уже каким-то образом нашли первые $k$ ближайших вершин и посчитали минимальные пути, проходящие только через них, то расстояние до ближайшей из оставшихся вершин посчитано корректно. Если посмотреть на величины значения $l(v)$, которые мы получаем после $k$-ого сканирования (обозначим её за $l(v, k)$), то получится величина минимального пути от $s$ до $v$, имеющая в качестве промежуточных вершин только $k$ ближайших к $s$. Если обозначить за $u(k)$ -- $k$-ую ближайшую вершину к $s$, то мы получаем следующее соотношение $$ l(v, k)=\min\{l(v, k-1), l(u(k), k-1)+\omega(u(k)\rightarrow v)\} $$ Левая величина в минимуме -- это минимум среди путей, которые используют $u(k)$, правая -- минимум среди путей, которые не используют $u(k)$. ```python graph = Graph(arcs) l, p, dijkstra_shortest_path_lst = \ base_scanning_method(graph, 1, least_distance_choice) animate_list(dijkstra_shortest_path_lst); ``` HBox(children=(Button(description='Prev', style=ButtonStyle()), Button(description='Next', style=ButtonStyle()… interactive(children=(IntSlider(value=0, description='step', max=13), Output()), _dom_classes=('widget-interac… В общем виде этот метод впервые этого методы обосновал Эдсгер Дейкстра. Ключевым вопросом в этом алгоритме является нахождение минимальной вершины для сканирования. В случае, если все длины одинаковы, то это можно сделать обычной очередью: сохраняем в очереди все вершины с пометкой $labelled$, при сканировании ребра помещаем вершину в конец очереди если расстояние уменьшилось, при выборе новой вершины берем первую из очереди. В общем то в этом случае алгоритм вырождается в обход в глубину. В общем случае для работы с вершинами, помеченными $labelled$ необходима специальная структура данных, позволяющая быстро делать следующие операции: * Добавить вершину в множество * Обновить расстояние для вершины из множества * Найти миимальную по расстоянию вершину из множества * Удалить вершину из множества Одним из простых способов реализовать все эти операции -- использовании бинарной кучи или бинарного дерева, все операции выполняются за $\mathcal{O}(\log N)$, где $N$ -- размер множества, что ведет к общей сложности алгоритма в $\mathcal{O}(E\log V)$. Наиболее асимптотически оптимальный известный алгоритм использует [кучу фибоначчи](https://en.wikipedia.org/wiki/Fibonacci_heap), которая умеет делать первые три операции за $\mathcal{O}(1)$ и последнюю за $\mathcal{O}(\log N)$, что ведет к общей сложности $\mathcal{O}(E+V\log V)$ К сожалению все описанные рассуждения ломаются, если в графе возникают ребра отрицательной длины, например единственность сканирования пропадает например на следующем примере ```python graph = Graph([ Arc(1, 2, 2), Arc(1, 3, 3), Arc(3, 2, -2), Arc(2, 4, 1), ]) l, p, dijkstra_shortest_path_lst = \ base_scanning_method(graph, 1, least_distance_choice) animate_list(dijkstra_shortest_path_lst); ``` HBox(children=(Button(description='Prev', style=ButtonStyle()), Button(description='Next', style=ButtonStyle()… interactive(children=(IntSlider(value=0, description='step', max=9), Output()), _dom_classes=('widget-interact… ### Алгоритм Форда-Беллмана Частично этот алгоритм похож на перидыдущий тем, что по сути является просто применением обычной очереди для общего случая. Обычно алгоритм Форда-Беллмана имеет следующий вид ```python def ford_bellman(graph, s): l = {key: float('Inf') for key in graph.nodes.keys()} p = {key: None for key in graph.nodes.keys()} mark = {key: False for key in graph.nodes.keys()} l[s] = 0 mark[s] = True mark_labelled(graph.nodes[s]) out_lst = [graph.Visualize(l)] for k in range(len(graph.nodes)-1): for node in graph.nodes.values(): scan_node(node) out_lst.append(graph.Visualize(l)) return l, p, out_lst ``` Здесь я специально сделал так, что внешний цикл итерируется фиксированное число раз -- $V-1$, при этом переменная $i$ не используется. Внутренний цикл сканирует каждую вершину по одному разу, это эквивалентно тому, чтобы просканировать по одному разу каждое ребро. Оказывается, что такого количества проходов всегда достаточно, даже если в графе есть отрицательные ребра. Идея следующая: давайте рассмотрим величину $l(v, k)$ -- минимальная длина пути от $s$ до $v$, состоящего из не более, чем $k$ ребер, тогда для неё справедливо следующее соотношение $$ l(v, k)=\min \{l(v, k-1), \min_u[l(u, k-1)+\omega(u\rightarrow v)]\}. $$ Иначе говоря, либо оптимальный путь использует меньше, чем $k$ ребер, либо из него можно выделить последнее ребро, а оставшаяся часть использует $k-1$ ребро. Один проход по всем ребрам гарантирует нам переход от $l(v, k-1)$ к $l(v, k)$, однако из-за того, что мы не считаем непосредственно эти величины, а храним их в одном массиве $l$, то получается что на итерации $k$ у нас обычно чуть лучше, чем $l(v, k)$, охватывают пути не только длины $k$, но гарантировать мы может охват только таких путей. Наконец, после $V-1$ итераций мы обязательно охватим все простые пути. Если же оказалось, что после $V-1$ итерации сканирование ребер продолжит уменьшать вес, то в графе есть отрицательный цикл. Этот факт позволяет использовать Алгоритм Форда-Беллмана для нахождения отрицательных циклов. Возвращаясь к сканирующему методу: мы можем спокойно пропускать в цикле вершины, которые помечены $scanned$. С точки зрения вызовов $scan\_node$ это будет эквивалентно тому, чтобы использовать в сканирующем методе обычную очередь, но при этом использование очереди эффективнее. # Примеры из МО ### Алгоритм Витерби Одна из основных задач для марковских цепей заключается в том, чтобы найти последовательность состояний в марковской цепи наиболее правдоподобно соответствующую некоторой последовательности наблюдений $$ H(O)=argmax_{v=\{v_0, \ldots, v_n\}}\prod_{i=1}^nP(v_{i-1}\rightarrow v_i~|~O_i) $$ Например в распознавании речи $P(u\rightarrow v~|~O)$ -- это акустическая модель, классифицирующая кусок звука по нескольким языковым единицам, например фонемам. Из наиболее правдоподобной последовательности состояний можно извлечь последовательность фонем и в конце концов последовательность слов. Если немного переписать величину выше, можно получить в точности задачу о кратчайшем пути $$ argmax_{v=\{v_0, \ldots, v_n\}}\prod_{i=1}^nP(v_{i-1}\rightarrow v_i~|~O_i)=argmax_{v=\{v_0, \ldots, v_n\}}\sum_{i=1}^n\mathcal \log{P}(v_{i-1}\rightarrow v_i~|~O_i)=argmin_{v=\{v_0, \ldots, v_n\}}\sum_{i=1}^n(-\log P(v_{i-1}\rightarrow v_i~|~O_i)) $$ Стоит отметить, если $P$ -- вероятность, то что $-\log P\geq 0$, что, как мы уже обсудили, имеет значение для кратчайших путей, но не в этом случае. Пока что мы перешли от умножения к сложению, и от максимума к минимуму, но мы пока еще не получили задачу о кратчайшем пути: пока что у нас задача нахождения минимального пути, содержащую фиксированное число переходов, котором веса ребер зависят от времени. Эта задачу можно свести к обычной задаче о кратчачйшем пути на так расгиренном графе как на следующих примерах. ```python graph = Graph([ Arc(0, 1), Arc(1, 2), Arc(2, 0), Arc(1, 1), Arc(2, 2), Arc(0, 0) ]) graph.Visualize() ``` ```python expanded_graph = graph.expand_in_time(4) expanded_graph.Visualize() ``` ## Отслеживание объекта на плоскости Предположим, что у нас есть набор из $m$ сенсоров, расположенныз в точках $x_1, \ldots, x_m$ соответственно, которые умеют измерять расстояния до объекта (не важно, каким образом) и выдавать его в качестве функции правдоподобия (если сенсор выдает одно число, то можно считать, что он выдает индикатор-функцию для этого числа). Допустим мы снимаем показание на равных промежутках времени, на замере $t$ мы получаем функции правдоподобия $g_i(t, \|x-x_i\|)$. Оценка максимального правдоподобия положения объекта в пространстве c учетом сделанных замеров выглядит как-то так \begin{align*} x&=argmax_{y}\sum_{i=1}^m\log P(y~|~g_i) \\ &=argmax_{y}\sum_{i=1}^m\log [P(g_i~|~y)P(y)] \\ &=argmax_{y}\sum_{i=1}^m\sum_{t=0}^T\log [g_i(t, \|y(t)-x_i\|)P(y)] \end{align*} Если не накладывать никакие априорные ограничения ограничения на $x$, то вероятность $P(y)$ можно убрать и получить, что $$ x(t)=argmax_{z}\sum_{i=1}^T \log g_i(t, \|z-x_i\|), $$ т.е. оценка координат происходит раздельно раздельно. Такой подход например может привести к тому, что оценка будет сильно болтаться, в то время, как мы ожидаем, что между двумя последовательными оценками разница должна быть небольшой. ```python import numpy as np import scipy, scipy.stats, scipy.optimize from scipy.stats import chi2 class Sensor: def __init__(self, x, y, r=10, scale=4): self.position = np.array([x, y]) self.max_distortion_range = r self.distortion_scale = scale def loglikelihood(self, x, y, x_real, y_real): k = int(np.linalg.norm(self.position- np.array([x_real, y_real]))) p = random.randint(1, self.max_distortion_range) return chi2.logpdf(np.linalg.norm(self.position - np.array([x, y])), k) + self.distortion_scale * chi2.logpdf(np.linalg.norm(self.position - np.array([x, y])), p) ``` Здесь сенсоры моделируются с помощью $\chi$-квадрат распределения. Используется тот факт, что максимум ```python import matplotlib.pyplot as plt ``` ```python plt.rcParams['font.size'] = 15 plt.rcParams["figure.figsize"] = [11,11] ``` ```python path = [np.array([5, 5])] for i in range(30): dx = 2 * np.random.rand(2) - 1 path.append(path[-1] + dx) def paths(path): figures = [] for i in range(len(path)): fig = plt.figure() ax = fig.add_axes([0, 0, 1, 1]) ax.set(xlim=(-10, 20), ylim=(-10, 20)) ax.plot([x for x, y in path[:i+1]], [y for x, y in path[:i+1]]) ax.scatter([x for x, y in path[i:i+1]], [y for x, y in path[i:i+1]], color='black') plt.close(fig) figures.append(fig) return figures animate_list(paths(path)); ``` HBox(children=(Button(description='Prev', style=ButtonStyle()), Button(description='Next', style=ButtonStyle()… interactive(children=(IntSlider(value=0, description='step', max=30), Output()), _dom_classes=('widget-interac… ```python distortion_level = 0.25 distortion_radius = 20 bottom_left = -10 top_right = 20 sensors = [ Sensor(bottom_left, bottom_left, r = distortion_radius, scale=distortion_level), Sensor(bottom_left, top_right, r = distortion_radius,scale=distortion_level), Sensor(top_right, bottom_left, r = distortion_radius, scale=distortion_level), Sensor(top_right, top_right, r = distortion_radius, scale=distortion_level) ] def minimize_simple(f, x_min, y_min, x_max, y_max): best = (x_min, y_min, float('inf')) for i in range(10): for j in range(10): x = x_min + i * (x_max - x_min) / 10 y = y_min + j * (y_max - y_min) / 10 cost = f([x, y]) if best[2] > cost: best = (x, y, cost) for i in range(10): step = 1.0 / (i + 1) dx, dy = step * (np.random.rand(2) * 2 - 1) cost = f([best[0] + dx, best[1] + dy]) if cost < best[2]: best = (best[0] + dx, best[1] + dy, cost) return best[:2] estimates = [] prev = [0, 0] for x in path: def J(y): return -sum([sensor.loglikelihood(y[0], y[1], x[0], x[1]) for sensor in sensors]) #estimates.append(scipy.optimize.minimize(J, prev, method='Nelder-Mead').x) estimates.append(minimize_simple(J, bottom_left, bottom_left, top_right, top_right)) cur = estimates[-1] #print(J(cur), J([cur[0] - 1, cur[1]]), J([cur[0], cur[1] - 1]), J([cur[0] + 1, cur[1]]), J([cur[0], cur[1] + 1])) prev = estimates[-1] def two_paths(path, estimates): figures = [] for i in range(len(path)): fig = plt.figure() ax = fig.add_axes([0, 0, 1, 1]) ax.set(xlim=(-10, 20), ylim=(-10, 20)) ax.plot([x for x, y in path[:i+1]], [y for x, y in path[:i+1]]) ax.plot([x for x, y in estimates[:i+1]], [y for x, y in estimates[:i+1]]) ax.scatter([x for x, y in path[i:i+1]], [y for x, y in path[i:i+1]], color='black') ax.scatter([x for x, y in estimates[i:i+1]], [y for x, y in estimates[i:i+1]], color='black') plt.close(fig) figures.append(fig) return figures max_like_distances = [] for x, y in zip(path, estimates): max_like_distances.append(np.linalg.norm(x - y)) animate_list(two_paths(path, estimates)); ``` <ipython-input-15-798f0051bc5b>:14: RuntimeWarning: invalid value encountered in double_scalars return chi2.logpdf(np.linalg.norm(self.position - np.array([x, y])), k) + self.distortion_scale * chi2.logpdf(np.linalg.norm(self.position - np.array([x, y])), p) HBox(children=(Button(description='Prev', style=ButtonStyle()), Button(description='Next', style=ButtonStyle()… interactive(children=(IntSlider(value=0, description='step', max=30), Output()), _dom_classes=('widget-interac… Из-за помех получается так себе. Тем не менее мы можем попытаться как-то ограничить эти скачки, так как в реальном мире движение происходит планомерно. простой способ сделать это -- сузbть поиск максимума правдоподобия на фиксированном расстоянии от предыдущей оценки. ```python estimates = [] prev = [0, 0] for x in path: def J(y): return -sum([sensor.loglikelihood(y[0], y[1], x[0], x[1]) for sensor in sensors]) #estimates.append(scipy.optimize.minimize(J, prev, method='Nelder-Mead').x) estimates.append(minimize_simple(J, prev[0] - 1, prev[1] - 1, prev[0] + 1, prev[1] + 1)) cur = estimates[-1] prev = estimates[-1] animate_list(two_paths(path, estimates)); base_distances = [] for x, y in zip(path, estimates): base_distances.append(np.linalg.norm(x - y)) ``` HBox(children=(Button(description='Prev', style=ButtonStyle()), Button(description='Next', style=ButtonStyle()… interactive(children=(IntSlider(value=0, description='step', max=30), Output()), _dom_classes=('widget-interac… Уже лучше, но есть проблема, этот алгоритм все-таки жадный и учитывает только предыдущую оценку. Можно ограничить возможные точки поиска до заранее посчитанной сетки и смоделировать $P(y)$ марковской цепью на этой сетке: переходы разрешаются только на узлах, расстояние между которыми не больше некоторого порога. Таким образом мы получаем задачу поиска наиболее правдоподобной последовательности переходов в марковской цепи, где вероятноть перехода соответствует правдоподобию нахждения в узле на конце этого перехода ```python pre_grid = [[(bottom_left + i * (top_right - bottom_left) / 30, bottom_left + j * (top_right - bottom_left) / 30) for j in range(31)] for i in range(31)] grid = [] for row in pre_grid: grid.extend(row) allowed_transitions = [] for i in range(len(grid)): allowed_transitions.append([]) for j in range(len(grid)): if np.linalg.norm(np.array(grid[i]) - np.array(grid[j])) <= 1.0: allowed_transitions[-1].append(j) ``` ```python beam = 5.0 history_importance = 1.0 estimates = [] for i in range(len(grid)): if abs(grid[i][0]) < 0.5 and abs(grid[i][1]) < 0.5: token = (i, 0.0, None) break tokens = [token] for x in path: def J(y): return -sum([sensor.loglikelihood(y[0], y[1], x[0], x[1]) for sensor in sensors]) new_tokens = dict() J_cache = dict() best_cost = float('inf') for token in tokens: state, cost, prev = token for j in allowed_transitions[state]: if j not in J_cache: new_cost = J(grid[j]) J_cache[j] = new_cost else: new_cost = J_cache[j] if new_cost + history_importance * cost > best_cost + beam: continue if j not in new_tokens or new_tokens[j][1] > new_cost + cost: new_tokens[j] = (j, new_cost + history_importance * cost, token) best_cost = min(best_cost, new_cost + history_importance * cost) tokens = new_tokens.values() #print(best_cost) reversed_estimates = [] tmp = min(tokens, key=lambda x: x[1]) while tmp is not None: reversed_estimates.append(grid[tmp[0]]) tmp = tmp[2] estimates = list(reversed(reversed_estimates)) markov_beam_search_distances = [] for x, y in zip(path, estimates): markov_beam_search_distances.append(np.linalg.norm(x - y)) animate_list(two_paths(path, estimates)); ``` HBox(children=(Button(description='Prev', style=ButtonStyle()), Button(description='Next', style=ButtonStyle()… interactive(children=(IntSlider(value=0, description='step', max=30), Output()), _dom_classes=('widget-interac… К сожалению довольно часто этот код уводит приближение на бесконечность, скорее всего это происходит просто из-за ошибок вычисления и помех ```python plt.plot([i for i in range(len(base_distances))], max_like_distances, label='Расстояние оценом МП') plt.plot([i for i in range(len(base_distances))], base_distances, label='Расстояние в простом режиме') plt.plot([i for i in range(len(base_distances))], markov_beam_search_distances, label='Расстояние при лучевом поиске') plt.legend() plt.show() ```
\chapter*{Notation} \addcontentsline{toc}{chapter}{Notation} Following notation is used throughout this text: \bigskip \begin{tabular}{l p{0.8\textwidth}} \(\mathbb{N}\) & set of natural numbers excluding zero \\ \(\mathbb{N}_0\) & set of natural numbers including zero \\ \(\mathbb{R}\) & set of real numbers \\ \(t\) & discrete time moment; \(t \in \mathbb{N}_0\) \\ \(a_t\) & value of quantity \(a\) at time \(t\); \(a_t \in \mathbb{R}^n, n \in \mathbb{N}\) \\ \(a_{t|t'}\) & quantity with two indices: \(t\) and \(t'\) \\ & there is no implicit link between \(a_{t}\), \(a_{t|t'}\) and \(a_{t'}\) \\ \(a_{t:t'}\) & sequence of quantities \((a_t, a_{t+1}, \dotsc, a_{t'-1}, a_{t'})\) \\ \(p(a_t)\) & probability density function{\footnotemark[1]} of quantity \(a\) at time \(t\) (unless noted otherwise) \\ \(p(a_t|b_{t'})\) & conditional {\pdf} of quantity \(a\) at time \(t\) given value of quantity \(b\) at time \(t'\) \\ \(\delta(a)\) & Dirac delta function; used exclusively in context of {\pdfs} to denote discrete distribution within framework of continuous distributions{\footnotemark[2]} \\ \(\mathcal{N}(\mu, \Sigma)\) & multivariate normal (Gaussian) {\pdf} with mean vector \(\mu\) and covariance matrix \(\Sigma\) \\ \end{tabular} % \footnote does not work in tabular environment, - this can be worked around with this \footnotetext[1]{for the purpose of this text, {\pdf} \(p\) is multivariate non-negative function \(\mathbb{R}^n \rightarrow \mathbb{R}; \; \int_{\supp p} p(x_1, x_2, \dotsc, x_n) \; \dx_1 \dx_2 \dotsb \dx_n = 1\)} \footnotetext[2]{so that \(\int_{-\infty}^{\infty} f(x) \delta(x - \mu) \; \dx = f(\mu)\) and more complex expressions can be derived using integral linearity and Fubini's theorem.}
(* Title: HOL/Auth/Guard/Guard_Public.thy Author: Frederic Blanqui, University of Cambridge Computer Laboratory Copyright 2002 University of Cambridge Lemmas on guarded messages for public protocols. *) theory Guard_Public imports Guard "../Public" Extensions begin subsection\<open>Extensions to Theory \<open>Public\<close>\<close> declare initState.simps [simp del] subsubsection\<open>signature\<close> definition sign :: "agent => msg => msg" where "sign A X == \<lbrace>Agent A, X, Crypt (priK A) (Hash X)\<rbrace>" lemma sign_inj [iff]: "(sign A X = sign A' X') = (A=A' & X=X')" by (auto simp: sign_def) subsubsection\<open>agent associated to a key\<close> definition agt :: "key => agent" where "agt K == SOME A. K = priK A | K = pubK A" lemma agt_priK [simp]: "agt (priK A) = A" by (simp add: agt_def) lemma agt_pubK [simp]: "agt (pubK A) = A" by (simp add: agt_def) subsubsection\<open>basic facts about \<^term>\<open>initState\<close>\<close> lemma no_Crypt_in_parts_init [simp]: "Crypt K X \<notin> parts (initState A)" by (cases A, auto simp: initState.simps) lemma no_Crypt_in_analz_init [simp]: "Crypt K X \<notin> analz (initState A)" by auto lemma no_priK_in_analz_init [simp]: "A \<notin> bad \<Longrightarrow> Key (priK A) \<notin> analz (initState Spy)" by (auto simp: initState.simps) lemma priK_notin_initState_Friend [simp]: "A \<noteq> Friend C \<Longrightarrow> Key (priK A) \<notin> parts (initState (Friend C))" by (auto simp: initState.simps) lemma keyset_init [iff]: "keyset (initState A)" by (cases A, auto simp: keyset_def initState.simps) subsubsection\<open>sets of private keys\<close> definition priK_set :: "key set => bool" where "priK_set Ks \<equiv> \<forall>K. K \<in> Ks \<longrightarrow> (\<exists>A. K = priK A)" lemma in_priK_set: "[| priK_set Ks; K \<in> Ks |] ==> \<exists>A. K = priK A" by (simp add: priK_set_def) lemma priK_set1 [iff]: "priK_set {priK A}" by (simp add: priK_set_def) lemma priK_set2 [iff]: "priK_set {priK A, priK B}" by (simp add: priK_set_def) subsubsection\<open>sets of good keys\<close> definition good :: "key set => bool" where "good Ks == \<forall>K. K \<in> Ks \<longrightarrow> agt K \<notin> bad" lemma in_good: "[| good Ks; K \<in> Ks |] ==> agt K \<notin> bad" by (simp add: good_def) lemma good1 [simp]: "A \<notin> bad \<Longrightarrow> good {priK A}" by (simp add: good_def) lemma good2 [simp]: "[| A \<notin> bad; B \<notin> bad |] ==> good {priK A, priK B}" by (simp add: good_def) subsubsection\<open>greatest nonce used in a trace, 0 if there is no nonce\<close> primrec greatest :: "event list => nat" where "greatest [] = 0" | "greatest (ev # evs) = max (greatest_msg (msg ev)) (greatest evs)" lemma greatest_is_greatest: "Nonce n \<in> used evs \<Longrightarrow> n \<le> greatest evs" apply (induct evs, auto simp: initState.simps) apply (drule used_sub_parts_used, safe) apply (drule greatest_msg_is_greatest, arith) by simp subsubsection\<open>function giving a new nonce\<close> definition new :: "event list \<Rightarrow> nat" where "new evs \<equiv> Suc (greatest evs)" lemma new_isnt_used [iff]: "Nonce (new evs) \<notin> used evs" by (clarify, drule greatest_is_greatest, auto simp: new_def) subsection\<open>Proofs About Guarded Messages\<close> subsubsection\<open>small hack necessary because priK is defined as the inverse of pubK\<close> lemma pubK_is_invKey_priK: "pubK A = invKey (priK A)" by simp lemmas pubK_is_invKey_priK_substI = pubK_is_invKey_priK [THEN ssubst] lemmas invKey_invKey_substI = invKey [THEN ssubst] lemma "Nonce n \<in> parts {X} \<Longrightarrow> Crypt (pubK A) X \<in> guard n {priK A}" apply (rule pubK_is_invKey_priK_substI, rule invKey_invKey_substI) by (rule Guard_Nonce, simp+) subsubsection\<open>guardedness results\<close> lemma sign_guard [intro]: "X \<in> guard n Ks \<Longrightarrow> sign A X \<in> guard n Ks" by (auto simp: sign_def) lemma Guard_init [iff]: "Guard n Ks (initState B)" by (induct B, auto simp: Guard_def initState.simps) lemma Guard_knows_max': "Guard n Ks (knows_max' C evs) ==> Guard n Ks (knows_max C evs)" by (simp add: knows_max_def) lemma Nonce_not_used_Guard_spies [dest]: "Nonce n \<notin> used evs \<Longrightarrow> Guard n Ks (spies evs)" by (auto simp: Guard_def dest: not_used_not_known parts_sub) lemma Nonce_not_used_Guard [dest]: "[| evs \<in> p; Nonce n \<notin> used evs; Gets_correct p; one_step p |] ==> Guard n Ks (knows (Friend C) evs)" by (auto simp: Guard_def dest: known_used parts_trans) lemma Nonce_not_used_Guard_max [dest]: "[| evs \<in> p; Nonce n \<notin> used evs; Gets_correct p; one_step p |] ==> Guard n Ks (knows_max (Friend C) evs)" by (auto simp: Guard_def dest: known_max_used parts_trans) lemma Nonce_not_used_Guard_max' [dest]: "[| evs \<in> p; Nonce n \<notin> used evs; Gets_correct p; one_step p |] ==> Guard n Ks (knows_max' (Friend C) evs)" apply (rule_tac H="knows_max (Friend C) evs" in Guard_mono) by (auto simp: knows_max_def) subsubsection\<open>regular protocols\<close> definition regular :: "event list set \<Rightarrow> bool" where "regular p \<equiv> \<forall>evs A. evs \<in> p \<longrightarrow> (Key (priK A) \<in> parts (spies evs)) = (A \<in> bad)" lemma priK_parts_iff_bad [simp]: "[| evs \<in> p; regular p |] ==> (Key (priK A) \<in> parts (spies evs)) = (A \<in> bad)" by (auto simp: regular_def) lemma priK_analz_iff_bad [simp]: "[| evs \<in> p; regular p |] ==> (Key (priK A) \<in> analz (spies evs)) = (A \<in> bad)" by auto lemma Guard_Nonce_analz: "[| Guard n Ks (spies evs); evs \<in> p; priK_set Ks; good Ks; regular p |] ==> Nonce n \<notin> analz (spies evs)" apply (clarify, simp only: knows_decomp) apply (drule Guard_invKey_keyset, simp+, safe) apply (drule in_good, simp) apply (drule in_priK_set, simp+, clarify) apply (frule_tac A=A in priK_analz_iff_bad) by (simp add: knows_decomp)+ end
If $s$ is a closed set and $a \notin s$, then there exists a positive real number $d$ such that for all $x \in s$, we have $d \leq |a - x|$.
function x=pcmu2lin(p,s) %PCMU2LIN Convert Mu-law PCM to linear X=(P,S) % lin = pcmu2lin(pcmu) where pcmu contains a vector % of mu-law values in the range 0 to 255. % No checking is performed to see that numbers are in this range. % % Output values are divided by the scale factor s: % % s Output Range % % 1 +-8031 (integer values) % 4004.2 +-2.005649 (default) % 8031 +-1 % 8159 +-0.9843118 (+-1 nominal full scale) % % The default scaling factor 4004.189931 is equal to % sqrt((2207^2 + 5215^2)/2) this follows ITU standard G.711. % The sine wave with PCM-Mu values [158 139 139 158 30 11 11 30] % has a mean square value of unity corresponding to 0 dBm0. % Copyright (C) Mike Brookes 1998 % Version: $Id: pcmu2lin.m,v 1.4 2007/05/04 07:01:39 dmb Exp $ % % VOICEBOX is a MATLAB toolbox for speech processing. % Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You can obtain a copy of the GNU General Public License from % http://www.gnu.org/copyleft/gpl.html or by writing to % Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargin<2 t=9.98953613E-4; else t=4/s; end m=15-rem(p,16); q=floor(p/128); e=(127-p-m+128*q)/16; x=(q-0.5).*(pow2(m+16.5,e)-16.5)*t;
/- Copyright (c) 2019 Jean Lo. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jean Lo, Bhavik Mehta, Yaël Dillies -/ import analysis.normed_space.basic /-! # Local convexity This file defines absorbent and balanced sets. An absorbent set is one that "surrounds" the origin. The idea is made precise by requiring that any point belongs to all large enough scalings of the set. This is the vector world analog of a topological neighborhood of the origin. A balanced set is one that is everywhere around the origin. This means that `a • s ⊆ s` for all `a` of norm less than `1`. ## Main declarations For a module over a normed ring: * `absorbs`: A set `s` absorbs a set `t` if all large scalings of `s` contain `t`. * `absorbent`: A set `s` is absorbent if every point eventually belongs to all large scalings of `s`. * `balanced`: A set `s` is balanced if `a • s ⊆ s` for all `a` of norm less than `1`. ## References * [H. H. Schaefer, *Topological Vector Spaces*][schaefer1966] ## Tags absorbent, balanced, locally convex, LCTVS -/ open set open_locale pointwise topological_space variables {𝕜 𝕝 E ι : Type*} section semi_normed_ring variables [semi_normed_ring 𝕜] section has_scalar variables (𝕜) [has_scalar 𝕜 E] /-- A set `A` absorbs another set `B` if `B` is contained in all scalings of `A` by elements of sufficiently large norm. -/ def absorbs (A B : set E) := ∃ r, 0 < r ∧ ∀ a : 𝕜, r ≤ ∥a∥ → B ⊆ a • A variables {𝕜} {s t u v A B : set E} @[simp] lemma absorbs_empty {s : set E}: absorbs 𝕜 s (∅ : set E) := ⟨1, one_pos, λ a ha, set.empty_subset _⟩ lemma absorbs.mono (hs : absorbs 𝕜 s u) (hst : s ⊆ t) (hvu : v ⊆ u) : absorbs 𝕜 t v := let ⟨r, hr, h⟩ := hs in ⟨r, hr, λ a ha, hvu.trans $ (h _ ha).trans $ smul_set_mono hst⟩ lemma absorbs.mono_left (hs : absorbs 𝕜 s u) (h : s ⊆ t) : absorbs 𝕜 t u := hs.mono h subset.rfl lemma absorbs.mono_right (hs : absorbs 𝕜 s u) (h : v ⊆ u) : absorbs 𝕜 s v := hs.mono subset.rfl h lemma absorbs.union (hu : absorbs 𝕜 s u) (hv : absorbs 𝕜 s v) : absorbs 𝕜 s (u ∪ v) := begin obtain ⟨a, ha, hu⟩ := hu, obtain ⟨b, hb, hv⟩ := hv, exact ⟨max a b, lt_max_of_lt_left ha, λ c hc, union_subset (hu _ $ le_of_max_le_left hc) (hv _ $ le_of_max_le_right hc)⟩, end @[simp] lemma absorbs_union : absorbs 𝕜 s (u ∪ v) ↔ absorbs 𝕜 s u ∧ absorbs 𝕜 s v := ⟨λ h, ⟨h.mono_right $ subset_union_left _ _, h.mono_right $ subset_union_right _ _⟩, λ h, h.1.union h.2⟩ lemma absorbs_Union_finset {s : set E} {t : finset ι} {f : ι → set E} : absorbs 𝕜 s (⋃ (i ∈ t), f i) ↔ ∀ i ∈ t, absorbs 𝕜 s (f i) := begin classical, induction t using finset.induction_on with i t ht hi, { simp only [finset.not_mem_empty, set.Union_false, set.Union_empty, absorbs_empty, forall_false_left, implies_true_iff] }, rw [finset.set_bUnion_insert, absorbs_union, hi], split; intro h, { refine λ _ hi', (finset.mem_insert.mp hi').elim _ (h.2 _), exact (λ hi'', by { rw hi'', exact h.1 }) }, exact ⟨h i (finset.mem_insert_self i t), λ i' hi', h i' (finset.mem_insert_of_mem hi')⟩, end lemma set.finite.absorbs_Union {s : set E} {t : set ι} {f : ι → set E} (hi : t.finite) : absorbs 𝕜 s (⋃ (i : ι) (hy : i ∈ t), f i) ↔ ∀ i ∈ t, absorbs 𝕜 s (f i) := begin lift t to finset ι using hi, simp only [finset.mem_coe], exact absorbs_Union_finset, end variables (𝕜) /-- A set is absorbent if it absorbs every singleton. -/ def absorbent (A : set E) := ∀ x, ∃ r, 0 < r ∧ ∀ a : 𝕜, r ≤ ∥a∥ → x ∈ a • A variables {𝕜} lemma absorbent.subset (hA : absorbent 𝕜 A) (hAB : A ⊆ B) : absorbent 𝕜 B := begin refine forall_imp (λ x, _) hA, exact Exists.imp (λ r, and.imp_right $ forall₂_imp $ λ a ha hx, set.smul_set_mono hAB hx), end lemma absorbent_iff_forall_absorbs_singleton : absorbent 𝕜 A ↔ ∀ x, absorbs 𝕜 A {x} := by simp_rw [absorbs, absorbent, singleton_subset_iff] lemma absorbent.absorbs (hs : absorbent 𝕜 s) {x : E} : absorbs 𝕜 s {x} := absorbent_iff_forall_absorbs_singleton.1 hs _ lemma absorbent_iff_nonneg_lt : absorbent 𝕜 A ↔ ∀ x, ∃ r, 0 ≤ r ∧ ∀ ⦃a : 𝕜⦄, r < ∥a∥ → x ∈ a • A := forall_congr $ λ x, ⟨λ ⟨r, hr, hx⟩, ⟨r, hr.le, λ a ha, hx a ha.le⟩, λ ⟨r, hr, hx⟩, ⟨r + 1, add_pos_of_nonneg_of_pos hr zero_lt_one, λ a ha, hx ((lt_add_of_pos_right r zero_lt_one).trans_le ha)⟩⟩ lemma absorbent.absorbs_finite {s : set E} (hs : absorbent 𝕜 s) {v : set E} (hv : v.finite) : absorbs 𝕜 s v := begin rw ←set.bUnion_of_singleton v, exact hv.absorbs_Union.mpr (λ _ _, hs.absorbs), end variables (𝕜) /-- A set `A` is balanced if `a • A` is contained in `A` whenever `a` has norm at most `1`. -/ def balanced (A : set E) := ∀ a : 𝕜, ∥a∥ ≤ 1 → a • A ⊆ A variables {𝕜} lemma balanced_mem {s : set E} (hs : balanced 𝕜 s) {x : E} (hx : x ∈ s) {a : 𝕜} (ha : ∥a∥ ≤ 1) : a • x ∈ s := mem_of_subset_of_mem (hs a ha) (smul_mem_smul_set hx) lemma balanced_univ : balanced 𝕜 (univ : set E) := λ a ha, subset_univ _ lemma balanced.union (hA : balanced 𝕜 A) (hB : balanced 𝕜 B) : balanced 𝕜 (A ∪ B) := begin intros a ha t ht, rw smul_set_union at ht, exact ht.imp (λ x, hA _ ha x) (λ x, hB _ ha x), end lemma balanced.inter (hA : balanced 𝕜 A) (hB : balanced 𝕜 B) : balanced 𝕜 (A ∩ B) := begin rintro a ha _ ⟨x, ⟨hx₁, hx₂⟩, rfl⟩, exact ⟨hA _ ha ⟨_, hx₁, rfl⟩, hB _ ha ⟨_, hx₂, rfl⟩⟩, end end has_scalar section add_comm_monoid variables [add_comm_monoid E] [module 𝕜 E] {s s' t t' u v A B : set E} lemma absorbs.add (h : absorbs 𝕜 s t) (h' : absorbs 𝕜 s' t') : absorbs 𝕜 (s + s') (t + t') := begin rcases h with ⟨r, hr, h⟩, rcases h' with ⟨r', hr', h'⟩, refine ⟨max r r', lt_max_of_lt_left hr, λ a ha, _⟩, rw smul_add, exact set.add_subset_add (h a (le_of_max_le_left ha)) (h' a (le_of_max_le_right ha)), end lemma balanced.add (hA₁ : balanced 𝕜 A) (hA₂ : balanced 𝕜 B) : balanced 𝕜 (A + B) := begin rintro a ha _ ⟨_, ⟨x, y, hx, hy, rfl⟩, rfl⟩, rw smul_add, exact add_mem_add (hA₁ _ ha ⟨_, hx, rfl⟩) (hA₂ _ ha ⟨_, hy, rfl⟩), end lemma zero_singleton_balanced : balanced 𝕜 ({0} : set E) := λ a ha, by simp only [smul_set_singleton, smul_zero] end add_comm_monoid end semi_normed_ring section normed_comm_ring variables [normed_comm_ring 𝕜] [add_comm_monoid E] [module 𝕜 E] {A B : set E} (a : 𝕜) lemma balanced.smul (hA : balanced 𝕜 A) : balanced 𝕜 (a • A) := begin rintro b hb _ ⟨_, ⟨x, hx, rfl⟩, rfl⟩, exact ⟨b • x, hA _ hb ⟨_, hx, rfl⟩, smul_comm _ _ _⟩, end end normed_comm_ring section normed_field variables [normed_field 𝕜] [normed_ring 𝕝] [normed_space 𝕜 𝕝] [add_comm_group E] [module 𝕜 E] [smul_with_zero 𝕝 E] [is_scalar_tower 𝕜 𝕝 E] {s t u v A B : set E} {a b : 𝕜} /-- Scalar multiplication (by possibly different types) of a balanced set is monotone. -/ lemma balanced.smul_mono (hs : balanced 𝕝 s) {a : 𝕝} {b : 𝕜} (h : ∥a∥ ≤ ∥b∥) : a • s ⊆ b • s := begin obtain rfl | hb := eq_or_ne b 0, { rw norm_zero at h, rw norm_eq_zero.1 (h.antisymm $ norm_nonneg _), obtain rfl | h := s.eq_empty_or_nonempty, { simp_rw [smul_set_empty] }, { simp_rw [zero_smul_set h] } }, rintro _ ⟨x, hx, rfl⟩, refine ⟨b⁻¹ • a • x, _, smul_inv_smul₀ hb _⟩, rw ←smul_assoc, refine hs _ _ (smul_mem_smul_set hx), rw [norm_smul, norm_inv, ←div_eq_inv_mul], exact div_le_one_of_le h (norm_nonneg _), end /-- A balanced set absorbs itself. -/ lemma balanced.absorbs_self (hA : balanced 𝕜 A) : absorbs 𝕜 A A := begin refine ⟨1, zero_lt_one, λ a ha x hx, _⟩, rw mem_smul_set_iff_inv_smul_mem₀ (norm_pos_iff.1 $ zero_lt_one.trans_le ha), refine hA a⁻¹ _ (smul_mem_smul_set hx), rw norm_inv, exact inv_le_one ha, end lemma balanced.subset_smul (hA : balanced 𝕜 A) (ha : 1 ≤ ∥a∥) : A ⊆ a • A := begin refine (subset_set_smul_iff₀ _).2 (hA (a⁻¹) _), { rintro rfl, rw norm_zero at ha, exact zero_lt_one.not_le ha }, { rw norm_inv, exact inv_le_one ha } end lemma balanced.smul_eq (hA : balanced 𝕜 A) (ha : ∥a∥ = 1) : a • A = A := (hA _ ha.le).antisymm $ hA.subset_smul ha.ge lemma absorbs.inter (hs : absorbs 𝕜 s u) (ht : absorbs 𝕜 t u) : absorbs 𝕜 (s ∩ t) u := begin obtain ⟨a, ha, hs⟩ := hs, obtain ⟨b, hb, ht⟩ := ht, have h : 0 < max a b := lt_max_of_lt_left ha, refine ⟨max a b, lt_max_of_lt_left ha, λ c hc, _⟩, rw smul_set_inter₀ (norm_pos_iff.1 $ h.trans_le hc), exact subset_inter (hs _ $ le_of_max_le_left hc) (ht _ $ le_of_max_le_right hc), end @[simp] lemma absorbs_inter : absorbs 𝕜 (s ∩ t) u ↔ absorbs 𝕜 s u ∧ absorbs 𝕜 t u := ⟨λ h, ⟨h.mono_left $ inter_subset_left _ _, h.mono_left $ inter_subset_right _ _⟩, λ h, h.1.inter h.2⟩ lemma absorbent_univ : absorbent 𝕜 (univ : set E) := begin refine λ x, ⟨1, zero_lt_one, λ a ha, _⟩, rw smul_set_univ₀ (norm_pos_iff.1 $ zero_lt_one.trans_le ha), exact trivial, end variables [topological_space E] [has_continuous_smul 𝕜 E] /-- Every neighbourhood of the origin is absorbent. -/ lemma absorbent_nhds_zero (hA : A ∈ 𝓝 (0 : E)) : absorbent 𝕜 A := begin intro x, obtain ⟨w, hw₁, hw₂, hw₃⟩ := mem_nhds_iff.mp hA, have hc : continuous (λ t : 𝕜, t • x) := continuous_id.smul continuous_const, obtain ⟨r, hr₁, hr₂⟩ := metric.is_open_iff.mp (hw₂.preimage hc) 0 (by rwa [mem_preimage, zero_smul]), have hr₃ := inv_pos.mpr (half_pos hr₁), refine ⟨(r / 2)⁻¹, hr₃, λ a ha₁, _⟩, have ha₂ : 0 < ∥a∥ := hr₃.trans_le ha₁, refine (mem_smul_set_iff_inv_smul_mem₀ (norm_pos_iff.mp ha₂) _ _).2 (hw₁ $ hr₂ _), rw [metric.mem_ball, dist_zero_right, norm_inv], calc ∥a∥⁻¹ ≤ r/2 : (inv_le (half_pos hr₁) ha₂).mp ha₁ ... < r : half_lt_self hr₁, end /-- The union of `{0}` with the interior of a balanced set is balanced. -/ lemma balanced_zero_union_interior (hA : balanced 𝕜 A) : balanced 𝕜 ((0 : set E) ∪ interior A) := begin intros a ha, obtain rfl | h := eq_or_ne a 0, { rw zero_smul_set, exacts [subset_union_left _ _, ⟨0, or.inl rfl⟩] }, { rw [←image_smul, image_union], apply union_subset_union, { rw [image_zero, smul_zero], refl }, { calc a • interior A ⊆ interior (a • A) : (is_open_map_smul₀ h).image_interior_subset A ... ⊆ interior A : interior_mono (hA _ ha) } } end /-- The interior of a balanced set is balanced if it contains the origin. -/ lemma balanced.interior (hA : balanced 𝕜 A) (h : (0 : E) ∈ interior A) : balanced 𝕜 (interior A) := begin rw ←union_eq_self_of_subset_left (singleton_subset_iff.2 h), exact balanced_zero_union_interior hA, end lemma balanced.closure (hA : balanced 𝕜 A) : balanced 𝕜 (closure A) := λ a ha, (image_closure_subset_closure_image $ continuous_id.const_smul _).trans $ closure_mono $ hA _ ha end normed_field section nondiscrete_normed_field variables [nondiscrete_normed_field 𝕜] [add_comm_group E] [module 𝕜 E] {s : set E} lemma absorbs_zero_iff : absorbs 𝕜 s 0 ↔ (0 : E) ∈ s := begin refine ⟨_, λ h, ⟨1, zero_lt_one, λ a _, zero_subset.2 $ zero_mem_smul_set h⟩⟩, rintro ⟨r, hr, h⟩, obtain ⟨a, ha⟩ := normed_space.exists_lt_norm 𝕜 𝕜 r, have := h _ ha.le, rwa [zero_subset, zero_mem_smul_set_iff] at this, exact norm_ne_zero_iff.1 (hr.trans ha).ne', end lemma absorbent.zero_mem (hs : absorbent 𝕜 s) : (0 : E) ∈ s := absorbs_zero_iff.1 $ absorbent_iff_forall_absorbs_singleton.1 hs _ end nondiscrete_normed_field
import order.with_bot open function namespace with_bot variables {α : Type*} {C : with_bot α → Sort*} (h₁ : C ⊥) (h₂ : Π a : α, C ↑a) lemma coe_ne_coe {a b : α} : (a : with_bot α) ≠ b ↔ a ≠ b := coe_eq_coe.not instance [has_lt α] [is_well_order α (<)] : is_strict_total_order (with_bot α) (<) := begin classical, letI : linear_order α := linear_order_of_STO (<), apply_instance end instance [preorder α] [is_well_order α (<)] : is_well_order (with_bot α) (<) := {} end with_bot
module parameter_scan_arrays implicit none private public :: current_scan_parameter_value, write_scan_parameter public :: run_scan, scan_parameter_switch, scan_spec public :: scan_parameter_tprim, scan_parameter_g_exb public :: hflux_tot, momflux_tot, phi2_tot public :: growth_rate, nout real :: current_scan_parameter_value logical :: write_scan_parameter logical :: run_scan integer :: scan_parameter_switch integer, parameter :: scan_parameter_tprim = 1, scan_parameter_g_exb = 2 integer :: scan_spec integer :: nout real, dimension(:), allocatable :: hflux_tot, momflux_tot, phi2_tot real, dimension(:), allocatable :: growth_rate end module parameter_scan_arrays
section "Auxiliary algebraic laws for abrupt designs" theory algebraic_laws_fault_aux imports "../../../theories/Fault/utp_fault_designs" begin named_theorems uflt_simpl and uflt_cond and uflt_comp and uflt_lens subsection {*THM setup*} declare design_condr[urel_cond] subsection {*abrupt alphabet behavior*} lemma assigns_flt_alpha: "(fault :== (\<not> &fault)) = (\<lceil>II\<rceil>\<^sub>F\<^sub>L\<^sub>T \<and> $fault\<acute> =\<^sub>u (\<not>$fault) \<and> $ok =\<^sub>u $ok\<acute>)" "(ok :== (\<not> &ok)) = (\<lceil>II\<rceil>\<^sub>F\<^sub>L\<^sub>T \<and> $fault\<acute> =\<^sub>u $fault \<and> $ok =\<^sub>u (\<not>$ok\<acute>))" by rel_auto+ lemma vwb_of_fault[simp]: "vwb_lens ok" "vwb_lens fault" by simp_all lemma unrest_pre_out\<alpha>_flt[unrest]: "out\<alpha> \<sharp> \<lceil>b\<rceil>\<^sub>F\<^sub>L\<^sub>T\<^sub><" by (transfer, auto simp add: out\<alpha>_def lens_prod_def) lemma unrest_post_in\<alpha>_flt[unrest]: "in\<alpha> \<sharp> \<lceil>b\<rceil>\<^sub>F\<^sub>L\<^sub>T\<^sub>>" by (transfer, auto simp add: in\<alpha>_def lens_prod_def) lemma unrest_ok_fault_rel_uexpr_lift_cpf[unrest]: "$ok \<sharp> \<lceil>P\<rceil>\<^sub>F\<^sub>L\<^sub>T" "$ok\<acute> \<sharp> \<lceil>P\<rceil>\<^sub>F\<^sub>L\<^sub>T" "$fault \<sharp> \<lceil>P\<rceil>\<^sub>F\<^sub>L\<^sub>T" "$fault\<acute> \<sharp> \<lceil>P\<rceil>\<^sub>F\<^sub>L\<^sub>T" by (pred_auto)+ lemma unrest_ok_fault_rel_usubst_lift_cpf[unrest]: "$ok\<acute> \<sharp> \<lceil>\<sigma>\<rceil>\<^sub>S\<^sub>F\<^sub>L\<^sub>T" "$ok \<sharp> \<lceil>\<sigma>\<rceil>\<^sub>S\<^sub>F\<^sub>L\<^sub>T" "$fault\<acute> \<sharp> \<lceil>\<sigma>\<rceil>\<^sub>S\<^sub>F\<^sub>L\<^sub>T" "$fault \<sharp> \<lceil>\<sigma>\<rceil>\<^sub>S\<^sub>F\<^sub>L\<^sub>T" by rel_auto+ lemma unrest_in_out_rel_ok_fault_res_flt [unrest]: "$ok \<sharp> (P \<restriction>\<^sub>\<alpha> ok)" "$ok\<acute> \<sharp> (P \<restriction>\<^sub>\<alpha> ok)" "$fault \<sharp> (P \<restriction>\<^sub>\<alpha> fault)" "$fault\<acute> \<sharp> (P \<restriction>\<^sub>\<alpha> fault)" by (simp_all add: rel_var_res_def unrest) lemma uflt_alphabet_unrest[unrest]:(*FIXEME:These laws should be generated automatically by alphabet backend since all the fields of alphabet are independant*) "$ok\<acute> \<sharp> $fault\<acute>" "$ok \<sharp> $fault" "$ok\<acute> \<sharp> $x" "$ok \<sharp> $fault\<acute>" "$fault\<acute> \<sharp> $ok\<acute>" "$fault \<sharp> $ok " "$fault \<sharp> $ok\<acute>" "$fault\<acute> \<sharp> $x" by pred_simp+ lemma cpf_ord [usubst]: "$ok \<prec>\<^sub>v $ok\<acute>" "$abrupt \<prec>\<^sub>v $abrupt\<acute>" "$ok \<prec>\<^sub>v $abrupt\<acute>" "$ok \<prec>\<^sub>v $abrupt" "$ok\<acute> \<prec>\<^sub>v $abrupt\<acute>" "$ok\<acute> \<prec>\<^sub>v $abrupt" by (simp_all add: var_name_ord_def) lemma rel_usubst_lift_cpf_in_out_fault_ok[usubst]: "\<lceil>\<sigma>\<rceil>\<^sub>S\<^sub>F\<^sub>L\<^sub>T \<dagger> $fault = $fault" "\<lceil>\<sigma>\<rceil>\<^sub>S\<^sub>F\<^sub>L\<^sub>T \<dagger> (\<not>$fault) = (\<not>$fault)" "\<lceil>\<sigma>\<rceil>\<^sub>S\<^sub>F\<^sub>L\<^sub>T \<dagger> ($ok) = ($ok)" "\<lceil>\<sigma>\<rceil>\<^sub>S\<^sub>F\<^sub>L\<^sub>T \<dagger> (\<not>$ok) = (\<not>$ok)" "\<lceil>\<sigma>\<rceil>\<^sub>S\<^sub>F\<^sub>L\<^sub>T \<dagger> ($fault\<acute>) = (($fault\<acute>))" "\<lceil>\<sigma>\<rceil>\<^sub>S\<^sub>F\<^sub>L\<^sub>T \<dagger> (\<not>$fault\<acute>) = (\<not>$fault\<acute>)" "\<lceil>\<sigma>\<rceil>\<^sub>S\<^sub>F\<^sub>L\<^sub>T \<dagger> ($ok\<acute>) = ($ok\<acute>)" "\<lceil>\<sigma>\<rceil>\<^sub>S\<^sub>F\<^sub>L\<^sub>T \<dagger> (\<not>$ok\<acute>) = (\<not>$ok\<acute>)" by (simp_all add: usubst unrest) lemma abrupt_ok_simpl[uflt_comp]: "($fault ;; Simpl\<^sub>F\<^sub>L\<^sub>T P) = $fault" "(\<not>$ok ;; Simpl\<^sub>F\<^sub>L\<^sub>T P) = (\<not>$ok)" "($fault ;; (P \<turnstile> Q)) = $fault" "(\<not>$ok ;; (P \<turnstile> Q)) = (\<not>$ok)" "(\<not>$fault ;; Simpl\<^sub>F\<^sub>L\<^sub>T P) = (\<not>$fault)" "(\<not>$ok ;; Simpl\<^sub>F\<^sub>L\<^sub>T P) = (\<not>$ok)" "(\<not>$fault ;; (P \<turnstile> Q)) = (\<not>$fault)" "(\<not>$ok ;; (P \<turnstile> Q)) = (\<not>$ok)" "($fault\<acute> ;; Simpl\<^sub>F\<^sub>L\<^sub>T P) = $fault\<acute>" "(\<not>$fault\<acute> ;; Simpl\<^sub>F\<^sub>L\<^sub>T P) = (\<not>$fault\<acute>)" by rel_auto+ lemma simpl_flt_in_ok: "Simpl\<^sub>F\<^sub>L\<^sub>T ($ok) = ((\<not>$fault \<and> ($ok \<Rightarrow>$ok\<acute>)) \<or> (II))" by rel_auto lemma simpl_flt_our_ok: "Simpl\<^sub>F\<^sub>L\<^sub>T ($ok\<acute>) = ((\<not>$fault \<and> ($ok \<Rightarrow>$ok\<acute>)) \<or> (II))" by rel_auto lemma simpl_flt_in_abrupt: "Simpl\<^sub>F\<^sub>L\<^sub>T ($fault) = ((\<not>$fault \<and> ($ok \<Rightarrow>($ok\<acute> \<and> $fault))) \<or> ($fault \<and> II))" by rel_auto lemma simpl_flt_alt_def: "Simpl\<^sub>F\<^sub>L\<^sub>T (P) = ((\<not>$fault \<and> ($ok \<Rightarrow>($ok\<acute> \<and> P))) \<or> ($fault \<and> II))" by rel_auto subsection {*Healthiness condition behavior*} lemma rel_usubst_cpf_c3_flt[usubst]: assumes "$ok \<sharp> \<sigma>" "$ok\<acute> \<sharp> \<sigma> " shows "\<sigma> \<dagger> C3_flt(P) = (\<sigma> \<dagger> P \<triangleleft> \<sigma> \<dagger> (\<not>$fault) \<triangleright> (\<sigma> \<dagger> II))" using assms unfolding C3_flt_def by (simp add: usubst) lemma Simpl_flt_idem[simp]: "Simpl\<^sub>F\<^sub>L\<^sub>T(Simpl\<^sub>F\<^sub>L\<^sub>T(P)) = Simpl\<^sub>F\<^sub>L\<^sub>T(P)" by (rel_auto) lemma simpl_flt_Idempotent: "Idempotent Simpl\<^sub>F\<^sub>L\<^sub>T" by (simp add: Idempotent_def) lemma Simpl_flt_mono: "P \<sqsubseteq> Q \<Longrightarrow> Simpl\<^sub>F\<^sub>L\<^sub>T(P) \<sqsubseteq> Simpl\<^sub>F\<^sub>L\<^sub>T(Q)" by (rel_auto) lemma simpl_flt_Monotonic: "Monotonic Simpl\<^sub>F\<^sub>L\<^sub>T" by (simp add: Monotonic_def Simpl_flt_mono) lemma simpl_flt_def: "Simpl\<^sub>F\<^sub>L\<^sub>T(P) = ((\<lceil>true\<rceil>\<^sub>F\<^sub>L\<^sub>T \<turnstile> P) \<triangleleft> \<not>$fault \<triangleright> II)" unfolding C3_flt_def .. lemma simpl_flt_condr[uflt_simpl]: "Simpl\<^sub>F\<^sub>L\<^sub>T(P \<triangleleft> b \<triangleright> Q) = (Simpl\<^sub>F\<^sub>L\<^sub>T(P) \<triangleleft> b \<triangleright> Simpl\<^sub>F\<^sub>L\<^sub>T(Q))" unfolding simpl_flt_def by (simp add: urel_cond) lemma simpl_abr_skip_abr[uflt_simpl]: "Simpl\<^sub>F\<^sub>L\<^sub>T(SKIP\<^sub>F\<^sub>L\<^sub>T) = (SKIP\<^sub>F\<^sub>L\<^sub>T)" by (simp add: urel_cond urel_defs) lemma simpl_flt_assign_flt[uflt_simpl]: "Simpl\<^sub>F\<^sub>L\<^sub>T(\<langle>\<sigma>\<rangle>\<^sub>F\<^sub>L\<^sub>T) = (\<langle>\<sigma>\<rangle>\<^sub>F\<^sub>L\<^sub>T)" by (simp add: urel_cond urel_defs) lemma simpl_flt_form: "Simpl\<^sub>F\<^sub>L\<^sub>T(P) = (((\<not>$fault) \<and> (\<lceil>true\<rceil>\<^sub>F\<^sub>L\<^sub>T \<turnstile> (P))) \<or> ($fault \<and> II))" by rel_auto lemma abrupt_simpl_flt[uflt_simpl]: "($fault \<and> Simpl\<^sub>F\<^sub>L\<^sub>T(P)) = ($fault \<and>II)" by rel_auto lemma nabrupt_simpl_flt[uflt_simpl]: "(\<not>$fault \<and> Simpl\<^sub>F\<^sub>L\<^sub>T(P)) = (\<not>$fault \<and> (\<lceil>true\<rceil>\<^sub>F\<^sub>L\<^sub>T \<turnstile> (P)))" by (rel_auto) definition design_flt_sup :: "('\<alpha>,'\<beta>) rel_cpf set \<Rightarrow> ('\<alpha>,'\<beta>) rel_cpf" ("\<Sqinter>\<^sub>F\<^sub>L\<^sub>T_" [900] 900) where "\<Sqinter>\<^sub>F\<^sub>L\<^sub>T A = (if (A = {}) then \<top>\<^sub>F\<^sub>L\<^sub>T else \<Sqinter> A)" lemma simpl_flt_Continuous: "Continuous Simpl\<^sub>F\<^sub>L\<^sub>T" unfolding Continuous_def SUP_def apply rel_simp unfolding SUP_def apply transfer apply auto done lemma simpl_flt_R3_conj: "Simpl\<^sub>F\<^sub>L\<^sub>T(P \<and> Q) = (Simpl\<^sub>F\<^sub>L\<^sub>T(P) \<and> Simpl\<^sub>F\<^sub>L\<^sub>T(Q))" by (rel_auto) lemma simpl_flt_disj: "Simpl\<^sub>F\<^sub>L\<^sub>T(P \<or> Q) = (Simpl\<^sub>F\<^sub>L\<^sub>T(P) \<or> Simpl\<^sub>F\<^sub>L\<^sub>T(Q))" by (rel_auto) lemma Simpl_flt_USUP: assumes "A \<noteq> {}" shows "Simpl\<^sub>F\<^sub>L\<^sub>T(\<Sqinter> i \<in> A \<bullet> P(i)) = (\<Sqinter> i \<in> A \<bullet> Simpl\<^sub>F\<^sub>L\<^sub>T(P(i)))" using assms by (rel_auto) lemma design_flt_sup_non_empty [simp]: "A \<noteq> {} \<Longrightarrow> \<Sqinter>\<^sub>F\<^sub>L\<^sub>T A = \<Sqinter> A" by (simp add: design_flt_sup_def) subsection {*Signature behavior*} lemma design_top_flt: "(P \<turnstile> Q) \<sqsubseteq> \<top>\<^sub>F\<^sub>L\<^sub>T" by (rel_auto) lemma design_flt_sup_empty [simp]: "\<Sqinter>\<^sub>F\<^sub>L\<^sub>T {} = \<top>\<^sub>F\<^sub>L\<^sub>T" by (simp add: design_flt_sup_def) abbreviation design_inf :: "('\<alpha>, '\<beta>) rel_des set \<Rightarrow> ('\<alpha>, '\<beta>) rel_des" ("\<Squnion>\<^sub>F\<^sub>L\<^sub>T_" [900] 900) where "\<Squnion>\<^sub>F\<^sub>L\<^sub>T A \<equiv> \<Squnion> A" lemma design_bottom_flt: "\<bottom>\<^sub>F\<^sub>L\<^sub>T \<sqsubseteq> (P \<turnstile> Q)" by simp lemma Simpl_flt_UINF: assumes "A \<noteq> {}" shows "Simpl\<^sub>F\<^sub>L\<^sub>T(\<Squnion> i \<in> A \<bullet> P(i)) = (\<Squnion> i \<in> A \<bullet> Simpl\<^sub>F\<^sub>L\<^sub>T(P(i)))" using assms by (rel_auto) lemma skip_cpf_def: "II = (\<lceil>II\<rceil>\<^sub>F\<^sub>L\<^sub>T \<and> $fault =\<^sub>u $fault\<acute> \<and> $ok =\<^sub>u $ok\<acute>)" by rel_auto lemma skip_lift_flt_def: "\<lceil>II\<rceil>\<^sub>F\<^sub>L\<^sub>T = ($\<Sigma>\<^sub>F\<^sub>L\<^sub>T\<acute> =\<^sub>u $\<Sigma>\<^sub>F\<^sub>L\<^sub>T)" by rel_auto lemma seqr_fault_true [usubst]: "(P ;; Q) \<^sub>f\<^sub>t = (P \<^sub>f\<^sub>t ;; Q)" by (rel_auto) lemma seqr_fault_false [usubst]: "(P ;; Q) \<^sub>f\<^sub>f = (P \<^sub>f\<^sub>f ;; Q)" by (rel_auto) lemma rel_usubst_lift_cpf_uexpr_lift_cpf[usubst]: "\<lceil>\<sigma>\<rceil>\<^sub>S\<^sub>F\<^sub>L\<^sub>T \<dagger> \<lceil>P\<rceil>\<^sub>F\<^sub>L\<^sub>T = \<lceil>\<sigma> \<dagger> P\<rceil>\<^sub>F\<^sub>L\<^sub>T" by rel_auto lemma usubst_lift_cpf_assigns_lift_cpf [usubst]: "\<lceil>\<sigma>\<rceil>\<^sub>s\<^sub>F\<^sub>L\<^sub>T \<dagger> \<lceil>\<langle>\<rho>\<rangle>\<^sub>a\<rceil>\<^sub>F\<^sub>L\<^sub>T = \<lceil>\<langle>\<rho> \<circ> \<sigma>\<rangle>\<^sub>a\<rceil>\<^sub>F\<^sub>L\<^sub>T" by (simp add: usubst) lemma usubst_lift_cpf_pre_uexpr_lift_cpf[usubst]: "\<lceil>\<sigma>\<rceil>\<^sub>s\<^sub>F\<^sub>L\<^sub>T \<dagger> \<lceil>b\<rceil>\<^sub>F\<^sub>L\<^sub>T\<^sub>< = \<lceil>\<sigma> \<dagger> b\<rceil>\<^sub>F\<^sub>L\<^sub>T\<^sub><" by (simp add: usubst) lemma rel_usubst_lift_cpf_design[usubst]: "(\<lceil>\<sigma>\<rceil>\<^sub>S\<^sub>F\<^sub>L\<^sub>T \<dagger> (Q \<turnstile> P)) = (\<lceil>\<sigma>\<rceil>\<^sub>S\<^sub>F\<^sub>L\<^sub>T \<dagger> Q) \<turnstile> (\<lceil>\<sigma>\<rceil>\<^sub>S\<^sub>F\<^sub>L\<^sub>T \<dagger> P)" by (simp add: usubst unrest) lemma usubst_cpf_true[usubst]: "\<sigma> \<dagger> \<lceil>true\<rceil>\<^sub>F\<^sub>L\<^sub>T = \<lceil>true\<rceil>\<^sub>F\<^sub>L\<^sub>T" by rel_auto lemma usubst_cpf_false[usubst]: "\<sigma> \<dagger> \<lceil>false\<rceil>\<^sub>F\<^sub>L\<^sub>T = \<lceil>false\<rceil>\<^sub>F\<^sub>L\<^sub>T" by rel_auto lemma rel_usubst_cpf_skip_cpf[usubst]: "(\<sigma> \<dagger> II) = ((\<sigma> \<dagger> \<lceil>II\<rceil>\<^sub>F\<^sub>L\<^sub>T) \<and> \<sigma> \<dagger> $fault =\<^sub>u \<sigma> \<dagger> $fault\<acute> \<and> \<sigma> \<dagger> $ok =\<^sub>u \<sigma> \<dagger> $ok\<acute>)" by (simp add: usubst unrest skip_cpf_def) lemma usubst_lift_cpf_skip_lift_cpf[usubst]: "(\<lceil>\<sigma>\<rceil>\<^sub>s\<^sub>F\<^sub>L\<^sub>T \<dagger> \<lceil>II\<rceil>\<^sub>F\<^sub>L\<^sub>T) = \<lceil>\<langle>\<sigma>\<rangle>\<^sub>a\<rceil>\<^sub>F\<^sub>L\<^sub>T" unfolding skip_r_def by (simp add: usubst_lift_cpf_assigns_lift_cpf) lemma usubst_cpf_skip_cpf [usubst]: assumes "$ok \<sharp> \<sigma>" "$ok\<acute> \<sharp> \<sigma> " shows "(\<sigma> \<dagger> SKIP\<^sub>F\<^sub>L\<^sub>T) = (\<lceil>true\<rceil>\<^sub>F\<^sub>L\<^sub>T \<turnstile> (\<sigma> \<dagger> (\<not>$fault\<acute> \<and> \<lceil>II\<rceil>\<^sub>F\<^sub>L\<^sub>T)) \<triangleleft> \<sigma> \<dagger> (\<not>$fault) \<triangleright> (\<sigma> \<dagger> (II)))" using assms unfolding skip_flt_def by (simp add: usubst) lemma usubst_cpf_assigns_cpf [usubst]: assumes "$ok \<sharp> \<sigma>" "$ok\<acute> \<sharp> \<sigma> " shows "\<sigma> \<dagger> \<langle>\<rho>\<rangle>\<^sub>F\<^sub>L\<^sub>T = (\<lceil>true\<rceil>\<^sub>F\<^sub>L\<^sub>T \<turnstile> (\<sigma> \<dagger> ((\<not>$fault\<acute>) \<and> \<lceil>\<langle>\<rho>\<rangle>\<^sub>a\<rceil>\<^sub>F\<^sub>L\<^sub>T)) \<triangleleft> \<sigma> \<dagger> (\<not>$fault) \<triangleright> (\<sigma> \<dagger> (II)))" using assms unfolding assigns_flt_def by (simp add: usubst) lemma c3_flt_comp_left_distr: "(C3_flt (P) ;; R) = ((P;;R) \<triangleleft> \<not>$fault \<triangleright> (II ;; R))" apply pred_simp apply rel_simp apply fastforce done lemma c3_flt_comp_semir: "(C3_flt(P) ;; C3_flt(R)) = C3_flt (P ;; C3_flt(R))" by rel_auto lemma c3_flt_comp_simpl[uflt_comp]: "(C3_flt(P) ;; C3_flt(R)) = ((P ;; C3_flt(R)) \<triangleleft> \<not>$fault \<triangleright> (II))" by rel_auto lemma simpl_flt_comp_semir: "(Simpl\<^sub>F\<^sub>L\<^sub>T(P) ;; Simpl\<^sub>F\<^sub>L\<^sub>T(R)) = Simpl\<^sub>F\<^sub>L\<^sub>T ((\<lceil>true\<rceil>\<^sub>F\<^sub>L\<^sub>T \<turnstile> P) ;; Simpl\<^sub>F\<^sub>L\<^sub>T(R))" by rel_auto theorem design_top_flt_left_zero[uflt_comp]: "(\<top>\<^sub>F\<^sub>L\<^sub>T ;; (P \<turnstile> Q)) = \<top>\<^sub>F\<^sub>L\<^sub>T" by (rel_auto) theorem Simpl_flt_top_flt_left_zero[uflt_comp]: "(\<top>\<^sub>F\<^sub>L\<^sub>T ;; Simpl\<^sub>F\<^sub>L\<^sub>T (P)) = \<top>\<^sub>F\<^sub>L\<^sub>T" by (rel_auto) lemma assigns_lift_cpf_comp_rel_cpf[uflt_comp]: assumes "$ok \<sharp> P" "$fault \<sharp> P" shows "(\<lceil>\<langle>\<sigma>\<rangle>\<^sub>a\<rceil>\<^sub>F\<^sub>L\<^sub>T ;; P) = (\<lceil>\<sigma>\<rceil>\<^sub>s\<^sub>F\<^sub>L\<^sub>T \<dagger> P)" apply (insert assms) apply pred_simp apply rel_blast done lemma lift_des_skip_dr_unit_flt [uflt_comp]: "(\<lceil>P\<rceil>\<^sub>F\<^sub>L\<^sub>T ;; \<lceil>II\<rceil>\<^sub>F\<^sub>L\<^sub>T) = \<lceil>P\<rceil>\<^sub>F\<^sub>L\<^sub>T" "(\<lceil>II\<rceil>\<^sub>F\<^sub>L\<^sub>T ;; \<lceil>P\<rceil>\<^sub>F\<^sub>L\<^sub>T) = \<lceil>P\<rceil>\<^sub>F\<^sub>L\<^sub>T" by (rel_auto)+ lemma skip_cpf_left_comp_simpl[uflt_comp]: "(SKIP\<^sub>F\<^sub>L\<^sub>T ;; Simpl\<^sub>F\<^sub>L\<^sub>T(R)) = (Simpl\<^sub>F\<^sub>L\<^sub>T(R))" by rel_auto lemma skip_cpf_right_comp_simpl[uflt_comp]: "(Simpl\<^sub>F\<^sub>L\<^sub>T(R) ;; SKIP\<^sub>F\<^sub>L\<^sub>T) = (Simpl\<^sub>F\<^sub>L\<^sub>T(R))" by rel_auto lemma assign_flt_alt_def: "\<langle>\<sigma>\<rangle>\<^sub>F\<^sub>L\<^sub>T = Simpl\<^sub>F\<^sub>L\<^sub>T (\<not>$fault\<acute> \<and> \<lceil>\<lceil>\<sigma>\<rceil>\<^sub>s \<dagger> II\<rceil>\<^sub>F\<^sub>L\<^sub>T)" by rel_auto lemma assign_flt_left_comp_c3[uflt_comp]: "\<langle>a\<rangle>\<^sub>F\<^sub>L\<^sub>T ;; C3_flt (P \<turnstile> Q) = C3_flt (\<lceil>a\<rceil>\<^sub>s\<^sub>F\<^sub>L\<^sub>T \<dagger> (P \<turnstile> Q))" by rel_auto lemma assigns_flt_comp[uflt_comp]: "(\<langle>f\<rangle>\<^sub>F\<^sub>L\<^sub>T ;; \<langle>g\<rangle>\<^sub>F\<^sub>L\<^sub>T) = \<langle>g \<circ> f\<rangle>\<^sub>F\<^sub>L\<^sub>T" by rel_auto lemma usubst_cpf_des_cond_flt [usubst]: "\<lbrakk>$ok \<sharp> \<sigma>; $ok\<acute> \<sharp> \<sigma> \<rbrakk> \<Longrightarrow> \<sigma> \<dagger> (R \<turnstile> bif b then P else Q eif) = (\<sigma> \<dagger> R \<turnstile> (\<sigma> \<dagger> P \<triangleleft> \<sigma> \<dagger> \<lceil>b\<rceil>\<^sub>F\<^sub>L\<^sub>T\<^sub>< \<triangleright> \<sigma> \<dagger> Q))" by (simp add: usubst) lemma comp_cond_flt_left_distr[uflt_comp]: "((bif b then Simpl\<^sub>F\<^sub>L\<^sub>T P else Simpl\<^sub>F\<^sub>L\<^sub>T Q eif) ;; Simpl\<^sub>F\<^sub>L\<^sub>T R) = (bif b then (Simpl\<^sub>F\<^sub>L\<^sub>T P ;; Simpl\<^sub>F\<^sub>L\<^sub>T R) else (Simpl\<^sub>F\<^sub>L\<^sub>T Q ;; Simpl\<^sub>F\<^sub>L\<^sub>T R) eif)" apply pred_simp apply rel_simp done lemma if_mono: "\<lbrakk> P\<^sub>1 \<sqsubseteq> P\<^sub>2; Q\<^sub>1 \<sqsubseteq> Q\<^sub>2 \<rbrakk> \<Longrightarrow> (bif b then P\<^sub>1 else Q\<^sub>1 eif) \<sqsubseteq> (bif b then P\<^sub>2 else Q\<^sub>2 eif)" by rel_auto lemma design_post_seqr_rcond_left_not_ivar[urel_cond]: "S \<turnstile> (\<lceil>true\<rceil>\<^sub>F\<^sub>L\<^sub>T \<turnstile> (\<lceil>R\<rceil>\<^sub>F\<^sub>L\<^sub>T \<and> $x\<acute>) ;; P \<triangleleft> \<not> $x \<triangleright> Q) = S \<turnstile> (\<lceil>true\<rceil>\<^sub>F\<^sub>L\<^sub>T \<turnstile> (\<lceil>R\<rceil>\<^sub>F\<^sub>L\<^sub>T \<and> $x\<acute>);; Q)" apply pred_simp apply fastforce done lemma design_post_seqr_rcond_left_ivar [urel_cond]: "S \<turnstile> (\<lceil>true\<rceil>\<^sub>F\<^sub>L\<^sub>T \<turnstile> (\<lceil>R\<rceil>\<^sub>F\<^sub>L\<^sub>T \<and> $x\<acute>) ;; P \<triangleleft> $x \<triangleright> Q) = S \<turnstile> (\<lceil>true\<rceil>\<^sub>F\<^sub>L\<^sub>T \<turnstile> (\<lceil>R\<rceil>\<^sub>F\<^sub>L\<^sub>T \<and> $x\<acute>);; P)" apply pred_simp apply fastforce done subsection {*While abrupt usubst*} subsection {*block abrupt usubst*} subsection {*Catch abrupt usubst*} end
\documentclass{subfile} \begin{document} \section{CMO}\label{sec:cmo} \end{document}
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.pempty import category_theory.limits.has_limits import category_theory.epi_mono import category_theory.category.preorder /-! # Initial and terminal objects in a category. ## References * [Stacks: Initial and final objects](https://stacks.math.columbia.edu/tag/002B) -/ noncomputable theory universes w w' v v₁ v₂ u u₁ u₂ open category_theory namespace category_theory.limits variables {C : Type u₁} [category.{v₁} C] /-- Construct a cone for the empty diagram given an object. -/ @[simps] def as_empty_cone (X : C) : cone (functor.empty.{w} C) := { X := X, π := by tidy } /-- Construct a cocone for the empty diagram given an object. -/ @[simps] def as_empty_cocone (X : C) : cocone (functor.empty.{w} C) := { X := X, ι := by tidy } /-- `X` is terminal if the cone it induces on the empty diagram is limiting. -/ abbreviation is_terminal (X : C) := is_limit (as_empty_cone.{v₁} X) /-- `X` is initial if the cocone it induces on the empty diagram is colimiting. -/ abbreviation is_initial (X : C) := is_colimit (as_empty_cocone.{v₁} X) /-- An object `Y` is terminal iff for every `X` there is a unique morphism `X ⟶ Y`. -/ def is_terminal_equiv_unique (F : discrete.{v₁} pempty ⥤ C) (Y : C) : is_limit (⟨Y, by tidy⟩ : cone F) ≃ ∀ X : C, unique (X ⟶ Y) := { to_fun := λ t X, { default := t.lift ⟨X, by tidy⟩, uniq := λ f, t.uniq ⟨X, by tidy⟩ f (by tidy) }, inv_fun := λ u, { lift := λ s, (u s.X).default, uniq' := λ s _ _, (u s.X).2 _ }, left_inv := by tidy, right_inv := by tidy } /-- An object `Y` is terminal if for every `X` there is a unique morphism `X ⟶ Y` (as an instance). -/ def is_terminal.of_unique (Y : C) [h : Π X : C, unique (X ⟶ Y)] : is_terminal Y := { lift := λ s, (h s.X).default } /-- If `α` is a preorder with top, then `⊤` is a terminal object. -/ def is_terminal_top {α : Type*} [preorder α] [order_top α] : is_terminal (⊤ : α) := is_terminal.of_unique _ /-- Transport a term of type `is_terminal` across an isomorphism. -/ def is_terminal.of_iso {Y Z : C} (hY : is_terminal Y) (i : Y ≅ Z) : is_terminal Z := is_limit.of_iso_limit hY { hom := { hom := i.hom }, inv := { hom := i.inv } } /-- An object `X` is initial iff for every `Y` there is a unique morphism `X ⟶ Y`. -/ def is_initial_equiv_unique (F : discrete.{v₁} pempty ⥤ C) (X : C) : is_colimit (⟨X, by tidy⟩ : cocone F) ≃ ∀ Y : C, unique (X ⟶ Y) := { to_fun := λ t X, { default := t.desc ⟨X, by tidy⟩, uniq := λ f, t.uniq ⟨X, by tidy⟩ f (by tidy) }, inv_fun := λ u, { desc := λ s, (u s.X).default, uniq' := λ s _ _, (u s.X).2 _ }, left_inv := by tidy, right_inv := by tidy } /-- An object `X` is initial if for every `Y` there is a unique morphism `X ⟶ Y` (as an instance). -/ def is_initial.of_unique (X : C) [h : Π Y : C, unique (X ⟶ Y)] : is_initial X := { desc := λ s, (h s.X).default } /-- If `α` is a preorder with bot, then `⊥` is an initial object. -/ def is_initial_bot {α : Type*} [preorder α] [order_bot α] : is_initial (⊥ : α) := is_initial.of_unique _ /-- Transport a term of type `is_initial` across an isomorphism. -/ def is_initial.of_iso {X Y : C} (hX : is_initial X) (i : X ≅ Y) : is_initial Y := is_colimit.of_iso_colimit hX { hom := { hom := i.hom }, inv := { hom := i.inv } } /-- Give the morphism to a terminal object from any other. -/ def is_terminal.from {X : C} (t : is_terminal X) (Y : C) : Y ⟶ X := t.lift (as_empty_cone Y) /-- Any two morphisms to a terminal object are equal. -/ lemma is_terminal.hom_ext {X Y : C} (t : is_terminal X) (f g : Y ⟶ X) : f = g := t.hom_ext (by tidy) @[simp] lemma is_terminal.comp_from {Z : C} (t : is_terminal Z) {X Y : C} (f : X ⟶ Y) : f ≫ t.from Y = t.from X := t.hom_ext _ _ @[simp] lemma is_terminal.from_self {X : C} (t : is_terminal X) : t.from X = 𝟙 X := t.hom_ext _ _ /-- Give the morphism from an initial object to any other. -/ def is_initial.to {X : C} (t : is_initial X) (Y : C) : X ⟶ Y := t.desc (as_empty_cocone Y) /-- Any two morphisms from an initial object are equal. -/ lemma is_initial.hom_ext {X Y : C} (t : is_initial X) (f g : X ⟶ Y) : f = g := t.hom_ext (by tidy) @[simp] lemma is_initial.to_comp {X : C} (t : is_initial X) {Y Z : C} (f : Y ⟶ Z) : t.to Y ≫ f = t.to Z := t.hom_ext _ _ @[simp] lemma is_initial.to_self {X : C} (t : is_initial X) : t.to X = 𝟙 X := t.hom_ext _ _ /-- Any morphism from a terminal object is split mono. -/ def is_terminal.split_mono_from {X Y : C} (t : is_terminal X) (f : X ⟶ Y) : split_mono f := ⟨t.from _, t.hom_ext _ _⟩ /-- Any morphism to an initial object is split epi. -/ def is_initial.split_epi_to {X Y : C} (t : is_initial X) (f : Y ⟶ X) : split_epi f := ⟨t.to _, t.hom_ext _ _⟩ /-- Any morphism from a terminal object is mono. -/ lemma is_terminal.mono_from {X Y : C} (t : is_terminal X) (f : X ⟶ Y) : mono f := by haveI := t.split_mono_from f; apply_instance /-- Any morphism to an initial object is epi. -/ lemma is_initial.epi_to {X Y : C} (t : is_initial X) (f : Y ⟶ X) : epi f := by haveI := t.split_epi_to f; apply_instance /-- If `T` and `T'` are terminal, they are isomorphic. -/ @[simps] def is_terminal.unique_up_to_iso {T T' : C} (hT : is_terminal T) (hT' : is_terminal T') : T ≅ T' := { hom := hT'.from _, inv := hT.from _ } /-- If `I` and `I'` are initial, they are isomorphic. -/ @[simps] def is_initial.unique_up_to_iso {I I' : C} (hI : is_initial I) (hI' : is_initial I') : I ≅ I' := { hom := hI.to _, inv := hI'.to _ } variable (C) /-- A category has a terminal object if it has a limit over the empty diagram. Use `has_terminal_of_unique` to construct instances. -/ abbreviation has_terminal := has_limits_of_shape (discrete.{v₁} pempty) C /-- A category has an initial object if it has a colimit over the empty diagram. Use `has_initial_of_unique` to construct instances. -/ abbreviation has_initial := has_colimits_of_shape (discrete.{v₁} pempty) C section univ variables (X : C) {F₁ : discrete.{w} pempty ⥤ C} {F₂ : discrete.{w'} pempty ⥤ C} /-- Being terminal is independent of the empty diagram, its universe, and the cone over it, as long as the cone points are isomorphic. -/ def is_limit_change_empty_cone {c₁ : cone F₁} (hl : is_limit c₁) (c₂ : cone F₂) (hi : c₁.X ≅ c₂.X) : is_limit c₂ := { lift := λ c, hl.lift ⟨c.X, by tidy⟩ ≫ hi.hom, fac' := λ _ j, j.elim, uniq' := λ c f _, by { erw ← hl.uniq ⟨c.X, by tidy⟩ (f ≫ hi.inv) (λ j, j.elim), simp } } /-- Replacing an empty cone in `is_limit` by another with the same cone point is an equivalence. -/ def is_limit_empty_cone_equiv (c₁ : cone F₁) (c₂ : cone F₂) (h : c₁.X ≅ c₂.X) : is_limit c₁ ≃ is_limit c₂ := { to_fun := λ hl, is_limit_change_empty_cone C hl c₂ h, inv_fun := λ hl, is_limit_change_empty_cone C hl c₁ h.symm, left_inv := by tidy, right_inv := by tidy } lemma has_terminal_change_diagram (h : has_limit F₁) : has_limit F₂ := ⟨⟨⟨⟨limit F₁, by tidy⟩, is_limit_change_empty_cone C (limit.is_limit F₁) _ (eq_to_iso rfl)⟩⟩⟩ lemma has_terminal_change_universe [h : has_limits_of_shape (discrete.{w} pempty) C] : has_limits_of_shape (discrete.{w'} pempty) C := { has_limit := λ J, has_terminal_change_diagram C (let f := h.1 in f (functor.empty C)) } /-- Being initial is independent of the empty diagram, its universe, and the cocone over it, as long as the cocone points are isomorphic. -/ def is_colimit_change_empty_cocone {c₁ : cocone F₁} (hl : is_colimit c₁) (c₂ : cocone F₂) (hi : c₁.X ≅ c₂.X) : is_colimit c₂ := { desc := λ c, hi.inv ≫ hl.desc ⟨c.X, by tidy⟩, fac' := λ _ j, j.elim, uniq' := λ c f _, by { erw ← hl.uniq ⟨c.X, by tidy⟩ (hi.hom ≫ f) (λ j, j.elim), simp } } /-- Replacing an empty cocone in `is_colimit` by another with the same cocone point is an equivalence. -/ def is_colimit_empty_cocone_equiv (c₁ : cocone F₁) (c₂ : cocone F₂) (h : c₁.X ≅ c₂.X) : is_colimit c₁ ≃ is_colimit c₂ := { to_fun := λ hl, is_colimit_change_empty_cocone C hl c₂ h, inv_fun := λ hl, is_colimit_change_empty_cocone C hl c₁ h.symm, left_inv := by tidy, right_inv := by tidy } lemma has_initial_change_diagram (h : has_colimit F₁) : has_colimit F₂ := ⟨⟨⟨⟨colimit F₁, by tidy⟩, is_colimit_change_empty_cocone C (colimit.is_colimit F₁) _ (eq_to_iso rfl)⟩⟩⟩ end univ /-- An arbitrary choice of terminal object, if one exists. You can use the notation `⊤_ C`. This object is characterized by having a unique morphism from any object. -/ abbreviation terminal [has_terminal C] : C := limit (functor.empty.{v₁} C) /-- An arbitrary choice of initial object, if one exists. You can use the notation `⊥_ C`. This object is characterized by having a unique morphism to any object. -/ abbreviation initial [has_initial C] : C := colimit (functor.empty.{v₁} C) notation `⊤_ ` C:20 := terminal C notation `⊥_ ` C:20 := initial C section variables {C} /-- We can more explicitly show that a category has a terminal object by specifying the object, and showing there is a unique morphism to it from any other object. -/ lemma has_terminal_of_unique (X : C) [h : Π Y : C, unique (Y ⟶ X)] : has_terminal C := { has_limit := λ F, has_limit.mk ⟨_, (is_terminal_equiv_unique F X).inv_fun h⟩ } /-- We can more explicitly show that a category has an initial object by specifying the object, and showing there is a unique morphism from it to any other object. -/ lemma has_initial_of_unique (X : C) [h : Π Y : C, unique (X ⟶ Y)] : has_initial C := { has_colimit := λ F, has_colimit.mk ⟨_, (is_initial_equiv_unique F X).inv_fun h⟩ } /-- The map from an object to the terminal object. -/ abbreviation terminal.from [has_terminal C] (P : C) : P ⟶ ⊤_ C := limit.lift (functor.empty C) (as_empty_cone P) /-- The map to an object from the initial object. -/ abbreviation initial.to [has_initial C] (P : C) : ⊥_ C ⟶ P := colimit.desc (functor.empty C) (as_empty_cocone P) /-- A terminal object is terminal. -/ def terminal_is_terminal [has_terminal C] : is_terminal (⊤_ C) := { lift := λ s, terminal.from _ } /-- An initial object is initial. -/ def initial_is_initial [has_initial C] : is_initial (⊥_ C) := { desc := λ s, initial.to _ } instance unique_to_terminal [has_terminal C] (P : C) : unique (P ⟶ ⊤_ C) := is_terminal_equiv_unique _ (⊤_ C) terminal_is_terminal P instance unique_from_initial [has_initial C] (P : C) : unique (⊥_ C ⟶ P) := is_initial_equiv_unique _ (⊥_ C) initial_is_initial P @[simp] lemma terminal.comp_from [has_terminal C] {P Q : C} (f : P ⟶ Q) : f ≫ terminal.from Q = terminal.from P := by tidy @[simp] lemma initial.to_comp [has_initial C] {P Q : C} (f : P ⟶ Q) : initial.to P ≫ f = initial.to Q := by tidy /-- Any morphism from a terminal object is split mono. -/ instance terminal.split_mono_from {Y : C} [has_terminal C] (f : ⊤_ C ⟶ Y) : split_mono f := is_terminal.split_mono_from terminal_is_terminal _ /-- Any morphism to an initial object is split epi. -/ instance initial.split_epi_to {Y : C} [has_initial C] (f : Y ⟶ ⊥_ C) : split_epi f := is_initial.split_epi_to initial_is_initial _ /-- An initial object is terminal in the opposite category. -/ def terminal_op_of_initial {X : C} (t : is_initial X) : is_terminal (opposite.op X) := { lift := λ s, (t.to s.X.unop).op, uniq' := λ s m w, quiver.hom.unop_inj (t.hom_ext _ _) } /-- An initial object in the opposite category is terminal in the original category. -/ def terminal_unop_of_initial {X : Cᵒᵖ} (t : is_initial X) : is_terminal X.unop := { lift := λ s, (t.to (opposite.op s.X)).unop, uniq' := λ s m w, quiver.hom.op_inj (t.hom_ext _ _) } /-- A terminal object is initial in the opposite category. -/ def initial_op_of_terminal {X : C} (t : is_terminal X) : is_initial (opposite.op X) := { desc := λ s, (t.from s.X.unop).op, uniq' := λ s m w, quiver.hom.unop_inj (t.hom_ext _ _) } /-- A terminal object in the opposite category is initial in the original category. -/ def initial_unop_of_terminal {X : Cᵒᵖ} (t : is_terminal X) : is_initial X.unop := { desc := λ s, (t.from (opposite.op s.X)).unop, uniq' := λ s m w, quiver.hom.op_inj (t.hom_ext _ _) } /-- A category is a `initial_mono_class` if the canonical morphism of an initial object is a monomorphism. In practice, this is most useful when given an arbitrary morphism out of the chosen initial object, see `initial.mono_from`. Given a terminal object, this is equivalent to the assumption that the unique morphism from initial to terminal is a monomorphism, which is the second of Freyd's axioms for an AT category. TODO: This is a condition satisfied by categories with zero objects and morphisms. -/ class initial_mono_class (C : Type u₁) [category.{v₁} C] : Prop := (is_initial_mono_from : ∀ {I} (X : C) (hI : is_initial I), mono (hI.to X)) lemma is_initial.mono_from [initial_mono_class C] {I} {X : C} (hI : is_initial I) (f : I ⟶ X) : mono f := begin rw hI.hom_ext f (hI.to X), apply initial_mono_class.is_initial_mono_from, end @[priority 100] instance initial.mono_from [has_initial C] [initial_mono_class C] (X : C) (f : ⊥_ C ⟶ X) : mono f := initial_is_initial.mono_from f /-- To show a category is a `initial_mono_class` it suffices to give an initial object such that every morphism out of it is a monomorphism. -/ lemma initial_mono_class.of_is_initial {I : C} (hI : is_initial I) (h : ∀ X, mono (hI.to X)) : initial_mono_class C := { is_initial_mono_from := λ I' X hI', begin rw hI'.hom_ext (hI'.to X) ((hI'.unique_up_to_iso hI).hom ≫ hI.to X), apply mono_comp, end } /-- To show a category is a `initial_mono_class` it suffices to show every morphism out of the initial object is a monomorphism. -/ lemma initial_mono_class.of_initial [has_initial C] (h : ∀ X : C, mono (initial.to X)) : initial_mono_class C := initial_mono_class.of_is_initial initial_is_initial h /-- To show a category is a `initial_mono_class` it suffices to show the unique morphism from an initial object to a terminal object is a monomorphism. -/ lemma initial_mono_class.of_is_terminal {I T : C} (hI : is_initial I) (hT : is_terminal T) (f : mono (hI.to T)) : initial_mono_class C := initial_mono_class.of_is_initial hI (λ X, mono_of_mono_fac (hI.hom_ext (_ ≫ hT.from X) (hI.to T))) /-- To show a category is a `initial_mono_class` it suffices to show the unique morphism from the initial object to a terminal object is a monomorphism. -/ lemma initial_mono_class.of_terminal [has_initial C] [has_terminal C] (h : mono (initial.to (⊤_ C))) : initial_mono_class C := initial_mono_class.of_is_terminal initial_is_initial terminal_is_terminal h section comparison variables {D : Type u₂} [category.{v₂} D] (G : C ⥤ D) /-- The comparison morphism from the image of a terminal object to the terminal object in the target category. This is an isomorphism iff `G` preserves terminal objects, see `category_theory.limits.preserves_terminal.of_iso_comparison`. -/ def terminal_comparison [has_terminal C] [has_terminal D] : G.obj (⊤_ C) ⟶ ⊤_ D := terminal.from _ /-- The comparison morphism from the initial object in the target category to the image of the initial object. -/ -- TODO: Show this is an isomorphism if and only if `G` preserves initial objects. def initial_comparison [has_initial C] [has_initial D] : ⊥_ D ⟶ G.obj (⊥_ C) := initial.to _ end comparison variables {J : Type u} [category.{v} J] /-- From a functor `F : J ⥤ C`, given an initial object of `J`, construct a cone for `J`. In `limit_of_diagram_initial` we show it is a limit cone. -/ @[simps] def cone_of_diagram_initial {X : J} (tX : is_initial X) (F : J ⥤ C) : cone F := { X := F.obj X, π := { app := λ j, F.map (tX.to j), naturality' := λ j j' k, begin dsimp, rw [← F.map_comp, category.id_comp, tX.hom_ext (tX.to j ≫ k) (tX.to j')], end } } /-- From a functor `F : J ⥤ C`, given an initial object of `J`, show the cone `cone_of_diagram_initial` is a limit. -/ def limit_of_diagram_initial {X : J} (tX : is_initial X) (F : J ⥤ C) : is_limit (cone_of_diagram_initial tX F) := { lift := λ s, s.π.app X, uniq' := λ s m w, begin rw [← w X, cone_of_diagram_initial_π_app, tX.hom_ext (tX.to X) (𝟙 _)], dsimp, simp -- See note [dsimp, simp] end} -- This is reducible to allow usage of lemmas about `cone_point_unique_up_to_iso`. /-- For a functor `F : J ⥤ C`, if `J` has an initial object then the image of it is isomorphic to the limit of `F`. -/ @[reducible] def limit_of_initial (F : J ⥤ C) [has_initial J] [has_limit F] : limit F ≅ F.obj (⊥_ J) := is_limit.cone_point_unique_up_to_iso (limit.is_limit _) (limit_of_diagram_initial initial_is_initial F) /-- From a functor `F : J ⥤ C`, given a terminal object of `J`, construct a cone for `J`, provided that the morphisms in the diagram are isomorphisms. In `limit_of_diagram_terminal` we show it is a limit cone. -/ @[simps] def cone_of_diagram_terminal {X : J} (hX : is_terminal X) (F : J ⥤ C) [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : cone F := { X := F.obj X, π := { app := λ i, inv (F.map (hX.from _)), naturality' := begin intros i j f, dsimp, simp only [is_iso.eq_inv_comp, is_iso.comp_inv_eq, category.id_comp, ← F.map_comp, hX.hom_ext (hX.from i) (f ≫ hX.from j)], end } } /-- From a functor `F : J ⥤ C`, given a terminal object of `J` and that the morphisms in the diagram are isomorphisms, show the cone `cone_of_diagram_terminal` is a limit. -/ def limit_of_diagram_terminal {X : J} (hX : is_terminal X) (F : J ⥤ C) [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_limit (cone_of_diagram_terminal hX F) := { lift := λ S, S.π.app _ } -- This is reducible to allow usage of lemmas about `cone_point_unique_up_to_iso`. /-- For a functor `F : J ⥤ C`, if `J` has a terminal object and all the morphisms in the diagram are isomorphisms, then the image of the terminal object is isomorphic to the limit of `F`. -/ @[reducible] def limit_of_terminal (F : J ⥤ C) [has_terminal J] [has_limit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : limit F ≅ F.obj (⊤_ J) := is_limit.cone_point_unique_up_to_iso (limit.is_limit _) (limit_of_diagram_terminal terminal_is_terminal F) /-- From a functor `F : J ⥤ C`, given a terminal object of `J`, construct a cocone for `J`. In `colimit_of_diagram_terminal` we show it is a colimit cocone. -/ @[simps] def cocone_of_diagram_terminal {X : J} (tX : is_terminal X) (F : J ⥤ C) : cocone F := { X := F.obj X, ι := { app := λ j, F.map (tX.from j), naturality' := λ j j' k, begin dsimp, rw [← F.map_comp, category.comp_id, tX.hom_ext (k ≫ tX.from j') (tX.from j)], end } } /-- From a functor `F : J ⥤ C`, given a terminal object of `J`, show the cocone `cocone_of_diagram_terminal` is a colimit. -/ def colimit_of_diagram_terminal {X : J} (tX : is_terminal X) (F : J ⥤ C) : is_colimit (cocone_of_diagram_terminal tX F) := { desc := λ s, s.ι.app X, uniq' := λ s m w, by { rw [← w X, cocone_of_diagram_terminal_ι_app, tX.hom_ext (tX.from X) (𝟙 _)], simp } } -- This is reducible to allow usage of lemmas about `cocone_point_unique_up_to_iso`. /-- For a functor `F : J ⥤ C`, if `J` has a terminal object then the image of it is isomorphic to the colimit of `F`. -/ @[reducible] def colimit_of_terminal (F : J ⥤ C) [has_terminal J] [has_colimit F] : colimit F ≅ F.obj (⊤_ J) := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) (colimit_of_diagram_terminal terminal_is_terminal F) /-- From a functor `F : J ⥤ C`, given an initial object of `J`, construct a cocone for `J`, provided that the morphisms in the diagram are isomorphisms. In `colimit_of_diagram_initial` we show it is a colimit cocone. -/ @[simps] def cocone_of_diagram_initial {X : J} (hX : is_initial X) (F : J ⥤ C) [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : cocone F := { X := F.obj X, ι := { app := λ i, inv (F.map (hX.to _)), naturality' := begin intros i j f, dsimp, simp only [is_iso.eq_inv_comp, is_iso.comp_inv_eq, category.comp_id, ← F.map_comp, hX.hom_ext (hX.to i ≫ f) (hX.to j)], end } } /-- From a functor `F : J ⥤ C`, given an initial object of `J` and that the morphisms in the diagram are isomorphisms, show the cone `cocone_of_diagram_initial` is a colimit. -/ def colimit_of_diagram_initial {X : J} (hX : is_initial X) (F : J ⥤ C) [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_colimit (cocone_of_diagram_initial hX F) := { desc := λ S, S.ι.app _ } -- This is reducible to allow usage of lemmas about `cocone_point_unique_up_to_iso`. /-- For a functor `F : J ⥤ C`, if `J` has an initial object and all the morphisms in the diagram are isomorphisms, then the image of the initial object is isomorphic to the colimit of `F`. -/ @[reducible] def colimit_of_initial (F : J ⥤ C) [has_initial J] [has_colimit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : colimit F ≅ F.obj (⊥_ J) := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) (colimit_of_diagram_initial initial_is_initial _) /-- If `j` is initial in the index category, then the map `limit.π F j` is an isomorphism. -/ lemma is_iso_π_of_is_initial {j : J} (I : is_initial j) (F : J ⥤ C) [has_limit F] : is_iso (limit.π F j) := ⟨⟨limit.lift _ (cone_of_diagram_initial I F), ⟨by { ext, simp }, by simp⟩⟩⟩ instance is_iso_π_initial [has_initial J] (F : J ⥤ C) [has_limit F] : is_iso (limit.π F (⊥_ J)) := is_iso_π_of_is_initial (initial_is_initial) F lemma is_iso_π_of_is_terminal {j : J} (I : is_terminal j) (F : J ⥤ C) [has_limit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_iso (limit.π F j) := ⟨⟨limit.lift _ (cone_of_diagram_terminal I F), by { ext, simp }, by simp ⟩⟩ instance is_iso_π_terminal [has_terminal J] (F : J ⥤ C) [has_limit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_iso (limit.π F (⊤_ J)) := is_iso_π_of_is_terminal terminal_is_terminal F /-- If `j` is terminal in the index category, then the map `colimit.ι F j` is an isomorphism. -/ lemma is_iso_ι_of_is_terminal {j : J} (I : is_terminal j) (F : J ⥤ C) [has_colimit F] : is_iso (colimit.ι F j) := ⟨⟨colimit.desc _ (cocone_of_diagram_terminal I F), ⟨by simp, by { ext, simp }⟩⟩⟩ instance is_iso_ι_terminal [has_terminal J] (F : J ⥤ C) [has_colimit F] : is_iso (colimit.ι F (⊤_ J)) := is_iso_ι_of_is_terminal (terminal_is_terminal) F lemma is_iso_ι_of_is_initial {j : J} (I : is_initial j) (F : J ⥤ C) [has_colimit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_iso (colimit.ι F j) := ⟨⟨colimit.desc _ (cocone_of_diagram_initial I F), ⟨by tidy, by { ext, simp }⟩⟩⟩ instance is_iso_ι_initial [has_initial J] (F : J ⥤ C) [has_colimit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_iso (colimit.ι F (⊥_ J)) := is_iso_ι_of_is_initial initial_is_initial F end end category_theory.limits
{-# OPTIONS --cubical --no-import-sorts --safe #-} module Cubical.Algebra.Group.Notation where open import Cubical.Foundations.Prelude open import Cubical.Foundations.HLevels open import Cubical.Algebra.Group.Base module GroupNotationG {ℓ : Level} ((_ , G) : Group {ℓ}) where 0ᴳ = GroupStr.0g G _+ᴳ_ = GroupStr._+_ G -ᴳ_ = GroupStr.-_ G _-ᴳ_ = GroupStr._-_ G lIdᴳ = GroupStr.lid G rIdᴳ = GroupStr.rid G lCancelᴳ = GroupStr.invl G rCancelᴳ = GroupStr.invr G assocᴳ = GroupStr.assoc G setᴳ = GroupStr.is-set G module GroupNotationᴴ {ℓ : Level} ((_ , G) : Group {ℓ}) where 0ᴴ = GroupStr.0g G _+ᴴ_ = GroupStr._+_ G -ᴴ_ = GroupStr.-_ G _-ᴴ_ = GroupStr._-_ G lIdᴴ = GroupStr.lid G rIdᴴ = GroupStr.rid G lCancelᴴ = GroupStr.invl G rCancelᴴ = GroupStr.invr G assocᴴ = GroupStr.assoc G setᴴ = GroupStr.is-set G module GroupNotation₀ {ℓ : Level} ((_ , G) : Group {ℓ}) where 0₀ = GroupStr.0g G _+₀_ = GroupStr._+_ G -₀_ = GroupStr.-_ G _-₀_ = GroupStr._-_ G lId₀ = GroupStr.lid G rId₀ = GroupStr.rid G lCancel₀ = GroupStr.invl G rCancel₀ = GroupStr.invr G assoc₀ = GroupStr.assoc G set₀ = GroupStr.is-set G module GroupNotation₁ {ℓ : Level} ((_ , G) : Group {ℓ}) where 0₁ = GroupStr.0g G _+₁_ = GroupStr._+_ G -₁_ = GroupStr.-_ G _-₁_ = GroupStr._-_ G lId₁ = GroupStr.lid G rId₁ = GroupStr.rid G lCancel₁ = GroupStr.invl G rCancel₁ = GroupStr.invr G assoc₁ = GroupStr.assoc G set₁ = GroupStr.is-set G
module Highlighting where Set-one : Set₂ Set-one = Set₁ record R (A : Set) : Set-one where constructor con field X : Set F : Set → Set → Set F A B = B field P : F A X → Set -- Note: we cannot check highlighting of non-termination -- any more (Andreas, 2014-09-05), since termination failure -- is a type error now. {-# NON_TERMINATING #-} Q : F A X → Set Q = Q postulate P : _ open import Highlighting.M data D (A : Set) : Set-one where d : let X = D in X A
import data.finset data.multiset import tactic import init.classical noncomputable theory open_locale classical local attribute [instance, priority 100000] classical.prop_decidable -- avoid decidability hell namespace list def ihead {α : Type} : Π l : list α, l ≠ [] → α | [] h := absurd rfl h | (a :: t) h := a end list structure multigraph (α : Type) := (V : finset α) (E : multiset (α × α)) (valid_edges : ∀ e : α × α, e ∈ E → e.1 ∈ V ∧ e.2 ∈ V) (no_self_loops : ∀ {u v}, (u, v) ∈ E → u ≠ v) namespace multigraph variable {α : Type} @[simp] instance : has_mem (α × α) (multigraph α) := ⟨λ e g, e ∈ g.E⟩ def walk_vertices_match (g : multigraph α) : list (α × α) → Prop | [] := true | [e] := true | (e :: f :: t) := e.2 = f.1 ∧ walk_vertices_match t def is_walk (g : multigraph α) (l : list (α × α)): Prop := (∀{e}, e ∈ l → e ∈ g) ∧ walk_vertices_match g l inductive walk (g : multigraph α) : α → α → Type | nil : Π (v ∈ g.V), walk v v | cons : Π (u v w : α) (hmem : (u, v) ∈ g) (l : walk v w), walk u w namespace walk variables {g : multigraph α} @[simp] def edges : Π {s t : α} (w : walk g s t), list (α × α) | _ _ (nil g t) := [] | _ _ (cons s t w hmem l) := (s, t) :: (@edges t w l) def append : Π {s t u : α} (wst : walk g s t) (wtu : walk g t u), walk g s u | _ _ _ (nil g _) w := w | _ _ u (cons s v t hmem w1) w2 := cons s v u hmem (append w1 w2) def s_mem : Π {s t : α} (w : walk g s t), s ∈ g.V | _ _ (nil g t) := t | _ _ (cons s v t hmem l) := (g.valid_edges _ hmem).left def t_mem : Π {s t : α} (w : walk g s t), t ∈ g.V | _ _ (nil g t) := t | _ _ (cons s v t hmem l) := t_mem l def length {u v : α} : walk g u v → ℕ := λ w, w.edges.length variables {s t : α} variable w : walk g s t lemma valid_edge_of_mem_walk (e : α × α) : e ∈ w.edges → e ∈ g := begin intro hmem, induction w with _ _ u v w hemem l ih, { simp at hmem, exfalso, exact hmem }, simp at hmem, cases hmem with hl hr, { rw ← hl at hemem, exact hemem, }, exact ih hr, end @[reducible] def is_eulerian : Prop := ∀ u v : α, g.E.countp (λ e, e = (u, v) ∨ e = (v, u)) = w.edges.countp (λ e, e = (u, v) ∨ e = (v, u)) def is_cycle : Prop := s = t end walk variable (g : multigraph α) def degree (v : α) : ℕ := g.E.countp (λ e, ∃ u, e = (u, v) ∨ e = (v, u)) def reachable : α → α → Prop := relation.refl_trans_gen (λ u v, (u, v) ∈ g) @[reducible] def is_connected : Prop := ∀ u v ∈ g.V, reachable g u v @[reducible] def is_eulerian : Prop := ∃ (s t : α) (w : walk g s t), w.is_eulerian end multigraph open multigraph variable {α : Type} variable (g : multigraph α) variable (hcon : g.is_connected) @[simp] lemma fun_abstract {α β : Type} (f : α → β) : f = (λ x : α, f x) := rfl namespace list universe u variable (a : α) variable (l : list α) theorem countp_cons (p : α → Prop) [∀ a, decidable (p a)] : countp p (a :: l) = ite (p a) 1 0 + countp p l := by {by_cases p a; rw countp; simp [h], ring,} theorem length_filter_eq_sum_map {α : Type} (l : list α) (p : α → Prop) : length (filter p l) = sum (map (λ x, ite (p x) 1 0) l) := begin induction l with x l ih; simp, by_cases hx : p x, all_goals { rw filter_cons_of_pos _ hx <|> rw filter_cons_of_neg _ hx, simp [length_cons, ih, hx],}, end theorem not_mem_of_countp_eq_zero {α : Type} (l : list α) (p : α → Prop) : l.countp p = 0 ↔ ∀ a ∈ l, ¬ p a := begin split, { intros hzero a hmem hp, induction l with x l ih, { simp at hmem, exact hmem, }, simp [countp_cons] at *, cases hmem with hx hl, { rw ← hx at hzero, simp [hp] at hzero, exact hzero, }, exact ih hzero.left hl,}, intros h, induction l with x l ih, { simp, }, simp [countp_cons], split, { rw ih, intros a hmem, exact h a (by simp [hmem]), }, simp [h x], end theorem countp_split {α : Type} {l : list α} {p q : α → Prop} : l.countp p = (l.filter q).countp p + (l.filter (λ a, ¬ q a)).countp p := begin induction l with x l ih, { simp, }, simp [countp_cons], by_cases p x, { by_cases q x; simp *, }, simp [h, ih], end theorem countp_le_length {α : Type} {l : list α} {p : α → Prop} : l.countp p ≤ l.length := begin induction l with x l ih, simp, by_cases p x; simp [h, ih], linarith, end theorem length_lt_of_filter_of_mem {α : Type} (l : list α) (p : α → Prop) : (∃ a ∈ l, ¬ p a) → (l.filter p).length < l.length := begin intro h, cases h with a h, cases h with hmem ha, induction l with x l ih, { simp at ⊢ hmem, exfalso, exact hmem, }, rw ← list.countp_eq_length_filter, simp [list.countp_cons], by_cases heq : a = x, { rw ← heq, simp [ha], have : countp p l ≤ length l, from countp_le_length, linarith, }, have : a ∈ l, { simp at hmem, cases hmem, exact absurd hmem heq, exact hmem, }, have : l.countp p < length l, by simp [list.countp_eq_length_filter, ih this], have hleite : ite (p x) 1 0 ≤ 1, by by_cases p x; simp *, linarith, end theorem countp_false_eq_zero {l : list α} : l.countp (λ x, false) = 0 := by {induction l with x l ih, simp, simp [ih]} end list namespace multiset theorem countp_cons (s : multiset α) (a : α) (p : α → Prop) [∀ a, decidable (p a)] : countp p (a :: s) = ite (p a) 1 0 + countp p s := by {by_cases p a; simp [h]} theorem countp_false_eq_zero {s : multiset α} : s.countp (λ x, false) = 0 := by {induction s; simp, induction s with x l ih, simp, simp [ih]} theorem countp_eq_zero_of_false_of_mem {s : multiset α} {p : α → Prop} (h : ∀ x ∈ s, ¬ p x) : s.countp p = 0 := begin rcases s with s, simp * at *, revert h, induction s with x l ih; simp [list.countp_cons], intros hx hl, split, { exact ih hl, }, { simp [hx], }, end theorem countp_eq_card_of_true_of_mem {s : multiset α} {p : α → Prop} (h : ∀ x ∈ s, p x) : s.countp p = s.card := begin rcases s with l, simp * at *, revert h, induction l with x l ih; simp [list.countp_cons], intros hx hl, simp [hx, ih hl], end theorem countp_split {α : Type} (s : multiset α) {p : α → Prop} (q : α → Prop) : s.countp p = (s.filter q).countp p + (s.filter (λ a, ¬ q a)).countp p := begin rcases s with l, exact list.countp_split, end theorem not_mem_of_countp_eq_zero {α : Type} (s : multiset α) (p : α → Prop) : s.countp p = 0 ↔ ∀ a ∈ s, ¬ p a := begin rcases s with l, simp [list.not_mem_of_countp_eq_zero], end end multiset namespace finset @[simp] def countp (p : α → Prop) [decidable_pred p] (s : finset α) : ℕ := s.val.countp p theorem filter_eq_multiset_filter (p : α → Prop) [decidable_pred p] (s : finset α) : (s.filter p).val = s.val.filter p := by {rcases s, simp} theorem multiset_card_eq_card (s : finset α) : s.val.card = s.card := by {rcases s, simp [card] } lemma eq_of_subset_of_subset {s t : finset α} (h₁ : s ⊆ t) (h₂ : t ⊆ s) : s = t := (eq_of_subset_of_card_le h₁ (card_le_of_subset h₂)) end finset namespace nat @[simp] theorem eq_of_succ_eq_succ (n m : ℕ) : n.succ = m.succ ↔ n = m := by {split, intro h, injection h, intro h, apply_fun nat.succ at h, exact h, } @[simp] theorem not_succ_eq_zero (n : ℕ) : n.succ ≠ 0 := by {intro h, injection h } @[simp] theorem not_zero_eq_succ (n : ℕ) : 0 ≠ n.succ := by {intro h, injection h } @[simp] theorem add_mul_mod (a b m : ℕ) : (a + m * b) % m = a % m := by simp @[simp] theorem add_mod_mod (a b m : ℕ) : (a + b % m) % m = (a + b) % m := begin conv in (a + b) { rw ← nat.mod_add_div b m, }, rw ← nat.add_assoc, rw add_mul_mod, end @[simp] theorem mod_add_mod (a b m : ℕ) : (a % m + b) % m = (a + b) % m := begin simp, end @[simp] theorem even_of_not_odd (n : ℕ) : ¬ n % 2 = 1 ↔ n % 2 = 0 := begin have := nat.mod_two_eq_zero_or_one n, split; intro h; finish, end @[simp] theorem odd_of_not_even (n : ℕ) : ¬ n % 2 = 0 ↔ n % 2 = 1 := begin have := nat.mod_two_eq_zero_or_one n, split; intro h; finish, end @[simp] theorem one_mod_two_eq_one : 1 % 2 = 1 := nat.mod_eq_of_lt (by linarith) @[simp] theorem zero_mod_two_eq_zero : 0 % 2 = 0 := nat.mod_eq_of_lt (by linarith) @[simp] theorem even_of_succ_odd (n : ℕ) : (n + 1) % 2 = 1 ↔ n % 2 = 0 := begin rw ← mod_add_mod, split; intro h, { by_contradiction hn, simp at hn, simp [hn] at h, exact h, }, simp [h], end @[simp] theorem odd_of_succ_even (n : ℕ) : (n + 1) % 2 = 0 ↔ n % 2 = 1 := begin rw ← mod_add_mod, split; intro h, { by_contradiction hn, simp at hn, simp [hn] at h, exact h, }, simp [h], end end nat open multigraph variable {β : Type} lemma vert_in_walk (x : α) : ∀ (s t : α) (wlk : walk g s t), wlk.edges.countp (λ e, ∃ u, e = (x, u)) + ite (t = x) 1 0 = wlk.edges.countp (λ e, ∃ u, e = (u, x)) + ite (s = x) 1 0 | _ _ (walk.nil g s) := by simp | _ _ (walk.cons s v t hmem w) := have hdec : @list.length (α × α) (@walk.edges α g v t w) < 1 + @list.length (α × α) (@walk.edges α g v t w), by linarith, begin have indrw := vert_in_walk v t w, by_cases (s = x), { have hne : v ≠ x, { rw h at hmem, have this := g.no_self_loops hmem, symmetry, exact this, }, simp [list.countp_cons, h, hne] at ⊢ indrw, exact indrw, }, by_cases hcase: v = x; { simp [list.countp_cons, h, hcase] at ⊢ indrw, exact indrw, }, end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ psig, psig.2.2.edges.length)⟩], dec_tac := well_founded_tactics.default_dec_tac'} @[simp] lemma exists_and (a : α) (p : α → Prop) : (∃ x, p x) ∧ p a ↔ p a := by { split; simp, intro hp, split, exact ⟨a, hp⟩, exact hp, } lemma injective_count_aux (len : ℕ) {r : α → β → Prop} (nodup : ∀ (x y : α) (b : β), x ≠ y → ¬ (r x b ∧ r y b)) : ∀ l1 l2 : list β, l1.length ≤ len → (∀ a : α, l1.countp (r a) = l2.countp (r a)) → l1.countp (λ b, ∃ a, r a b) = l2.countp (λ b, ∃ a, r a b) := begin induction len with len, { intros l1 l2 hlen hp, simp at hlen, have : l1 = list.nil, by rw list.eq_nil_of_length_eq_zero hlen, rw this at hp ⊢, simp at hp ⊢, have : ∀ b ∈ l2, ¬ ∃ a, r a b, { intros b hmem h, cases h with a ha, have : ∀ c ∈ l2, ¬ r a c, rw ← list.not_mem_of_countp_eq_zero, { symmetry, exact hp a, }, exact absurd ha (this b hmem), }, symmetry, rw list.not_mem_of_countp_eq_zero, exact this, }, intros l1 l2 hlen h, by_cases hex : ∃ a, ∃ b ∈ l1, r a b, { cases hex with a ha, rw @list.countp_split _ l1 _ (λ b, r a b), rw @list.countp_split _ l2 _ (λ b, r a b), repeat {rw @list.countp_filter _ _ _ (λ (b : β), r a b) _ _}, simp [-list.countp_filter], suffices : list.countp (λ (b : β), ∃ (a : α), r a b) (list.filter (λ (a_1 : β), ¬r a a_1) l1) + list.countp (r a) l1 = list.countp (λ (b : β), ∃ (a : α), r a b) (list.filter (λ (a_1 : β), ¬r a a_1) l2) + list.countp (r a) l2, { convert this }, -- decidability hell simp [h a, -list.countp_filter], set l1' := (list.filter (λ (a_1 : β), ¬r a a_1) l1), set l2' := (list.filter (λ (a_1 : β), ¬r a a_1) l2), have hlen' : l1'.length ≤ len, { have : l1'.length < l1.length, { apply list.length_lt_of_filter_of_mem, simp at ⊢ ha, exact ha, }, have : nat.succ l1'.length ≤ nat.succ len, { apply nat.succ_le_of_lt, apply nat.lt_of_lt_of_le this hlen, }, exact nat.le_of_succ_le_succ this, }, have heqcountp : ∀ l (a' : α) (hne : a' ≠ a), (list.filter (λ (b : β), ¬r a b) l).countp (r a') = l.countp (r a'), { intros l a' hne, induction l with x l ih, simp, simp at ih, simp [list.countp_cons, ih], by_cases r a' x, { have : ¬ r a x, { have not_and := nodup a' a x hne, finish [nodup a' a x hne], }, simp *, }, simp *, }, have h' : ∀ (a : α), list.countp (r a) l1' = list.countp (r a) l2', { intro a', by_cases hcase : a' = a, { rw hcase, simp, suffices : list.countp (λ (a : β), false) l1 = list.countp (λ (a : β), false) l2, { convert this, }, -- more decidability hell simp [list.countp_false_eq_zero], }, rw heqcountp l1 _ hcase, rw heqcountp l2 _ hcase, exact h a', }, exact len_ih l1' l2' (by simp [hlen']) h', }, have : ∀ b ∈ l1, ¬ ∃ a, r a b, { intros b hmem h, cases h with a ha, have : ∃ (a : α) (b : β) (H : b ∈ l1), r a b, exact ⟨a, ⟨b, ⟨hmem, ha⟩⟩⟩, exact absurd this hex, }, rw list.countp_eq_length_filter, rw list.countp_eq_length_filter, have : ∀ b, b ∉ list.filter (λ (b : β), ∃ (a : α), r a b) l1, { intros b h, simp at h, exact absurd h.right (this b h.left), }, rw list.eq_nil_iff_forall_not_mem.mpr this, have : ∀ b, b ∉ list.filter (λ (b : β), ∃ (a : α), r a b) l2, { intros b h, simp at h, cases h with hmem hr, cases hr with a hr, have : list.countp (r a) l2 = 0, { rw ← h a, have : ∀ b, b ∉ list.filter (r a) l1, { intros b h, simp at h, cases h with hmem hr, have : ∃ (a : α) (b : β) (H : b ∈ l1), r a b, exact ⟨a, ⟨b, ⟨hmem, hr⟩⟩⟩, exact absurd this hex, }, rw list.countp_eq_length_filter, rw list.eq_nil_iff_forall_not_mem.mpr this, simp, }, rw list.countp_eq_length_filter at this, have : l2.filter (r a) = [], from list.eq_nil_of_length_eq_zero this, have hfilter_mem : b ∈ l2.filter (r a), { rw list.mem_filter, exact ⟨hmem, hr⟩, }, rw list.eq_nil_iff_forall_not_mem at this, exact absurd hfilter_mem (this b), }, rw list.eq_nil_iff_forall_not_mem.mpr this, end lemma injective_count {l1 l2 : list β} {r : α → β → Prop} (nodup : ∀ (x y : α) (b : β), x ≠ y → ¬ (r x b ∧ r y b)) : (∀ a : α, l1.countp (r a) = l2.countp (r a)) → l1.countp (λ b, ∃ a, r a b) = l2.countp (λ b, ∃ a, r a b) := begin set len := l1.length, exact injective_count_aux len nodup l1 l2 (by simp [len]), end lemma count_plus (l : list α) (p q : α → Prop) (nodup : ∀ a ∈ l, ¬ (p a ∧ q a)) : l.countp p + l.countp q = l.countp (λ a, p a ∨ q a) := begin induction l with a l1 ih, { simp }, simp [list.count_cons', list.countp_cons], by_cases p a ∨ q a, { cases h, { have : ¬ q a, by finish, simp [h, this], rw ih, intros a hmem, exact nodup a (by simp [hmem]),}, { have : ¬ p a, by finish, simp [h, this], rw ih, intros a hmem, exact nodup a (by simp [hmem]),} }, { have hane : ¬ p a, by finish, have hbne : ¬ q a, by finish, simp [hane, hbne], rw ih, intros a hmem, exact nodup a (by simp [hmem]),} end lemma degree_of_eulerian_walk {s t : α} {w : walk g s t} (he : w.is_eulerian) {v : α} : g.degree v = list.countp (λ (a : α × α), ∃ (x : α), a = (x, v)) (walk.edges w) + list.countp (λ (a : α × α), ∃ (x : α), a = (v, x)) (walk.edges w) := begin have : g.degree v = w.edges.countp (λ e, ∃ u, e = (u, v) ∨ e = (v, u)), { rw degree, have he := (λ u, he u v), revert he, induction g.E with l; intro he; simp at *, apply injective_count (by finish) he }, rw this, simp [exists_or_distrib], suffices : list.countp (λ (e : α × α), (∃ (x : α), e = (x, v)) ∨ ∃ (x : α), e = (v, x)) (walk.edges w) = list.countp (λ (a : α × α), ∃ (x : α), a = (x, v)) (walk.edges w) + list.countp (λ (a : α × α), ∃ (x : α), a = (v, x)) (walk.edges w), { convert this, }, rw ← count_plus, intros e hmem h, cases h with hl hr, cases hl with xl hl, cases hr with xr hr, rw hr at hl, have hmem := w.valid_edge_of_mem_walk _ hmem, rw hr at hmem, have hv_ne_xr := g.no_self_loops hmem, simp at hl, finish, end lemma degree_constraint_of_eulerian (h : g.is_eulerian) : g.V.countp (λ v, g.degree v % 2 = 1) = 0 ∨ g.V.countp (λ v, g.degree v % 2 = 1) = 2 := begin rw is_eulerian at h, cases h with s h, cases h with t h, cases h with w he, unfold finset.countp, by_cases hcase : s = t, { left, have : ∀ v ∈ g.V, g.degree v % 2 = 0, { intros v hmem, have hcnt := vert_in_walk g v _ _ w, simp [hcase] at hcnt, rw degree_of_eulerian_walk _ he, by_cases htv : t = v; simp [htv] at hcnt; rw hcnt; ring; simp, }, conv at this in (_ = 0) { rw ← nat.even_of_not_odd, }, exact multiset.countp_eq_zero_of_false_of_mem this, }, right, rw multiset.countp_split g.V.val (λ x, s = x ∨ t = x), simp, have : ∀ v ∈ g.V, ¬ (s = v ∨ t = v) → g.degree v % 2 = 0, { intros v hmem hne, rw not_or_distrib at hne, cases hne with hnes hnet, have hcnt := vert_in_walk g v _ _ w, rw degree_of_eulerian_walk _ he, simp [hnes, hnet] at hcnt, simp [hcnt], ring, simp, }, have : ∀ v ∈ g.V, ¬ (degree g v % 2 = 1 ∧ ¬(s = v ∨ t = v)), { intros v hmem h, cases h with h hne, rw ← nat.odd_of_not_even at h, exact absurd (this v hmem hne) h, }, suffices : multiset.countp (λ (a : α), degree g a % 2 = 1 ∧ (s = a ∨ t = a)) g.V.val + multiset.countp (λ (a : α), degree g a % 2 = 1 ∧ ¬(s = a ∨ t = a)) g.V.val = 2, { convert this, }, simp [multiset.countp_eq_zero_of_false_of_mem this], rw multiset.countp_eq_card_filter, rw ← finset.filter_eq_multiset_filter, have hsdeg : g.degree s % 2 = 1, { have hcnt := vert_in_walk g s _ _ w, simp [ne.symm hcase] at hcnt, rw degree_of_eulerian_walk _ he, simp [hcnt], ring, simp, }, have htdeg : g.degree t % 2 = 1, { have hcnt := vert_in_walk g t _ _ w, simp [hcase] at hcnt, rw degree_of_eulerian_walk _ he, simp [eq.symm hcnt], ring, simp, }, have : finset.filter (λ (a : α), degree g a % 2 = 1 ∧ (s = a ∨ t = a)) g.V = {s, t}, { apply finset.eq_of_subset_of_subset; rw finset.subset_iff; intros x hmem, { rw finset.mem_filter at hmem, rcases hmem with ⟨hmem, hdeg, hcase | hcase⟩; simp [hcase],}, { simp at hmem, cases hmem; rw hmem, { simp [htdeg, w.t_mem], }, { simp [hsdeg, w.s_mem], }, }, }, rw this, rw finset.multiset_card_eq_card, simp, change s ≠ t at hcase, rw @finset.card_insert_of_not_mem _ _ t (finset.singleton s) (by simp [ne_comm.mp hcase]), simp [hcase], end namespace konigsberg @[simp] def V : finset ℕ := {0, 1, 2, 3} @[simp] def E : multiset (ℕ × ℕ) := (0, 1) :: (0, 1) :: (1, 2) :: (1, 2) :: (0, 3) :: (1, 3) :: (2, 3) :: {} lemma valid_edges : ∀ e : ℕ × ℕ, e ∈ E → e.1 ∈ V ∧ e.2 ∈ V := begin intros e hmem, rw V, rw E at hmem, fin_cases hmem; simp, end lemma no_self_loops : ∀ u v : ℕ, (u, v) ∈ E → u ≠ v := begin intros u v hmem heq, rw heq at hmem, rw E at hmem, fin_cases hmem; simp at hmem; finish, end @[simp] def G := multigraph.mk V E valid_edges no_self_loops lemma all_degrees_odd : ∀ v ∈ G.V, G.degree v % 2 = 1 := begin intros v hmem, simp at hmem, rcases hmem with rfl | rfl | rfl | rfl; unfold degree; simp, end lemma four_odd_degree_verts : G.V.countp (λ v, G.degree v % 2 = 1) = 4 := begin unfold finset.countp, rw multiset.countp_eq_card_of_true_of_mem, { simp, }, exact all_degrees_odd, end theorem no_euler_walk_in_konigsberg_bridge : ¬ G.is_eulerian := begin intro h, have hdeg := degree_constraint_of_eulerian _ h, rw four_odd_degree_verts at hdeg, simp at hdeg, exact hdeg, end end konigsberg
! Generated by TAPENADE (INRIA, Tropics team) ! tapenade 3.x ! !> @brief commonly used character global variables MODULE MOD_GENRLC_AD IMPLICIT NONE ! CHARACTER :: title*80, project*256 ! CHARACTER(len=256) :: restart_name, status_log, status_log_inv ! ! defines the PROPS and USER choice ! CHARACTER(len=80) :: def_props, def_user ! ! binary can be one of: 'forward', 'simul' or 'inverse' ! CHARACTER(len=7) :: def_binary ! ! external file control for: simul, enkf, inverse, data ! CHARACTER(len=256) :: filename_simul, filename_enkf, filename_inverse ! CHARACTER(len=256) :: filename_data END MODULE MOD_GENRLC_AD
lemma integral_restrict: fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space" assumes "S \<subseteq> T" "S \<in> sets lebesgue" "T \<in> sets lebesgue" shows "integral\<^sup>L (lebesgue_on T) (\<lambda>x. if x \<in> S then f x else 0) = integral\<^sup>L (lebesgue_on S) f"
import matplotlib.pyplot as plt import matplotlib.pylab as pylab from io import BytesIO import skimage.io as io from PIL import Image import numpy as np pylab.rcParams['figure.figsize'] = (8.0, 10.0) from pycocotools.coco import COCO from maskrcnn_benchmark.config import cfg from demo.predictor import COCODemo import argparse import os # def load(url): # """ # Given an url of an image, downloads the image and # returns a PIL image # """ # response = requests.get(url) # pil_image = Image.open(BytesIO(response.content)).convert("RGB") # # convert to BGR format # image = np.array(pil_image)[:, :, [2, 1, 0]] # return image def imshow(img): plt.imshow(img[:, :, [2, 1, 0]]) plt.axis("off") def main(): parser = argparse.ArgumentParser(description="PyTorch Object Detection Training") parser.add_argument( "--config-file", default="", metavar="FILE", help="path to config file", type=str, ) args = parser.parse_args() cfg.merge_from_file(args.config_file) cfg.merge_from_list(["MODEL.DEVICE", "cpu"]) coco_demo = COCODemo( cfg, min_image_size=800, confidence_threshold=0.7, ) dataDir='/depudata1/coco' dataType='val2017' annFile='{}/annotations/instances_{}.json'.format(dataDir,dataType) coco=COCO(annFile) # display COCO categories and supercategories cats = coco.loadCats(coco.getCatIds()) nms=[cat['name'] for cat in cats] print('COCO categories: \n{}\n'.format(' '.join(nms))) nms = set([cat['supercategory'] for cat in cats]) print('COCO supercategories: \n{}'.format(' '.join(nms))) catIds = coco.getCatIds(catNms=['person']) imgIds = coco.getImgIds(catIds=catIds ) # imgIds = coco.getImgIds(imgIds = [341681]) curr_img_id = imgIds[np.random.randint(0,len(imgIds))] img = coco.loadImgs(curr_img_id)[0] image = io.imread(img['coco_url']) # image = load("http://farm3.staticflickr.com/2469/3915380994_2e611b1779_z.jpg") plt.imshow(image) predictions = coco_demo.run_on_opencv_image(image) plt.imshow(predictions) str1 = '%s.jpg' % curr_img_id plt.savefig(str1) if __name__ == "__main__": main()
\documentclass[a4paper, onecolumn, 10pt]{article} \input{preamble.tex} \title{Hello World} \author{Eisoku Kuroiwa} \date{\Filemodtoday{\jobname}} \begin{document} \maketitle \section{sample} \autoref{eq:eom} is an equation of motion for a floating base robot. \begin{equation} \begin{bmatrix} \bm{M}_{BB} & \bm{M}_{BJ}\\ \bm{M}_{JB} & \bm{M}_{JJ} \end{bmatrix} \begin{bmatrix} \ddot{\bm{q}}_{B}\\ \ddot{\bm{q}}_{J} \end{bmatrix} + \begin{bmatrix} \bm{b}_{B}\\ \bm{b}_{J} \end{bmatrix} = \begin{bmatrix} \bm{0}\\ \bm{\tau} \end{bmatrix} + \begin{bmatrix} \bm{J}_{B1} & \cdots & \bm{J}_{BN}\\ \bm{J}_{J1} & \cdots & \bm{J}_{JN} \end{bmatrix} \begin{bmatrix} \bm{f}_1\\ \vdots\\ \bm{f}_N \end{bmatrix} \label{eq:eom} \end{equation} \end{document}
(* * Copyright 2014, NICTA * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(NICTA_BSD) *) section "32-Bit Machine Word Setup" theory Word_Setup_32 imports Word_Enum begin text \<open>This theory defines standard platform-specific word size and alignment.\<close> type_synonym machine_word_len = 32 type_synonym machine_word = "machine_word_len word" definition word_bits :: nat where "word_bits = len_of TYPE(machine_word_len)" text \<open>The following two are numerals so they can be used as nats and words.\<close> definition word_size_bits :: "'a :: numeral" where "word_size_bits = 2" definition word_size :: "'a :: numeral" where "word_size = 4" lemma word_bits_conv[code]: "word_bits = 32" unfolding word_bits_def by simp lemma word_size_word_size_bits: "(word_size::nat) = 2 ^ word_size_bits" unfolding word_size_def word_size_bits_def by simp lemma word_bits_word_size_conv: "word_bits = word_size * 8" unfolding word_bits_def word_size_def by simp end
The M @-@ 240 Storm <unk> Vehicle is the first of three Storm generations . A variant of the 1991 Jeep Wrangler YJ and the older CJ @-@ 6 / CJ @-@ 8 wheelbase , it is entirely produced in Israel by Automotive Industries Ltd. with the exception of the engines , as their manufacture is not economically viable on the Storm 's market scale .
[STATEMENT] lemma mtx_nonzero_iff[simp]: "mtx_nonzero c = E" [PROOF STATE] proof (prove) goal (1 subgoal): 1. mtx_nonzero c = E [PROOF STEP] unfolding E_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. mtx_nonzero c = {(u, v). c (u, v) \<noteq> 0} [PROOF STEP] by (auto simp: mtx_nonzero_def)
[STATEMENT] lemma nsqn_invalidate_other [simp]: assumes "dip\<in>kD(rt)" and "dip\<notin>dom dests" shows "nsqn (invalidate rt dests) dip = nsqn rt dip" [PROOF STATE] proof (prove) goal (1 subgoal): 1. nsqn (invalidate rt dests) dip = nsqn rt dip [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: dip \<in> kD rt dip \<notin> dom dests goal (1 subgoal): 1. nsqn (invalidate rt dests) dip = nsqn rt dip [PROOF STEP] by (clarsimp simp add: kD_nsqn)
(* Title: HOL/Auth/n_mutualEx_on_inis.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_mutualEx Protocol Case Study*} theory n_mutualEx_on_inis imports n_mutualEx_on_ini begin lemma on_inis: assumes b1: "f \<in> (invariants N)" and b2: "ini \<in> {andList (allInitSpecs N)}" and b3: "formEval ini s" shows "formEval f s" proof - have c1: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__1 p__Inv3 p__Inv4)\<or> (\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__2 p__Inv4)\<or> (\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__3 p__Inv3 p__Inv4)\<or> (\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)\<or> (\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__5 p__Inv3 p__Inv4)" apply (cut_tac b1, simp) done moreover { assume d1: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__1 p__Inv3 p__Inv4)" have "formEval f s" apply (rule iniImply_inv__1) apply (cut_tac d1, assumption) apply (cut_tac b2 b3, blast) done } moreover { assume d1: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__2 p__Inv4)" have "formEval f s" apply (rule iniImply_inv__2) apply (cut_tac d1, assumption) apply (cut_tac b2 b3, blast) done } moreover { assume d1: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__3 p__Inv3 p__Inv4)" have "formEval f s" apply (rule iniImply_inv__3) apply (cut_tac d1, assumption) apply (cut_tac b2 b3, blast) done } moreover { assume d1: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" have "formEval f s" apply (rule iniImply_inv__4) apply (cut_tac d1, assumption) apply (cut_tac b2 b3, blast) done } moreover { assume d1: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__5 p__Inv3 p__Inv4)" have "formEval f s" apply (rule iniImply_inv__5) apply (cut_tac d1, assumption) apply (cut_tac b2 b3, blast) done } ultimately show "formEval f s" by satx qed end
%!TEX root = ../thesis.tex \chapter{The title of chapter two} The integers, along with the two operations of addition and multiplication, form the prototypical example of a ring. In mathematics, a ring is one of the fundamental algebraic structures used in abstract algebra. It consists of a set equipped with two binary operations that generalize the arithmetic operations of addition and multiplication. Through this generalization, theorems from arithmetic are extended to non-numerical objects such as polynomials, series, matrices and functions. A ring is an abelian group with a second binary operation that is associative, is distributive over the abelian group operation, and has an identity element (this last property is not required by some authors, see § Notes on the definition). By extension from the integers, the abelian group operation is called addition and the second binary operation is called multiplication. Whether a ring is commutative or not (that is, whether the order in which two elements are multiplied changes the result or not) has profound implications on its behavior as an abstract object. As a result, commutative ring theory, commonly known as commutative algebra, is a key topic in ring theory. Its development has been greatly influenced by problems and ideas occurring naturally in algebraic number theory and algebraic geometry. Examples of commutative rings include the set of integers equipped with the addition and multiplication operations, the set of polynomials equipped with their addition and multiplication, the coordinate ring of an affine algebraic variety, and the ring of integers of a number field. Examples of noncommutative rings include the ring of \(n \times n\) real square matrices with \(n \geq 2\), group rings in representation theory, operator algebras in functional analysis, rings of differential operators in the theory of differential operators, and the cohomology ring of a topological space in topology.
\chapter{Overview} \noindent This document is a user's guide for the Stan programming language. A separate document serves as a reference manual, defining the precise syntax and semantics of the Stan language. \section{Latest Updates} For links to the latest news, releases, source code, issue trackers, examples, documentation, discussion forums, and everything else Stan related, the best place to start is the Stan home page, at % \begin{quote} \url{http://mc-stan.org} \end{quote}
Mie Hama as Kissy Suzuki : An Ama diving girl who replaces Aki after her death .
{-# LANGUAGE Strict , OverloadedStrings#-} module Lib where import qualified Data.HashTable.IO as H import qualified Data.Text as T import qualified Data.Text.IO as TIO import Numeric.LinearAlgebra import qualified Data.Vector.Storable as VS import System.IO import Data.List import Control.Monad import System.Process import System.Random import Text.Read (readMaybe) someFunc :: IO () someFunc = putStrLn "someFunc" nanCheck :: Double -> Double nanCheck x = if show x == "NaN" || show x == "Infinity" then 0 else x st :: Double st = 10 delta :: Double delta = 1 chars :: T.Text chars = "qwertyuiopasdfghjklzxcvbnmęóąśłżźćń\t1234567890 " el :: Char -> T.Text -> Bool el = T.any . (==) preprocess :: T.Text -> [T.Text] preprocess = map (T.take 20) . T.words . T.map check . T.toLower where check x = if x `el` chars then x else ' ' type Probs = H.CuckooHashTable T.Text Double readWords :: Handle -> IO Probs readWords handl = do dict <- H.newSized 2500000 loop handl dict randomIO >>= H.insert dict "<bias>" return dict where loop :: Handle -> Probs -> IO () loop hdl dic = hIsEOF hdl >>= \x -> if x then return () else do line <- preprocess <$> TIO.hGetLine hdl let ins word = if (T.length word > 4) then H.lookup dic word >>= \mprob -> case mprob of Just _ -> do return () Nothing -> randomIO >>= H.insert dic word else return () case line of _:dat -> mapM_ ins dat _ -> hPutStrLn stderr "Can't parse line:" >> hPrint stderr line loop hdl dic saveProbs :: Probs -> IO () saveProbs dic = do H.mapM_ (\(word, v) -> putStrLn . unwords $ [T.unpack . T.strip $ word, show v]) dic readProbs :: String -> IO Probs readProbs filename = do dict <- H.newSized 2500000 withFile filename ReadMode $ readFromFile dict return dict where readFromFile :: Probs -> Handle -> IO () readFromFile dic hdl = hIsEOF hdl >>= \x -> if x then return () else do w <- hGetLine hdl case words w of [p, pr] -> H.insert dic (T.pack p) (read pr) _ -> return () readFromFile dic hdl linear :: Vector Double -> Vector Double -> Double linear = (<.>) rmse :: Vector Double -> Vector Double -> Double -> Double rmse weights inp ex = let prob = linear weights inp in (prob - ex)^2 gradRMSE :: Vector Double -> Vector Double -> Double -> Double -> Vector Double gradRMSE weights inp ex m = VS.map (\x -> x * (linear weights inp - ex)/m) inp counts :: Eq a => a -> [a] -> Double counts = ((fromIntegral. length).).filter.(==) evalLine :: Probs -> [T.Text] -> IO Double evalLine dict line = do let wek@(_:words) = "<bias>" : (filter ((>4). T.length) . nub $ line) inp = VS.cons 1 (foldr (\c acc -> VS.cons (log . (+1) . counts c $ line) acc) VS.empty words) weights <- foldM (\vec c -> do mval <- H.lookup dict c case mval of Just v -> return $ VS.cons v vec Nothing-> return $ VS.cons 0 vec) VS.empty wek return ((1900+).(100*).linear weights $ inp) updateWeights :: Probs -> [T.Text] -> Double -> Double -> Double -> IO Double updateWeights dict line ex step m = do let wek@(_:words) = "<bias>":(filter ((>4).T.length) . nub $ line) inp = VS.cons 1 (foldr (\c acc -> VS.cons (log . (+1) . counts c $ line) acc) VS.empty words) weights <- foldM (\vec c -> do mval <- H.lookup dict c case mval of Just v -> return $ VS.snoc vec v Nothing-> return $ VS.snoc vec 0) VS.empty wek let grad = gradRMSE weights inp ex m newWeights = weights - (VS.map (clip.nanCheck.(step *)) grad) newError = rmse newWeights inp ex foldM_ (\acc x -> do let newW = VS.head acc unless (newW == 0) $ H.insert dict x newW return $ VS.tail acc) newWeights words return $ nanCheck newError where clip x = max x 3 checkError :: Probs -> [T.Text] -> Double -> IO Double checkError dict line ex = do let wek@(_:words) = "<bias>":nub line inp = VS.cons 1 . foldr (\c acc -> VS.cons (log . (+1) . counts c $ line) acc) VS.empty $ words weights <- foldM (\vec c -> do mval <- H.lookup dict c case mval of Just v -> return $ VS.snoc vec v Nothing-> return $ VS.snoc vec 0) VS.empty wek return $ rmse weights inp ex train :: [(Double,[T.Text])] -> Probs -> Int -> IO () train corpus dict maxEp = do let len = length corpus testset = take (len`div`10) corpus trainset= drop (len`div`10) corpus trlen = length trainset testlen = length testset trainHelp :: Double -> Int -> Double -> IO () trainHelp err epoch step = do let trainOnLine (year, dat) = updateWeights dict dat year step (fromIntegral trlen) mapM_ trainOnLine trainset newErr <- sqrt <$> foldM (\er (ex, line) -> (+(er/(fromIntegral testlen))) <$> checkError dict line ex) 0 testset let lossRate = (err - newErr) newSteptmp = if lossRate > 0 then step*2 else step/100 newStep = if newSteptmp > 20 then 20 else newSteptmp hPutStrLn stderr $ "***********************" hPutStrLn stderr $ " Old Error: " ++ show err hPutStrLn stderr $ " New Error: " ++ show newErr hPutStrLn stderr $ " LossRate: " ++ show lossRate unless ((abs lossRate <= delta)||(epoch == maxEp)) $ trainHelp newErr (1+epoch) newStep startErr <- sqrt <$> foldM (\er (ex, line) -> (+(er/fromIntegral testlen)) <$> checkError dict line ex) 0 testset trainHelp startErr 1 st loadCorpus :: String -> IO [(Double,[T.Text])] loadCorpus filename = do withFile filename ReadMode (loop []) where loop corp hdl = hIsEOF hdl >>= \x -> if x then return corp else do line <- preprocess <$> TIO.hGetLine hdl newEntry <- case line of cl:dat -> case readMaybe . T.unpack $ cl of Just year -> return $ Just ((year-1900)/100, dat) Nothing -> hPutStrLn stderr "Can't read as a number:" >> hPrint stderr cl >> return Nothing _ -> hPutStrLn stderr "Can't parse line:" >> hPrint stderr line >> return Nothing case newEntry of Nothing -> loop corp hdl Just x -> loop (x:corp) hdl eval :: Handle -> Probs -> IO () eval hdl dict = hIsEOF hdl >>= \x -> if x then return () else do line <- preprocess <$> TIO.hGetLine hdl pred <- evalLine dict line print pred eval hdl dict
[STATEMENT] lemma remdups_append: "remdups (xs @ ys) = remdups (filter (\<lambda>x. x \<notin> set ys) xs) @ remdups ys" [PROOF STATE] proof (prove) goal (1 subgoal): 1. remdups (xs @ ys) = remdups (filter (\<lambda>x. x \<notin> set ys) xs) @ remdups ys [PROOF STEP] by (induct xs) auto
[STATEMENT] lemma Match: fixes P :: pi and b :: name and x :: name and a :: name and P' :: pi and \<alpha> :: freeRes shows "P \<Longrightarrow>b<\<nu>x> \<prec> P' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P'" and "P \<Longrightarrow>\<alpha> \<prec> P' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P'" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (P \<Longrightarrow>b<\<nu>x> \<prec> P' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P') &&& (P \<Longrightarrow>\<alpha> \<prec> P' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P') [PROOF STEP] proof - [PROOF STATE] proof (state) goal (2 subgoals): 1. P \<Longrightarrow>b<\<nu>x> \<prec> P' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' 2. P \<Longrightarrow>\<alpha> \<prec> P' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' [PROOF STEP] assume "P \<Longrightarrow> b<\<nu>x> \<prec> P'" [PROOF STATE] proof (state) this: P \<Longrightarrow>b<\<nu>x> \<prec> P' goal (2 subgoals): 1. P \<Longrightarrow>b<\<nu>x> \<prec> P' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' 2. P \<Longrightarrow>\<alpha> \<prec> P' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' [PROOF STEP] then [PROOF STATE] proof (chain) picking this: P \<Longrightarrow>b<\<nu>x> \<prec> P' [PROOF STEP] obtain P'' P''' where PChain: "P \<Longrightarrow>\<^sub>\<tau> P'''" and P'''Trans: "P''' \<longmapsto>b<\<nu>x> \<prec> P''" and P''Chain: "P'' \<Longrightarrow>\<^sub>\<tau> P'" [PROOF STATE] proof (prove) using this: P \<Longrightarrow>b<\<nu>x> \<prec> P' goal (1 subgoal): 1. (\<And>P''' P''. \<lbrakk>P \<Longrightarrow>\<^sub>\<tau> P'''; P''' \<longmapsto> b<\<nu>x> \<prec> P''; P'' \<Longrightarrow>\<^sub>\<tau> P'\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by(force dest: transitionE) [PROOF STATE] proof (state) this: P \<Longrightarrow>\<^sub>\<tau> P''' P''' \<longmapsto> b<\<nu>x> \<prec> P'' P'' \<Longrightarrow>\<^sub>\<tau> P' goal (2 subgoals): 1. P \<Longrightarrow>b<\<nu>x> \<prec> P' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' 2. P \<Longrightarrow>\<alpha> \<prec> P' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' [PROOF STEP] show "[a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P'" [PROOF STATE] proof (prove) goal (1 subgoal): 1. [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' [PROOF STEP] proof(cases "P = P'''") [PROOF STATE] proof (state) goal (2 subgoals): 1. P = P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' 2. P \<noteq> P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' [PROOF STEP] case True [PROOF STATE] proof (state) this: P = P''' goal (2 subgoals): 1. P = P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' 2. P \<noteq> P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' [PROOF STEP] have "[a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> [a\<frown>a]P" [PROOF STATE] proof (prove) goal (1 subgoal): 1. [a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> [a\<frown>a]P [PROOF STEP] by simp [PROOF STATE] proof (state) this: [a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> [a\<frown>a]P goal (2 subgoals): 1. P = P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' 2. P \<noteq> P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' [PROOF STEP] moreover [PROOF STATE] proof (state) this: [a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> [a\<frown>a]P goal (2 subgoals): 1. P = P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' 2. P \<noteq> P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' [PROOF STEP] from \<open>P = P'''\<close> P'''Trans [PROOF STATE] proof (chain) picking this: P = P''' P''' \<longmapsto> b<\<nu>x> \<prec> P'' [PROOF STEP] have "[a\<frown>a]P \<longmapsto> b<\<nu>x> \<prec> P''" [PROOF STATE] proof (prove) using this: P = P''' P''' \<longmapsto> b<\<nu>x> \<prec> P'' goal (1 subgoal): 1. [a\<frown>a]P \<longmapsto> b<\<nu>x> \<prec> P'' [PROOF STEP] by(rule_tac Early_Semantics.Match) auto [PROOF STATE] proof (state) this: [a\<frown>a]P \<longmapsto> b<\<nu>x> \<prec> P'' goal (2 subgoals): 1. P = P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' 2. P \<noteq> P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: [a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> [a\<frown>a]P [a\<frown>a]P \<longmapsto> b<\<nu>x> \<prec> P'' [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: [a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> [a\<frown>a]P [a\<frown>a]P \<longmapsto> b<\<nu>x> \<prec> P'' goal (1 subgoal): 1. [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' [PROOF STEP] using P''Chain [PROOF STATE] proof (prove) using this: [a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> [a\<frown>a]P [a\<frown>a]P \<longmapsto> b<\<nu>x> \<prec> P'' P'' \<Longrightarrow>\<^sub>\<tau> P' goal (1 subgoal): 1. [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' [PROOF STEP] by(rule transitionI) [PROOF STATE] proof (state) this: [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' goal (1 subgoal): 1. P \<noteq> P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. P \<noteq> P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' [PROOF STEP] case False [PROOF STATE] proof (state) this: P \<noteq> P''' goal (1 subgoal): 1. P \<noteq> P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' [PROOF STEP] from PChain \<open>P \<noteq> P'''\<close> [PROOF STATE] proof (chain) picking this: P \<Longrightarrow>\<^sub>\<tau> P''' P \<noteq> P''' [PROOF STEP] have "[a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> P'''" [PROOF STATE] proof (prove) using this: P \<Longrightarrow>\<^sub>\<tau> P''' P \<noteq> P''' goal (1 subgoal): 1. [a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> P''' [PROOF STEP] by(rule matchChain) [PROOF STATE] proof (state) this: [a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> P''' goal (1 subgoal): 1. P \<noteq> P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: [a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> P''' goal (1 subgoal): 1. [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' [PROOF STEP] using P'''Trans P''Chain [PROOF STATE] proof (prove) using this: [a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> P''' P''' \<longmapsto> b<\<nu>x> \<prec> P'' P'' \<Longrightarrow>\<^sub>\<tau> P' goal (1 subgoal): 1. [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' [PROOF STEP] by(rule transitionI) [PROOF STATE] proof (state) this: [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: [a\<frown>a]P \<Longrightarrow>b<\<nu>x> \<prec> P' goal (1 subgoal): 1. P \<Longrightarrow>\<alpha> \<prec> P' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. P \<Longrightarrow>\<alpha> \<prec> P' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' [PROOF STEP] assume "P \<Longrightarrow>\<alpha> \<prec> P'" [PROOF STATE] proof (state) this: P \<Longrightarrow>\<alpha> \<prec> P' goal (1 subgoal): 1. P \<Longrightarrow>\<alpha> \<prec> P' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' [PROOF STEP] then [PROOF STATE] proof (chain) picking this: P \<Longrightarrow>\<alpha> \<prec> P' [PROOF STEP] obtain P'' P''' where PChain: "P \<Longrightarrow>\<^sub>\<tau> P'''" and P'''Trans: "P''' \<longmapsto>\<alpha> \<prec> P''" and P''Chain: "P'' \<Longrightarrow>\<^sub>\<tau> P'" [PROOF STATE] proof (prove) using this: P \<Longrightarrow>\<alpha> \<prec> P' goal (1 subgoal): 1. (\<And>P''' P''. \<lbrakk>P \<Longrightarrow>\<^sub>\<tau> P'''; P''' \<longmapsto> \<alpha> \<prec> P''; P'' \<Longrightarrow>\<^sub>\<tau> P'\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by(force dest: transitionE) [PROOF STATE] proof (state) this: P \<Longrightarrow>\<^sub>\<tau> P''' P''' \<longmapsto> \<alpha> \<prec> P'' P'' \<Longrightarrow>\<^sub>\<tau> P' goal (1 subgoal): 1. P \<Longrightarrow>\<alpha> \<prec> P' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' [PROOF STEP] show "[a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P'" [PROOF STATE] proof (prove) goal (1 subgoal): 1. [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' [PROOF STEP] proof(cases "P = P'''") [PROOF STATE] proof (state) goal (2 subgoals): 1. P = P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' 2. P \<noteq> P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' [PROOF STEP] case True [PROOF STATE] proof (state) this: P = P''' goal (2 subgoals): 1. P = P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' 2. P \<noteq> P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' [PROOF STEP] have "[a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> [a\<frown>a]P" [PROOF STATE] proof (prove) goal (1 subgoal): 1. [a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> [a\<frown>a]P [PROOF STEP] by simp [PROOF STATE] proof (state) this: [a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> [a\<frown>a]P goal (2 subgoals): 1. P = P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' 2. P \<noteq> P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' [PROOF STEP] moreover [PROOF STATE] proof (state) this: [a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> [a\<frown>a]P goal (2 subgoals): 1. P = P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' 2. P \<noteq> P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' [PROOF STEP] from \<open>P = P'''\<close> P'''Trans [PROOF STATE] proof (chain) picking this: P = P''' P''' \<longmapsto> \<alpha> \<prec> P'' [PROOF STEP] have "[a\<frown>a]P \<longmapsto>\<alpha> \<prec> P''" [PROOF STATE] proof (prove) using this: P = P''' P''' \<longmapsto> \<alpha> \<prec> P'' goal (1 subgoal): 1. [a\<frown>a]P \<longmapsto> \<alpha> \<prec> P'' [PROOF STEP] by(rule_tac Early_Semantics.Match) auto [PROOF STATE] proof (state) this: [a\<frown>a]P \<longmapsto> \<alpha> \<prec> P'' goal (2 subgoals): 1. P = P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' 2. P \<noteq> P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: [a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> [a\<frown>a]P [a\<frown>a]P \<longmapsto> \<alpha> \<prec> P'' [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: [a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> [a\<frown>a]P [a\<frown>a]P \<longmapsto> \<alpha> \<prec> P'' goal (1 subgoal): 1. [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' [PROOF STEP] using P''Chain [PROOF STATE] proof (prove) using this: [a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> [a\<frown>a]P [a\<frown>a]P \<longmapsto> \<alpha> \<prec> P'' P'' \<Longrightarrow>\<^sub>\<tau> P' goal (1 subgoal): 1. [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' [PROOF STEP] by(rule transitionI) [PROOF STATE] proof (state) this: [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' goal (1 subgoal): 1. P \<noteq> P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. P \<noteq> P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' [PROOF STEP] case False [PROOF STATE] proof (state) this: P \<noteq> P''' goal (1 subgoal): 1. P \<noteq> P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' [PROOF STEP] from PChain \<open>P \<noteq> P'''\<close> [PROOF STATE] proof (chain) picking this: P \<Longrightarrow>\<^sub>\<tau> P''' P \<noteq> P''' [PROOF STEP] have "[a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> P'''" [PROOF STATE] proof (prove) using this: P \<Longrightarrow>\<^sub>\<tau> P''' P \<noteq> P''' goal (1 subgoal): 1. [a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> P''' [PROOF STEP] by(rule matchChain) [PROOF STATE] proof (state) this: [a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> P''' goal (1 subgoal): 1. P \<noteq> P''' \<Longrightarrow> [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: [a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> P''' goal (1 subgoal): 1. [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' [PROOF STEP] using P'''Trans P''Chain [PROOF STATE] proof (prove) using this: [a\<frown>a]P \<Longrightarrow>\<^sub>\<tau> P''' P''' \<longmapsto> \<alpha> \<prec> P'' P'' \<Longrightarrow>\<^sub>\<tau> P' goal (1 subgoal): 1. [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' [PROOF STEP] by(rule transitionI) [PROOF STATE] proof (state) this: [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: [a\<frown>a]P \<Longrightarrow>\<alpha> \<prec> P' goal: No subgoals! [PROOF STEP] qed
// Ref: // G.P. Lepage, LQCD for Novices #include "su3_utils.c" #include <stdlib.h> #include <stdio.h> #include <gsl/gsl_fit.h> // globals const gsl_rng_type *T; gsl_rng *r; // random generator su3_matrix links[4*N*N*N*N]; // link variables su3_matrix rands[50]; // random unitary matrices FILE *output; // prototypes void setup(); void cleanup(); int main (int argc, char** argv) { setup(); int O[4]={0,0,0,0}; for(int n=0;n<Ntherm;n++) { //fprintf(output, "%f \n",plaquette(links,0,1,O)); hb_update(links,r,rands); //thermalize } // Confinement phase should have small Polyakov VEV if(confined){ while(polyakov_mean(links) > pol_thres){ hb_update(links,r,rands); //thermalize } } printf("Thermalized! \n"); for(int n=0;n<Ncf;n++){ // Decorrelate for(int k=0;k<Ncor;k++){ hb_update(links,r,rands); } if(n%5==0){printf("%d \n",n);} // Measurement //fprintf(output, "%f %f \n", wloop_mean(1,1,links),wloop_mean(1,2,links)); //fprintf(output, "%f %f %f %f %f %f %f %f\n",twloop2_mean(1,links),twloop2_mean(2,links),twloop2_mean(3,links),twloop2_mean(4,links),twloop2_mean(5,links),twloop2_mean(6,links),twloop2_mean(7,links),twloop2_mean(8,links)); //fprintf(output, "%f %f %f %f %f %f %f %f\n",plaq_corr(1,links),plaq_corr(2,links),plaq_corr(3,links),plaq_corr(4,links),plaq_corr(5,links),plaq_corr(6,links),plaq_corr(7,links),plaq_corr(8,links)); //printf("%f \n",polyakov_mean(links)); printf( "%f \n", plaq_mean_s(0,links)); printf( "%f %f \n", wloop_mean(1,1,links),wloop_mean(1,2,links) ); } printf("acc=%f\n", (double)acc/tot); cleanup(); return 0; } void setup (){ acc=0; tot=0; // ready random num generator gsl_rng_env_setup (); T = gsl_rng_mt19937; r = gsl_rng_alloc (T); // fill in table of rand matrices for(int i=0;i<25;i++){ rands[2*i]=su3_rand(r); rands[2*i+1]=su3_inv(rands[2*i]); } //init links to identities for(int i=0;i<4*N*N*N*N;i++){ links[i]=su3_unit(); } output = fopen("out.txt", "w+"); } void cleanup (){ gsl_rng_free(r); fclose(output); }
(* Title: HOL/Auth/n_germanSimp_lemma_inv__29_on_rules.thy Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences *) header{*The n_germanSimp Protocol Case Study*} theory n_germanSimp_lemma_inv__29_on_rules imports n_germanSimp_lemma_on_inv__29 begin section{*All lemmas on causal relation between inv__29*} lemma lemma_inv__29_on_rules: assumes b1: "r \<in> rules N" and b2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__29 p__Inv4)" shows "invHoldForRule s f r (invariants N)" proof - have c1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__0 N i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__1 N i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInvAck i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendGntS i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendGntE N i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvGntS i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" apply (cut_tac b1, auto) done moreover { assume d1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_StoreVsinv__29) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvReqSVsinv__29) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__0 N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvReqE__part__0Vsinv__29) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__1 N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvReqE__part__1Vsinv__29) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInv__part__0Vsinv__29) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInv__part__1Vsinv__29) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInvAckVsinv__29) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvInvAckVsinv__29) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendGntSVsinv__29) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendGntEVsinv__29) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvGntSVsinv__29) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvGntEVsinv__29) done } ultimately show "invHoldForRule s f r (invariants N)" by satx qed end
--/** -- * <copyright> -- * -- * Copyright (c) 2008 Eclipse.org and others. -- * All rights reserved. This program and the accompanying materials -- * are made available under the terms of the Eclipse Public License v2.0 -- * which accompanies this distribution, and is available at -- * http://www.eclipse.org/legal/epl-v20.html -- * -- * Contributors: -- * E.D. Willink - Initial API and implementation -- * Adolfo Sanchez-Barbudo Herrera (Open Canarias): -- * - 242153: LPG v 2.0.17 adoption. -- * - 299396: Introducing new LPG templates. -- * - 300534: Removing the use of deprecated macros. -- * -- * </copyright> -- */ -- -- Additional ERROR_TOKEN rules for The OCL Parser -- %Import OCLParser.g %End %Import EssentialOCLErrors.gi %End %Rules ----------------------------------------------------------------------- -- Calls ----------------------------------------------------------------------- OclMessageExpCS ::= primaryExpCS '^^' simpleNameCS ERROR_TOKEN /.$NewCase./ OclMessageExpCS ::= primaryExpCS '^' simpleNameCS ERROR_TOKEN /.$BeginCode reportErrorTokenMessage(getRhsTokenIndex(2), OCLParserErrors.MISSING_MESSAGE_ARGUMENTS); OCLExpressionCS target = (OCLExpressionCS)getRhsSym(1); MessageExpCS result = createMessageExpCS( target, getRhsIToken(2).getKind() == $sym_type.TK_CARET, (SimpleNameCS)getRhsSym(3), new BasicEList<OCLMessageArgCS>() ); setOffsets(result, target, getRhsIToken(4)); setResult(result); $EndCode ./ ----------------------------------------------------------------------- -- Contexts ----------------------------------------------------------------------- classifierContextDeclCS ::= context pathNameCS ERROR_TOKEN /.$BeginCode reportErrorTokenMessage(getRhsTokenIndex(3), OCLParserErrors.MISSING_INV_OR_DEF); ClassifierContextDeclCS result = createClassifierContextDeclCS( null, (PathNameCS)getRhsSym(2), new BasicEList<InvOrDefCS>() ); setOffsets(result, getRhsIToken(1), getRhsIToken(3)); setResult(result); $EndCode ./ defExpressionCS ::= typedUninitializedVariableCS ERROR_TOKEN /.$BeginCode reportErrorTokenMessage(getRhsTokenIndex(2), OCLParserErrors.MISSING_EQUALS); VariableCS variableCS = (VariableCS)getRhsSym(1); DefExpressionCS result = createDefExpressionCS( variableCS, null, null ); setOffsets(result, variableCS, getRhsIToken(2)); setResult(result); $EndCode ./ defExpressionCS ::= simpleNameCS ERROR_Colon /.$BeginCode SimpleNameCS name = (SimpleNameCS)getRhsSym(1); VariableCS variableCS = createVariableCS(name, null, null); setOffsets(variableCS, name, getRhsIToken(2)); DefExpressionCS result = createDefExpressionCS( variableCS, null, null ); setOffsets(result, variableCS, getRhsIToken(2)); setResult(result); $EndCode ./ invOrDefCS ::= inv unreservedSimpleNameCS ERROR_Colon /.$BeginCode InvCS result = createInvCS( (SimpleNameCS)getRhsSym(2), null ); setOffsets(result, getRhsIToken(1), getRhsIToken(3)); setResult(result); $EndCode ./ invOrDefCS ::= def unreservedSimpleNameCS ERROR_Colon /.$BeginCode DefCS result = createDefCS( false, (SimpleNameCS)getRhsSym(2), null ); setOffsets(result, getRhsIToken(1), getRhsIToken(3)); setResult(result); $EndCode ./ invOrDefCS ::= static def unreservedSimpleNameCS ERROR_Colon /.$BeginCode DefCS result = createDefCS( true, (SimpleNameCS)getRhsSym(3), null ); setOffsets(result, getRhsIToken(1), getRhsIToken(4)); setResult(result); $EndCode ./ operationCS1 ::= simpleNameCS '(' parametersCSopt ')' ERROR_Colon /.$BeginCode OperationCS result = createOperationCS( getRhsIToken(1), new BasicEList<VariableCS>(), null ); setOffsets(result, getRhsIToken(1), getRhsIToken(5)); setResult(result); $EndCode ./ operationCS1 ::= simpleNameCS ERROR_TOKEN /.$BeginCode reportErrorTokenMessage(getRhsTokenIndex(2), OCLParserErrors.MISSING_LPAREN); OperationCS result = createOperationCS( getRhsIToken(1), new BasicEList<VariableCS>(), null ); setOffsets(result, getRhsIToken(1), getRhsIToken(2)); setResult(result); $EndCode ./ operationCS1 ::= ERROR_TOKEN /.$BeginCode reportErrorTokenMessage(getRhsTokenIndex(1), OCLParserErrors.MISSING_IDENTIFIER); OperationCS result = createOperationCS( getRhsIToken(1), new BasicEList<VariableCS>(), null ); setOffsets(result, getRhsIToken(1)); setResult(result); $EndCode ./ operationCS2 ::= pathNameCS '::' unreservedSimpleNameCS '(' parametersCSopt ')' ERROR_Colon /.$BeginCode PathNameCS pathNameCS = (PathNameCS)getRhsSym(1); SimpleNameCS simpleNameCS = (SimpleNameCS)getRhsSym(3); OperationCS result = createOperationCS( pathNameCS, simpleNameCS, (EList<VariableCS>)getRhsSym(5), null ); setOffsets(result, pathNameCS, getRhsIToken(7)); setResult(result); $EndCode ./ operationCS2 ::= pathNameCS '::' ERROR_SimpleNameCS /.$BeginCode PathNameCS pathNameCS = (PathNameCS)getRhsSym(1); SimpleNameCS simpleNameCS = (SimpleNameCS)getRhsSym(3); OperationCS result = createOperationCS( pathNameCS, simpleNameCS, new BasicEList<VariableCS>(), null ); setOffsets(result, pathNameCS, simpleNameCS); setResult(result); $EndCode ./ prePostOrBodyDeclCS ::= pre unreservedSimpleNameCS ERROR_Colon /.$BeginCode PrePostOrBodyDeclCS result = createPrePostOrBodyDeclCS( PrePostOrBodyEnum.PRE_LITERAL, (SimpleNameCS)getRhsSym(2), createInvalidLiteralExpCS(getRhsTokenText(3)) ); setOffsets(result, getRhsIToken(1), getRhsIToken(3)); setResult(result); $EndCode ./ prePostOrBodyDeclCS ::= post unreservedSimpleNameCS ERROR_Colon /.$BeginCode PrePostOrBodyDeclCS result = createPrePostOrBodyDeclCS( PrePostOrBodyEnum.POST_LITERAL, (SimpleNameCS)getRhsSym(2), createInvalidLiteralExpCS(getRhsTokenText(3)) ); setOffsets(result, getRhsIToken(1), getRhsIToken(3)); setResult(result); $EndCode ./ prePostOrBodyDeclCS ::= body unreservedSimpleNameCS ERROR_Colon /.$BeginCode PrePostOrBodyDeclCS result = createPrePostOrBodyDeclCS( PrePostOrBodyEnum.BODY_LITERAL, (SimpleNameCS)getRhsSym(2), createInvalidLiteralExpCS(getRhsTokenText(3)) ); setOffsets(result, getRhsIToken(1), getRhsIToken(3)); setResult(result); $EndCode ./ initOrDerValueCS ::= init ERROR_Colon /.$BeginCode InitValueCS result = createInitValueCS(null); setOffsets(result, getRhsIToken(2), getRhsIToken(3)); setResult(result); $EndCode ./ initOrDerValueCS ::= derive ERROR_Colon /.$BeginCode DerValueCS result = createDerValueCS(null); setOffsets(result, getRhsIToken(2), getRhsIToken(3)); setResult(result); $EndCode ./ packageDeclarationCS_A ::= package pathNameCS contextDeclsCSopt ERROR_Empty endpackage /.$BeginCode PackageDeclarationCS result = createPackageDeclarationCS( (PathNameCS)getRhsSym(2), (EList<ContextDeclCS>)getRhsSym(3) ); setOffsets(result, getRhsIToken(1), getRhsIToken(5)); setResult(result); $EndCode ./ packageDeclarationCS_A ::= package pathNameCS contextDeclsCSopt ERROR_TOKEN /.$BeginCode reportErrorTokenMessage(getRhsTokenIndex(4), OCLParserErrors.MISSING_ENDPACKAGE); PackageDeclarationCS result = createPackageDeclarationCS( (PathNameCS)getRhsSym(2), (EList<ContextDeclCS>)getRhsSym(3) ); setOffsets(result, getRhsIToken(1), getRhsIToken(4)); setResult(result); $EndCode ./ %End
State Before: l : Type ?u.131023 m : Type u_1 n : Type u_2 o : Type u_4 p : Type ?u.131035 q : Type ?u.131038 m' : o → Type ?u.131043 n' : o → Type ?u.131048 p' : o → Type ?u.131053 R : Type ?u.131056 S : Type ?u.131059 α : Type u_3 β : Type ?u.131065 inst✝² : DecidableEq o inst✝¹ : Zero α inst✝ : Zero β M : o → Matrix m n α ⊢ (blockDiagonal M)ᵀ = blockDiagonal fun k => (M k)ᵀ State After: case a.h l : Type ?u.131023 m : Type u_1 n : Type u_2 o : Type u_4 p : Type ?u.131035 q : Type ?u.131038 m' : o → Type ?u.131043 n' : o → Type ?u.131048 p' : o → Type ?u.131053 R : Type ?u.131056 S : Type ?u.131059 α : Type u_3 β : Type ?u.131065 inst✝² : DecidableEq o inst✝¹ : Zero α inst✝ : Zero β M : o → Matrix m n α i✝ : n × o x✝ : m × o ⊢ (blockDiagonal M)ᵀ i✝ x✝ = blockDiagonal (fun k => (M k)ᵀ) i✝ x✝ Tactic: ext State Before: case a.h l : Type ?u.131023 m : Type u_1 n : Type u_2 o : Type u_4 p : Type ?u.131035 q : Type ?u.131038 m' : o → Type ?u.131043 n' : o → Type ?u.131048 p' : o → Type ?u.131053 R : Type ?u.131056 S : Type ?u.131059 α : Type u_3 β : Type ?u.131065 inst✝² : DecidableEq o inst✝¹ : Zero α inst✝ : Zero β M : o → Matrix m n α i✝ : n × o x✝ : m × o ⊢ (blockDiagonal M)ᵀ i✝ x✝ = blockDiagonal (fun k => (M k)ᵀ) i✝ x✝ State After: case a.h l : Type ?u.131023 m : Type u_1 n : Type u_2 o : Type u_4 p : Type ?u.131035 q : Type ?u.131038 m' : o → Type ?u.131043 n' : o → Type ?u.131048 p' : o → Type ?u.131053 R : Type ?u.131056 S : Type ?u.131059 α : Type u_3 β : Type ?u.131065 inst✝² : DecidableEq o inst✝¹ : Zero α inst✝ : Zero β M : o → Matrix m n α i✝ : n × o x✝ : m × o ⊢ (if i✝.snd = x✝.snd then M i✝.snd x✝.fst i✝.fst else 0) = if i✝.snd = x✝.snd then M x✝.snd x✝.fst i✝.fst else 0 Tactic: simp only [transpose_apply, blockDiagonal_apply, eq_comm] State Before: case a.h l : Type ?u.131023 m : Type u_1 n : Type u_2 o : Type u_4 p : Type ?u.131035 q : Type ?u.131038 m' : o → Type ?u.131043 n' : o → Type ?u.131048 p' : o → Type ?u.131053 R : Type ?u.131056 S : Type ?u.131059 α : Type u_3 β : Type ?u.131065 inst✝² : DecidableEq o inst✝¹ : Zero α inst✝ : Zero β M : o → Matrix m n α i✝ : n × o x✝ : m × o ⊢ (if i✝.snd = x✝.snd then M i✝.snd x✝.fst i✝.fst else 0) = if i✝.snd = x✝.snd then M x✝.snd x✝.fst i✝.fst else 0 State After: case a.h.inl l : Type ?u.131023 m : Type u_1 n : Type u_2 o : Type u_4 p : Type ?u.131035 q : Type ?u.131038 m' : o → Type ?u.131043 n' : o → Type ?u.131048 p' : o → Type ?u.131053 R : Type ?u.131056 S : Type ?u.131059 α : Type u_3 β : Type ?u.131065 inst✝² : DecidableEq o inst✝¹ : Zero α inst✝ : Zero β M : o → Matrix m n α i✝ : n × o x✝ : m × o h : i✝.snd = x✝.snd ⊢ M i✝.snd x✝.fst i✝.fst = M x✝.snd x✝.fst i✝.fst case a.h.inr l : Type ?u.131023 m : Type u_1 n : Type u_2 o : Type u_4 p : Type ?u.131035 q : Type ?u.131038 m' : o → Type ?u.131043 n' : o → Type ?u.131048 p' : o → Type ?u.131053 R : Type ?u.131056 S : Type ?u.131059 α : Type u_3 β : Type ?u.131065 inst✝² : DecidableEq o inst✝¹ : Zero α inst✝ : Zero β M : o → Matrix m n α i✝ : n × o x✝ : m × o h : ¬i✝.snd = x✝.snd ⊢ 0 = 0 Tactic: split_ifs with h State Before: case a.h.inl l : Type ?u.131023 m : Type u_1 n : Type u_2 o : Type u_4 p : Type ?u.131035 q : Type ?u.131038 m' : o → Type ?u.131043 n' : o → Type ?u.131048 p' : o → Type ?u.131053 R : Type ?u.131056 S : Type ?u.131059 α : Type u_3 β : Type ?u.131065 inst✝² : DecidableEq o inst✝¹ : Zero α inst✝ : Zero β M : o → Matrix m n α i✝ : n × o x✝ : m × o h : i✝.snd = x✝.snd ⊢ M i✝.snd x✝.fst i✝.fst = M x✝.snd x✝.fst i✝.fst State After: no goals Tactic: rw [h] State Before: case a.h.inr l : Type ?u.131023 m : Type u_1 n : Type u_2 o : Type u_4 p : Type ?u.131035 q : Type ?u.131038 m' : o → Type ?u.131043 n' : o → Type ?u.131048 p' : o → Type ?u.131053 R : Type ?u.131056 S : Type ?u.131059 α : Type u_3 β : Type ?u.131065 inst✝² : DecidableEq o inst✝¹ : Zero α inst✝ : Zero β M : o → Matrix m n α i✝ : n × o x✝ : m × o h : ¬i✝.snd = x✝.snd ⊢ 0 = 0 State After: no goals Tactic: rfl
[STATEMENT] lemma from_to_dtree_eq_orig: "from_dtree (to_dtree) = T" [PROOF STATE] proof (prove) goal (1 subgoal): 1. local.from_dtree to_dtree = T [PROOF STEP] using to_dtree_dhead_eq_head to_dtree_dtail_eq_tail darcs_eq_arcs dverts_eq_verts [PROOF STATE] proof (prove) using this: dhead to_dtree (head T) = head T dtail to_dtree (tail T) = tail T darcs to_dtree = arcs T dverts to_dtree = verts T goal (1 subgoal): 1. local.from_dtree to_dtree = T [PROOF STEP] by simp
import data.real.basic variables (f g : ℝ → ℝ) #check mul_le_mul_of_nonneg_left -- BEGIN example {c : ℝ} (mf : monotone f) (nnc : 0 ≤ c) : monotone (λ x, c * f x) := begin intros a b aleb, dsimp, have : f a ≤ f b, from mf aleb, exact mul_le_mul_of_nonneg_left this nnc, end example (mf : monotone f) (mg : monotone g) : monotone (λ x, f x + g x) := begin intros a b aleb, apply add_le_add, apply mf aleb, apply mg aleb, end example (mf : monotone f) (mg : monotone g) : monotone (λ x, f (g x)) := begin intros a b aleb, dsimp, apply mf, apply mg, apply aleb, end -- END
{-# OPTIONS --sized-types #-} module SizedTypesVarSwap where postulate Size : Set _^ : Size -> Size ∞ : Size {-# BUILTIN SIZE Size #-} {-# BUILTIN SIZESUC _^ #-} {-# BUILTIN SIZEINF ∞ #-} data Nat : {size : Size} -> Set where zero : {size : Size} -> Nat {size ^} suc : {size : Size} -> Nat {size} -> Nat {size ^} bad : {i j : Size} -> Nat {i} -> Nat {j} -> Nat {∞} bad (suc x) y = bad (suc y) x bad zero y = y
Formal statement is: lemma filtermap_at_shift: "filtermap (\<lambda>x. x - d) (at a) = at (a - d)" for a d :: "'a::real_normed_vector" Informal statement is: The filter of neighbourhoods of $a$ is mapped to the filter of neighbourhoods of $a - d$ by the map $x \mapsto x - d$.
% designsim_gui_script % Last modified 3/21/01 by Tor Wager fix HRF bug / various name = input('Enter output file name: '); % sets defaults, reads GUI values from optimizeGUI, and runs simulation disp('Designsim_gui_script') disp('===============================') disp(' ...Setting up variables from GUI.') % returns vector of t values as t in workspace. if ~exist('M') | ~isstruct(M),disp('No GA results (M struct) detected - using only random designs.'),end clear SIM clear H; format compact % defaults noise_var = 0.3; beta = [.5 .5 0 0;1 1 0 0]; % 20 c = [1 1 -1 -1]; % 13 niterations = 500; conditions = [1 2 3 4]; ISI = 1.2; restevery = 9; % 26 restlength = 2; % 25 HPlength = 60; % 23 xc = [1 0]; % 24 % read values from GUI for GA H = findobj('Tag', 'E1'); conditions = str2num(get(H(1), 'String')); H = findobj('Tag', 'E4'); ISI = str2num(get(H(1), 'String')); H = findobj('Tag', 'E12'); noise_var = str2num(get(H(1), 'String')); H = findobj('Tag', 'E13'); c = str2num(get(H(1), 'String')); H = findobj('Tag', 'E14'); niterations = str2num(get(H(1), 'String')); H = findobj('Tag', 'E15'); respMean = str2num(get(H(1), 'String')); H = findobj('Tag', 'E16'); respSD = str2num(get(H(1), 'String')); H = findobj('Tag', 'C1'); addResponseVariability = get(H(1), 'Value'); % additional values required for random sim. H = findobj('Tag', 'E2'); freqConditions = str2num(get(H(1), 'String')); H = findobj('Tag', 'E3'); scanLength = str2num(get(H(1), 'String')); H = findobj('Tag', 'E5'); TR = str2num(get(H(1), 'String')); H = findobj('Tag', 'E6'); cbalColinPowerWeights = str2num(get(H(1), 'String')); H = findobj('Tag', 'E7'); numGenerations = str2num(get(H(1), 'String')); H = findobj('Tag', 'E8'); sizeGenerations = str2num(get(H(1), 'String')); H = findobj('Tag', 'E9'); lowerLimit = str2num(get(H(1), 'String')); H = findobj('Tag', 'E10'); maxOrder = str2num(get(H(1), 'String')); H = findobj('Tag', 'E11'); plotFlag = str2num(get(H(1), 'String')); H = findobj('Tag', 'E20'); beta = str2num(get(H(1), 'String')); H = findobj('Tag', 'E23'); HPlength = str2num(get(H(1), 'String')); H = findobj('Tag', 'E24'); eval(['load ' get(H(1), 'String')]); H = findobj('Tag', 'E25'); restlength = str2num(get(H(1), 'String')); H = findobj('Tag', 'E26'); restevery = str2num(get(H(1), 'String')); HRF = spm_hrf(.1); HRF = HRF/ max(HRF); for myISI = 1:16 ISI = myISI; disp(['Starting simulation with ISI ' num2str(myISI)]); SIM.beta = beta; SIM.contrasts = c; SIM.noise_var = noise_var; SIM.xc = xc; SIM.ISI = ISI; SIM.HPlength = HPlength; SIM.restevery = restevery; SIM.restlen = restlength; SIM.niterations = niterations; SIM.noise_var = noise_var; SIM.freqConditions = freqConditions; disp(' ...Generating design list.') % for building RANDOM designs to test against GA design fitnessMatrix = zeros(4,sizeGenerations); numStim = ceil(scanLength / (ISI)); numRestStim = (ceil(numStim/restevery) - 1) * restlength; numStimEachCond = ceil((numStim-numRestStim) * freqConditions); % row vector of stim in each cond numsamps = ceil(numStim*ISI/TR); SIM.numsamps = numsamps; if exist('M') & isstruct(M), SIM.numsamps = size(M.modelatTR,1);,end SIM.numStimEachCond = numStimEachCond; unsortedList = []; for i = 1:size(conditions,2) % unsorted list of all stims in proper frequencies startIndex = size(unsortedList,1)+1; unsortedList(startIndex:(startIndex + numStimEachCond(i)-1),1) = conditions(i); end if addResponseVariability == 1 % THIS ISN'T FINISHED, AND I'M NOT SURE I SEE THE POINT, REALLY. else disp([' ...loading smoothing matrix with hrf LP and HP filter length of ' num2str(HPlength)]) [hpS] = use_spm_filter(TR,SIM.numsamps,'none','specify',HPlength); [fullS] = use_spm_filter(TR,SIM.numsamps,'hrf','specify',HPlength); if exist('M') & isstruct(M), stimList = M.stimlist(1:numsamps+1,1); % cut off to make more efficient stimList = sampleInSeconds(stimList,ISI,.1); dmodel = getPredictors(stimList, HRF); dmodel = resample(dmodel,1,TR*10); % dmodel = dmodel / max(max(dmodel)); % scale so that max = 1; if size(dmodel,1) > SIM.numsamps dmodel = dmodel(1:SIM.numsamps,:); elseif size(dmodel,1) < SIM.numsamps warning('stimlist for GA is too short for this ISI! Results may not be accurate for this ISI!') dmodel = [dmodel; zeros(SIM.numsamps - size(dmodel,1),size(dmodel,2))]; end disp([' ...simulating GA results with noisy data at variance ' num2str(noise_var)]) SIM % Test idealized GA - no response variability fprintf(' ...original model') [dummy,SIM.ga.se,SIM.ga.t] = designsim('myxc',dmodel,HRF,ISI,TR,noise_var,c,beta,0,xc,niterations); fprintf('...high-pass filtered') [dummy,SIM.ga.HPse,SIM.ga.HPt] = designsim('myxc',dmodel,HRF,ISI,TR,noise_var,c,beta,hpS,xc,niterations); fprintf('...smoothed\n') [dummy,SIM.ga.HLse,SIM.ga.HLt] = designsim('myxc',dmodel,HRF,ISI,TR,noise_var,c,beta,fullS,xc,niterations); end disp([' ...simulating random designs with ' num2str(niterations) ' iterations...']); SIM whos unsortedList % to do: % cut off model at numscans done, i think % rebuild ga at different isis done % cut off stimlist beforehand cause it's too long. done % warning if stimlist in GA is too short for selected isi - then pad with zeros. done % computing random SIM model % ============================================================================================ for i = 1:niterations % Test Random models % Prepare Stimulus List stimList = getRandom(unsortedList); % ====== insert rests, if needed, and trim list =================== stimList = insert_rests(stimList,restevery,restlength); if size(stimList,1) < numStim, stimList(end+1:numStim,:) = 0; elseif size(stimList,1) > numStim,stimList = stimList(1:numStim,:); end stimList = sampleInSeconds(stimList,ISI,.1); dmodel = getPredictors(stimList, HRF); dmodel = resample(dmodel,1,TR*10); % dmodel = dmodel / max(max(dmodel)); % scale so that max = 1; if size(dmodel,1) > SIM.numsamps dmodel = dmodel(1:SIM.numsamps,:); elseif size(dmodel,1) < SIM.numsamps dmodel = [dmodel; zeros(SIM.numsamps - size(dmodel,1),size(dmodel,2))]; end % this gets the average over [numnoise] simulations with different noise vectors % ===================================================================================================== % no smoothing or filtering [dummy,SIM.rnd.se(:,i),SIM.rnd.t(:,i)] = designsim('myxc',dmodel,HRF,ISI,TR,noise_var,c,beta,0,xc); % high-pass only [dummy, SIM.rnd.HPse(:,i),SIM.rnd.HPt(:,i)] = designsim('myxc',dmodel,HRF,ISI,TR,noise_var,c,beta,hpS,xc); % now with smoothing [dummy, SIM.rnd.HLse(:,i),SIM.rnd.HLt(:,i)] = designsim('myxc',dmodel,HRF,ISI,TR,noise_var,c,beta,fullS,xc); fprintf('.') if mod(i,30) == 0, fprintf(' %d ',i),end if mod(i,90) == 0, fprintf('\n'),end % this gets the average over [numnoise] simulations with different noise vectors % ===================================================================================================== % no smoothing or filtering %[SIM.rnd.t(:,i), SIM.rnd.se(:,i)] = designsim('myxc',dmodel,HRF,ISI,TR,noise_var,c,beta,0,xc,100); % high-pass only %[SIM.rnd.HPt(:,i), SIM.rnd.HPse(:,i)] = designsim('myxc',dmodel,HRF,ISI,TR,noise_var,c,beta,hpS,xc,100); % now with smoothing %[SIM.rnd.HLt(:,i), SIM.rnd.HLse(:,i)] = designsim('myxc',dmodel,HRF,ISI,TR,noise_var,c,beta,fullS,xc,100); %fprintf('.') %if mod(i,30) == 0, fprintf(' %d\n',i),end %if mod(i,50) == 0, disp(['done ' num2str(i)]),end; end end MyISIMean.ga.t(myISI) = mean(SIM.ga.t); MyISIMean.rnd.t(myISI) = mean(SIM.rnd.t); MyISIMean.ga.HPt(myISI) = mean(SIM.ga.HPt); MyISIMean.rnd.HPt(myISI) = mean(SIM.rnd.HPt); MyISIMean.ga.HLt(myISI) = mean(SIM.ga.HLt); MyISIMean.rnd.HLt(myISI) = mean(SIM.rnd.HLt); MyISIMean.ISI(myISI) = ISI; MyISIMean.ga.se(myISI) = std(SIM.ga.t)/sqrt(size(SIM.ga.t,2)); MyISIMean.rnd.se(myISI) = std(SIM.rnd.t)/sqrt(size(SIM.rnd.t,2)); MyISIMean.ga.HPse(myISI) = std(SIM.ga.HPt)/sqrt(size(SIM.ga.HPt,2)); MyISIMean.rnd.HPse(myISI) = std(SIM.rnd.HPt)/sqrt(size(SIM.rnd.HPt,2)); MyISIMean.ga.HLse(myISI) = std(SIM.ga.HLt)/sqrt(size(SIM.ga.HLt,2)); MyISIMean.rnd.HLse(myISI) = std(SIM.rnd.HLt)/sqrt(size(SIM.rnd.HLt,2)); end % end loop through simulations eval(['save ' name ' MyISIMean'])
[GOAL] G : Type u_1 inst✝ : Group G ι : Type u_2 s : Finset ι f : ι → G comm : Set.Pairwise ↑s fun a b => Commute (f a) (f b) K : ι → Subgroup G hind : CompleteLattice.Independent K hmem : ∀ (x : ι), x ∈ s → f x ∈ K x heq1 : Finset.noncommProd s f comm = 1 ⊢ ∀ (i : ι), i ∈ s → f i = 1 [PROOFSTEP] classical revert heq1 induction' s using Finset.induction_on with i s hnmem ih · simp · have hcomm := comm.mono (Finset.coe_subset.2 <| Finset.subset_insert _ _) simp only [Finset.forall_mem_insert] at hmem have hmem_bsupr : s.noncommProd f hcomm ∈ ⨆ i ∈ (s : Set ι), K i := by refine' Subgroup.noncommProd_mem _ _ _ intro x hx have : K x ≤ ⨆ i ∈ (s : Set ι), K i := le_iSup₂ (f := fun i _ => K i) x hx exact this (hmem.2 x hx) intro heq1 rw [Finset.noncommProd_insert_of_not_mem _ _ _ _ hnmem] at heq1 have hnmem' : i ∉ (s : Set ι) := by simpa obtain ⟨heq1i : f i = 1, heq1S : s.noncommProd f _ = 1⟩ := Subgroup.disjoint_iff_mul_eq_one.mp (hind.disjoint_biSup hnmem') hmem.1 hmem_bsupr heq1 intro i h simp only [Finset.mem_insert] at h rcases h with (rfl | h) · exact heq1i · refine' ih hcomm hmem.2 heq1S _ h [GOAL] G : Type u_1 inst✝ : Group G ι : Type u_2 s : Finset ι f : ι → G comm : Set.Pairwise ↑s fun a b => Commute (f a) (f b) K : ι → Subgroup G hind : CompleteLattice.Independent K hmem : ∀ (x : ι), x ∈ s → f x ∈ K x heq1 : Finset.noncommProd s f comm = 1 ⊢ ∀ (i : ι), i ∈ s → f i = 1 [PROOFSTEP] revert heq1 [GOAL] G : Type u_1 inst✝ : Group G ι : Type u_2 s : Finset ι f : ι → G comm : Set.Pairwise ↑s fun a b => Commute (f a) (f b) K : ι → Subgroup G hind : CompleteLattice.Independent K hmem : ∀ (x : ι), x ∈ s → f x ∈ K x ⊢ Finset.noncommProd s f comm = 1 → ∀ (i : ι), i ∈ s → f i = 1 [PROOFSTEP] induction' s using Finset.induction_on with i s hnmem ih [GOAL] case empty G : Type u_1 inst✝ : Group G ι : Type u_2 s : Finset ι f : ι → G comm✝ : Set.Pairwise ↑s fun a b => Commute (f a) (f b) K : ι → Subgroup G hind : CompleteLattice.Independent K hmem✝ : ∀ (x : ι), x ∈ s → f x ∈ K x comm : Set.Pairwise ↑∅ fun a b => Commute (f a) (f b) hmem : ∀ (x : ι), x ∈ ∅ → f x ∈ K x ⊢ Finset.noncommProd ∅ f comm = 1 → ∀ (i : ι), i ∈ ∅ → f i = 1 [PROOFSTEP] simp [GOAL] case insert G : Type u_1 inst✝ : Group G ι : Type u_2 s✝ : Finset ι f : ι → G comm✝ : Set.Pairwise ↑s✝ fun a b => Commute (f a) (f b) K : ι → Subgroup G hind : CompleteLattice.Independent K hmem✝ : ∀ (x : ι), x ∈ s✝ → f x ∈ K x i : ι s : Finset ι hnmem : ¬i ∈ s ih : ∀ (comm : Set.Pairwise ↑s fun a b => Commute (f a) (f b)), (∀ (x : ι), x ∈ s → f x ∈ K x) → Finset.noncommProd s f comm = 1 → ∀ (i : ι), i ∈ s → f i = 1 comm : Set.Pairwise ↑(insert i s) fun a b => Commute (f a) (f b) hmem : ∀ (x : ι), x ∈ insert i s → f x ∈ K x ⊢ Finset.noncommProd (insert i s) f comm = 1 → ∀ (i_1 : ι), i_1 ∈ insert i s → f i_1 = 1 [PROOFSTEP] have hcomm := comm.mono (Finset.coe_subset.2 <| Finset.subset_insert _ _) [GOAL] case insert G : Type u_1 inst✝ : Group G ι : Type u_2 s✝ : Finset ι f : ι → G comm✝ : Set.Pairwise ↑s✝ fun a b => Commute (f a) (f b) K : ι → Subgroup G hind : CompleteLattice.Independent K hmem✝ : ∀ (x : ι), x ∈ s✝ → f x ∈ K x i : ι s : Finset ι hnmem : ¬i ∈ s ih : ∀ (comm : Set.Pairwise ↑s fun a b => Commute (f a) (f b)), (∀ (x : ι), x ∈ s → f x ∈ K x) → Finset.noncommProd s f comm = 1 → ∀ (i : ι), i ∈ s → f i = 1 comm : Set.Pairwise ↑(insert i s) fun a b => Commute (f a) (f b) hmem : ∀ (x : ι), x ∈ insert i s → f x ∈ K x hcomm : Set.Pairwise ↑s fun a b => Commute (f a) (f b) ⊢ Finset.noncommProd (insert i s) f comm = 1 → ∀ (i_1 : ι), i_1 ∈ insert i s → f i_1 = 1 [PROOFSTEP] simp only [Finset.forall_mem_insert] at hmem [GOAL] case insert G : Type u_1 inst✝ : Group G ι : Type u_2 s✝ : Finset ι f : ι → G comm✝ : Set.Pairwise ↑s✝ fun a b => Commute (f a) (f b) K : ι → Subgroup G hind : CompleteLattice.Independent K hmem✝ : ∀ (x : ι), x ∈ s✝ → f x ∈ K x i : ι s : Finset ι hnmem : ¬i ∈ s ih : ∀ (comm : Set.Pairwise ↑s fun a b => Commute (f a) (f b)), (∀ (x : ι), x ∈ s → f x ∈ K x) → Finset.noncommProd s f comm = 1 → ∀ (i : ι), i ∈ s → f i = 1 comm : Set.Pairwise ↑(insert i s) fun a b => Commute (f a) (f b) hcomm : Set.Pairwise ↑s fun a b => Commute (f a) (f b) hmem : f i ∈ K i ∧ ∀ (x : ι), x ∈ s → f x ∈ K x ⊢ Finset.noncommProd (insert i s) f comm = 1 → ∀ (i_1 : ι), i_1 ∈ insert i s → f i_1 = 1 [PROOFSTEP] have hmem_bsupr : s.noncommProd f hcomm ∈ ⨆ i ∈ (s : Set ι), K i := by refine' Subgroup.noncommProd_mem _ _ _ intro x hx have : K x ≤ ⨆ i ∈ (s : Set ι), K i := le_iSup₂ (f := fun i _ => K i) x hx exact this (hmem.2 x hx) [GOAL] G : Type u_1 inst✝ : Group G ι : Type u_2 s✝ : Finset ι f : ι → G comm✝ : Set.Pairwise ↑s✝ fun a b => Commute (f a) (f b) K : ι → Subgroup G hind : CompleteLattice.Independent K hmem✝ : ∀ (x : ι), x ∈ s✝ → f x ∈ K x i : ι s : Finset ι hnmem : ¬i ∈ s ih : ∀ (comm : Set.Pairwise ↑s fun a b => Commute (f a) (f b)), (∀ (x : ι), x ∈ s → f x ∈ K x) → Finset.noncommProd s f comm = 1 → ∀ (i : ι), i ∈ s → f i = 1 comm : Set.Pairwise ↑(insert i s) fun a b => Commute (f a) (f b) hcomm : Set.Pairwise ↑s fun a b => Commute (f a) (f b) hmem : f i ∈ K i ∧ ∀ (x : ι), x ∈ s → f x ∈ K x ⊢ Finset.noncommProd s f hcomm ∈ ⨆ (i : ι) (_ : i ∈ ↑s), K i [PROOFSTEP] refine' Subgroup.noncommProd_mem _ _ _ [GOAL] G : Type u_1 inst✝ : Group G ι : Type u_2 s✝ : Finset ι f : ι → G comm✝ : Set.Pairwise ↑s✝ fun a b => Commute (f a) (f b) K : ι → Subgroup G hind : CompleteLattice.Independent K hmem✝ : ∀ (x : ι), x ∈ s✝ → f x ∈ K x i : ι s : Finset ι hnmem : ¬i ∈ s ih : ∀ (comm : Set.Pairwise ↑s fun a b => Commute (f a) (f b)), (∀ (x : ι), x ∈ s → f x ∈ K x) → Finset.noncommProd s f comm = 1 → ∀ (i : ι), i ∈ s → f i = 1 comm : Set.Pairwise ↑(insert i s) fun a b => Commute (f a) (f b) hcomm : Set.Pairwise ↑s fun a b => Commute (f a) (f b) hmem : f i ∈ K i ∧ ∀ (x : ι), x ∈ s → f x ∈ K x ⊢ ∀ (c : ι), c ∈ s → f c ∈ ⨆ (i : ι) (_ : i ∈ ↑s), K i [PROOFSTEP] intro x hx [GOAL] G : Type u_1 inst✝ : Group G ι : Type u_2 s✝ : Finset ι f : ι → G comm✝ : Set.Pairwise ↑s✝ fun a b => Commute (f a) (f b) K : ι → Subgroup G hind : CompleteLattice.Independent K hmem✝ : ∀ (x : ι), x ∈ s✝ → f x ∈ K x i : ι s : Finset ι hnmem : ¬i ∈ s ih : ∀ (comm : Set.Pairwise ↑s fun a b => Commute (f a) (f b)), (∀ (x : ι), x ∈ s → f x ∈ K x) → Finset.noncommProd s f comm = 1 → ∀ (i : ι), i ∈ s → f i = 1 comm : Set.Pairwise ↑(insert i s) fun a b => Commute (f a) (f b) hcomm : Set.Pairwise ↑s fun a b => Commute (f a) (f b) hmem : f i ∈ K i ∧ ∀ (x : ι), x ∈ s → f x ∈ K x x : ι hx : x ∈ s ⊢ f x ∈ ⨆ (i : ι) (_ : i ∈ ↑s), K i [PROOFSTEP] have : K x ≤ ⨆ i ∈ (s : Set ι), K i := le_iSup₂ (f := fun i _ => K i) x hx [GOAL] G : Type u_1 inst✝ : Group G ι : Type u_2 s✝ : Finset ι f : ι → G comm✝ : Set.Pairwise ↑s✝ fun a b => Commute (f a) (f b) K : ι → Subgroup G hind : CompleteLattice.Independent K hmem✝ : ∀ (x : ι), x ∈ s✝ → f x ∈ K x i : ι s : Finset ι hnmem : ¬i ∈ s ih : ∀ (comm : Set.Pairwise ↑s fun a b => Commute (f a) (f b)), (∀ (x : ι), x ∈ s → f x ∈ K x) → Finset.noncommProd s f comm = 1 → ∀ (i : ι), i ∈ s → f i = 1 comm : Set.Pairwise ↑(insert i s) fun a b => Commute (f a) (f b) hcomm : Set.Pairwise ↑s fun a b => Commute (f a) (f b) hmem : f i ∈ K i ∧ ∀ (x : ι), x ∈ s → f x ∈ K x x : ι hx : x ∈ s this : K x ≤ ⨆ (i : ι) (_ : i ∈ ↑s), K i ⊢ f x ∈ ⨆ (i : ι) (_ : i ∈ ↑s), K i [PROOFSTEP] exact this (hmem.2 x hx) [GOAL] case insert G : Type u_1 inst✝ : Group G ι : Type u_2 s✝ : Finset ι f : ι → G comm✝ : Set.Pairwise ↑s✝ fun a b => Commute (f a) (f b) K : ι → Subgroup G hind : CompleteLattice.Independent K hmem✝ : ∀ (x : ι), x ∈ s✝ → f x ∈ K x i : ι s : Finset ι hnmem : ¬i ∈ s ih : ∀ (comm : Set.Pairwise ↑s fun a b => Commute (f a) (f b)), (∀ (x : ι), x ∈ s → f x ∈ K x) → Finset.noncommProd s f comm = 1 → ∀ (i : ι), i ∈ s → f i = 1 comm : Set.Pairwise ↑(insert i s) fun a b => Commute (f a) (f b) hcomm : Set.Pairwise ↑s fun a b => Commute (f a) (f b) hmem : f i ∈ K i ∧ ∀ (x : ι), x ∈ s → f x ∈ K x hmem_bsupr : Finset.noncommProd s f hcomm ∈ ⨆ (i : ι) (_ : i ∈ ↑s), K i ⊢ Finset.noncommProd (insert i s) f comm = 1 → ∀ (i_1 : ι), i_1 ∈ insert i s → f i_1 = 1 [PROOFSTEP] intro heq1 [GOAL] case insert G : Type u_1 inst✝ : Group G ι : Type u_2 s✝ : Finset ι f : ι → G comm✝ : Set.Pairwise ↑s✝ fun a b => Commute (f a) (f b) K : ι → Subgroup G hind : CompleteLattice.Independent K hmem✝ : ∀ (x : ι), x ∈ s✝ → f x ∈ K x i : ι s : Finset ι hnmem : ¬i ∈ s ih : ∀ (comm : Set.Pairwise ↑s fun a b => Commute (f a) (f b)), (∀ (x : ι), x ∈ s → f x ∈ K x) → Finset.noncommProd s f comm = 1 → ∀ (i : ι), i ∈ s → f i = 1 comm : Set.Pairwise ↑(insert i s) fun a b => Commute (f a) (f b) hcomm : Set.Pairwise ↑s fun a b => Commute (f a) (f b) hmem : f i ∈ K i ∧ ∀ (x : ι), x ∈ s → f x ∈ K x hmem_bsupr : Finset.noncommProd s f hcomm ∈ ⨆ (i : ι) (_ : i ∈ ↑s), K i heq1 : Finset.noncommProd (insert i s) f comm = 1 ⊢ ∀ (i_1 : ι), i_1 ∈ insert i s → f i_1 = 1 [PROOFSTEP] rw [Finset.noncommProd_insert_of_not_mem _ _ _ _ hnmem] at heq1 [GOAL] case insert G : Type u_1 inst✝ : Group G ι : Type u_2 s✝ : Finset ι f : ι → G comm✝ : Set.Pairwise ↑s✝ fun a b => Commute (f a) (f b) K : ι → Subgroup G hind : CompleteLattice.Independent K hmem✝ : ∀ (x : ι), x ∈ s✝ → f x ∈ K x i : ι s : Finset ι hnmem : ¬i ∈ s ih : ∀ (comm : Set.Pairwise ↑s fun a b => Commute (f a) (f b)), (∀ (x : ι), x ∈ s → f x ∈ K x) → Finset.noncommProd s f comm = 1 → ∀ (i : ι), i ∈ s → f i = 1 comm : Set.Pairwise ↑(insert i s) fun a b => Commute (f a) (f b) hcomm : Set.Pairwise ↑s fun a b => Commute (f a) (f b) hmem : f i ∈ K i ∧ ∀ (x : ι), x ∈ s → f x ∈ K x hmem_bsupr : Finset.noncommProd s f hcomm ∈ ⨆ (i : ι) (_ : i ∈ ↑s), K i heq1 : f i * Finset.noncommProd s f (_ : Set.Pairwise ↑s fun a b => Commute (f a) (f b)) = 1 ⊢ ∀ (i_1 : ι), i_1 ∈ insert i s → f i_1 = 1 [PROOFSTEP] have hnmem' : i ∉ (s : Set ι) := by simpa [GOAL] G : Type u_1 inst✝ : Group G ι : Type u_2 s✝ : Finset ι f : ι → G comm✝ : Set.Pairwise ↑s✝ fun a b => Commute (f a) (f b) K : ι → Subgroup G hind : CompleteLattice.Independent K hmem✝ : ∀ (x : ι), x ∈ s✝ → f x ∈ K x i : ι s : Finset ι hnmem : ¬i ∈ s ih : ∀ (comm : Set.Pairwise ↑s fun a b => Commute (f a) (f b)), (∀ (x : ι), x ∈ s → f x ∈ K x) → Finset.noncommProd s f comm = 1 → ∀ (i : ι), i ∈ s → f i = 1 comm : Set.Pairwise ↑(insert i s) fun a b => Commute (f a) (f b) hcomm : Set.Pairwise ↑s fun a b => Commute (f a) (f b) hmem : f i ∈ K i ∧ ∀ (x : ι), x ∈ s → f x ∈ K x hmem_bsupr : Finset.noncommProd s f hcomm ∈ ⨆ (i : ι) (_ : i ∈ ↑s), K i heq1 : f i * Finset.noncommProd s f (_ : Set.Pairwise ↑s fun a b => Commute (f a) (f b)) = 1 ⊢ ¬i ∈ ↑s [PROOFSTEP] simpa [GOAL] case insert G : Type u_1 inst✝ : Group G ι : Type u_2 s✝ : Finset ι f : ι → G comm✝ : Set.Pairwise ↑s✝ fun a b => Commute (f a) (f b) K : ι → Subgroup G hind : CompleteLattice.Independent K hmem✝ : ∀ (x : ι), x ∈ s✝ → f x ∈ K x i : ι s : Finset ι hnmem : ¬i ∈ s ih : ∀ (comm : Set.Pairwise ↑s fun a b => Commute (f a) (f b)), (∀ (x : ι), x ∈ s → f x ∈ K x) → Finset.noncommProd s f comm = 1 → ∀ (i : ι), i ∈ s → f i = 1 comm : Set.Pairwise ↑(insert i s) fun a b => Commute (f a) (f b) hcomm : Set.Pairwise ↑s fun a b => Commute (f a) (f b) hmem : f i ∈ K i ∧ ∀ (x : ι), x ∈ s → f x ∈ K x hmem_bsupr : Finset.noncommProd s f hcomm ∈ ⨆ (i : ι) (_ : i ∈ ↑s), K i heq1 : f i * Finset.noncommProd s f (_ : Set.Pairwise ↑s fun a b => Commute (f a) (f b)) = 1 hnmem' : ¬i ∈ ↑s ⊢ ∀ (i_1 : ι), i_1 ∈ insert i s → f i_1 = 1 [PROOFSTEP] obtain ⟨heq1i : f i = 1, heq1S : s.noncommProd f _ = 1⟩ := Subgroup.disjoint_iff_mul_eq_one.mp (hind.disjoint_biSup hnmem') hmem.1 hmem_bsupr heq1 [GOAL] case insert.intro G : Type u_1 inst✝ : Group G ι : Type u_2 s✝ : Finset ι f : ι → G comm✝ : Set.Pairwise ↑s✝ fun a b => Commute (f a) (f b) K : ι → Subgroup G hind : CompleteLattice.Independent K hmem✝ : ∀ (x : ι), x ∈ s✝ → f x ∈ K x i : ι s : Finset ι hnmem : ¬i ∈ s ih : ∀ (comm : Set.Pairwise ↑s fun a b => Commute (f a) (f b)), (∀ (x : ι), x ∈ s → f x ∈ K x) → Finset.noncommProd s f comm = 1 → ∀ (i : ι), i ∈ s → f i = 1 comm : Set.Pairwise ↑(insert i s) fun a b => Commute (f a) (f b) hcomm : Set.Pairwise ↑s fun a b => Commute (f a) (f b) hmem : f i ∈ K i ∧ ∀ (x : ι), x ∈ s → f x ∈ K x hmem_bsupr : Finset.noncommProd s f hcomm ∈ ⨆ (i : ι) (_ : i ∈ ↑s), K i heq1 : f i * Finset.noncommProd s f (_ : Set.Pairwise ↑s fun a b => Commute (f a) (f b)) = 1 hnmem' : ¬i ∈ ↑s heq1i : f i = 1 heq1S : Finset.noncommProd s f hcomm = 1 ⊢ ∀ (i_1 : ι), i_1 ∈ insert i s → f i_1 = 1 [PROOFSTEP] intro i h [GOAL] case insert.intro G : Type u_1 inst✝ : Group G ι : Type u_2 s✝ : Finset ι f : ι → G comm✝ : Set.Pairwise ↑s✝ fun a b => Commute (f a) (f b) K : ι → Subgroup G hind : CompleteLattice.Independent K hmem✝ : ∀ (x : ι), x ∈ s✝ → f x ∈ K x i✝ : ι s : Finset ι hnmem : ¬i✝ ∈ s ih : ∀ (comm : Set.Pairwise ↑s fun a b => Commute (f a) (f b)), (∀ (x : ι), x ∈ s → f x ∈ K x) → Finset.noncommProd s f comm = 1 → ∀ (i : ι), i ∈ s → f i = 1 comm : Set.Pairwise ↑(insert i✝ s) fun a b => Commute (f a) (f b) hcomm : Set.Pairwise ↑s fun a b => Commute (f a) (f b) hmem : f i✝ ∈ K i✝ ∧ ∀ (x : ι), x ∈ s → f x ∈ K x hmem_bsupr : Finset.noncommProd s f hcomm ∈ ⨆ (i : ι) (_ : i ∈ ↑s), K i heq1 : f i✝ * Finset.noncommProd s f (_ : Set.Pairwise ↑s fun a b => Commute (f a) (f b)) = 1 hnmem' : ¬i✝ ∈ ↑s heq1i : f i✝ = 1 heq1S : Finset.noncommProd s f hcomm = 1 i : ι h : i ∈ insert i✝ s ⊢ f i = 1 [PROOFSTEP] simp only [Finset.mem_insert] at h [GOAL] case insert.intro G : Type u_1 inst✝ : Group G ι : Type u_2 s✝ : Finset ι f : ι → G comm✝ : Set.Pairwise ↑s✝ fun a b => Commute (f a) (f b) K : ι → Subgroup G hind : CompleteLattice.Independent K hmem✝ : ∀ (x : ι), x ∈ s✝ → f x ∈ K x i✝ : ι s : Finset ι hnmem : ¬i✝ ∈ s ih : ∀ (comm : Set.Pairwise ↑s fun a b => Commute (f a) (f b)), (∀ (x : ι), x ∈ s → f x ∈ K x) → Finset.noncommProd s f comm = 1 → ∀ (i : ι), i ∈ s → f i = 1 comm : Set.Pairwise ↑(insert i✝ s) fun a b => Commute (f a) (f b) hcomm : Set.Pairwise ↑s fun a b => Commute (f a) (f b) hmem : f i✝ ∈ K i✝ ∧ ∀ (x : ι), x ∈ s → f x ∈ K x hmem_bsupr : Finset.noncommProd s f hcomm ∈ ⨆ (i : ι) (_ : i ∈ ↑s), K i heq1 : f i✝ * Finset.noncommProd s f (_ : Set.Pairwise ↑s fun a b => Commute (f a) (f b)) = 1 hnmem' : ¬i✝ ∈ ↑s heq1i : f i✝ = 1 heq1S : Finset.noncommProd s f hcomm = 1 i : ι h : i = i✝ ∨ i ∈ s ⊢ f i = 1 [PROOFSTEP] rcases h with (rfl | h) [GOAL] case insert.intro.inl G : Type u_1 inst✝ : Group G ι : Type u_2 s✝ : Finset ι f : ι → G comm✝ : Set.Pairwise ↑s✝ fun a b => Commute (f a) (f b) K : ι → Subgroup G hind : CompleteLattice.Independent K hmem✝ : ∀ (x : ι), x ∈ s✝ → f x ∈ K x s : Finset ι ih : ∀ (comm : Set.Pairwise ↑s fun a b => Commute (f a) (f b)), (∀ (x : ι), x ∈ s → f x ∈ K x) → Finset.noncommProd s f comm = 1 → ∀ (i : ι), i ∈ s → f i = 1 hcomm : Set.Pairwise ↑s fun a b => Commute (f a) (f b) hmem_bsupr : Finset.noncommProd s f hcomm ∈ ⨆ (i : ι) (_ : i ∈ ↑s), K i heq1S : Finset.noncommProd s f hcomm = 1 i : ι hnmem : ¬i ∈ s comm : Set.Pairwise ↑(insert i s) fun a b => Commute (f a) (f b) hmem : f i ∈ K i ∧ ∀ (x : ι), x ∈ s → f x ∈ K x heq1 : f i * Finset.noncommProd s f (_ : Set.Pairwise ↑s fun a b => Commute (f a) (f b)) = 1 hnmem' : ¬i ∈ ↑s heq1i : f i = 1 ⊢ f i = 1 [PROOFSTEP] exact heq1i [GOAL] case insert.intro.inr G : Type u_1 inst✝ : Group G ι : Type u_2 s✝ : Finset ι f : ι → G comm✝ : Set.Pairwise ↑s✝ fun a b => Commute (f a) (f b) K : ι → Subgroup G hind : CompleteLattice.Independent K hmem✝ : ∀ (x : ι), x ∈ s✝ → f x ∈ K x i✝ : ι s : Finset ι hnmem : ¬i✝ ∈ s ih : ∀ (comm : Set.Pairwise ↑s fun a b => Commute (f a) (f b)), (∀ (x : ι), x ∈ s → f x ∈ K x) → Finset.noncommProd s f comm = 1 → ∀ (i : ι), i ∈ s → f i = 1 comm : Set.Pairwise ↑(insert i✝ s) fun a b => Commute (f a) (f b) hcomm : Set.Pairwise ↑s fun a b => Commute (f a) (f b) hmem : f i✝ ∈ K i✝ ∧ ∀ (x : ι), x ∈ s → f x ∈ K x hmem_bsupr : Finset.noncommProd s f hcomm ∈ ⨆ (i : ι) (_ : i ∈ ↑s), K i heq1 : f i✝ * Finset.noncommProd s f (_ : Set.Pairwise ↑s fun a b => Commute (f a) (f b)) = 1 hnmem' : ¬i✝ ∈ ↑s heq1i : f i✝ = 1 heq1S : Finset.noncommProd s f hcomm = 1 i : ι h : i ∈ s ⊢ f i = 1 [PROOFSTEP] refine' ih hcomm hmem.2 heq1S _ h [GOAL] M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → N i ⊢ (fun f => Finset.noncommProd Finset.univ (fun i => ↑(ϕ i) (f i)) (_ : ∀ (i : ι), i ∈ ↑Finset.univ → ∀ (j : ι), j ∈ ↑Finset.univ → i ≠ j → Commute (↑(ϕ i) (f i)) (↑(ϕ j) (f j)))) 1 = 1 [PROOFSTEP] apply (Finset.noncommProd_eq_pow_card _ _ _ _ _).trans (one_pow _) [GOAL] M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → N i ⊢ ∀ (x : ι), x ∈ Finset.univ → ↑(ϕ x) (OfNat.ofNat 1 x) = 1 [PROOFSTEP] simp [GOAL] M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ f g : (i : ι) → N i ⊢ OneHom.toFun { toFun := fun f => Finset.noncommProd Finset.univ (fun i => ↑(ϕ i) (f i)) (_ : ∀ (i : ι), i ∈ ↑Finset.univ → ∀ (j : ι), j ∈ ↑Finset.univ → i ≠ j → Commute (↑(ϕ i) (f i)) (↑(ϕ j) (f j))), map_one' := (_ : Finset.noncommProd Finset.univ (fun i => ↑(ϕ i) (OfNat.ofNat 1 i)) (_ : ∀ (i : ι), i ∈ ↑Finset.univ → ∀ (j : ι), j ∈ ↑Finset.univ → i ≠ j → Commute (↑(ϕ i) (OfNat.ofNat 1 i)) (↑(ϕ j) (OfNat.ofNat 1 j))) = 1) } (f * g) = OneHom.toFun { toFun := fun f => Finset.noncommProd Finset.univ (fun i => ↑(ϕ i) (f i)) (_ : ∀ (i : ι), i ∈ ↑Finset.univ → ∀ (j : ι), j ∈ ↑Finset.univ → i ≠ j → Commute (↑(ϕ i) (f i)) (↑(ϕ j) (f j))), map_one' := (_ : Finset.noncommProd Finset.univ (fun i => ↑(ϕ i) (OfNat.ofNat 1 i)) (_ : ∀ (i : ι), i ∈ ↑Finset.univ → ∀ (j : ι), j ∈ ↑Finset.univ → i ≠ j → Commute (↑(ϕ i) (OfNat.ofNat 1 i)) (↑(ϕ j) (OfNat.ofNat 1 j))) = 1) } f * OneHom.toFun { toFun := fun f => Finset.noncommProd Finset.univ (fun i => ↑(ϕ i) (f i)) (_ : ∀ (i : ι), i ∈ ↑Finset.univ → ∀ (j : ι), j ∈ ↑Finset.univ → i ≠ j → Commute (↑(ϕ i) (f i)) (↑(ϕ j) (f j))), map_one' := (_ : Finset.noncommProd Finset.univ (fun i => ↑(ϕ i) (OfNat.ofNat 1 i)) (_ : ∀ (i : ι), i ∈ ↑Finset.univ → ∀ (j : ι), j ∈ ↑Finset.univ → i ≠ j → Commute (↑(ϕ i) (OfNat.ofNat 1 i)) (↑(ϕ j) (OfNat.ofNat 1 j))) = 1) } g [PROOFSTEP] classical simp only convert @Finset.noncommProd_mul_distrib _ _ _ _ (fun i => ϕ i (f i)) (fun i => ϕ i (g i)) _ _ _ · exact map_mul _ _ _ · rintro i - j - h exact hcomm h _ _ [GOAL] M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ f g : (i : ι) → N i ⊢ OneHom.toFun { toFun := fun f => Finset.noncommProd Finset.univ (fun i => ↑(ϕ i) (f i)) (_ : ∀ (i : ι), i ∈ ↑Finset.univ → ∀ (j : ι), j ∈ ↑Finset.univ → i ≠ j → Commute (↑(ϕ i) (f i)) (↑(ϕ j) (f j))), map_one' := (_ : Finset.noncommProd Finset.univ (fun i => ↑(ϕ i) (OfNat.ofNat 1 i)) (_ : ∀ (i : ι), i ∈ ↑Finset.univ → ∀ (j : ι), j ∈ ↑Finset.univ → i ≠ j → Commute (↑(ϕ i) (OfNat.ofNat 1 i)) (↑(ϕ j) (OfNat.ofNat 1 j))) = 1) } (f * g) = OneHom.toFun { toFun := fun f => Finset.noncommProd Finset.univ (fun i => ↑(ϕ i) (f i)) (_ : ∀ (i : ι), i ∈ ↑Finset.univ → ∀ (j : ι), j ∈ ↑Finset.univ → i ≠ j → Commute (↑(ϕ i) (f i)) (↑(ϕ j) (f j))), map_one' := (_ : Finset.noncommProd Finset.univ (fun i => ↑(ϕ i) (OfNat.ofNat 1 i)) (_ : ∀ (i : ι), i ∈ ↑Finset.univ → ∀ (j : ι), j ∈ ↑Finset.univ → i ≠ j → Commute (↑(ϕ i) (OfNat.ofNat 1 i)) (↑(ϕ j) (OfNat.ofNat 1 j))) = 1) } f * OneHom.toFun { toFun := fun f => Finset.noncommProd Finset.univ (fun i => ↑(ϕ i) (f i)) (_ : ∀ (i : ι), i ∈ ↑Finset.univ → ∀ (j : ι), j ∈ ↑Finset.univ → i ≠ j → Commute (↑(ϕ i) (f i)) (↑(ϕ j) (f j))), map_one' := (_ : Finset.noncommProd Finset.univ (fun i => ↑(ϕ i) (OfNat.ofNat 1 i)) (_ : ∀ (i : ι), i ∈ ↑Finset.univ → ∀ (j : ι), j ∈ ↑Finset.univ → i ≠ j → Commute (↑(ϕ i) (OfNat.ofNat 1 i)) (↑(ϕ j) (OfNat.ofNat 1 j))) = 1) } g [PROOFSTEP] simp only [GOAL] M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ f g : (i : ι) → N i ⊢ Finset.noncommProd Finset.univ (fun x => ↑(ϕ x) ((f * g) x)) (_ : ∀ (x : ι), x ∈ ↑Finset.univ → ∀ (y : ι), y ∈ ↑Finset.univ → x ≠ y → (fun a b => Commute (↑(ϕ a) ((f * g) a)) (↑(ϕ b) ((f * g) b))) x y) = Finset.noncommProd Finset.univ (fun x => ↑(ϕ x) (f x)) (_ : ∀ (x : ι), x ∈ ↑Finset.univ → ∀ (y : ι), y ∈ ↑Finset.univ → x ≠ y → (fun a b => Commute (↑(ϕ a) (f a)) (↑(ϕ b) (f b))) x y) * Finset.noncommProd Finset.univ (fun x => ↑(ϕ x) (g x)) (_ : ∀ (x : ι), x ∈ ↑Finset.univ → ∀ (y : ι), y ∈ ↑Finset.univ → x ≠ y → (fun a b => Commute (↑(ϕ a) (g a)) (↑(ϕ b) (g b))) x y) [PROOFSTEP] convert @Finset.noncommProd_mul_distrib _ _ _ _ (fun i => ϕ i (f i)) (fun i => ϕ i (g i)) _ _ _ [GOAL] case h.e'_2.h₂ M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ f g : (i : ι) → N i x✝ : ι a✝ : x✝ ∈ Finset.univ ⊢ ↑(ϕ x✝) ((f * g) x✝) = ((fun i => ↑(ϕ i) (f i)) * fun i => ↑(ϕ i) (g i)) x✝ [PROOFSTEP] exact map_mul _ _ _ [GOAL] case convert_4 M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ f g : (i : ι) → N i ⊢ Set.Pairwise ↑Finset.univ fun x y => Commute ((fun i => ↑(ϕ i) (g i)) x) ((fun i => ↑(ϕ i) (f i)) y) [PROOFSTEP] rintro i - j - h [GOAL] case convert_4 M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ f g : (i : ι) → N i i j : ι h : i ≠ j ⊢ Commute ((fun i => ↑(ϕ i) (g i)) i) ((fun i => ↑(ϕ i) (f i)) j) [PROOFSTEP] exact hcomm h _ _ [GOAL] M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → N i i : ι y : N i ⊢ ↑(noncommPiCoprod ϕ hcomm) (Pi.mulSingle i y) = ↑(ϕ i) y [PROOFSTEP] change Finset.univ.noncommProd (fun j => ϕ j (Pi.mulSingle i y j)) (fun _ _ _ _ h => hcomm h _ _) = ϕ i y [GOAL] M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → N i i : ι y : N i ⊢ Finset.noncommProd Finset.univ (fun j => ↑(ϕ j) (Pi.mulSingle i y j)) (_ : ∀ (x : ι), x ∈ ↑Finset.univ → ∀ (x_2 : ι), x_2 ∈ ↑Finset.univ → x ≠ x_2 → Commute (↑(ϕ x) (Pi.mulSingle i y x)) (↑(ϕ x_2) (Pi.mulSingle i y x_2))) = ↑(ϕ i) y [PROOFSTEP] simp (config := { singlePass := true }) only [← Finset.insert_erase (Finset.mem_univ i)] [GOAL] M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → N i i : ι y : N i ⊢ Finset.noncommProd (insert i (Finset.erase Finset.univ i)) (fun x => ↑(ϕ x) (Pi.mulSingle i y x)) (_ : ∀ (x : ι), x ∈ ↑(insert i (Finset.erase Finset.univ i)) → ∀ (y_1 : ι), y_1 ∈ ↑(insert i (Finset.erase Finset.univ i)) → x ≠ y_1 → (fun a b => Commute (↑(ϕ a) (Pi.mulSingle i y a)) (↑(ϕ b) (Pi.mulSingle i y b))) x y_1) = ↑(ϕ i) y [PROOFSTEP] rw [Finset.noncommProd_insert_of_not_mem _ _ _ _ (Finset.not_mem_erase i _)] [GOAL] M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → N i i : ι y : N i ⊢ ↑(ϕ i) (Pi.mulSingle i y i) * Finset.noncommProd (Finset.erase Finset.univ i) (fun x => ↑(ϕ x) (Pi.mulSingle i y x)) (_ : Set.Pairwise ↑(Finset.erase Finset.univ i) fun a b => Commute (↑(ϕ a) (Pi.mulSingle i y a)) (↑(ϕ b) (Pi.mulSingle i y b))) = ↑(ϕ i) y [PROOFSTEP] rw [Pi.mulSingle_eq_same] [GOAL] M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → N i i : ι y : N i ⊢ ↑(ϕ i) y * Finset.noncommProd (Finset.erase Finset.univ i) (fun x => ↑(ϕ x) (Pi.mulSingle i y x)) (_ : Set.Pairwise ↑(Finset.erase Finset.univ i) fun a b => Commute (↑(ϕ a) (Pi.mulSingle i y a)) (↑(ϕ b) (Pi.mulSingle i y b))) = ↑(ϕ i) y [PROOFSTEP] rw [Finset.noncommProd_eq_pow_card] [GOAL] M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → N i i : ι y : N i ⊢ ↑(ϕ i) y * ?m ^ Finset.card (Finset.erase Finset.univ i) = ↑(ϕ i) y [PROOFSTEP] rw [one_pow] [GOAL] M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → N i i : ι y : N i ⊢ ↑(ϕ i) y * 1 = ↑(ϕ i) y [PROOFSTEP] exact mul_one _ [GOAL] case h M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → N i i : ι y : N i ⊢ ∀ (x : ι), x ∈ Finset.erase Finset.univ i → ↑(ϕ x) (Pi.mulSingle i y x) = 1 [PROOFSTEP] intro j hj [GOAL] case h M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → N i i : ι y : N i j : ι hj : j ∈ Finset.erase Finset.univ i ⊢ ↑(ϕ j) (Pi.mulSingle i y j) = 1 [PROOFSTEP] simp only [Finset.mem_erase] at hj [GOAL] case h M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → N i i : ι y : N i j : ι hj : j ≠ i ∧ j ∈ Finset.univ ⊢ ↑(ϕ j) (Pi.mulSingle i y j) = 1 [PROOFSTEP] simp [hj] [GOAL] M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ✝ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ✝ i) x) (↑(ϕ✝ j) y) f g : (i : ι) → N i ϕ : { ϕ // Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) } ⊢ (fun f => { val := fun i => comp f (single N i), property := (_ : ∀ (i j : ι), i ≠ j → ∀ (x : N i) (y : N j), Commute (↑f (Pi.mulSingle i x)) (↑f (Pi.mulSingle j y))) }) ((fun ϕ => noncommPiCoprod ↑ϕ (_ : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(↑ϕ i) x) (↑(↑ϕ j) y))) ϕ) = ϕ [PROOFSTEP] ext [GOAL] case a.h.h M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ✝ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ✝ i) x) (↑(ϕ✝ j) y) f g : (i : ι) → N i ϕ : { ϕ // Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) } x✝¹ : ι x✝ : N x✝¹ ⊢ ↑(↑((fun f => { val := fun i => comp f (single N i), property := (_ : ∀ (i j : ι), i ≠ j → ∀ (x : N i) (y : N j), Commute (↑f (Pi.mulSingle i x)) (↑f (Pi.mulSingle j y))) }) ((fun ϕ => noncommPiCoprod ↑ϕ (_ : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(↑ϕ i) x) (↑(↑ϕ j) y))) ϕ)) x✝¹) x✝ = ↑(↑ϕ x✝¹) x✝ [PROOFSTEP] simp [GOAL] M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g : (i : ι) → N i f : ((i : ι) → N i) →* M i : ι x : N i ⊢ ↑((fun ϕ => noncommPiCoprod ↑ϕ (_ : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(↑ϕ i) x) (↑(↑ϕ j) y))) ((fun f => { val := fun i => comp f (single N i), property := (_ : ∀ (i j : ι), i ≠ j → ∀ (x : N i) (y : N j), Commute (↑f (Pi.mulSingle i x)) (↑f (Pi.mulSingle j y))) }) f)) (Pi.mulSingle i x) = ↑f (Pi.mulSingle i x) [PROOFSTEP] simp [GOAL] M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → N i ⊢ mrange (noncommPiCoprod ϕ hcomm) = ⨆ (i : ι), mrange (ϕ i) [PROOFSTEP] classical apply le_antisymm · rintro x ⟨f, rfl⟩ refine Submonoid.noncommProd_mem _ _ _ (fun _ _ _ _ h => hcomm h _ _) (fun i _ => ?_) apply Submonoid.mem_sSup_of_mem · use i simp · refine' iSup_le _ rintro i x ⟨y, rfl⟩ refine' ⟨Pi.mulSingle i y, noncommPiCoprod_mulSingle _ _ _⟩ [GOAL] M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → N i ⊢ mrange (noncommPiCoprod ϕ hcomm) = ⨆ (i : ι), mrange (ϕ i) [PROOFSTEP] apply le_antisymm [GOAL] case a M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → N i ⊢ mrange (noncommPiCoprod ϕ hcomm) ≤ ⨆ (i : ι), mrange (ϕ i) [PROOFSTEP] rintro x ⟨f, rfl⟩ [GOAL] case a.intro M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g f : (i : ι) → N i ⊢ ↑(noncommPiCoprod ϕ hcomm) f ∈ ⨆ (i : ι), mrange (ϕ i) [PROOFSTEP] refine Submonoid.noncommProd_mem _ _ _ (fun _ _ _ _ h => hcomm h _ _) (fun i _ => ?_) [GOAL] case a.intro M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g f : (i : ι) → N i i : ι x✝ : i ∈ Finset.univ ⊢ ↑(ϕ i) (f i) ∈ ⨆ (i : ι), mrange (ϕ i) [PROOFSTEP] apply Submonoid.mem_sSup_of_mem [GOAL] case a.intro.hs M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g f : (i : ι) → N i i : ι x✝ : i ∈ Finset.univ ⊢ ?a.intro.s✝ ∈ Set.range fun i => mrange (ϕ i) [PROOFSTEP] use i [GOAL] case a.intro.a M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g f : (i : ι) → N i i : ι x✝ : i ∈ Finset.univ ⊢ ↑(ϕ i) (f i) ∈ (fun i => mrange (ϕ i)) i [PROOFSTEP] simp [GOAL] case a M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → N i ⊢ ⨆ (i : ι), mrange (ϕ i) ≤ mrange (noncommPiCoprod ϕ hcomm) [PROOFSTEP] refine' iSup_le _ [GOAL] case a M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → N i ⊢ ∀ (i : ι), mrange (ϕ i) ≤ mrange (noncommPiCoprod ϕ hcomm) [PROOFSTEP] rintro i x ⟨y, rfl⟩ [GOAL] case a.intro M : Type u_1 inst✝² : Monoid M ι : Type u_2 hdec : DecidableEq ι inst✝¹ : Fintype ι N : ι → Type u_3 inst✝ : (i : ι) → Monoid (N i) ϕ : (i : ι) → N i →* M hcomm : Pairwise fun i j => ∀ (x : N i) (y : N j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → N i i : ι y : N i ⊢ ↑(ϕ i) y ∈ mrange (noncommPiCoprod ϕ hcomm) [PROOFSTEP] refine' ⟨Pi.mulSingle i y, noncommPiCoprod_mulSingle _ _ _⟩ [GOAL] G : Type u_1 inst✝¹ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝ : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → H i ⊢ range (noncommPiCoprod ϕ hcomm) = ⨆ (i : ι), range (ϕ i) [PROOFSTEP] classical apply le_antisymm · rintro x ⟨f, rfl⟩ refine Subgroup.noncommProd_mem _ (fun _ _ _ _ h => hcomm _ _ h _ _) ?_ intro i _hi apply Subgroup.mem_sSup_of_mem · use i simp · refine' iSup_le _ rintro i x ⟨y, rfl⟩ refine' ⟨Pi.mulSingle i y, noncommPiCoprod_mulSingle _ _ _⟩ [GOAL] G : Type u_1 inst✝¹ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝ : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → H i ⊢ range (noncommPiCoprod ϕ hcomm) = ⨆ (i : ι), range (ϕ i) [PROOFSTEP] apply le_antisymm [GOAL] case a G : Type u_1 inst✝¹ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝ : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → H i ⊢ range (noncommPiCoprod ϕ hcomm) ≤ ⨆ (i : ι), range (ϕ i) [PROOFSTEP] rintro x ⟨f, rfl⟩ [GOAL] case a.intro G : Type u_1 inst✝¹ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝ : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g f : (i : ι) → H i ⊢ ↑(noncommPiCoprod ϕ hcomm) f ∈ ⨆ (i : ι), range (ϕ i) [PROOFSTEP] refine Subgroup.noncommProd_mem _ (fun _ _ _ _ h => hcomm _ _ h _ _) ?_ [GOAL] case a.intro G : Type u_1 inst✝¹ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝ : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g f : (i : ι) → H i ⊢ ∀ (c : ι), c ∈ Finset.univ → ↑(ϕ c) (f c) ∈ ⨆ (i : ι), range (ϕ i) [PROOFSTEP] intro i _hi [GOAL] case a.intro G : Type u_1 inst✝¹ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝ : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g f : (i : ι) → H i i : ι _hi : i ∈ Finset.univ ⊢ ↑(ϕ i) (f i) ∈ ⨆ (i : ι), range (ϕ i) [PROOFSTEP] apply Subgroup.mem_sSup_of_mem [GOAL] case a.intro.hs G : Type u_1 inst✝¹ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝ : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g f : (i : ι) → H i i : ι _hi : i ∈ Finset.univ ⊢ ?a.intro.s✝ ∈ Set.range fun i => range (ϕ i) [PROOFSTEP] use i [GOAL] case a.intro.a G : Type u_1 inst✝¹ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝ : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g f : (i : ι) → H i i : ι _hi : i ∈ Finset.univ ⊢ ↑(ϕ i) (f i) ∈ (fun i => range (ϕ i)) i [PROOFSTEP] simp [GOAL] case a G : Type u_1 inst✝¹ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝ : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → H i ⊢ ⨆ (i : ι), range (ϕ i) ≤ range (noncommPiCoprod ϕ hcomm) [PROOFSTEP] refine' iSup_le _ [GOAL] case a G : Type u_1 inst✝¹ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝ : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → H i ⊢ ∀ (i : ι), range (ϕ i) ≤ range (noncommPiCoprod ϕ hcomm) [PROOFSTEP] rintro i x ⟨y, rfl⟩ [GOAL] case a.intro G : Type u_1 inst✝¹ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝ : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → H i i : ι y : H i ⊢ ↑(ϕ i) y ∈ range (noncommPiCoprod ϕ hcomm) [PROOFSTEP] refine' ⟨Pi.mulSingle i y, noncommPiCoprod_mulSingle _ _ _⟩ [GOAL] G : Type u_1 inst✝¹ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝ : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → H i hind : CompleteLattice.Independent fun i => range (ϕ i) hinj : ∀ (i : ι), Function.Injective ↑(ϕ i) ⊢ Function.Injective ↑(noncommPiCoprod ϕ hcomm) [PROOFSTEP] classical apply (MonoidHom.ker_eq_bot_iff _).mp apply eq_bot_iff.mpr intro f heq1 have : ∀ i, i ∈ Finset.univ → ϕ i (f i) = 1 := Subgroup.eq_one_of_noncommProd_eq_one_of_independent _ _ (fun _ _ _ _ h => hcomm _ _ h _ _) _ hind (by simp) heq1 ext i apply hinj simp [this i (Finset.mem_univ i)] [GOAL] G : Type u_1 inst✝¹ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝ : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → H i hind : CompleteLattice.Independent fun i => range (ϕ i) hinj : ∀ (i : ι), Function.Injective ↑(ϕ i) ⊢ Function.Injective ↑(noncommPiCoprod ϕ hcomm) [PROOFSTEP] apply (MonoidHom.ker_eq_bot_iff _).mp [GOAL] G : Type u_1 inst✝¹ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝ : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → H i hind : CompleteLattice.Independent fun i => range (ϕ i) hinj : ∀ (i : ι), Function.Injective ↑(ϕ i) ⊢ ker (noncommPiCoprod ϕ hcomm) = ⊥ [PROOFSTEP] apply eq_bot_iff.mpr [GOAL] G : Type u_1 inst✝¹ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝ : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → H i hind : CompleteLattice.Independent fun i => range (ϕ i) hinj : ∀ (i : ι), Function.Injective ↑(ϕ i) ⊢ ker (noncommPiCoprod ϕ hcomm) ≤ ⊥ [PROOFSTEP] intro f heq1 [GOAL] G : Type u_1 inst✝¹ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝ : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g : (i : ι) → H i hind : CompleteLattice.Independent fun i => range (ϕ i) hinj : ∀ (i : ι), Function.Injective ↑(ϕ i) f : (i : ι) → H i heq1 : f ∈ ker (noncommPiCoprod ϕ hcomm) ⊢ f ∈ ⊥ [PROOFSTEP] have : ∀ i, i ∈ Finset.univ → ϕ i (f i) = 1 := Subgroup.eq_one_of_noncommProd_eq_one_of_independent _ _ (fun _ _ _ _ h => hcomm _ _ h _ _) _ hind (by simp) heq1 [GOAL] G : Type u_1 inst✝¹ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝ : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g : (i : ι) → H i hind : CompleteLattice.Independent fun i => range (ϕ i) hinj : ∀ (i : ι), Function.Injective ↑(ϕ i) f : (i : ι) → H i heq1 : f ∈ ker (noncommPiCoprod ϕ hcomm) ⊢ ∀ (x : ι), x ∈ Finset.univ → ↑(ϕ x) (f x) ∈ range (ϕ x) [PROOFSTEP] simp [GOAL] G : Type u_1 inst✝¹ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝ : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g : (i : ι) → H i hind : CompleteLattice.Independent fun i => range (ϕ i) hinj : ∀ (i : ι), Function.Injective ↑(ϕ i) f : (i : ι) → H i heq1 : f ∈ ker (noncommPiCoprod ϕ hcomm) this : ∀ (i : ι), i ∈ Finset.univ → ↑(ϕ i) (f i) = 1 ⊢ f ∈ ⊥ [PROOFSTEP] ext i [GOAL] case h G : Type u_1 inst✝¹ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝ : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g : (i : ι) → H i hind : CompleteLattice.Independent fun i => range (ϕ i) hinj : ∀ (i : ι), Function.Injective ↑(ϕ i) f : (i : ι) → H i heq1 : f ∈ ker (noncommPiCoprod ϕ hcomm) this : ∀ (i : ι), i ∈ Finset.univ → ↑(ϕ i) (f i) = 1 i : ι ⊢ f i = OfNat.ofNat 1 i [PROOFSTEP] apply hinj [GOAL] case h.a G : Type u_1 inst✝¹ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝ : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g : (i : ι) → H i hind : CompleteLattice.Independent fun i => range (ϕ i) hinj : ∀ (i : ι), Function.Injective ↑(ϕ i) f : (i : ι) → H i heq1 : f ∈ ker (noncommPiCoprod ϕ hcomm) this : ∀ (i : ι), i ∈ Finset.univ → ↑(ϕ i) (f i) = 1 i : ι ⊢ ↑(ϕ i) (f i) = ↑(ϕ i) (OfNat.ofNat 1 i) [PROOFSTEP] simp [this i (Finset.mem_univ i)] [GOAL] G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) ⊢ CompleteLattice.Independent fun i => range (ϕ i) [PROOFSTEP] cases nonempty_fintype ι [GOAL] case intro G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι ⊢ CompleteLattice.Independent fun i => range (ϕ i) [PROOFSTEP] classical rintro i rw [disjoint_iff_inf_le] rintro f ⟨hxi, hxp⟩ dsimp at hxi hxp rw [iSup_subtype', ← noncommPiCoprod_range] at hxp rotate_left · intro _ _ hj apply hcomm exact hj ∘ Subtype.ext cases' hxp with g hgf cases' hxi with g' hg'f have hxi : orderOf f ∣ Fintype.card (H i) := by rw [← hg'f] exact (orderOf_map_dvd _ _).trans orderOf_dvd_card_univ have hxp : orderOf f ∣ ∏ j : { j // j ≠ i }, Fintype.card (H j) := by rw [← hgf, ← Fintype.card_pi] exact (orderOf_map_dvd _ _).trans orderOf_dvd_card_univ change f = 1 rw [← pow_one f, ← orderOf_dvd_iff_pow_eq_one] -- porting note: ouch, had to replace an ugly `convert` obtain ⟨c, hc⟩ := Nat.dvd_gcd hxp hxi use c rw [← hc] symm rw [← Nat.coprime_iff_gcd_eq_one] apply Nat.coprime_prod_left intro j _ apply hcoprime exact j.2 [GOAL] case intro G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι ⊢ CompleteLattice.Independent fun i => range (ϕ i) [PROOFSTEP] rintro i [GOAL] case intro G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι ⊢ Disjoint ((fun i => range (ϕ i)) i) (⨆ (j : ι) (_ : j ≠ i), (fun i => range (ϕ i)) j) [PROOFSTEP] rw [disjoint_iff_inf_le] [GOAL] case intro G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f g : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι ⊢ (fun i => range (ϕ i)) i ⊓ ⨆ (j : ι) (_ : j ≠ i), (fun i => range (ϕ i)) j ≤ ⊥ [PROOFSTEP] rintro f ⟨hxi, hxp⟩ [GOAL] case intro.intro G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxi : f ∈ ↑((fun i => range (ϕ i)) i).toSubmonoid hxp : f ∈ ↑(⨆ (j : ι) (_ : j ≠ i), (fun i => range (ϕ i)) j).toSubmonoid ⊢ f ∈ ⊥ [PROOFSTEP] dsimp at hxi hxp [GOAL] case intro.intro G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxi : f ∈ Set.range ↑(ϕ i) hxp : f ∈ ↑(⨆ (j : ι) (_ : ¬j = i), range (ϕ j)) ⊢ f ∈ ⊥ [PROOFSTEP] rw [iSup_subtype', ← noncommPiCoprod_range] at hxp [GOAL] case intro.intro G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxi : f ∈ Set.range ↑(ϕ i) hxp✝ : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) hxp : f ∈ ↑(range (noncommPiCoprod (fun x => ϕ ↑x) ?intro.intro.hcomm)) ⊢ f ∈ ⊥ case intro.intro.hcomm G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxi : f ∈ Set.range ↑(ϕ i) hxp : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) ⊢ ∀ (i_1 j : { j // ¬j = i }), i_1 ≠ j → ∀ (x : H ↑i_1) (y : H ↑j), Commute (↑(ϕ ↑i_1) x) (↑(ϕ ↑j) y) [PROOFSTEP] rotate_left [GOAL] case intro.intro.hcomm G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxi : f ∈ Set.range ↑(ϕ i) hxp : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) ⊢ ∀ (i_1 j : { j // ¬j = i }), i_1 ≠ j → ∀ (x : H ↑i_1) (y : H ↑j), Commute (↑(ϕ ↑i_1) x) (↑(ϕ ↑j) y) [PROOFSTEP] intro _ _ hj [GOAL] case intro.intro.hcomm G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxi : f ∈ Set.range ↑(ϕ i) hxp : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) i✝ j✝ : { j // ¬j = i } hj : i✝ ≠ j✝ ⊢ ∀ (x : H ↑i✝) (y : H ↑j✝), Commute (↑(ϕ ↑i✝) x) (↑(ϕ ↑j✝) y) [PROOFSTEP] apply hcomm [GOAL] case intro.intro.hcomm.a G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxi : f ∈ Set.range ↑(ϕ i) hxp : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) i✝ j✝ : { j // ¬j = i } hj : i✝ ≠ j✝ ⊢ ↑i✝ ≠ ↑j✝ [PROOFSTEP] exact hj ∘ Subtype.ext [GOAL] case intro.intro G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxi : f ∈ Set.range ↑(ϕ i) hxp✝ : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) hxp : f ∈ ↑(range (noncommPiCoprod (fun x => ϕ ↑x) (_ : ∀ (i_1 j : { j // ¬j = i }), i_1 ≠ j → ∀ (x : H ↑i_1) (y : H ↑j), Commute (↑(ϕ ↑i_1) x) (↑(ϕ ↑j) y)))) ⊢ f ∈ ⊥ [PROOFSTEP] cases' hxp with g hgf [GOAL] case intro.intro.intro G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxi : f ∈ Set.range ↑(ϕ i) hxp : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) g : (i_1 : { j // ¬j = i }) → H ↑i_1 hgf : ↑(noncommPiCoprod (fun x => ϕ ↑x) (_ : ∀ (i_1 j : { j // ¬j = i }), i_1 ≠ j → ∀ (x : H ↑i_1) (y : H ↑j), Commute (↑(ϕ ↑i_1) x) (↑(ϕ ↑j) y))) g = f ⊢ f ∈ ⊥ [PROOFSTEP] cases' hxi with g' hg'f [GOAL] case intro.intro.intro.intro G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxp : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) g : (i_1 : { j // ¬j = i }) → H ↑i_1 hgf : ↑(noncommPiCoprod (fun x => ϕ ↑x) (_ : ∀ (i_1 j : { j // ¬j = i }), i_1 ≠ j → ∀ (x : H ↑i_1) (y : H ↑j), Commute (↑(ϕ ↑i_1) x) (↑(ϕ ↑j) y))) g = f g' : H i hg'f : ↑(ϕ i) g' = f ⊢ f ∈ ⊥ [PROOFSTEP] have hxi : orderOf f ∣ Fintype.card (H i) := by rw [← hg'f] exact (orderOf_map_dvd _ _).trans orderOf_dvd_card_univ [GOAL] G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxp : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) g : (i_1 : { j // ¬j = i }) → H ↑i_1 hgf : ↑(noncommPiCoprod (fun x => ϕ ↑x) (_ : ∀ (i_1 j : { j // ¬j = i }), i_1 ≠ j → ∀ (x : H ↑i_1) (y : H ↑j), Commute (↑(ϕ ↑i_1) x) (↑(ϕ ↑j) y))) g = f g' : H i hg'f : ↑(ϕ i) g' = f ⊢ orderOf f ∣ Fintype.card (H i) [PROOFSTEP] rw [← hg'f] [GOAL] G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxp : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) g : (i_1 : { j // ¬j = i }) → H ↑i_1 hgf : ↑(noncommPiCoprod (fun x => ϕ ↑x) (_ : ∀ (i_1 j : { j // ¬j = i }), i_1 ≠ j → ∀ (x : H ↑i_1) (y : H ↑j), Commute (↑(ϕ ↑i_1) x) (↑(ϕ ↑j) y))) g = f g' : H i hg'f : ↑(ϕ i) g' = f ⊢ orderOf (↑(ϕ i) g') ∣ Fintype.card (H i) [PROOFSTEP] exact (orderOf_map_dvd _ _).trans orderOf_dvd_card_univ [GOAL] case intro.intro.intro.intro G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxp : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) g : (i_1 : { j // ¬j = i }) → H ↑i_1 hgf : ↑(noncommPiCoprod (fun x => ϕ ↑x) (_ : ∀ (i_1 j : { j // ¬j = i }), i_1 ≠ j → ∀ (x : H ↑i_1) (y : H ↑j), Commute (↑(ϕ ↑i_1) x) (↑(ϕ ↑j) y))) g = f g' : H i hg'f : ↑(ϕ i) g' = f hxi : orderOf f ∣ Fintype.card (H i) ⊢ f ∈ ⊥ [PROOFSTEP] have hxp : orderOf f ∣ ∏ j : { j // j ≠ i }, Fintype.card (H j) := by rw [← hgf, ← Fintype.card_pi] exact (orderOf_map_dvd _ _).trans orderOf_dvd_card_univ [GOAL] G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxp : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) g : (i_1 : { j // ¬j = i }) → H ↑i_1 hgf : ↑(noncommPiCoprod (fun x => ϕ ↑x) (_ : ∀ (i_1 j : { j // ¬j = i }), i_1 ≠ j → ∀ (x : H ↑i_1) (y : H ↑j), Commute (↑(ϕ ↑i_1) x) (↑(ϕ ↑j) y))) g = f g' : H i hg'f : ↑(ϕ i) g' = f hxi : orderOf f ∣ Fintype.card (H i) ⊢ orderOf f ∣ ∏ j : { j // j ≠ i }, Fintype.card (H ↑j) [PROOFSTEP] rw [← hgf, ← Fintype.card_pi] [GOAL] G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxp : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) g : (i_1 : { j // ¬j = i }) → H ↑i_1 hgf : ↑(noncommPiCoprod (fun x => ϕ ↑x) (_ : ∀ (i_1 j : { j // ¬j = i }), i_1 ≠ j → ∀ (x : H ↑i_1) (y : H ↑j), Commute (↑(ϕ ↑i_1) x) (↑(ϕ ↑j) y))) g = f g' : H i hg'f : ↑(ϕ i) g' = f hxi : orderOf f ∣ Fintype.card (H i) ⊢ orderOf (↑(noncommPiCoprod (fun x => ϕ ↑x) (_ : ∀ (i_1 j : { j // ¬j = i }), i_1 ≠ j → ∀ (x : H ↑i_1) (y : H ↑j), Commute (↑(ϕ ↑i_1) x) (↑(ϕ ↑j) y))) g) ∣ Fintype.card ((a : { j // j ≠ i }) → H ↑a) [PROOFSTEP] exact (orderOf_map_dvd _ _).trans orderOf_dvd_card_univ [GOAL] case intro.intro.intro.intro G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxp✝ : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) g : (i_1 : { j // ¬j = i }) → H ↑i_1 hgf : ↑(noncommPiCoprod (fun x => ϕ ↑x) (_ : ∀ (i_1 j : { j // ¬j = i }), i_1 ≠ j → ∀ (x : H ↑i_1) (y : H ↑j), Commute (↑(ϕ ↑i_1) x) (↑(ϕ ↑j) y))) g = f g' : H i hg'f : ↑(ϕ i) g' = f hxi : orderOf f ∣ Fintype.card (H i) hxp : orderOf f ∣ ∏ j : { j // j ≠ i }, Fintype.card (H ↑j) ⊢ f ∈ ⊥ [PROOFSTEP] change f = 1 [GOAL] case intro.intro.intro.intro G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxp✝ : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) g : (i_1 : { j // ¬j = i }) → H ↑i_1 hgf : ↑(noncommPiCoprod (fun x => ϕ ↑x) (_ : ∀ (i_1 j : { j // ¬j = i }), i_1 ≠ j → ∀ (x : H ↑i_1) (y : H ↑j), Commute (↑(ϕ ↑i_1) x) (↑(ϕ ↑j) y))) g = f g' : H i hg'f : ↑(ϕ i) g' = f hxi : orderOf f ∣ Fintype.card (H i) hxp : orderOf f ∣ ∏ j : { j // j ≠ i }, Fintype.card (H ↑j) ⊢ f = 1 [PROOFSTEP] rw [← pow_one f, ← orderOf_dvd_iff_pow_eq_one] -- porting note: ouch, had to replace an ugly `convert` [GOAL] case intro.intro.intro.intro G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxp✝ : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) g : (i_1 : { j // ¬j = i }) → H ↑i_1 hgf : ↑(noncommPiCoprod (fun x => ϕ ↑x) (_ : ∀ (i_1 j : { j // ¬j = i }), i_1 ≠ j → ∀ (x : H ↑i_1) (y : H ↑j), Commute (↑(ϕ ↑i_1) x) (↑(ϕ ↑j) y))) g = f g' : H i hg'f : ↑(ϕ i) g' = f hxi : orderOf f ∣ Fintype.card (H i) hxp : orderOf f ∣ ∏ j : { j // j ≠ i }, Fintype.card (H ↑j) ⊢ orderOf f ∣ 1 [PROOFSTEP] obtain ⟨c, hc⟩ := Nat.dvd_gcd hxp hxi [GOAL] case intro.intro.intro.intro.intro G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxp✝ : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) g : (i_1 : { j // ¬j = i }) → H ↑i_1 hgf : ↑(noncommPiCoprod (fun x => ϕ ↑x) (_ : ∀ (i_1 j : { j // ¬j = i }), i_1 ≠ j → ∀ (x : H ↑i_1) (y : H ↑j), Commute (↑(ϕ ↑i_1) x) (↑(ϕ ↑j) y))) g = f g' : H i hg'f : ↑(ϕ i) g' = f hxi : orderOf f ∣ Fintype.card (H i) hxp : orderOf f ∣ ∏ j : { j // j ≠ i }, Fintype.card (H ↑j) c : ℕ hc : Nat.gcd (∏ j : { j // j ≠ i }, Fintype.card (H ↑j)) (Fintype.card (H i)) = orderOf f * c ⊢ orderOf f ∣ 1 [PROOFSTEP] use c [GOAL] case h G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxp✝ : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) g : (i_1 : { j // ¬j = i }) → H ↑i_1 hgf : ↑(noncommPiCoprod (fun x => ϕ ↑x) (_ : ∀ (i_1 j : { j // ¬j = i }), i_1 ≠ j → ∀ (x : H ↑i_1) (y : H ↑j), Commute (↑(ϕ ↑i_1) x) (↑(ϕ ↑j) y))) g = f g' : H i hg'f : ↑(ϕ i) g' = f hxi : orderOf f ∣ Fintype.card (H i) hxp : orderOf f ∣ ∏ j : { j // j ≠ i }, Fintype.card (H ↑j) c : ℕ hc : Nat.gcd (∏ j : { j // j ≠ i }, Fintype.card (H ↑j)) (Fintype.card (H i)) = orderOf f * c ⊢ 1 = orderOf f * c [PROOFSTEP] rw [← hc] [GOAL] case h G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxp✝ : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) g : (i_1 : { j // ¬j = i }) → H ↑i_1 hgf : ↑(noncommPiCoprod (fun x => ϕ ↑x) (_ : ∀ (i_1 j : { j // ¬j = i }), i_1 ≠ j → ∀ (x : H ↑i_1) (y : H ↑j), Commute (↑(ϕ ↑i_1) x) (↑(ϕ ↑j) y))) g = f g' : H i hg'f : ↑(ϕ i) g' = f hxi : orderOf f ∣ Fintype.card (H i) hxp : orderOf f ∣ ∏ j : { j // j ≠ i }, Fintype.card (H ↑j) c : ℕ hc : Nat.gcd (∏ j : { j // j ≠ i }, Fintype.card (H ↑j)) (Fintype.card (H i)) = orderOf f * c ⊢ 1 = Nat.gcd (∏ j : { j // j ≠ i }, Fintype.card (H ↑j)) (Fintype.card (H i)) [PROOFSTEP] symm [GOAL] case h G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxp✝ : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) g : (i_1 : { j // ¬j = i }) → H ↑i_1 hgf : ↑(noncommPiCoprod (fun x => ϕ ↑x) (_ : ∀ (i_1 j : { j // ¬j = i }), i_1 ≠ j → ∀ (x : H ↑i_1) (y : H ↑j), Commute (↑(ϕ ↑i_1) x) (↑(ϕ ↑j) y))) g = f g' : H i hg'f : ↑(ϕ i) g' = f hxi : orderOf f ∣ Fintype.card (H i) hxp : orderOf f ∣ ∏ j : { j // j ≠ i }, Fintype.card (H ↑j) c : ℕ hc : Nat.gcd (∏ j : { j // j ≠ i }, Fintype.card (H ↑j)) (Fintype.card (H i)) = orderOf f * c ⊢ Nat.gcd (∏ j : { j // j ≠ i }, Fintype.card (H ↑j)) (Fintype.card (H i)) = 1 [PROOFSTEP] rw [← Nat.coprime_iff_gcd_eq_one] [GOAL] case h G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxp✝ : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) g : (i_1 : { j // ¬j = i }) → H ↑i_1 hgf : ↑(noncommPiCoprod (fun x => ϕ ↑x) (_ : ∀ (i_1 j : { j // ¬j = i }), i_1 ≠ j → ∀ (x : H ↑i_1) (y : H ↑j), Commute (↑(ϕ ↑i_1) x) (↑(ϕ ↑j) y))) g = f g' : H i hg'f : ↑(ϕ i) g' = f hxi : orderOf f ∣ Fintype.card (H i) hxp : orderOf f ∣ ∏ j : { j // j ≠ i }, Fintype.card (H ↑j) c : ℕ hc : Nat.gcd (∏ j : { j // j ≠ i }, Fintype.card (H ↑j)) (Fintype.card (H i)) = orderOf f * c ⊢ Nat.coprime (∏ j : { j // j ≠ i }, Fintype.card (H ↑j)) (Fintype.card (H i)) [PROOFSTEP] apply Nat.coprime_prod_left [GOAL] case h.a G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxp✝ : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) g : (i_1 : { j // ¬j = i }) → H ↑i_1 hgf : ↑(noncommPiCoprod (fun x => ϕ ↑x) (_ : ∀ (i_1 j : { j // ¬j = i }), i_1 ≠ j → ∀ (x : H ↑i_1) (y : H ↑j), Commute (↑(ϕ ↑i_1) x) (↑(ϕ ↑j) y))) g = f g' : H i hg'f : ↑(ϕ i) g' = f hxi : orderOf f ∣ Fintype.card (H i) hxp : orderOf f ∣ ∏ j : { j // j ≠ i }, Fintype.card (H ↑j) c : ℕ hc : Nat.gcd (∏ j : { j // j ≠ i }, Fintype.card (H ↑j)) (Fintype.card (H i)) = orderOf f * c ⊢ ∀ (i_1 : { j // j ≠ i }), i_1 ∈ Finset.univ → Nat.coprime (Fintype.card (H ↑i_1)) (Fintype.card (H i)) [PROOFSTEP] intro j _ [GOAL] case h.a G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxp✝ : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) g : (i_1 : { j // ¬j = i }) → H ↑i_1 hgf : ↑(noncommPiCoprod (fun x => ϕ ↑x) (_ : ∀ (i_1 j : { j // ¬j = i }), i_1 ≠ j → ∀ (x : H ↑i_1) (y : H ↑j), Commute (↑(ϕ ↑i_1) x) (↑(ϕ ↑j) y))) g = f g' : H i hg'f : ↑(ϕ i) g' = f hxi : orderOf f ∣ Fintype.card (H i) hxp : orderOf f ∣ ∏ j : { j // j ≠ i }, Fintype.card (H ↑j) c : ℕ hc : Nat.gcd (∏ j : { j // j ≠ i }, Fintype.card (H ↑j)) (Fintype.card (H i)) = orderOf f * c j : { j // j ≠ i } a✝ : j ∈ Finset.univ ⊢ Nat.coprime (Fintype.card (H ↑j)) (Fintype.card (H i)) [PROOFSTEP] apply hcoprime [GOAL] case h.a.a G : Type u_1 inst✝³ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Type u_3 inst✝² : (i : ι) → Group (H i) ϕ : (i : ι) → H i →* G hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), Commute (↑(ϕ i) x) (↑(ϕ j) y) f✝ g✝ : (i : ι) → H i inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype (H i) hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card (H i)) (Fintype.card (H j)) val✝ : Fintype ι i : ι f : G hxp✝ : f ∈ ↑(⨆ (x : { j // ¬j = i }), range (ϕ ↑x)) g : (i_1 : { j // ¬j = i }) → H ↑i_1 hgf : ↑(noncommPiCoprod (fun x => ϕ ↑x) (_ : ∀ (i_1 j : { j // ¬j = i }), i_1 ≠ j → ∀ (x : H ↑i_1) (y : H ↑j), Commute (↑(ϕ ↑i_1) x) (↑(ϕ ↑j) y))) g = f g' : H i hg'f : ↑(ϕ i) g' = f hxi : orderOf f ∣ Fintype.card (H i) hxp : orderOf f ∣ ∏ j : { j // j ≠ i }, Fintype.card (H ↑j) c : ℕ hc : Nat.gcd (∏ j : { j // j ≠ i }, Fintype.card (H ↑j)) (Fintype.card (H i)) = orderOf f * c j : { j // j ≠ i } a✝ : j ∈ Finset.univ ⊢ ↑j ≠ i [PROOFSTEP] exact j.2 [GOAL] G : Type u_1 inst✝ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Subgroup G f g : (i : ι) → { x // x ∈ H i } hcomm : ∀ (i j : ι), i ≠ j → ∀ (x y : G), x ∈ H i → y ∈ H j → Commute x y i j : ι hne : i ≠ j ⊢ ∀ (x : { x // x ∈ H i }) (y : { x // x ∈ H j }), Commute (↑(Subgroup.subtype (H i)) x) (↑(Subgroup.subtype (H j)) y) [PROOFSTEP] rintro ⟨x, hx⟩ ⟨y, hy⟩ [GOAL] case mk.mk G : Type u_1 inst✝ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Subgroup G f g : (i : ι) → { x // x ∈ H i } hcomm : ∀ (i j : ι), i ≠ j → ∀ (x y : G), x ∈ H i → y ∈ H j → Commute x y i j : ι hne : i ≠ j x : G hx : x ∈ H i y : G hy : y ∈ H j ⊢ Commute (↑(Subgroup.subtype (H i)) { val := x, property := hx }) (↑(Subgroup.subtype (H j)) { val := y, property := hy }) [PROOFSTEP] exact hcomm i j hne x y hx hy [GOAL] G : Type u_1 inst✝ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Subgroup G f g : (i : ι) → { x // x ∈ H i } hcomm : ∀ (i j : ι), i ≠ j → ∀ (x y : G), x ∈ H i → y ∈ H j → Commute x y i : ι y : { x // x ∈ H i } ⊢ ↑(noncommPiCoprod hcomm) (Pi.mulSingle i y) = ↑y [PROOFSTEP] apply MonoidHom.noncommPiCoprod_mulSingle [GOAL] G : Type u_1 inst✝ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Subgroup G f g : (i : ι) → { x // x ∈ H i } hcomm : ∀ (i j : ι), i ≠ j → ∀ (x y : G), x ∈ H i → y ∈ H j → Commute x y ⊢ MonoidHom.range (noncommPiCoprod hcomm) = ⨆ (i : ι), H i [PROOFSTEP] simp [noncommPiCoprod, MonoidHom.noncommPiCoprod_range] [GOAL] G : Type u_1 inst✝ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Subgroup G f g : (i : ι) → { x // x ∈ H i } hcomm : ∀ (i j : ι), i ≠ j → ∀ (x y : G), x ∈ H i → y ∈ H j → Commute x y hind : CompleteLattice.Independent H ⊢ Function.Injective ↑(noncommPiCoprod hcomm) [PROOFSTEP] apply MonoidHom.injective_noncommPiCoprod_of_independent [GOAL] case hind G : Type u_1 inst✝ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Subgroup G f g : (i : ι) → { x // x ∈ H i } hcomm : ∀ (i j : ι), i ≠ j → ∀ (x y : G), x ∈ H i → y ∈ H j → Commute x y hind : CompleteLattice.Independent H ⊢ CompleteLattice.Independent fun i => MonoidHom.range (Subgroup.subtype ((fun i => H i) i)) [PROOFSTEP] simpa using hind [GOAL] case hinj G : Type u_1 inst✝ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Subgroup G f g : (i : ι) → { x // x ∈ H i } hcomm : ∀ (i j : ι), i ≠ j → ∀ (x y : G), x ∈ H i → y ∈ H j → Commute x y hind : CompleteLattice.Independent H ⊢ ∀ (i : ι), Function.Injective ↑(Subgroup.subtype ((fun i => H i) i)) [PROOFSTEP] intro i [GOAL] case hinj G : Type u_1 inst✝ : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Subgroup G f g : (i : ι) → { x // x ∈ H i } hcomm : ∀ (i j : ι), i ≠ j → ∀ (x y : G), x ∈ H i → y ∈ H j → Commute x y hind : CompleteLattice.Independent H i : ι ⊢ Function.Injective ↑(Subgroup.subtype ((fun i => H i) i)) [PROOFSTEP] exact Subtype.coe_injective [GOAL] G : Type u_1 inst✝² : Group G ι : Type u_2 hdec : DecidableEq ι hfin : Fintype ι H : ι → Subgroup G f g : (i : ι) → { x // x ∈ H i } hcomm : ∀ (i j : ι), i ≠ j → ∀ (x y : G), x ∈ H i → y ∈ H j → Commute x y inst✝¹ : Finite ι inst✝ : (i : ι) → Fintype { x // x ∈ H i } hcoprime : ∀ (i j : ι), i ≠ j → Nat.coprime (Fintype.card { x // x ∈ H i }) (Fintype.card { x // x ∈ H j }) ⊢ CompleteLattice.Independent H [PROOFSTEP] simpa using MonoidHom.independent_range_of_coprime_order (fun i => (H i).subtype) (commute_subtype_of_commute hcomm) hcoprime
lemma continuous_on_components_open: fixes S :: "'a::real_normed_vector set" assumes "open S " "\<And>c. c \<in> components S \<Longrightarrow> continuous_on c f" shows "continuous_on S f"
[STATEMENT] lemma below_less_iff [iff]: "i \<in> below k \<longleftrightarrow> i < k" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (i \<in> below k) = (i < k) [PROOF STEP] by (simp add: below_def)
FUNCTION:NAME :BEGIN -- @@stderr -- dtrace: script 'test/unittest/drops/drp.DTRACEDROP_SPECUNAVAIL.d' matched 5 probes dtrace: [DTRACEDROP_SPECUNAVAIL] 3 failed speculations (no speculative buffer available: No such process
theory T177 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) " nitpick[card nat=4,timeout=86400] oops end
Formal statement is: lemma lmeasurable_open: "bounded S \<Longrightarrow> open S \<Longrightarrow> S \<in> lmeasurable" Informal statement is: If $S$ is a bounded open set, then $S$ is Lebesgue measurable.
lemma open_Collect_less_Int: fixes f g :: "'a::topological_space \<Rightarrow> real" assumes f: "continuous_on s f" and g: "continuous_on s g" shows "\<exists>A. open A \<and> A \<inter> s = {x\<in>s. f x < g x}"
lemma locally_path_connected_components: "\<lbrakk>locally path_connected S; c \<in> components S\<rbrakk> \<Longrightarrow> locally path_connected c"
South of Heaven was Slayer 's second album to enter the Billboard 200 , and its last to be released by Def Jam Recordings , although the album became an American Recordings album after Rick Rubin ended his partnership with Russell Simmons . It was one of only two Def Jam titles to be distributed by Geffen Records through Warner Bros. Records because of original distributor Columbia Records ' refusal to release work by the band . The release peaked at number 57 and in 1992 was awarded a gold certification by the Recording Industry Association of America .
Formal statement is: lemma ksimplex_0: "ksimplex p 0 s \<longleftrightarrow> s = {(\<lambda>x. p)}" Informal statement is: A $k$-simplex of dimension $0$ is a single point.
#include "rtfw/detail/core.hpp" #include "rtfw/detail/util.hpp" #include "propertytree.hpp" #include <iostream> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/ini_parser.hpp> namespace rtfw{ namespace detail{ using namespace std::literals::chrono_literals; namespace pt = propertytree; namespace bpt = boost::property_tree; namespace { bool file_exists(const std::string& path){ std::ifstream f{path}; return f.good(); } template<class Iter> std::string join(Iter iter, Iter end){ std::string out{}; while(iter != end){ out += *iter; ++iter; if(iter != end) out.push_back('.'); else break; } return out; } void print_keys(const pt::Dict& d, std::vector<std::string>& stack){ for(const auto& [key, node] : d){ stack.push_back(key.cast<std::string>()); if(node.type() == pt::Node::Type::Dict){ print_keys(node.as_dict(), stack); } else{ std::cerr << join(stack.begin(), stack.end()) << '\n'; } stack.pop_back(); } } void validate_config_files(const pt::Dict& mod_confs, const pt::Dict& file_confs){ auto tmp = file_confs; tmp -= mod_confs; if(!tmp.empty()){ std::cerr << "\nWARNING: unsupported configurations in config files:\n"; std::vector<std::string> stack; print_keys(tmp, stack); std::cerr << '\n'; } } template<class Iter> pt::Node read_ini_file(Iter iter, Iter end){ pt::Node result{pt::Dict()}; while(iter != end){ if(file_exists(*iter)){ bpt::ptree tree; bpt::read_ini(*iter, tree); result.as_dict().right_union(pt::Node{tree}.as_dict()); } else{ std::cerr << "file " << *iter << " not found. Skipping\n"; } ++iter; } return result; } pt::Node populate_configs(pt::Node&& confs){ std::vector<std::string> ini_files{"rtfw.ini"}; auto from_files = read_ini_file(ini_files.begin(), ini_files.end()); validate_config_files(confs.as_dict(), from_files.as_dict()); confs.as_dict().right_union(from_files.as_dict()); return confs; } pt::Node invoke_configs(List& module_list){ auto* iter = module_list.first(); pt::Node dict{pt::Dict()}; while(iter){ auto* ptr = static_cast<ModuleHolder*>(iter); std::cerr << "configuring " << ptr->name() << '\n'; auto& conf = ptr->config(); if(conf.name() == "") conf.name() = ptr->name(); if(dict.as_dict().count(conf.name())) throw std::runtime_error("Conflicting module names"); pt::Node tmp{std::move(conf)}; dict.as_dict().left_union(tmp.as_dict()); iter = List::next(*iter); } return dict; } void init(List& init_stack, List& module_list, const pt::Node& configs){ ListHead* iterator = module_list.first(); while(iterator){ auto* target = iterator; iterator = List::next(*iterator); init_stack.push_back(*target); std::cerr << "initializing " << static_cast<ModuleHolder*>(target)->name() << '\n'; static_cast<ModuleHolder*>(target)->init(rtfw::Config()); module_list.push_front(*target); } } void deinit(List& module_list){ ListHead* iterator = module_list.first(); while(iterator){ auto* target = static_cast<ModuleHolder*>(iterator); std::cerr << "destroying " << target->name() << '\n'; iterator = List::next(*iterator); target->clear(); } } } Core::Core(){} Core::~Core(){} void Core::run(){ // Lambda is called in object destructor Defer defer{[&](){ setup_ = false; }}; setup_ = false; rtfw_thread_id_ = std::this_thread::get_id(); auto configs = invoke_configs(ModuleHolder::instances); configs = populate_configs(std::move(configs)); init(init_stack_, ModuleHolder::instances, configs); setup_ = true; std::this_thread::sleep_for(1s); deinit(ModuleHolder::instances); } Core core{}; } }
Formal statement is: lemma Bseq_iff: "Bseq X \<longleftrightarrow> (\<exists>N. \<forall>n. norm (X n) \<le> real(Suc N))" Informal statement is: A sequence $X$ is bounded if and only if there exists a natural number $N$ such that $|X_n| \leq N$ for all $n$.
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.monoidal.coherence /-! # Monoidal opposites We write `Cᵐᵒᵖ` for the monoidal opposite of a monoidal category `C`. -/ universes v₁ v₂ u₁ u₂ variables {C : Type u₁} namespace category_theory open category_theory.monoidal_category /-- A type synonym for the monoidal opposite. Use the notation `Cᴹᵒᵖ`. -/ @[nolint has_inhabited_instance] def monoidal_opposite (C : Type u₁) := C namespace monoidal_opposite notation C `ᴹᵒᵖ`:std.prec.max_plus := monoidal_opposite C /-- Think of an object of `C` as an object of `Cᴹᵒᵖ`. -/ @[pp_nodot] def mop (X : C) : Cᴹᵒᵖ := X /-- Think of an object of `Cᴹᵒᵖ` as an object of `C`. -/ @[pp_nodot] def unmop (X : Cᴹᵒᵖ) : C := X lemma op_injective : function.injective (mop : C → Cᴹᵒᵖ) := λ _ _, id lemma unop_injective : function.injective (unmop : Cᴹᵒᵖ → C) := λ _ _, id @[simp] lemma op_inj_iff (x y : C) : mop x = mop y ↔ x = y := iff.rfl @[simp] lemma unop_inj_iff (x y : Cᴹᵒᵖ) : unmop x = unmop y ↔ x = y := iff.rfl attribute [irreducible] monoidal_opposite @[simp] lemma mop_unmop (X : Cᴹᵒᵖ) : mop (unmop X) = X := rfl @[simp] lemma unmop_mop (X : C) : unmop (mop X) = X := rfl instance monoidal_opposite_category [I : category.{v₁} C] : category Cᴹᵒᵖ := { hom := λ X Y, unmop X ⟶ unmop Y, id := λ X, 𝟙 (unmop X), comp := λ X Y Z f g, f ≫ g, } end monoidal_opposite end category_theory open category_theory open category_theory.monoidal_opposite variables [category.{v₁} C] /-- The monoidal opposite of a morphism `f : X ⟶ Y` is just `f`, thought of as `mop X ⟶ mop Y`. -/ def quiver.hom.mop {X Y : C} (f : X ⟶ Y) : @quiver.hom Cᴹᵒᵖ _ (mop X) (mop Y) := f /-- We can think of a morphism `f : mop X ⟶ mop Y` as a morphism `X ⟶ Y`. -/ def quiver.hom.unmop {X Y : Cᴹᵒᵖ} (f : X ⟶ Y) : unmop X ⟶ unmop Y := f namespace category_theory lemma mop_inj {X Y : C} : function.injective (quiver.hom.mop : (X ⟶ Y) → (mop X ⟶ mop Y)) := λ _ _ H, congr_arg quiver.hom.unmop H lemma unmop_inj {X Y : Cᴹᵒᵖ} : function.injective (quiver.hom.unmop : (X ⟶ Y) → (unmop X ⟶ unmop Y)) := λ _ _ H, congr_arg quiver.hom.mop H @[simp] lemma unmop_mop {X Y : C} {f : X ⟶ Y} : f.mop.unmop = f := rfl @[simp] lemma mop_unmop {X Y : Cᴹᵒᵖ} {f : X ⟶ Y} : f.unmop.mop = f := rfl @[simp] lemma mop_comp {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} : (f ≫ g).mop = f.mop ≫ g.mop := rfl @[simp] lemma mop_id {X : C} : (𝟙 X).mop = 𝟙 (mop X) := rfl @[simp] lemma unmop_comp {X Y Z : Cᴹᵒᵖ} {f : X ⟶ Y} {g : Y ⟶ Z} : (f ≫ g).unmop = f.unmop ≫ g.unmop := rfl @[simp] lemma unmop_id {X : Cᴹᵒᵖ} : (𝟙 X).unmop = 𝟙 (unmop X) := rfl @[simp] lemma unmop_id_mop {X : C} : (𝟙 (mop X)).unmop = 𝟙 X := rfl @[simp] lemma mop_id_unmop {X : Cᴹᵒᵖ} : (𝟙 (unmop X)).mop = 𝟙 X := rfl namespace iso variables {X Y : C} /-- An isomorphism in `C` gives an isomorphism in `Cᴹᵒᵖ`. -/ @[simps] def mop (f : X ≅ Y) : mop X ≅ mop Y := { hom := f.hom.mop, inv := f.inv.mop, hom_inv_id' := unmop_inj f.hom_inv_id, inv_hom_id' := unmop_inj f.inv_hom_id } end iso variables [monoidal_category.{v₁} C] open opposite monoidal_category instance monoidal_category_op : monoidal_category Cᵒᵖ := { tensor_obj := λ X Y, op (unop X ⊗ unop Y), tensor_hom := λ X₁ Y₁ X₂ Y₂ f g, (f.unop ⊗ g.unop).op, tensor_unit := op (𝟙_ C), associator := λ X Y Z, (α_ (unop X) (unop Y) (unop Z)).symm.op, left_unitor := λ X, (λ_ (unop X)).symm.op, right_unitor := λ X, (ρ_ (unop X)).symm.op, associator_naturality' := by { intros, apply quiver.hom.unop_inj, simp, }, left_unitor_naturality' := by { intros, apply quiver.hom.unop_inj, simp, }, right_unitor_naturality' := by { intros, apply quiver.hom.unop_inj, simp, }, triangle' := by { intros, apply quiver.hom.unop_inj, coherence, }, pentagon' := by { intros, apply quiver.hom.unop_inj, coherence, }, } lemma op_tensor_obj (X Y : Cᵒᵖ) : X ⊗ Y = op (unop X ⊗ unop Y) := rfl lemma op_tensor_unit : (𝟙_ Cᵒᵖ) = op (𝟙_ C) := rfl instance monoidal_category_mop : monoidal_category Cᴹᵒᵖ := { tensor_obj := λ X Y, mop (unmop Y ⊗ unmop X), tensor_hom := λ X₁ Y₁ X₂ Y₂ f g, (g.unmop ⊗ f.unmop).mop, tensor_unit := mop (𝟙_ C), associator := λ X Y Z, (α_ (unmop Z) (unmop Y) (unmop X)).symm.mop, left_unitor := λ X, (ρ_ (unmop X)).mop, right_unitor := λ X, (λ_ (unmop X)).mop, associator_naturality' := by { intros, apply unmop_inj, simp, }, left_unitor_naturality' := by { intros, apply unmop_inj, simp, }, right_unitor_naturality' := by { intros, apply unmop_inj, simp, }, triangle' := by { intros, apply unmop_inj, coherence, }, pentagon' := by { intros, apply unmop_inj, coherence, }, } lemma mop_tensor_obj (X Y : Cᴹᵒᵖ) : X ⊗ Y = mop (unmop Y ⊗ unmop X) := rfl lemma mop_tensor_unit : (𝟙_ Cᴹᵒᵖ) = mop (𝟙_ C) := rfl end category_theory
= = Life and career = =
lemma closed_real: fixes s :: "real set" shows "closed s \<longleftrightarrow> (\<forall>x. (\<forall>e>0. \<exists>x' \<in> s. x' \<noteq> x \<and> \<bar>x' - x\<bar> < e) \<longrightarrow> x \<in> s)"
Kelsey Nelson is an Ohio-an gone South Carolina. After journalism school at Ohio University, Kelsey started her career in communications in Cleveland and now works for a Greenville-based advertising agency. A runner and a foodie, you can find Kelsey on the trails or eating her way through her new town. Hopefully not at the same time.
Formal statement is: lemma smallo_powr_nonneg: fixes f :: "'a \<Rightarrow> real" assumes "f \<in> o[F](g)" "p > 0" "eventually (\<lambda>x. f x \<ge> 0) F" "eventually (\<lambda>x. g x \<ge> 0) F" shows "(\<lambda>x. f x powr p) \<in> o[F](\<lambda>x. g x powr p)" Informal statement is: If $f(x)$ is small compared to $g(x)$ and both $f(x)$ and $g(x)$ are eventually nonnegative, then $f(x)^p$ is small compared to $g(x)^p$.
State Before: R : Type u_2 inst✝¹¹ : CommSemiring R l : Type u_1 m : Type ?u.2073940 n : Type ?u.2073943 inst✝¹⁰ : Fintype n inst✝⁹ : Fintype m inst✝⁸ : DecidableEq n M₁ : Type u_3 M₂ : Type u_4 inst✝⁷ : AddCommMonoid M₁ inst✝⁶ : AddCommMonoid M₂ inst✝⁵ : Module R M₁ inst✝⁴ : Module R M₂ v₁ : Basis n R M₁ v₂ : Basis m R M₂ M₃ : Type ?u.2074466 inst✝³ : AddCommMonoid M₃ inst✝² : Module R M₃ v₃ : Basis l R M₃ inst✝¹ : Fintype l inst✝ : DecidableEq l b : Basis l R M₁ b' : Basis l R M₂ ⊢ ↑(toMatrix b' b) ↑(Basis.equiv b' b (Equiv.refl l)) = 1 State After: case a.h R : Type u_2 inst✝¹¹ : CommSemiring R l : Type u_1 m : Type ?u.2073940 n : Type ?u.2073943 inst✝¹⁰ : Fintype n inst✝⁹ : Fintype m inst✝⁸ : DecidableEq n M₁ : Type u_3 M₂ : Type u_4 inst✝⁷ : AddCommMonoid M₁ inst✝⁶ : AddCommMonoid M₂ inst✝⁵ : Module R M₁ inst✝⁴ : Module R M₂ v₁ : Basis n R M₁ v₂ : Basis m R M₂ M₃ : Type ?u.2074466 inst✝³ : AddCommMonoid M₃ inst✝² : Module R M₃ v₃ : Basis l R M₃ inst✝¹ : Fintype l inst✝ : DecidableEq l b : Basis l R M₁ b' : Basis l R M₂ i j : l ⊢ ↑(toMatrix b' b) (↑(Basis.equiv b' b (Equiv.refl l))) i j = OfNat.ofNat 1 i j Tactic: ext (i j) State Before: case a.h R : Type u_2 inst✝¹¹ : CommSemiring R l : Type u_1 m : Type ?u.2073940 n : Type ?u.2073943 inst✝¹⁰ : Fintype n inst✝⁹ : Fintype m inst✝⁸ : DecidableEq n M₁ : Type u_3 M₂ : Type u_4 inst✝⁷ : AddCommMonoid M₁ inst✝⁶ : AddCommMonoid M₂ inst✝⁵ : Module R M₁ inst✝⁴ : Module R M₂ v₁ : Basis n R M₁ v₂ : Basis m R M₂ M₃ : Type ?u.2074466 inst✝³ : AddCommMonoid M₃ inst✝² : Module R M₃ v₃ : Basis l R M₃ inst✝¹ : Fintype l inst✝ : DecidableEq l b : Basis l R M₁ b' : Basis l R M₂ i j : l ⊢ ↑(toMatrix b' b) (↑(Basis.equiv b' b (Equiv.refl l))) i j = OfNat.ofNat 1 i j State After: no goals Tactic: simp [LinearMap.toMatrix_apply, Matrix.one_apply, Finsupp.single_apply, eq_comm]
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import data.nat.parity import order.filter.at_top_bot /-! # Numbers are frequently modeq to fixed numbers In this file we prove that `m ≡ d [MOD n]` frequently as `m → ∞`. -/ open filter namespace nat /-- Infinitely many natural numbers are equal to `d` mod `n`. -/ lemma frequently_mod_eq {d n : ℕ} (h : d < n) : ∃ᶠ m in at_top, m % n = d := by simpa only [nat.modeq, mod_eq_of_lt h] using frequently_modeq h.ne_bot d lemma frequently_even : ∃ᶠ m : ℕ in at_top, even m := by simpa only [even_iff] using frequently_mod_eq zero_lt_two lemma frequently_odd : ∃ᶠ m : ℕ in at_top, odd m := by simpa only [odd_iff] using frequently_mod_eq one_lt_two end nat
[STATEMENT] lemma sshiftr_uint64_code [code]: "signed_drop_bit_uint64 n x = (if n < 64 then uint64_sshiftr x (integer_of_nat n) else if bit x 63 then - 1 else 0)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. signed_drop_bit_uint64 n x = (if n < 64 then uint64_sshiftr x (integer_of_nat n) else if bit x 63 then - 1 else 0) [PROOF STEP] including undefined_transfer integer.lifting [PROOF STATE] proof (prove) goal (1 subgoal): 1. signed_drop_bit_uint64 n x = (if n < 64 then uint64_sshiftr x (integer_of_nat n) else if bit x 63 then - 1 else 0) [PROOF STEP] unfolding uint64_sshiftr_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. signed_drop_bit_uint64 n x = (if n < 64 then if integer_of_nat n < 0 \<or> 64 \<le> integer_of_nat n then undefined signed_drop_bit_uint64 (integer_of_nat n) x else signed_drop_bit_uint64 (nat_of_integer (integer_of_nat n)) x else if bit x 63 then - 1 else 0) [PROOF STEP] by transfer (simp add: not_less signed_drop_bit_beyond)
{- Byzantine Fault Tolerant Consensus Verification in Agda, version 0.9. Copyright (c) 2021, Oracle and/or its affiliates. Licensed under the Universal Permissive License v 1.0 as shown at https://opensource.oracle.com/licenses/upl -} open import LibraBFT.Impl.OBM.Rust.RustTypes module LibraBFT.Impl.OBM.Rust.Duration where record Duration : Set where constructor Duration∙new postulate -- TODO-1 : fromMillis, asMillis fromMillis : U64 → Duration asMillis : Duration → U128
var t1 : int := 0; var t2 : int := 1; var t3 : int := t1 + t2; var nTimes : int := 0; print "nth term? "; read nTimes; var x : int; for x in 2..nTimes-1 do t1:=t2; t2:=t3; t3:=t1+t2; end for; print t3; print "\n";
(* Copyright (C) 2017 M.A.L. Marques This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. *) (* type: work_gga_c *) $define lda_c_pw_params $define lda_c_pw_modified_params $include "lda_c_pw.mpl" malpha := 2.804: mgamma := 0.8098: XX := s -> 1/(1 + malpha*s^2): ff := s -> XX(s) + mgamma*(1 - XX(s)): f := (rs, z, xt, xs0, xs1) -> f_pw(rs, z)*( + (1 + z)/2 * ff(X2S*xs0) + (1 - z)/2 * ff(X2S*xs1) ):
-- --------------------------------------------------------- [ Categorical.idr ] module Data.ML.Categorical import public Data.ML.Util %access export catToNum : (Num n, Cast Bool n, Ord a) => List a -> List (List n) catToNum xs = [ cast . (== cat) <$> xs | cat <- unique xs ] -- --------------------------------------------------------------------- [ EOF ]
[STATEMENT] lemma cp_OclSize: "X->size\<^sub>S\<^sub>e\<^sub>t() \<tau> = ((\<lambda>_. X \<tau>)->size\<^sub>S\<^sub>e\<^sub>t()) \<tau>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. X->size\<^sub>S\<^sub>e\<^sub>t() \<tau> = \<lambda>_. X \<tau>->size\<^sub>S\<^sub>e\<^sub>t() \<tau> [PROOF STEP] by(simp add: OclSize_def cp_defined[symmetric])
(* Title: HOL/Auth/n_mutualExFsm_on_inis.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_mutualExFsm Protocol Case Study*} theory n_mutualExFsm_on_inis imports n_mutualExFsm_on_ini begin lemma on_inis: assumes b1: "f \<in> (invariants N)" and b2: "ini \<in> {andList (allInitSpecs N)}" and b3: "formEval ini s" shows "formEval f s" proof - have c1: "(\<exists> p__Inv0 p__Inv1. p__Inv0\<le>N\<and>p__Inv1\<le>N\<and>p__Inv0~=p__Inv1\<and>f=inv__1 p__Inv0 p__Inv1)\<or> (\<exists> p__Inv0. p__Inv0\<le>N\<and>f=inv__2 p__Inv0)\<or> (\<exists> p__Inv0 p__Inv1. p__Inv0\<le>N\<and>p__Inv1\<le>N\<and>p__Inv0~=p__Inv1\<and>f=inv__3 p__Inv0 p__Inv1)\<or> (\<exists> p__Inv0. p__Inv0\<le>N\<and>f=inv__4 p__Inv0)\<or> (\<exists> p__Inv0 p__Inv1. p__Inv0\<le>N\<and>p__Inv1\<le>N\<and>p__Inv0~=p__Inv1\<and>f=inv__5 p__Inv0 p__Inv1)" apply (cut_tac b1, simp) done moreover { assume d1: "(\<exists> p__Inv0 p__Inv1. p__Inv0\<le>N\<and>p__Inv1\<le>N\<and>p__Inv0~=p__Inv1\<and>f=inv__1 p__Inv0 p__Inv1)" have "formEval f s" apply (rule iniImply_inv__1) apply (cut_tac d1, assumption) apply (cut_tac b2 b3, blast) done } moreover { assume d1: "(\<exists> p__Inv0. p__Inv0\<le>N\<and>f=inv__2 p__Inv0)" have "formEval f s" apply (rule iniImply_inv__2) apply (cut_tac d1, assumption) apply (cut_tac b2 b3, blast) done } moreover { assume d1: "(\<exists> p__Inv0 p__Inv1. p__Inv0\<le>N\<and>p__Inv1\<le>N\<and>p__Inv0~=p__Inv1\<and>f=inv__3 p__Inv0 p__Inv1)" have "formEval f s" apply (rule iniImply_inv__3) apply (cut_tac d1, assumption) apply (cut_tac b2 b3, blast) done } moreover { assume d1: "(\<exists> p__Inv0. p__Inv0\<le>N\<and>f=inv__4 p__Inv0)" have "formEval f s" apply (rule iniImply_inv__4) apply (cut_tac d1, assumption) apply (cut_tac b2 b3, blast) done } moreover { assume d1: "(\<exists> p__Inv0 p__Inv1. p__Inv0\<le>N\<and>p__Inv1\<le>N\<and>p__Inv0~=p__Inv1\<and>f=inv__5 p__Inv0 p__Inv1)" have "formEval f s" apply (rule iniImply_inv__5) apply (cut_tac d1, assumption) apply (cut_tac b2 b3, blast) done } ultimately show "formEval f s" by satx qed end
(************************************************************ * Lambda-calculus with exceptions and sums, * * Encoding of exceptions into sums * *************************************************************) Set Implicit Arguments. Require Export LambdaExnSum_Syntax. Implicit Types v : val. Implicit Types t : trm. (*==========================================================*) (* * Definitions *) (************************************************************) (* ** Variables introduced by the translation *) Parameter x1 x2 x3 : var. Parameter x1_neq_x2 : x1 <> x2. Parameter x1_neq_x3 : x1 <> x3. Parameter x2_neq_x3 : x2 <> x3. Definition L := x1::x2::x3::nil. Lemma L_eq : L = x1::x2::x3::nil. Proof. auto. Defined. Global Opaque L. Hint Resolve x1_neq_x2 x2_neq_x3 x1_neq_x3. Hint Extern 1 (_ \notin _) => rewrite L_eq in *. Coercion trm_var : var >-> trm. (************************************************************) (* ** Definition of the translation *) Definition tr_ret t := trm_inj true t. Definition tr_exn t := trm_inj false t. Definition tr_bind t' x k := trm_case t' (trm_abs x k) (trm_abs x (tr_exn (trm_var x))). Definition tr_cont t' := trm_abs x2 (tr_bind t' x3 (trm_app x3 x2)). Fixpoint tr_trm (t:trm) : trm := let s := tr_trm in match t with | trm_val v => tr_ret (tr_val v) | trm_var y => tr_ret t | trm_abs y t3 => tr_ret (trm_abs y (s t3)) | trm_app t1 t2 => tr_bind (s t1) x1 (tr_bind (s t2) x2 (trm_app x1 x2)) | trm_inj b t1 => tr_bind (s t1) x1 (tr_ret (trm_inj b x1)) | trm_case t1 t2 t3 => tr_bind (s t1) x1 (trm_case x1 (tr_cont (s t2)) (tr_cont (s t3))) | trm_try t1 t2 => trm_case (s t1) (trm_abs x1 (tr_ret x1)) (tr_cont (s t2)) | trm_raise t1 => tr_bind (s t1) x1 (tr_exn x1) end with tr_val (v:val) : val := match v with | val_abs y t3 => val_abs y (tr_trm t3) | val_inj b v1 => val_inj b (tr_val v1) | _ => v end. (*==========================================================*) (* * Proofs *) (************************************************************) (* * Freshness *) (** Distribution of substitution over the translation *) Ltac imp x := try rewrite L_eq in *; asserts: (x \notin \{x}); [ auto | notin_false ]. Ltac imp_any := solve [ imp x1 | imp x2 | imp x3 ]. Ltac neq_any := solve [ false x1_neq_x2; assumption | false x1_neq_x3; assumption | false x2_neq_x3; assumption ]. Ltac simpl_subst := repeat (case_if; subst; try neq_any; try imp_any). Lemma tr_val_subst : forall x v t, fresh (trm_vars not_used t \u \{x}) 3 L -> tr_trm (subst x v t) = subst x (tr_val v) (tr_trm t). Proof. induction t; introv F; simpls. fequals. simpl_subst; fequals. simpl_subst; fequals. rewrite~ IHt. simpl_subst. rewrite~ IHt1. rewrite~ IHt2. simpl_subst. rewrite~ IHt. simpl_subst. rewrite~ IHt1. rewrite~ IHt2. rewrite~ IHt3. simpl_subst. rewrite~ IHt1. rewrite~ IHt2. simpl_subst. rewrite~ IHt. Qed. Lemma subst_tr_bind : forall t x k y v, x <> y -> subst y v (tr_bind t x k) = tr_bind (subst y v t) x (subst y v k). Proof. introv N. simpl. case_if. fequals. Qed. Lemma subst_tr_cont : forall t y v, fresh (\{y}) 2 (x2::x3::nil) -> subst y v (tr_cont t) = tr_cont (subst y v t). Proof. introv H. simpl. simpl_subst. fequals. Qed. Lemma tr_trm_vars : forall t, fresh (trm_vars not_used t) 3 L -> fresh (trm_vars not_free (tr_trm t)) 3 L with tr_val_vars : forall v, fresh (trm_vars not_used v) 3 L -> fresh (trm_vars not_free (tr_val v)) 3 L. Proof. (* trm *) induction t; introv F; simpls. apply~ tr_val_vars. auto. applys~ fresh_remove_weaken. specializes~ IHt1. specializes~ IHt2. fset_simpl. do 2 (rewrite union_remove; [ | apply~ notin_elim_single ]). auto. specializes~ IHt. fset_simpl. auto. specializes~ IHt1. specializes~ IHt2. specializes~ IHt3. fset_simpl. rewrite (@union_remove' _ \{x2}); [ | apply~ notin_elim_single ]. do 2 (rewrite union_remove; [ | apply~ notin_elim_single ]). rewrite union_remove'; [ | apply~ notin_elim_single ]. auto. specializes~ IHt1. specializes~ IHt2. fset_simpl. rewrite union_remove'; [ | apply~ notin_elim_single ]. rewrite union_remove; [ | apply~ notin_elim_single ]. auto. specializes~ IHt. fset_simpl. auto. (* val *) induction v; introv F; simpls. auto. applys fresh_remove_weaken. applys~ tr_trm_vars. auto. Qed.