diff --git a/Project.toml b/Project.toml index 5c254e8..f935ffe 100644 --- a/Project.toml +++ b/Project.toml @@ -3,10 +3,10 @@ uuid = "2fff4b78-0b6c-428d-bac8-85ccea8c4bdf" version = "0.4.0" [deps] -DelimitedFiles = "8bb1440f-4735-579b-a4ab-409b98df4dab" ExaModels = "1037b233-b668-4ce9-9b63-f9f681f55dd2" ExaPowerIO = "14903efe-9500-4d7f-a589-7ab7e15da6de" JSON = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" +PowerIO = "05ed8b54-f668-4096-9d0d-e8c3dd9dc169" [weakdeps] ExaModelsCompiler = "3d1e9a26-5b74-4f0c-9a2b-7c8f4e11d3a7" @@ -18,6 +18,7 @@ ExaModelsPowerExaModelsCompilerExt = "ExaModelsCompiler" ExaModels = "0.11" ExaPowerIO = "0.3" JSON = "0.21" +PowerIO = "0.9" julia = "1.11" [sources] diff --git a/src/ExaModelsPower.jl b/src/ExaModelsPower.jl index 2ce84b1..8731e8b 100644 --- a/src/ExaModelsPower.jl +++ b/src/ExaModelsPower.jl @@ -1,15 +1,14 @@ module ExaModelsPower import ExaModels: ExaModels, ExaCore, @add_var, @add_par, @add_con, @add_obj, @add_con!, ExaModel, convert_array, solution -using DelimitedFiles -using ExaPowerIO +using ExaPowerIO # the bundled PGLib-OPF directory, and nothing else using JSON +using PowerIO # Parsers and data stay separate from the models that consume them. -include("parser.jl") # matpower -> the tables every model is built from +include("parser.jl") # case file -> the tables every model is built from include("constraint.jl") # the algebraic expressions, shared by all three -include("goc3_parser.jl") # GOC3-specific parsing -include("sc_parser.jl") # " +include("sc_parser.jl") # GOC3-specific parsing include("opf.jl") # static: polar, rect, DC include("mpopf.jl") # multi-period: polar, rect, DC diff --git a/src/goc3.jl b/src/goc3.jl index 99cd888..c9cc67a 100644 --- a/src/goc3.jl +++ b/src/goc3.jl @@ -10,12 +10,11 @@ function goc3_model( uc_data = JSON.parsefile(uc_filename) - data = get_data_from_file(filename) - data_json = JSON.parsefile(filename) - sc_data, lengths, producers_first = parse_sc_data(data, uc_data, data_json) + data = PowerIO.parse_goc3_json(filename) + sc_data, lengths, producers_first = parse_sc_data(data, uc_data) @info "parsed data" - (L_J_xf, L_J_ln, L_J_ac, L_J_dc, L_J_br, L_J_cs, + (; L_J_xf, L_J_ln, L_J_ac, L_J_dc, L_J_br, L_J_cs, L_J_pr, L_J_cspr, L_J_sh, I, L_T, L_N_p, L_N_q, L_W_en_min_pr, L_W_en_min_cs, L_W_en_max_pr, L_W_en_max_cs, K) = lengths diff --git a/src/goc3_parser.jl b/src/goc3_parser.jl deleted file mode 100644 index 44d4ea8..0000000 --- a/src/goc3_parser.jl +++ /dev/null @@ -1,105 +0,0 @@ -# The source code below is adapted from GOC3Benchmark.jl (https://github.com/lanl-ansi/GOC3Benchmark.jl) - -# Copyright © 2019, Triad National Security, LLC -# All rights reserved. - -# This software was produced under U.S. Government contract 89233218CNA000001 for Los Alamos National Laboratory (LANL), which is operated by Triad National Security, LLC for the U.S. Department of Energy/National Nuclear Security Administration. All rights in the program are reserved by Triad National Security, LLC, and the U.S. Department of Energy/National Nuclear Security Administration. The Government is granted for itself and others acting on its behalf a nonexclusive, paid-up, irrevocable worldwide license in this material to reproduce, prepare derivative works, distribute copies to the public, perform publicly and display publicly, and to permit others to do so. - -# This program is open source under the BSD-3 License. - -# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. -# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -""" -Process data from input (problem) file into a more convenient form. - -`data` should be the dict obtained by parsing an input JSON file. -The return type is a NamedTuple with fields that are useful for constructing -the scheduling and ACOPF models. - -""" -function process_input_data(data::Dict)::NamedTuple - dt = data["time_series_input"]["general"]["interval_duration"] - periods = 1:data["time_series_input"]["general"]["time_periods"] - @assert(length(dt) == length(periods)) - - bus_lookup = Dict(sdd["uid"] => sdd for sdd in data["network"]["bus"]) - # NOTE: We never check inclusion in these IDs, so no reason for them - # to be arbitrary-order KeySets as opposed to sorted Vectors. - bus_ids = sort([uid for uid in keys(bus_lookup)]) - - shunt_lookup = Dict(sdd["uid"] => sdd for sdd in data["network"]["shunt"]) - shunt_ids = sort([uid for uid in keys(shunt_lookup)]) - - ac_line_lookup = Dict(sdd["uid"] => sdd for sdd in data["network"]["ac_line"]) - ac_line_ids = sort([uid for uid in keys(ac_line_lookup)]) - - twt_lookup = Dict(sdd["uid"] => sdd for sdd in data["network"]["two_winding_transformer"]) - twt_ids = sort([uid for uid in keys(twt_lookup)]) - - dc_line_lookup = Dict(sdd["uid"] => sdd for sdd in data["network"]["dc_line"]) - dc_line_ids = sort([uid for uid in keys(dc_line_lookup)]) - - sdd_lookup = Dict(sdd["uid"] => sdd for sdd in data["network"]["simple_dispatchable_device"]) - sdd_ts_lookup = Dict(sdd["uid"] => sdd for sdd in data["time_series_input"]["simple_dispatchable_device"]) - sdd_ids = sort([uid for uid in keys(sdd_lookup)]) - - sdd_ids_producer = sort([uid for (uid,sdd) in sdd_lookup if sdd["device_type"]=="producer"]) - sdd_ids_consumer = sort([uid for (uid,sdd) in sdd_lookup if sdd["device_type"]=="consumer"]) - - azr_key = "active_zonal_reserve" - azr_lookup = Dict(zone["uid"] => zone for zone in data["network"][azr_key]) - azr_ts_lookup = Dict(zone["uid"] => zone for zone in data["time_series_input"][azr_key]) - azr_ids = sort([zone for zone in keys(azr_lookup)]) - - rzr_key = "reactive_zonal_reserve" - rzr_lookup = Dict(zone["uid"] => zone for zone in data["network"][rzr_key]) - rzr_ts_lookup = Dict(zone["uid"] => zone for zone in data["time_series_input"][rzr_key]) - rzr_ids = sort([zone for zone in keys(rzr_lookup)]) - - data_tuple = ( - dt = dt, - periods = periods, - bus_lookup = bus_lookup, - bus_ids = bus_ids, - shunt_lookup = shunt_lookup, - shunt_ids = shunt_ids, - ac_line_lookup = ac_line_lookup, - ac_line_ids = ac_line_ids, - twt_lookup = twt_lookup, - twt_ids = twt_ids, - dc_line_lookup = dc_line_lookup, - dc_line_ids = dc_line_ids, - sdd_lookup = sdd_lookup, - sdd_ts_lookup = sdd_ts_lookup, - sdd_ids = sdd_ids, - sdd_ids_producer = sdd_ids_producer, - sdd_ids_consumer = sdd_ids_consumer, - violation_cost = data["network"]["violation_cost"], - azr_lookup = azr_lookup, - azr_ts_lookup = azr_ts_lookup, - azr_ids = azr_ids, - rzr_lookup = rzr_lookup, - rzr_ts_lookup = rzr_ts_lookup, - rzr_ids = rzr_ids, - ) - return data_tuple -end - - -function get_data_from_file(input_file::String; process_data = true) - data = Dict{String, Any}() - open(input_file, "r") do io - data = JSON.parse(io) - end - if process_data - # NOTE: Type-unstable - data = process_input_data(data) - end - return data -end diff --git a/src/mpopf.jl b/src/mpopf.jl index 68348fc..2a71d78 100644 --- a/src/mpopf.jl +++ b/src/mpopf.jl @@ -1,23 +1,32 @@ +# The load series and the powerdata come off the SAME parsed network, so row +# `k` of `series.pd` and `data.bus[k]` are the same bus by construction. +# Reparsing the file for each would align them only by coincidence. +# # `::Type{T}`, not a `Type`-typed value — the same fault the static parser had: -# as a plain argument it arrives abstract and `parse_ac_power_data` cannot -# specialize, so every field read off the result widens. -parse_mp_power_data(filename, N, r) = parse_mp_power_data(filename, N, r, Float64) -function parse_mp_power_data(filename, N, corrective_action_ratio, ::Type{T}) where {T} - - raw = parse_ac_power_data(filename, T) +# as a plain argument it arrives abstract and the parse cannot specialize, so +# every field read off the result widens. +parse_mp_power_data(net, series, N, r) = parse_mp_power_data(net, series, N, r, Float64) +function parse_mp_power_data(net, series, N, corrective_action_ratio, ::Type{T}) where {T} - nbus = length(raw.bus) + raw = PowerIO.parse_ac_power_data(net; T = T) + _check_periods(series, N) # No empty-storage ternary: its two branches had DIFFERENT types (a vector # of one NamedTuple shape against a matrix of another), which made the whole # return non-concrete — the same fault the static parser had. A comprehension # over empty storage is a well-typed 0xN matrix on its own. + # + # The per-period loads are merged onto each bus row as the array is built, + # so `busarray` is constructed once rather than built and then mutated. The + # rows are `@NamedTuple`s and `merge` keeps their field order, so the + # element type stays isbits and the GPU backends accept it. data = ( ; raw..., refarray = [(i,t) for i in raw.ref_buses, t in 1:N], barray = [(;b, t = t) for b in raw.branch, t in 1:N ], - busarray = [(;b, t = t) for b in raw.bus, t in 1:N ], + busarray = [(; b = merge(b, (; pd = series.pd[k, t], qd = series.qd[k, t])), t = t) + for (k, b) in enumerate(raw.bus), t in 1:N], arcarray = [(;a, t = t) for a in raw.arc, t in 1:N ], genarray = [(;g, t = t) for g in raw.gen, t in 1:N ], storarray = [(;s, t = t) for s in raw.storage, t in 1:N], @@ -28,57 +37,32 @@ function parse_mp_power_data(filename, N, corrective_action_ratio, ::Type{T}) wh return data end -function update_load_data(busarray, curve) - - for t in eachindex(curve) - for x in 1:size(busarray, 1) - b = busarray[x, t] - busarray[x, t] = ( - b=ExaPowerIO.BusData{typeof(b.b.pd)}( - b.b.i, - b.b.bus_i, - b.b.type, - b.b.pd*curve[t], - b.b.qd*curve[t], - b.b.gs*curve[t], - b.b.bs*curve[t], - b.b.area, - b.b.vm, - b.b.va, - b.b.baseKV, - b.b.zone, - b.b.vmax, - b.b.vmin, - ), t=t - ) - end - end +function _check_periods(series, N) + n = PowerIO.n_periods(series) + N <= n || throw( + DimensionMismatch( + "a horizon of $N periods was asked for, but the load series has $n", + ), + ) + return nothing end -#Pd, Qd as input -function update_load_data(busarray, pd, qd, baseMVA) - for (idx ,pd_t) in pairs(pd) - b = busarray[idx[1], idx[2]] - busarray[idx[1], idx[2]] = ( - b=ExaPowerIO.BusData{typeof(b.b.pd)}( - b.b.i, - b.b.bus_i, - b.b.type, - pd_t / baseMVA, - qd[idx[1], idx[2]] / baseMVA, - b.b.gs, - b.b.bs, - b.b.area, - b.b.vm, - b.b.va, - b.b.baseKV, - b.b.zone, - b.b.vmax, - b.b.vmin, - ), - t=idx[2], - ) +# Both load matrices, or neither. One of the two leaves the other at its +# base-case value with no sign that half the input was ignored. +function _load_series(net, pd_path, qd_path, pd, qd, ::Type{T}) where {T} + if pd === nothing && qd === nothing + return PowerIO.read_load_series(net, pd_path, qd_path; T = T) + elseif pd !== nothing && qd !== nothing + return PowerIO.LoadSeries(net, pd, qd; T = T) end + throw( + ArgumentError( + "mpopf_model: pass both `pd` and `qd` as in-memory matrices, or neither " * + "(to read both from the given load files). Got pd=" * + (pd === nothing ? "nothing" : "a matrix") * ", qd=" * + (qd === nothing ? "nothing" : "a matrix") * ".", + ), + ) end #If no storage contraints, the "build_base_mpopf" returns the final version of the mpopf @@ -157,7 +141,8 @@ library can call. Define your own one-argument wrapper in your package for a different curve. """ mpopf_args_default(filename) = - mpopf_args(filename, MPOPF_DEFAULT_CURVE, length(MPOPF_DEFAULT_CURVE), Float64, nothing, 0.1) + mpopf_args(filename, MPOPF_DEFAULT_CURVE, length(MPOPF_DEFAULT_CURVE), Float64, nothing, + 0.1, nothing) """ mpopf_args(filename, curve; N, T, backend, corrective_action_ratio) -> (data,) @@ -178,15 +163,17 @@ elementwise past 31 fields, which would leave the whole argument tuple with concrete names and no value types. """ mpopf_args(filename, curve; N = length(curve), T = Float64, backend = nothing, - corrective_action_ratio = 0.1) = - mpopf_args(filename, curve, N, T, backend, corrective_action_ratio) + corrective_action_ratio = 0.1, from = nothing) = + mpopf_args(filename, curve, N, T, backend, corrective_action_ratio, from) # The positional method is the one a compiled library reaches: `::Type{T}` makes # `T` a static parameter, where the keyword form leaves it a `Type`-typed value # nothing downstream can specialize on. -function mpopf_args(filename, curve, N, ::Type{T}, backend, corrective_action_ratio) where {T} - d = parse_mp_power_data(filename, N, corrective_action_ratio, T) - update_load_data(d.busarray, curve) +function mpopf_args(filename, curve, N, ::Type{T}, backend, corrective_action_ratio, + from = nothing) where {T} + net = parse_mp_network(filename; from = from) + d = parse_mp_power_data(net, PowerIO.LoadSeries(net, curve; T = T), N, + corrective_action_ratio, T) return (convert_data(_mp_narrow(d, N, T), backend),) end @@ -633,13 +620,14 @@ function mpopf_model( backend = nothing, form::OPFForm = Polar(), T = Float64, + from = nothing, storage_complementarity_constraint = false, user_callback = dummy_extension, kwargs..., ) @assert length(curve) > 0 - data, = mpopf_args(filename, curve; N, T, backend, corrective_action_ratio) + data, = mpopf_args(filename, curve; N, T, backend, corrective_action_ratio, from) Nbus = length(data.bus) return build_mpopf(data, Nbus, N, form, user_callback, backend = backend, T = T, storage_complementarity_constraint = storage_complementarity_constraint, kwargs...) @@ -648,25 +636,27 @@ end function mpopf_model( filename, active_power_data, reactive_power_data; - pd = readdlm(active_power_data), - qd = readdlm(reactive_power_data), - N = size(pd, 2), + pd = nothing, + qd = nothing, + N = nothing, corrective_action_ratio = 0.1, backend = nothing, form::OPFForm = Polar(), T = Float64, + from = nothing, storage_complementarity_constraint = false, user_callback = dummy_extension, kwargs..., ) - d = parse_mp_power_data(filename, N, corrective_action_ratio, T) - update_load_data(d.busarray, pd, qd, d.baseMVA[]) - data = convert_data(_mp_narrow(d, N, T), backend) + net = parse_mp_network(filename; from = from) + series = _load_series(net, active_power_data, reactive_power_data, pd, qd, T) + Np = N === nothing ? PowerIO.n_periods(series) : N + d = parse_mp_power_data(net, series, Np, corrective_action_ratio, T) + data = convert_data(_mp_narrow(d, Np, T), backend) Nbus = length(data.bus) - @assert Nbus == size(pd, 1) - return build_mpopf(data, Nbus, N, form, user_callback, backend = backend, T = T, storage_complementarity_constraint = storage_complementarity_constraint, kwargs...) + return build_mpopf(data, Nbus, Np, form, user_callback, backend = backend, T = T, storage_complementarity_constraint = storage_complementarity_constraint, kwargs...) end @@ -678,12 +668,13 @@ function mpopf_model( backend = nothing, form::OPFForm = Polar(), T = Float64, + from = nothing, user_callback = dummy_extension, kwargs..., ) @assert length(curve) > 0 - data, = mpopf_args(filename, curve; N, T, backend, corrective_action_ratio) + data, = mpopf_args(filename, curve; N, T, backend, corrective_action_ratio, from) Nbus = length(data.bus) return build_mpopf(data, Nbus, N, discharge_func, form,user_callback, backend = backend, T = T, kwargs...) @@ -692,25 +683,26 @@ end function mpopf_model( filename, active_power_data, reactive_power_data, discharge_func::Function; - pd = readdlm(active_power_data), - qd = readdlm(reactive_power_data), - N = size(pd, 2), + pd = nothing, + qd = nothing, + N = nothing, corrective_action_ratio = 0.1, backend = nothing, form::OPFForm = Polar(), T = Float64, + from = nothing, storage_complementarity_constraint = false, user_callback = dummy_extension, kwargs..., ) - - d = parse_mp_power_data(filename, N, corrective_action_ratio, T) - update_load_data(d.busarray, pd, qd, d.baseMVA[]) - data = convert_data(_mp_narrow(d, N, T), backend) + net = parse_mp_network(filename; from = from) + series = _load_series(net, active_power_data, reactive_power_data, pd, qd, T) + Np = N === nothing ? PowerIO.n_periods(series) : N + d = parse_mp_power_data(net, series, Np, corrective_action_ratio, T) + data = convert_data(_mp_narrow(d, Np, T), backend) Nbus = length(data.bus) - @assert Nbus == size(pd, 1) - return build_mpopf(data, Nbus, N, discharge_func, form,user_callback, backend = backend, T = T, kwargs...) + return build_mpopf(data, Nbus, Np, discharge_func, form,user_callback, backend = backend, T = T, kwargs...) end diff --git a/src/opf.jl b/src/opf.jl index 8b7079a..946b5d8 100644 --- a/src/opf.jl +++ b/src/opf.jl @@ -97,14 +97,14 @@ args = opf_args("pglib_opf_case118_ieee.m"; start = (vm = d -> d.vm0, va = d -> model = ExaModel(ac_opf_recipe()[1], args...) ``` """ -opf_args(filename; T = Float64, backend = nothing, start = (;)) = - opf_args(filename, T, backend, start) +opf_args(filename; T = Float64, backend = nothing, start = (;), from = nothing) = + opf_args(filename, T, backend, start, from) # The positional method is the one a compiled library calls: `::Type{T}` makes # `T` a static parameter, where the keyword form leaves it a `Type`-typed value # that nothing downstream can specialize on. -function opf_args(filename, ::Type{T}, backend = nothing, start = (;)) where {T} - p = parse_ac_power_data(filename, T) +function opf_args(filename, ::Type{T}, backend = nothing, start = (;), from = nothing) where {T} + p = parse_ac_power_data(filename, T; from = from) s = merge(_default_start(T), NamedTuple(start)) bus, gen, arc, branch = p.bus, p.gen, p.arc, p.branch nbus, ngen, narc, nbranch = length(bus), length(gen), length(arc), length(branch) @@ -387,11 +387,12 @@ function opf_model( form::OPFForm = Polar(), user_callback = dummy_extension, start = (;), + from = nothing, kwargs..., ) core, vars, cons = opf_recipe(; backend = backend, T = T, form = form, user_callback = user_callback) - args = opf_args(filename; T = T, backend = backend, start = start) + args = opf_args(filename; T = T, backend = backend, start = start, from = from) model = ExaModel(core, args...; prod = true, kwargs...) # The handles come out of the RECIPE, so their offsets are ArgNode # expressions; `solution(result, v)` cannot index with those. Resolve them diff --git a/src/parser.jl b/src/parser.jl index d7b20ea..ce6074d 100644 --- a/src/parser.jl +++ b/src/parser.jl @@ -9,66 +9,26 @@ convert_data(data::NamedTuple, backend) = map(d -> _convert_field(d, backend), d _convert_field(d, backend) = convert_array(d, backend) _convert_field(d::NamedTuple, backend) = convert_data(d, backend) +# A case name that is not a path on disk is looked up in the bundled PGLib-OPF +# directory, which is the one thing ExaPowerIO is still here for. +_case_path(filename) = + isfile(filename) ? filename : joinpath(ExaPowerIO.get_path(:pglib), filename) + # `T` is a TYPE PARAMETER, not a value of type `Type`. As a plain positional -# argument it arrives typed `Type` — abstract — and then `parse_matpower(T, …)` -# cannot specialize, so its result is an unparameterized `PowerData` and every -# field read off it widens to `AbstractArray{BusData{T}} where T`. Written -# `::Type{T}` it is a static parameter and the whole chain stays concrete. +# argument it arrives typed `Type` — abstract — and then the parse cannot +# specialize, so its result is an unparameterized NamedTuple and every field +# read off it widens to `AbstractArray{BusRow{T}} where T`. Written `::Type{T}` +# it is a static parameter and the whole chain stays concrete. parse_ac_power_data(filename) = parse_ac_power_data(filename, Float64) -function parse_ac_power_data(filename, ::Type{T}) where {T} - _, f = splitdir(filename) - name, _ = splitext(f) - - @info "Loading matpower file" - - # Branch on the CALL, not on the keyword. A `library` of - # `Union{Nothing,Symbol}` leaves `parse_matpower`'s return type - # uninferable, and every field assembled from it below then infers as - # `Any`. Measured: given either value concretely, `parse_matpower` returns - # a fully concrete `PowerData{Float64, Vector{BusData{Float64}}, …}` — so - # the instability was ours, not the parser's. - raw = - isfile(filename) ? ExaPowerIO.parse_matpower(T, filename; library = nothing) : - ExaPowerIO.parse_matpower(T, filename; library = :pglib) - - # `raw`, not a second binding called `data`. Assigning the same name twice - # while a closure captures it — the `ref_buses` comprehension does — makes - # Julia box it as a `Core.Box`, whose contents are `Any`. That single box - # was what made the whole function infer as `Any`, and it is invisible in - # the source: both assignments are perfectly ordinary. - # - # The storage fields below are NOT special-cased on emptiness. A ternary - # whose branches return different types (`Vector{NamedTuple{(:i,)}}` when - # empty, `Vector{T}` otherwise) makes this whole NamedTuple non-concrete, - # which is the other half of the same instability. An empty - # `Vector{StorageData{T}}` iterates to an empty `Vector{T}` on its own, so - # the guard bought nothing and cost the return type. - data = ( - baseMVA = [raw.baseMVA], - bus = raw.bus, - gen = raw.gen, - arc = raw.arc, - branch = raw.branch, - storage = raw.storage, - ref_buses = [i for i in 1:length(raw.bus) if raw.bus[i].type == 3], - vmax = [bu.vmax for bu in raw.bus], - vmin = [bu.vmin for bu in raw.bus], - pmax = [g.pmax for g in raw.gen], - pmin = [g.pmin for g in raw.gen], - qmax = [g.qmax for g in raw.gen], - qmin = [g.qmin for g in raw.gen], - angmax = [br.angmax for br in raw.branch], - angmin = [br.angmin for br in raw.branch], - rate_a = [a.rate_a for a in raw.arc], - vm0 = [b.vm for b in raw.bus], - va0 = [b.va for b in raw.bus], - pg0 = [g.pg for g in raw.gen], - qg0 = [g.qg for g in raw.gen], - pdmax = [s.charge_rating for s in raw.storage], - pcmax = [s.discharge_rating for s in raw.storage], - srating = [s.thermal_rating for s in raw.storage], - emax = [s.energy_rating for s in raw.storage], - ) +function parse_ac_power_data(filename, ::Type{T}; from = nothing) where {T} + @info "Loading power case file" + return PowerIO.parse_ac_power_data(_case_path(filename); from = from, T = T) +end - return data +# Resolve a case name to a parsed network. The same network feeds both the +# powerdata NamedTuple and the LoadSeries, so their bus order aligns by +# construction rather than by assumption. +function parse_mp_network(filename; from = nothing) + @info "Loading power case file" + return PowerIO.parse_file(_case_path(filename); from = from) end diff --git a/src/sc_parser.jl b/src/sc_parser.jl index c60b895..c17ec16 100644 --- a/src/sc_parser.jl +++ b/src/sc_parser.jl @@ -1,12 +1,11 @@ -is_pr(uid::Int, L_J_pr::Int, L_J_cs::Int, producers_first::Bool)::Bool = producers_first ? uid < L_J_pr : uid >= L_J_cs -function is_pr(uid_str::String, L_J_pr::Int, L_J_cs::Int, producers_first::Bool)::Bool - uid = parse(Int, match(r"\d+", uid_str).match) - is_pr(uid, L_J_pr, L_J_cs, producers_first) -end - -function get_j_prcs(uid_str::String, L_J_pr::Int, L_J_cs::Int, producers_first::Bool) +# PowerIO (src/goc3.jl) returns the general GOC3 topology and time-series rows, +# keyed by uid and per-class index. The stacked global variable numbering used +# below (j, j_pr, j_cs, j_prcs, j_sh: offsets into one variable vector) is +# specific to this optimization model, so it is defined and threaded on here. +is_pr(uid::Int, L_J_pr::Int, L_J_cs::Int, producers_first::Bool)::Bool = + producers_first ? uid < L_J_pr : uid >= L_J_cs +get_j_prcs(uid_str::String, L_J_pr::Int, L_J_cs::Int, producers_first::Bool) = parse(Int, match(r"\d+", uid_str).match) + 1 -end function get_j_pr(uid_str::String, L_J_pr::Int, L_J_cs::Int, producers_first::Bool) offset = Int64(producers_first ? 0 : (-L_J_cs)) @@ -18,857 +17,241 @@ function get_j_cs(uid_str::String, L_J_pr::Int, L_J_cs::Int, producers_first::Bo parse(Int, match(r"\d+", uid_str).match) + 1 + offset end -function parse_sc_data_static(data, producers_first) - L_J_xf = length(data.twt_lookup) - L_J_ln = length(data.ac_line_lookup) - L_J_ac = L_J_ln + L_J_xf - L_J_dc = length(data.dc_line_lookup) - L_J_br = L_J_ac + L_J_dc - L_J_cs = length(data.sdd_ids_consumer) - L_J_pr = length(data.sdd_ids_producer) - L_J_cspr = L_J_cs + L_J_pr - L_J_sh = length(data.shunt_lookup) - L_N_p = length(data.azr_lookup) - L_N_q = length(data.rzr_lookup) - I = length(data.bus_lookup) - L_T = length(data.dt) - - lengths = (L_J_xf=L_J_xf, L_J_ln=L_J_ln, L_J_ac=L_J_ac, L_J_dc=L_J_dc, L_J_br=L_J_br, L_J_cs=L_J_cs, - L_J_pr=L_J_pr, L_J_cspr = L_J_cspr, L_J_sh=L_J_sh, I=I, L_T=L_T, L_N_p, L_N_q) - - ε_time = 1e-6 - - cost_vector_pr = sort( - #producers - [ - begin - ts_val = data.sdd_ts_lookup[key] - j = parse(Int, match(r"\d+", val["uid"]).match) + L_J_br + 1 - j_prcs = get_j_prcs(val["uid"], L_J_pr, L_J_cs, producers_first) - j_pr = get_j_pr(val["uid"], L_J_pr, L_J_cs, producers_first) - bus = parse(Int, match(r"\d+", val["bus"]).match) + 1 - uid = val["uid"] - cost = ts_val["cost"] - (j = j, bus=bus, uid = uid, cost=cost, j_pr=j_pr, j_prcs=j_prcs) - end for (key, val) in data.sdd_lookup if val["device_type"] == "producer" - - ], by = x -> x.j) - - #Consumers - cost_vector_cs = sort( - [ - begin - ts_val = data.sdd_ts_lookup[key] - j = parse(Int, match(r"\d+", val["uid"]).match) + L_J_br + 1 - j_prcs = get_j_prcs(val["uid"], L_J_pr, L_J_cs, producers_first) - j_cs = get_j_cs(val["uid"], L_J_pr, L_J_cs, producers_first) - bus = parse(Int, match(r"\d+", val["bus"]).match) + 1 - uid = val["uid"] - cost = ts_val["cost"] - (j = j, bus=bus, uid = uid, cost=cost, j_cs=j_cs, j_prcs=j_prcs) - end for (key, val) in data.sdd_lookup if val["device_type"] == "consumer" - ], by = x -> x.j) - - - sc_data = ( - bus = sort([ - begin - i = parse(Int, match(r"\d+", val["uid"]).match)+1 - uid = val["uid"] - v_min = val["vm_lb"] - v_max = val["vm_ub"] - (i = i, uid = uid, v_min = v_min, v_max = v_max) - end for val in values(data.bus_lookup) - ], by = x -> x.i), - - shunt = sort([ - begin - j = parse(Int, match(r"\d+", val["uid"]).match) + L_J_br + L_J_cspr+1 - j_sh = parse(Int, match(r"\d+", val["uid"]).match)+1 - uid = val["uid"] - bus = parse(Int, match(r"\d+", val["bus"]).match)+1 - g_sh = val["gs"] - b_sh = val["bs"] - (j = j, j_sh=j_sh, uid = uid, bus=bus, g_sh = g_sh, b_sh = b_sh) - end for val in values(data.shunt_lookup) - ], by = x -> x.j), - - acl_branch = sort( - # AC lines - [ - begin - j = parse(Int, match(r"\d+", val["uid"]).match)+1 - j_ac = j - j_ln = j - uid = val["uid"] - to_bus = parse(Int, match(r"\d+", val["to_bus"]).match)+1 - fr_bus = parse(Int, match(r"\d+", val["fr_bus"]).match)+1 - c_su = Float64(val["connection_cost"]) - c_sd = Float64(val["disconnection_cost"]) - s_max = Float64(val["mva_ub_nom"]) - r = Float64(val["r"]) - x = Float64(val["x"]) - g_sr = Float64(r / (x^2 + r^2)) - b_sr = Float64(-x / (x^2 + r^2)) - b_ch = Float64(val["b"]) - if val["additional_shunt"] == 1 - g_fr = Float64(val["g_fr"]) - g_to = Float64(val["g_to"]) - b_fr = Float64(val["b_fr"]) - b_to = Float64(val["b_to"]) - else - g_fr = 0.0 - g_to = 0.0 - b_fr = 0.0 - b_to = 0.0 - end - (j = j, j_ac = j_ac, j_ln = j_ln, uid = uid, to_bus = to_bus, fr_bus = fr_bus, c_su = c_su, c_sd = c_sd, s_max = s_max, - g_sr = g_sr, b_sr = b_sr, b_ch = b_ch, g_fr = g_fr, g_to = g_to, b_fr = b_fr, b_to = b_to) - end for val in values(data.ac_line_lookup) - ],by = x -> x.j), - - # Transformers - acx_branch = sort( - [ - begin - j_xf = parse(Int, match(r"\d+", val["uid"]).match)+1 - j = j_xf + L_J_ln - j_ac = j - uid = val["uid"] - to_bus = parse(Int, match(r"\d+", val["to_bus"]).match)+1 - fr_bus = parse(Int, match(r"\d+", val["fr_bus"]).match)+1 - c_su = val["connection_cost"] - c_sd = val["disconnection_cost"] - s_max = val["mva_ub_nom"] - r = val["r"] - x = val["x"] - g_sr = r / (x^2 + r^2) - b_sr = -x / (x^2 + r^2) - b_ch = val["b"] - if val["additional_shunt"] == 1 - g_fr = val["g_fr"] - g_to = val["g_to"] - b_fr = val["b_fr"] - b_to = val["b_to"] - else - g_fr = 0 - g_to = 0 - b_fr = 0 - b_to = 0 - end - (j = j, j_ac = j_ac, j_xf=j_xf, uid = uid, to_bus = to_bus, fr_bus = fr_bus, c_su = c_su, c_sd = c_sd, s_max = s_max, - g_sr = g_sr, b_sr = b_sr, b_ch = b_ch, g_fr = g_fr, g_to = g_to, b_fr = b_fr, b_to = b_to) - end for val in values(data.twt_lookup) - ] - , by = x -> x.j), - #Variable phase difference - vpd = isempty(val for val in values(data.twt_lookup) if val["ta_lb"] < val["ta_ub"]) ? empty_data = Vector{NamedTuple{(:j,), Tuple{Int64}}}() : sort([ - begin - j_xf = parse(Int, match(r"\d+", val["uid"]).match)+1 - j = parse(Int, match(r"\d+", val["uid"]).match) + L_J_ln+1 - j_ac = j - phi_min = val["ta_lb"] - phi_max = val["ta_ub"] - (j = j, j_ac = j_ac, j_xf=j_xf, phi_min = phi_min, phi_max = phi_max) - end for val in values(data.twt_lookup) if val["ta_lb"] < val["ta_ub"] - ], by = x -> x.j), - #Fixed phase difference - fpd = isempty(val for val in values(data.twt_lookup) if val["ta_lb"] >= val["ta_ub"]) ? empty_data = Vector{NamedTuple{(:j,), Tuple{Int64}}}() : sort([ - begin - j = parse(Int, match(r"\d+", val["uid"]).match) + L_J_ln+1 - j_ac = j - j_xf = parse(Int, match(r"\d+", val["uid"]).match)+1 - phi_o = val["initial_status"]["ta"] - (j = j, j_ac = j_ac, j_xf=j_xf, phi_o = phi_o) - end for val in values(data.twt_lookup) if val["ta_lb"] >= val["ta_ub"] - ], by = x -> x.j), - #Variable winding ratio - vwr = isempty(val for val in values(data.twt_lookup) if val["tm_lb"] < val["tm_ub"]) ? empty_data = Vector{NamedTuple{(:j,), Tuple{Int64}}}() : sort([ - begin - j = parse(Int, match(r"\d+", val["uid"]).match) + L_J_ln+1 - j_ac = j - j_xf = parse(Int, match(r"\d+", val["uid"]).match)+1 - tau_min = val["tm_lb"] - tau_max = val["tm_ub"] - (j=j, j_ac=j_ac, j_xf=j_xf, tau_min=tau_min, tau_max=tau_max) - end for val in values(data.twt_lookup) if val["tm_lb"] < val["tm_ub"] - ], by = x -> x.j), - #Fixed winding ratio - fwr = isempty(val for val in values(data.twt_lookup) if val["tm_lb"] >= val["tm_ub"]) ? empty_data = Vector{NamedTuple{(:j,), Tuple{Int64}}}() : sort([ - begin - j = parse(Int, match(r"\d+", val["uid"]).match) + L_J_ln+1 - j_ac = j - j_xf = parse(Int, match(r"\d+", val["uid"]).match)+1 - tau_o = val["initial_status"]["tm"] - (j=j, j_ac=j_ac, j_xf=j_xf, tau_o=tau_o) - end for val in values(data.twt_lookup) if val["tm_lb"] >= val["tm_ub"] - - ], by = x -> x.j), - - dc_branch = sort([ - begin - j = parse(Int, match(r"\d+", val["uid"]).match) + L_J_ac+1 - j_dc = parse(Int, match(r"\d+", val["uid"]).match)+1 - uid = val["uid"] - pdc_max = val["pdc_ub"] - qdc_fr_min = val["qdc_fr_lb"] - qdc_to_min = val["qdc_to_lb"] - qdc_fr_max = val["qdc_fr_ub"] - qdc_to_max = val["qdc_to_ub"] - to_bus = parse(Int, match(r"\d+", val["to_bus"]).match)+1 - fr_bus = parse(Int, match(r"\d+", val["fr_bus"]).match)+1 - (j=j, j_dc = j_dc, uid=uid, pdc_max=pdc_max, qdc_fr_min=qdc_fr_min, qdc_to_min=qdc_to_min, qdc_fr_max=qdc_fr_max, qdc_to_max=qdc_to_max, to_bus=to_bus, fr_bus=fr_bus) - end for val in values(data.dc_line_lookup) - - ], by = x -> x.j), - - prod = sort( - # Producers - [ - begin - ts_val = data.sdd_ts_lookup[key] - j = Int(parse(Int, match(r"\d+", val["uid"]).match) + L_J_br + 1) - j_pr = get_j_pr(val["uid"], L_J_pr, L_J_cs, producers_first) - j_prcs = get_j_prcs(val["uid"], L_J_pr, L_J_cs, producers_first) - bus = Int(parse(Int, match(r"\d+", val["bus"]).match) + 1) - uid = String(val["uid"]) - c_on = Float64(val["on_cost"]) - c_su = Float64(val["startup_cost"]) - c_sd = Float64(val["shutdown_cost"]) - p_ru = Float64(val["p_ramp_up_ub"]) - p_rd = Float64(val["p_ramp_down_ub"]) - p_ru_su = Float64(val["p_startup_ramp_ub"]) - p_rd_sd = Float64(val["p_shutdown_ramp_ub"]) - c_rgu = convert(Vector{Float64}, ts_val["p_reg_res_up_cost"]) #these need checks to see if empty - c_rgd = convert(Vector{Float64}, ts_val["p_reg_res_down_cost"]) - c_scr = convert(Vector{Float64}, ts_val["p_syn_res_cost"]) - c_nsc = convert(Vector{Float64}, ts_val["p_nsyn_res_cost"]) - c_rru_on = convert(Vector{Float64}, ts_val["p_ramp_res_up_online_cost"]) - c_rru_off = convert(Vector{Float64}, ts_val["p_ramp_res_up_offline_cost"]) - c_rrd_on = convert(Vector{Float64}, ts_val["p_ramp_res_down_online_cost"]) - c_rrd_off = convert(Vector{Float64}, ts_val["p_ramp_res_down_offline_cost"]) - c_qru = convert(Vector{Float64}, ts_val["q_res_up_cost"]) - c_qrd = convert(Vector{Float64}, ts_val["q_res_down_cost"]) - p_rgu_max = Float64(val["p_reg_res_up_ub"]) - p_rgd_max = Float64(val["p_reg_res_down_ub"]) - p_scr_max = Float64(val["p_syn_res_ub"]) - p_nsc_max = Float64(val["p_nsyn_res_ub"]) - p_rru_on_max = Float64(val["p_ramp_res_up_online_ub"]) - p_rru_off_max = Float64(val["p_ramp_res_up_offline_ub"]) - p_rrd_on_max = Float64(val["p_ramp_res_down_online_ub"]) - p_rrd_off_max = Float64(val["p_ramp_res_down_offline_ub"]) - p_0 = Float64(val["initial_status"]["p"]) - q_0 = Float64(val["initial_status"]["q"]) - p_max = convert(Vector{Float64}, ts_val["p_ub"]) - p_min = convert(Vector{Float64}, ts_val["p_lb"]) - q_max = convert(Vector{Float64}, ts_val["q_ub"]) - q_min = convert(Vector{Float64}, ts_val["q_lb"]) - sus = convert(Vector{Vector{Float64}}, val["startup_states"]) - - (j = j, j_pr=j_pr, j_prcs=j_prcs, bus=bus, uid = uid, c_on = c_on, c_su = c_su, c_sd = c_sd, p_ru = p_ru, p_rd = p_rd, p_ru_su = p_ru_su, p_rd_sd = p_rd_sd, - c_rgu = c_rgu, c_rgd = c_rgd, c_scr = c_scr, c_nsc = c_nsc, c_rru_on = c_rru_on, c_rru_off = c_rru_off, c_rrd_on = c_rrd_on, c_rrd_off = c_rrd_off, - c_qru = c_qru, c_qrd = c_qrd, p_rgu_max = p_rgu_max, p_rgd_max = p_rgd_max, p_scr_max = p_scr_max, p_nsc_max = p_nsc_max, p_rru_on_max = p_rru_on_max, - p_rru_off_max=p_rru_off_max, p_rrd_on_max=p_rrd_on_max, p_rrd_off_max=p_rrd_off_max, p_0=p_0, q_0=q_0, p_max=p_max, p_min=p_min, q_max=q_max, q_min=q_min, sus=sus) - end for (key, val) in data.sdd_lookup if val["device_type"] == "producer" - ], by = x -> x.j), - - #Consumers - cons = sort( - [ - begin - ts_val = data.sdd_ts_lookup[key] - j = Int(parse(Int, match(r"\d+", val["uid"]).match) + L_J_br + 1) - j_prcs = get_j_prcs(val["uid"], L_J_pr, L_J_cs, producers_first) - j_cs = get_j_cs(val["uid"], L_J_pr, L_J_cs, producers_first) - bus = Int(parse(Int, match(r"\d+", val["bus"]).match) + 1) - uid = String(val["uid"]) - c_on = Float64(val["on_cost"]) - c_su = Float64(val["startup_cost"]) - c_sd = Float64(val["shutdown_cost"]) - p_ru = Float64(val["p_ramp_up_ub"]) - p_rd = Float64(val["p_ramp_down_ub"]) - p_ru_su = Float64(val["p_startup_ramp_ub"]) - p_rd_sd = Float64(val["p_shutdown_ramp_ub"]) - c_rgu = convert(Vector{Float64}, ts_val["p_reg_res_up_cost"]) - c_rgd = convert(Vector{Float64}, ts_val["p_reg_res_down_cost"]) - c_scr = convert(Vector{Float64}, ts_val["p_syn_res_cost"]) - c_nsc = convert(Vector{Float64}, ts_val["p_nsyn_res_cost"]) - c_rru_on = convert(Vector{Float64}, ts_val["p_ramp_res_up_online_cost"]) - c_rru_off = convert(Vector{Float64}, ts_val["p_ramp_res_up_offline_cost"]) - c_rrd_on = convert(Vector{Float64}, ts_val["p_ramp_res_down_online_cost"]) - c_rrd_off = convert(Vector{Float64}, ts_val["p_ramp_res_down_offline_cost"]) - c_qru = convert(Vector{Float64}, ts_val["q_res_up_cost"]) - c_qrd = convert(Vector{Float64}, ts_val["q_res_down_cost"]) - p_rgu_max = Float64(val["p_reg_res_up_ub"]) - p_rgd_max = Float64(val["p_reg_res_down_ub"]) - p_scr_max = Float64(val["p_syn_res_ub"]) - p_nsc_max = Float64(val["p_nsyn_res_ub"]) - p_rru_on_max = Float64(val["p_ramp_res_up_online_ub"]) - p_rru_off_max = Float64(val["p_ramp_res_up_offline_ub"]) - p_rrd_on_max = Float64(val["p_ramp_res_down_online_ub"]) - p_rrd_off_max = Float64(val["p_ramp_res_down_offline_ub"]) - p_0 = Float64(val["initial_status"]["p"]) - q_0 = Float64(val["initial_status"]["q"]) - p_max = convert(Vector{Float64}, ts_val["p_ub"]) - p_min = convert(Vector{Float64}, ts_val["p_lb"]) - q_max = convert(Vector{Float64}, ts_val["q_ub"]) - q_min = convert(Vector{Float64}, ts_val["q_lb"]) - sus = convert(Vector{Vector{Float64}}, val["startup_states"]) - - (j = j, j_cs=j_cs, j_prcs=j_prcs, bus=bus, uid = uid, c_on = c_on, c_su = c_su, c_sd = c_sd, p_ru = p_ru, p_rd = p_rd, p_ru_su = p_ru_su, p_rd_sd = p_rd_sd, - c_rgu = c_rgu, c_rgd = c_rgd, c_scr = c_scr, c_nsc = c_nsc, c_rru_on = c_rru_on, c_rru_off = c_rru_off, c_rrd_on = c_rrd_on, c_rrd_off = c_rrd_off, - c_qru = c_qru, c_qrd = c_qrd, p_rgu_max = p_rgu_max, p_rgd_max = p_rgd_max, p_scr_max = p_scr_max, p_nsc_max = p_nsc_max, p_rru_on_max = p_rru_on_max, - p_rru_off_max=p_rru_off_max, p_rrd_on_max=p_rrd_on_max, p_rrd_off_max=p_rrd_off_max, p_0=p_0, q_0=q_0, p_max=p_max, p_min=p_min, q_max=q_max, q_min=q_min, sus=sus) - end for (key, val) in data.sdd_lookup if val["device_type"] == "consumer" - ] - , by = x -> x.j), - active_reserve = sort([ - begin - ts_val = data.azr_ts_lookup[key] - n = parse(Int, match(r"\d+", val["uid"]).match) + 1 - n_p = n - uid = val["uid"] - c_rgu = val["REG_UP_vio_cost"] - c_rgd = val["REG_DOWN_vio_cost"] - c_scr = val["SYN_vio_cost"] - c_nsc = val["NSYN_vio_cost"] - c_rru = val["RAMPING_RESERVE_UP_vio_cost"] - c_rrd = val["RAMPING_RESERVE_DOWN_vio_cost"] - σ_rgu = val["REG_UP"] - σ_rgd = val["REG_DOWN"] - σ_scr = val["SYN"] - σ_nsc = val["NSYN"] - p_rru_min = convert(Vector{Float64}, ts_val["RAMPING_RESERVE_UP"]) - p_rrd_min = convert(Vector{Float64}, ts_val["RAMPING_RESERVE_DOWN"]) - (n=n, n_p=n_p, uid=uid, c_rgu=c_rgu, c_rgd=c_rgd, c_scr=c_scr, c_nsc=c_nsc, c_rru=c_rru, c_rrd=c_rrd, σ_rgu=σ_rgu, σ_rgd=σ_rgd, σ_scr=σ_scr, - σ_nsc=σ_nsc, p_rru_min=p_rru_min, p_rrd_min=p_rrd_min) - end for (key, val) in data.azr_lookup - ], by = x -> x.n), - reactive_reserve = sort([ - begin - ts_val = data.rzr_ts_lookup[key] - n = parse(Int, match(r"\d+", val["uid"]).match) + L_N_p + 1 - n_q = parse(Int, match(r"\d+", val["uid"]).match) + 1 - uid = val["uid"] - c_qru = val["REACT_UP_vio_cost"] - c_qrd = val["REACT_DOWN_vio_cost"] - q_qru_min = convert(Vector{Float64}, ts_val["REACT_UP"]) - q_qrd_min = convert(Vector{Float64}, ts_val["REACT_DOWN"]) - (n=n, n_q=n_q, uid=uid, c_qru=c_qru, c_qrd=c_qrd, q_qru_min=q_qru_min, q_qrd_min=q_qrd_min) - end for (key, val) in data.rzr_lookup - ], by = x -> x.n), - - active_reserve_set_pr = [ - (i = parse(Int, match(r"\d+", bus["uid"]).match) + 1, - j = parse(Int, match(r"\d+", device["uid"]).match) + L_J_br + 1, - n = parse(Int, match(r"\d+", uid).match) + 1, - n_p = parse(Int, match(r"\d+", uid).match) + 1, - j_pr=get_j_pr(device["uid"], L_J_pr, L_J_cs, producers_first), - j_prcs=get_j_prcs(device["uid"], L_J_pr, L_J_cs, producers_first), - ) - for uid in data.azr_ids - for bus in values(data.bus_lookup) - if uid in bus["active_reserve_uids"] - for device in values(data.sdd_lookup) - if device["bus"] == bus["uid"] && is_pr(device["uid"], L_J_pr, L_J_cs, producers_first) - ], - - active_reserve_set_cs = [ - (i = parse(Int, match(r"\d+", bus["uid"]).match) + 1, - j = parse(Int, match(r"\d+", device["uid"]).match) + L_J_br + 1, - n = parse(Int, match(r"\d+", uid).match) + 1, - n_p = parse(Int, match(r"\d+", uid).match) + 1, - j_cs=get_j_cs(device["uid"], L_J_pr, L_J_cs, producers_first), - j_prcs=get_j_prcs(device["uid"], L_J_pr, L_J_cs, producers_first),) - for uid in data.azr_ids - for bus in values(data.bus_lookup) - if uid in bus["active_reserve_uids"] - for device in values(data.sdd_lookup) - if device["bus"] == bus["uid"] && !is_pr(device["uid"], L_J_pr, L_J_cs, producers_first) - ], - - reactive_reserve_set_pr = [ - (i = parse(Int, match(r"\d+", bus["uid"]).match) + 1, - j = parse(Int, match(r"\d+", device["uid"]).match) + L_J_br + 1, - n = parse(Int, match(r"\d+", uid).match) + L_N_p + 1, - n_q = parse(Int, match(r"\d+", uid).match) + 1, - j_pr=get_j_pr(device["uid"], L_J_pr, L_J_cs, producers_first), - j_prcs=get_j_prcs(device["uid"], L_J_pr, L_J_cs, producers_first),) - for uid in data.rzr_ids - for bus in values(data.bus_lookup) - if uid in bus["reactive_reserve_uids"] - for device in values(data.sdd_lookup) - if device["bus"] == bus["uid"] && is_pr(device["uid"], L_J_pr, L_J_cs, producers_first) - ], - - reactive_reserve_set_cs = [ - (i = parse(Int, match(r"\d+", bus["uid"]).match) + 1, - j = parse(Int, match(r"\d+", device["uid"]).match) + L_J_br + 1, - n = parse(Int, match(r"\d+", uid).match) + L_N_p + 1, - n_q = parse(Int, match(r"\d+", uid).match) + 1, - j_cs=get_j_cs(device["uid"], L_J_pr, L_J_cs, producers_first), - j_prcs=get_j_prcs(device["uid"], L_J_pr, L_J_cs, producers_first),) - for uid in data.rzr_ids - for bus in values(data.bus_lookup) - if uid in bus["reactive_reserve_uids"] - for device in values(data.sdd_lookup) - if device["bus"] == bus["uid"] && !is_pr(device["uid"], L_J_pr, L_J_cs, producers_first) - ], - - ) - return sc_data, lengths, cost_vector_pr, cost_vector_cs +_uidnum(s) = parse(Int, match(r"\d+", s).match) + +# Shutdown power capability p_sdpc[j_prcs, t, t_prime]. Model-specific: it is +# indexed in this model's stacked producer/consumer variable space. +# +# `devices` are the threaded producer and consumer rows, which carry PowerIO's +# typed device fields: `p_0` is the GOC3 `initial_status.p`, `p_rd_sd` is +# `p_shutdown_ramp_ub`, and `p_min` is the `p_lb` time series. +function goc3_shutdown_power_cap(devices, lengths, periods, a_start, a_end) + p_sdpc = zeros(lengths.L_J_cspr, lengths.L_T, lengths.L_T) + for d in devices + for t in periods, t_prime in periods + t >= t_prime || continue + base = t_prime == 1 ? d.p_0 : d.p_min[t_prime-1] + p_sdpc[d.j_prcs, t, t_prime] = + base - d.p_rd_sd * (a_end[t] - a_start[t_prime]) + end + end + return p_sdpc end -function add_status_flags(uc_data, data) - for dict in uc_data - uid = dict["uid"] - on_status = dict["on_status"] - n = length(on_status) - u_on_o = data[uid]["initial_status"]["on_status"] - - su_status = zeros(Int, n) - sd_status = zeros(Int, n) - - # Handle first index using u_on_o if provided - - if u_on_o == 0 && on_status[1] == 1 - su_status[1] = 1 - elseif u_on_o == 1 && on_status[1] == 0 - sd_status[1] = 1 +# Constraints 69 and 112/113 (and their consumer twins) need only two sums over +# the startup power capability, so the sums are accumulated directly. The row +# arrays they were built from held one entry per (device, t, t_prime) triple and +# never left this file. +# +# `commitment` maps a device uid to its unit commitment record, so the status +# lookup is a hash rather than a scan over the whole commitment table per row. +# `p_ru_su` is the GOC3 `p_startup_ramp_ub` and `p_min` the `p_lb` series. +function goc3_startup_power_cap_sums!(sum_p, sum_u, devices, commitment, periods, a_end, jsel) + for d in devices + rec = get(commitment, d.uid, nothing) + rec === nothing && continue + u_su = rec["su_status"] + jc = jsel(d) + for t in periods, t_prime in periods + t_prime > t || continue + p_supc = d.p_min[t_prime] - d.p_ru_su * (a_end[t_prime] - a_end[t]) + p_supc > 0 || continue + sum_p[jc, t] += p_supc * u_su[t_prime] + sum_u[jc, t] += u_su[t_prime] end - + end + return nothing +end - # Iterate from 1 to n-1 for the rest - for i in 1:n-1 - if on_status[i] == 0 && on_status[i+1] == 1 - su_status[i+1] = 1 - end - if on_status[i] == 1 && on_status[i+1] == 0 - sd_status[i+1] = 1 - end +# Constraints 70 and 112/113, the shutdown half of the same pair. +function goc3_shutdown_power_cap_sums!(sum_p, sum_u, devices, commitment, periods, p_sdpc, jsel) + for d in devices + rec = get(commitment, d.uid, nothing) + rec === nothing && continue + u_sd = rec["sd_status"] + jc = jsel(d) + for t in periods, t_prime in periods + t_prime <= t || continue + v = p_sdpc[d.j_prcs, t, t_prime] + v > 0 || continue + sum_p[jc, t] += v * u_sd[t_prime] + sum_u[jc, t] += u_sd[t_prime] end - - dict["su_status"] = su_status - dict["sd_status"] = sd_status end + return nothing end -function get_as(dt, t) - a_end = sum(dt[1:t]) - a_start = a_end - dt[t] - a_mid = (a_start + a_end)/2 - return a_start, a_mid, a_end -end +function parse_sc_data(data, uc_data) + # One call to PowerIO returns the full set of format-neutral GOC3 SCOPF index + # sets; this function threads on the model's stacked variable numbering below. + scd = PowerIO.goc3_scopf_data(data) + sc_data = scd.static + lengths = scd.lengths + # Which device class owns the lower uid block, which is what the stacked + # producer/consumer offsets below are built on. PowerIO derives it from the uid + # numbers and warns when the two classes interleave. + producers_first = scd.producers_first + + # `lengths` is PowerIO's NamedTuple of static index-set sizes, including the + # contingency count K. Bind the names this function uses by name; the four + # energy-window lengths are computed below and merged on before it is returned. + (; L_J_ln, L_J_ac, L_J_br, L_J_cs, L_J_pr, L_J_cspr, L_T, L_N_p, K) = lengths + + # Thread this model's stacked global variable indices onto PowerIO's general + # rows, reproducing the numbering the model layer expects. + _j_pr(uid) = (j = _uidnum(uid) + L_J_br + 1, j_prcs = get_j_prcs(uid, L_J_pr, L_J_cs, producers_first), j_pr = get_j_pr(uid, L_J_pr, L_J_cs, producers_first)) + _j_cs(uid) = (j = _uidnum(uid) + L_J_br + 1, j_prcs = get_j_prcs(uid, L_J_pr, L_J_cs, producers_first), j_cs = get_j_cs(uid, L_J_pr, L_J_cs, producers_first)) + sc_data = ( + bus = sc_data.bus, + shunt = [(j = s.j_sh + L_J_br + L_J_cspr, s...) for s in sc_data.shunt], + acl_branch = [(j = b.j_ln, j_ac = b.j_ln, b...) for b in sc_data.acl_branch], + acx_branch = [(j = b.j_xf + L_J_ln, j_ac = b.j_xf + L_J_ln, b...) for b in sc_data.acx_branch], + vpd = [(j = b.j_xf + L_J_ln, j_ac = b.j_xf + L_J_ln, b...) for b in sc_data.vpd], + fpd = [(j = b.j_xf + L_J_ln, j_ac = b.j_xf + L_J_ln, b...) for b in sc_data.fpd], + vwr = [(j = b.j_xf + L_J_ln, j_ac = b.j_xf + L_J_ln, b...) for b in sc_data.vwr], + fwr = [(j = b.j_xf + L_J_ln, j_ac = b.j_xf + L_J_ln, b...) for b in sc_data.fwr], + dc_branch = [(j = b.j_dc + L_J_ac, b...) for b in sc_data.dc_branch], + prod = [(j = _uidnum(p.uid) + L_J_br + 1, j_pr = get_j_pr(p.uid, L_J_pr, L_J_cs, producers_first), j_prcs = get_j_prcs(p.uid, L_J_pr, L_J_cs, producers_first), p...) for p in sc_data.prod], + cons = [(j = _uidnum(p.uid) + L_J_br + 1, j_cs = get_j_cs(p.uid, L_J_pr, L_J_cs, producers_first), j_prcs = get_j_prcs(p.uid, L_J_pr, L_J_cs, producers_first), p...) for p in sc_data.cons], + active_reserve = [(n = r.n_p, r...) for r in sc_data.active_reserve], + reactive_reserve = [(n = r.n_q + L_N_p, r...) for r in sc_data.reactive_reserve], + active_reserve_set_pr = [(i = r.i, j = _uidnum(r.uid) + L_J_br + 1, n = r.n_p, n_p = r.n_p, j_pr = get_j_pr(r.uid, L_J_pr, L_J_cs, producers_first), j_prcs = get_j_prcs(r.uid, L_J_pr, L_J_cs, producers_first)) for r in sc_data.active_reserve_set_pr], + active_reserve_set_cs = [(i = r.i, j = _uidnum(r.uid) + L_J_br + 1, n = r.n_p, n_p = r.n_p, j_cs = get_j_cs(r.uid, L_J_pr, L_J_cs, producers_first), j_prcs = get_j_prcs(r.uid, L_J_pr, L_J_cs, producers_first)) for r in sc_data.active_reserve_set_cs], + reactive_reserve_set_pr = [(i = r.i, j = _uidnum(r.uid) + L_J_br + 1, n = r.n_q + L_N_p, n_q = r.n_q, j_pr = get_j_pr(r.uid, L_J_pr, L_J_cs, producers_first), j_prcs = get_j_prcs(r.uid, L_J_pr, L_J_cs, producers_first)) for r in sc_data.reactive_reserve_set_pr], + reactive_reserve_set_cs = [(i = r.i, j = _uidnum(r.uid) + L_J_br + 1, n = r.n_q + L_N_p, n_q = r.n_q, j_cs = get_j_cs(r.uid, L_J_pr, L_J_cs, producers_first), j_prcs = get_j_prcs(r.uid, L_J_pr, L_J_cs, producers_first)) for r in sc_data.reactive_reserve_set_cs], + ) -function parse_sc_data(data, uc_data, data_json) - producers_first = data.sdd_lookup[minimum(keys(data.sdd_lookup))]["device_type"] == "producer" - sc_data, lengths, cost_vector_pr, cost_vector_cs = parse_sc_data_static(data, producers_first) - @info typeof(sc_data) - - (L_J_xf, L_J_ln, L_J_ac, L_J_dc, L_J_br, L_J_cs, - L_J_pr, L_J_cspr, L_J_sh, I, L_T, L_N_p, L_N_q) = lengths periods = data.periods dt = Float64.(data.dt) - K = length(data_json["reliability"]["contingency"]) - add_status_flags(uc_data["time_series_output"]["ac_line"], data.ac_line_lookup) - add_status_flags(uc_data["time_series_output"]["two_winding_transformer"], data.twt_lookup) - add_status_flags(uc_data["time_series_output"]["simple_dispatchable_device"], data.sdd_lookup) - ε_time = 1e-6 - - T_supc_pr = [ - (j = parse(Int, match(r"\d+", val["uid"]).match) + L_J_br + 1, - j_pr=get_j_pr(val["uid"], L_J_pr, L_J_cs, producers_first), - j_prcs=get_j_prcs(val["uid"], L_J_pr, L_J_cs, producers_first), - t = t, - t_prime = t_prime, - p_supc = data.sdd_ts_lookup[key]["p_lb"][t_prime] - val["p_startup_ramp_ub"]*(get_as(dt, t_prime)[3] - get_as(dt, t)[3]), - u_su = uc["su_status"][t_prime] - ) - for (key, val) in data.sdd_lookup - if is_pr(val["uid"], L_J_pr, L_J_cs, producers_first) - for t in periods - for t_prime in periods - if t_prime > t && data.sdd_ts_lookup[key]["p_lb"][t_prime] - val["p_startup_ramp_ub"]*(get_as(dt, t_prime)[3] - get_as(dt, t)[3]) > 0 - for uc in uc_data["time_series_output"]["simple_dispatchable_device"] - if val["uid"] == uc["uid"] - ] - - #This sum corresponds to constraint 69 (summing p_supc*u_su) - sum_T_supc_pr = zeros(L_J_pr, length(periods)) - #This sum corresponds to constraint 112/113 (summing u_su) - sum2_T_supc_pr = zeros(L_J_pr, length(periods)) - - for b in T_supc_pr - sum_T_supc_pr[b.j_pr, b.t] += b.p_supc*b.u_su - sum2_T_supc_pr[b.j_pr, b.t] += b.u_su - end + # Interval end times, once, from the cumulative durations. `goc3_interval_bounds` + # re-sums `dt[1:t]` on every call, and these are read inside a t by t_prime loop + # over every device. + a_end = cumsum(dt) + a_start = a_end .- dt + + sdd_uc = uc_data["time_series_output"]["simple_dispatchable_device"] + PowerIO.goc3_add_status_flags!(uc_data["time_series_output"]["ac_line"], data.ac_line_lookup) + PowerIO.goc3_add_status_flags!(uc_data["time_series_output"]["two_winding_transformer"], data.twt_lookup) + PowerIO.goc3_add_status_flags!(sdd_uc, data.sdd_lookup) + # The commitment table is joined to the device rows by uid; as a linear scan per + # (device, t, t_prime) triple that join was the dominant cost of this function. + commitment = Dict{String,Any}(String(uc["uid"]) => uc for uc in sdd_uc) + + #Sums correspond to constraint 69 (p_supc*u_su) and to 112/113 and 122-126 (u_su) + sum_T_supc_pr = zeros(L_J_pr, L_T) + sum2_T_supc_pr = zeros(L_J_pr, L_T) + goc3_startup_power_cap_sums!(sum_T_supc_pr, sum2_T_supc_pr, sc_data.prod, commitment, + periods, a_end, p -> p.j_pr) - T_supc_cs = [ - (j = parse(Int, match(r"\d+", val["uid"]).match) + L_J_br + 1, - j_cs=get_j_cs(val["uid"], L_J_pr, L_J_cs, producers_first), - j_prcs=get_j_prcs(val["uid"], L_J_pr, L_J_cs, producers_first), - t = t, - t_prime = t_prime, - p_supc = data.sdd_ts_lookup[key]["p_lb"][t_prime] - val["p_startup_ramp_ub"]*(get_as(dt, t_prime)[3] - get_as(dt, t)[3]), - u_su = uc["su_status"][t_prime] - ) - for (key, val) in data.sdd_lookup - if !is_pr(val["uid"], L_J_pr, L_J_cs, producers_first) - for t in periods - for t_prime in periods - if t_prime > t && data.sdd_ts_lookup[key]["p_lb"][t_prime] - val["p_startup_ramp_ub"]*(get_as(dt, t_prime)[3] - get_as(dt, t)[3]) > 0 - for uc in uc_data["time_series_output"]["simple_dispatchable_device"] - if val["uid"] == uc["uid"] - ] - #This sum corresponds to constraint 69 (p_supc*u_su) sum_T_supc_cs = zeros(L_J_cs, L_T) - #This sum corresponds to constraints 122-126 (u_su) sum2_T_supc_cs = zeros(L_J_cs, L_T) - for b in T_supc_cs - sum_T_supc_cs[b.j_cs, b.t] += b.p_supc*b.u_su - sum2_T_supc_cs[b.j_cs, b.t] += b.u_su - end + goc3_startup_power_cap_sums!(sum_T_supc_cs, sum2_T_supc_cs, sc_data.cons, commitment, + periods, a_end, c -> c.j_cs) + # p_sdpc (shutdown power capability), indexed [j_prcs, t, t_prime] + p_sdpc = goc3_shutdown_power_cap(Iterators.flatten((sc_data.prod, sc_data.cons)), + lengths, periods, a_start, a_end) - #Build a p_sdpc set to be used for T_sdpc - #Index order is j_prcs, t, t_prime - p_sdpc = zeros(L_J_cspr, L_T, L_T) - - for t in periods - for t_prime in periods - for (key, val) in data.sdd_lookup - if t_prime == 1 && t >= t_prime - p_sdpc[get_j_prcs(val["uid"], L_J_pr, L_J_cs, producers_first), t, t_prime] = val["initial_status"]["p"] - val["p_shutdown_ramp_ub"]*(get_as(dt, t)[3] - get_as(dt, t_prime)[1]) - elseif t >= t_prime - p_sdpc[get_j_prcs(val["uid"], L_J_pr, L_J_cs, producers_first), t, t_prime] = data.sdd_ts_lookup[key]["p_lb"][t_prime-1]- val["p_shutdown_ramp_ub"]*(get_as(dt, t)[3] - get_as(dt, t_prime)[1]) - end - end - end - end - - T_sdpc_pr = [ - (j = parse(Int, match(r"\d+", val["uid"]).match) + L_J_br + 1, - j_pr=get_j_pr(val["uid"], L_J_pr, L_J_cs, producers_first), - j_prcs=get_j_prcs(val["uid"], L_J_pr, L_J_cs, producers_first), - t = t, - t_prime = t_prime, - p_sdpc = p_sdpc[parse(Int, match(r"\d+", val["uid"]).match)+1, t, t_prime], - u_sd = uc["sd_status"][t_prime] - ) - for (key, val) in data.sdd_lookup - if is_pr(val["uid"], L_J_pr, L_J_cs, producers_first) - for t in periods - for t_prime in periods - if t_prime <= t && p_sdpc[parse(Int, match(r"\d+", val["uid"]).match)+1, t, t_prime] > 0 - for uc in uc_data["time_series_output"]["simple_dispatchable_device"] - if val["uid"] == uc["uid"] - ] - - #This sum corresponds to constraint 70 (summing p_sdpc*u_sd) + #Sums correspond to constraint 70 (p_sdpc*u_sd) and to 112/113 and 122-126 (u_sd) sum_T_sdpc_pr = zeros(L_J_pr, L_T) - #This sum corresponds to constraints 112 and 113 (summing u_sd) sum2_T_sdpc_pr = zeros(L_J_pr, L_T) - for b in T_sdpc_pr - sum_T_sdpc_pr[b.j_pr, b.t] += b.p_sdpc*b.u_sd - sum2_T_sdpc_pr[b.j_pr, b.t] += b.u_sd - end + goc3_shutdown_power_cap_sums!(sum_T_sdpc_pr, sum2_T_sdpc_pr, sc_data.prod, commitment, + periods, p_sdpc, p -> p.j_pr) - T_sdpc_cs = [ - (j = parse(Int, match(r"\d+", val["uid"]).match) + L_J_br + 1, - j_cs=get_j_cs(val["uid"], L_J_pr, L_J_cs, producers_first), - j_prcs=get_j_prcs(val["uid"], L_J_pr, L_J_cs, producers_first), - t = t, - t_prime = t_prime, - p_sdpc = p_sdpc[parse(Int, match(r"\d+", val["uid"]).match)+1, t, t_prime], - u_sd = uc["sd_status"][t_prime] - ) - for (key, val) in data.sdd_lookup - if !is_pr(val["uid"], L_J_pr, L_J_cs, producers_first) - for t in periods - for t_prime in periods - if t_prime <= t && p_sdpc[parse(Int, match(r"\d+", val["uid"]).match)+1, t, t_prime] > 0 - for uc in uc_data["time_series_output"]["simple_dispatchable_device"] - if val["uid"] == uc["uid"] - ] - #This sum corresponds to constraint 70 (p_sdpc*u_sd) sum_T_sdpc_cs = zeros(L_J_cs, L_T) - #This sum corresponds to constraint 122-126 (u_sd) sum2_T_sdpc_cs = zeros(L_J_cs, L_T) - for b in T_sdpc_cs - sum_T_sdpc_cs[b.j_cs, b.t] += b.p_sdpc*b.u_sd - sum2_T_sdpc_cs[b.j_cs, b.t] += b.u_sd - end + goc3_shutdown_power_cap_sums!(sum_T_sdpc_cs, sum2_T_sdpc_cs, sc_data.cons, commitment, + periods, p_sdpc, c -> c.j_cs) - W_en_max_pr = Vector{@NamedTuple{w_en_max_pr_ind::Int, j::Int, j_prcs::Int, j_pr::Int, a_en_max_start::Float64, a_en_max_end::Float64, e_max::Float64}}() - w_en_max_pr_ind = 1 - for val in values(data.sdd_lookup) - if is_pr(val["uid"], L_J_pr, L_J_cs, producers_first) - for w in val["energy_req_ub"] - push!(W_en_max_pr, ( - w_en_max_pr_ind=w_en_max_pr_ind, - j=parse(Int, match(r"\d+", val["uid"]).match) + L_J_br + 1, - j_prcs=get_j_prcs(val["uid"], L_J_pr, L_J_cs, producers_first), - j_pr=get_j_pr(val["uid"], L_J_pr, L_J_cs, producers_first), - a_en_max_start = w[1], - a_en_max_end = w[2], - e_max = w[3]) - ) - w_en_max_pr_ind +=1 - end - end - end - + # Multi-interval energy requirement windows and their per-period membership. + ew = scd.energy_windows + W_en_max_pr = [(w_en_max_pr_ind = r.w_en_max_pr_ind, _j_pr(r.uid)..., a_en_max_start = r.a_en_max_start, a_en_max_end = r.a_en_max_end, e_max = r.e_max) for r in ew.W_en_max_pr] + W_en_max_cs = [(w_en_max_cs_ind = r.w_en_max_cs_ind, _j_cs(r.uid)..., a_en_max_start = r.a_en_max_start, a_en_max_end = r.a_en_max_end, e_max = r.e_max) for r in ew.W_en_max_cs] + W_en_min_pr = [(w_en_min_pr_ind = r.w_en_min_pr_ind, _j_pr(r.uid)..., a_en_min_start = r.a_en_min_start, a_en_min_end = r.a_en_min_end, e_min = r.e_min) for r in ew.W_en_min_pr] + W_en_min_cs = [(w_en_min_cs_ind = r.w_en_min_cs_ind, _j_cs(r.uid)..., a_en_min_start = r.a_en_min_start, a_en_min_end = r.a_en_min_end, e_min = r.e_min) for r in ew.W_en_min_cs] + T_w_en_max_pr = [(w_en_max_pr_ind = r.w_en_max_pr_ind, _j_pr(r.uid)..., t = r.t, dt = r.dt) for r in ew.T_w_en_max_pr] + T_w_en_max_cs = [(w_en_max_cs_ind = r.w_en_max_cs_ind, _j_cs(r.uid)..., t = r.t, dt = r.dt) for r in ew.T_w_en_max_cs] + T_w_en_min_pr = [(w_en_min_pr_ind = r.w_en_min_pr_ind, _j_pr(r.uid)..., t = r.t, dt = r.dt) for r in ew.T_w_en_min_pr] + T_w_en_min_cs = [(w_en_min_cs_ind = r.w_en_min_cs_ind, _j_cs(r.uid)..., t = r.t, dt = r.dt) for r in ew.T_w_en_min_cs] L_W_en_max_pr = length(W_en_max_pr) - - W_en_max_cs = Vector{@NamedTuple{w_en_max_cs_ind::Int, j::Int, j_prcs::Int, j_cs::Int, a_en_max_start::Float64, a_en_max_end::Float64, e_max::Float64}}() - w_en_max_cs_ind = 1 - for val in values(data.sdd_lookup) - if !is_pr(val["uid"], L_J_pr, L_J_cs, producers_first) - for w in val["energy_req_ub"] - push!(W_en_max_cs, ( - w_en_max_cs_ind=w_en_max_cs_ind, - j=parse(Int, match(r"\d+", val["uid"]).match) + L_J_br + 1, - j_prcs=get_j_prcs(val["uid"], L_J_pr, L_J_cs, producers_first), - j_cs=get_j_cs(val["uid"], L_J_pr, L_J_cs, producers_first), - a_en_max_start = w[1], - a_en_max_end = w[2], - e_max = w[3]) - ) - w_en_max_cs_ind +=1 - end - end - end - L_W_en_max_cs = length(W_en_max_cs) - - W_en_min_pr = Vector{@NamedTuple{w_en_min_pr_ind::Int, j::Int, j_prcs::Int, j_pr::Int, a_en_min_start::Float64, a_en_min_end::Float64, e_min::Float64}}() - w_en_min_pr_ind = 1 - for val in values(data.sdd_lookup) - if is_pr(val["uid"], L_J_pr, L_J_cs, producers_first) - for w in val["energy_req_lb"] - push!(W_en_min_pr, (w_en_min_pr_ind = w_en_min_pr_ind, - j = parse(Int, match(r"\d+", val["uid"]).match) + L_J_br + 1, - j_prcs=get_j_prcs(val["uid"], L_J_pr, L_J_cs, producers_first), - j_pr=get_j_pr(val["uid"], L_J_pr, L_J_cs, producers_first), - a_en_min_start = w[1], - a_en_min_end = w[2], - e_min = w[3])) - w_en_min_pr_ind += 1 - end - end - end - L_W_en_min_pr = length(W_en_min_pr) - - W_en_min_cs = Vector{@NamedTuple{w_en_min_cs_ind::Int, j::Int, j_prcs::Int, j_cs::Int, a_en_min_start::Float64, a_en_min_end::Float64, e_min::Float64}}() - w_en_min_cs_ind = 1 - for val in values(data.sdd_lookup) - if !is_pr(val["uid"], L_J_pr, L_J_cs, producers_first) - for w in val["energy_req_lb"] - push!(W_en_min_cs, (w_en_min_cs_ind = w_en_min_cs_ind, - j = parse(Int, match(r"\d+", val["uid"]).match) + L_J_br + 1, - j_prcs=get_j_prcs(val["uid"], L_J_pr, L_J_cs, producers_first), - j_cs=get_j_cs(val["uid"], L_J_pr, L_J_cs, producers_first), - a_en_min_start = w[1], - a_en_min_end = w[2], - e_min = w[3])) - w_en_min_cs_ind += 1 - end - end - end - L_W_en_min_cs = length(W_en_min_cs) - T_w_en_max_pr = Vector{@NamedTuple{w_en_max_pr_ind::Int, j::Int, j_prcs::Int, j_pr::Int, t::Int, dt::Float64}}() - w_en_max_pr_ind = 0 - for val in values(data.sdd_lookup) - if is_pr(val["uid"], L_J_pr, L_J_cs, producers_first) - for w in val["energy_req_ub"] - w_en_max_pr_ind += 1 - for t in periods - if w[1] + ε_time < get_as(dt, t)[2] && get_as(dt, t)[2] <= w[2] + ε_time - push!(T_w_en_max_pr, (w_en_max_pr_ind = w_en_max_pr_ind, - j = parse(Int, match(r"\d+", val["uid"]).match) + L_J_br + 1, - j_prcs=get_j_prcs(val["uid"], L_J_pr, L_J_cs, producers_first), - j_pr=get_j_pr(val["uid"], L_J_pr, L_J_cs, producers_first), - t = t, - dt=dt[t])) - end - end - end - end - end + pb_pr = scd.price_blocks.producer + pb_cs = scd.price_blocks.consumer + p_jtm_flattened_pr = [(flat_k = r.flat_k, _j_pr(r.uid)..., t = r.t, m = r.m, c_en = r.c_en, p_max = r.p_max) for r in pb_pr] + p_jtm_flattened_cs = [(flat_k = r.flat_k, _j_cs(r.uid)..., t = r.t, m = r.m, c_en = r.c_en, p_max = r.p_max) for r in pb_cs] - T_w_en_max_cs = Vector{@NamedTuple{w_en_max_cs_ind::Int, j::Int, j_prcs::Int, j_cs::Int, t::Int, dt::Float64}}() - w_en_max_cs_ind = 0 - for val in values(data.sdd_lookup) - if !is_pr(val["uid"], L_J_pr, L_J_cs, producers_first) - for w in val["energy_req_ub"] - w_en_max_cs_ind += 1 - for t in periods - if w[1] + ε_time < get_as(dt, t)[2] && get_as(dt, t)[2] <= w[2] + ε_time - push!(T_w_en_max_cs, (w_en_max_cs_ind = w_en_max_cs_ind, - j = parse(Int, match(r"\d+", val["uid"]).match) + L_J_br + 1, - j_prcs=get_j_prcs(val["uid"], L_J_pr, L_J_cs, producers_first), - j_cs=get_j_cs(val["uid"], L_J_pr, L_J_cs, producers_first), - t = t, - dt=dt[t])) - end - end - end - end - end - - T_w_en_min_pr = Vector{@NamedTuple{w_en_min_pr_ind::Int, j::Int, j_prcs::Int, j_pr::Int, t::Int, dt::Float64}}() - w_en_min_pr_ind = 0 - for val in values(data.sdd_lookup) - if is_pr(val["uid"], L_J_pr, L_J_cs, producers_first) - for w in val["energy_req_lb"] - w_en_min_pr_ind += 1 - for t in periods - if w[1] + ε_time < get_as(dt, t)[2] && get_as(dt, t)[2] <= w[2] + ε_time - push!(T_w_en_min_pr, (w_en_min_pr_ind=w_en_min_pr_ind, j = parse(Int, match(r"\d+", val["uid"]).match) + L_J_br + 1, - j_prcs=get_j_prcs(val["uid"], L_J_pr, L_J_cs, producers_first), - j_pr=get_j_pr(val["uid"], L_J_pr, L_J_cs, producers_first), - t = t, - dt = dt[t])) - end - end - end - end - end - - T_w_en_min_cs = Vector{@NamedTuple{w_en_min_cs_ind::Int, j::Int, j_prcs::Int, j_cs::Int, t::Int, dt::Float64}}() - w_en_min_cs_ind = 0 - for val in values(data.sdd_lookup) - if !is_pr(val["uid"], L_J_pr, L_J_cs, producers_first) - for w in val["energy_req_lb"] - w_en_min_cs_ind += 1 - for t in periods - if w[1] + ε_time < get_as(dt, t)[2] && get_as(dt, t)[2] <= w[2] + ε_time - push!(T_w_en_min_cs, (w_en_min_cs_ind=w_en_min_cs_ind, j = parse(Int, match(r"\d+", val["uid"]).match) + L_J_br + 1, - j_prcs=get_j_prcs(val["uid"], L_J_pr, L_J_cs, producers_first), - j_cs=get_j_cs(val["uid"], L_J_pr, L_J_cs, producers_first), - t = t, - dt = dt[t])) - end - end - end - end - end - - p_jtm_flattened_pr = Vector{@NamedTuple{flat_k::Int, j::Int, j_prcs::Int, j_pr::Int, t::Int, m::Int, c_en::Float64, p_max::Float64}}() - flat_k=1 - for (pc_idx, pc) in pairs(cost_vector_pr) - j=pc.j - j_prcs=pc.j_prcs - j_pr = pc.j_pr - for (t, cost_t) in enumerate(pc.cost) - for (m, cost_tm) in enumerate(cost_t) - c_en, p_max = cost_tm - push!(p_jtm_flattened_pr, (flat_k=flat_k, j=j, j_prcs=j_prcs, j_pr=pc.j_pr, t=t, m=m, c_en=c_en, p_max=p_max)) - flat_k+=1 - end - end - end - - p_jtm_flattened_cs = Vector{@NamedTuple{flat_k::Int, j::Int, j_prcs::Int, j_cs::Int, t::Int, m::Int, c_en::Float64, p_max::Float64}}() - flat_k=1 - for (pc_idx, pc) in pairs(cost_vector_cs) - j=pc.j - j_prcs=pc.j_prcs - j_cs = pc.j_cs - for (t, cost_t) in enumerate(pc.cost) - for (m, cost_tm) in enumerate(cost_t) - c_en, p_max = cost_tm - push!(p_jtm_flattened_cs, (flat_k=flat_k, j=j, j_prcs=j_prcs, j_cs=pc.j_cs, t=t, m=m, c_en=c_en, p_max=p_max)) - flat_k+=1 - end - end - end + # Post-contingency surviving AC branches. PowerIO enumerates the pure survivor + # rows per contingency; here we attach the UC on_status and expand over + # periods, preserving the (ctg, t, component, branch) flat ordering. + ctg_ac_survivors = scd.ac_contingency_survivors + uc_ln_lookup = Dict(uc["uid"] => uc for uc in uc_data["time_series_output"]["ac_line"]) + uc_xf_lookup = Dict(uc["uid"] => uc for uc in uc_data["time_series_output"]["two_winding_transformer"]) jtk_ln_flattened = Vector{@NamedTuple{flat_jtk_ln::Int, ctg::Int, j::Int, j_ac::Int, j_ln::Int, to_bus::Int, fr_bus::Int, b_sr::Float64, s_max_ctg::Float64, u_on::Int, t::Int, dt::Float64}}() flat_jtk_ln = 1 - for ctg in data_json["reliability"]["contingency"], t in periods - for component in ctg["components"] - for val in values(data.ac_line_lookup) - if val["uid"] != component - for uc in uc_data["time_series_output"]["ac_line"] - if val["uid"] == uc["uid"] - r = val["r"] - x = val["x"] - push!(jtk_ln_flattened, (flat_jtk_ln=flat_jtk_ln, ctg = parse(Int, match(r"\d+", ctg["uid"]).match)+1, j = parse(Int, match(r"\d+", val["uid"]).match)+1, j_ac = parse(Int, match(r"\d+", val["uid"]).match)+1, - j_ln = parse(Int, match(r"\d+", val["uid"]).match)+1, to_bus = parse(Int, match(r"\d+", val["to_bus"]).match)+1, - fr_bus = parse(Int, match(r"\d+", val["fr_bus"]).match)+1, b_sr = -x / (x^2 + r^2), s_max_ctg = val["mva_ub_em"], u_on=uc["on_status"][t], t=t, dt = dt[t])) - flat_jtk_ln += 1 - end - end - end + for rows in ctg_ac_survivors.ln + for t in periods + for r in rows + haskey(uc_ln_lookup, r.uid) || continue + uc = uc_ln_lookup[r.uid] + push!(jtk_ln_flattened, (flat_jtk_ln=flat_jtk_ln, ctg=r.ctg, j=r.j_ln, j_ac=r.j_ln, j_ln=r.j_ln, + to_bus=r.to_bus, fr_bus=r.fr_bus, b_sr=r.b_sr, s_max_ctg=r.s_max_ctg, u_on=uc["on_status"][t], t=t, dt=dt[t])) + flat_jtk_ln += 1 end end end - - jtk_xf_flattened = Vector{@NamedTuple{flat_jtk_xf::Int, ctg::Int, j::Int, j_ac::Int, j_xf::Int, to_bus::Int, fr_bus::Int, b_sr::Float64, s_max_ctg::Float64, u_on::Int, t::Int, dt::Float64}}() flat_jtk_xf = 1 - for ctg in data_json["reliability"]["contingency"], t in periods - for component in ctg["components"] - for val in values(data.twt_lookup) - if val["uid"] != component - for uc in uc_data["time_series_output"]["two_winding_transformer"] - if val["uid"] == uc["uid"] - r = val["r"] - x = val["x"] - push!(jtk_xf_flattened, (flat_jtk_xf=flat_jtk_xf, ctg = parse(Int, match(r"\d+", ctg["uid"]).match)+1, j = parse(Int, match(r"\d+", val["uid"]).match)+1+ L_J_ln, j_ac = parse(Int, match(r"\d+", val["uid"]).match)+1+ L_J_ln, - j_xf = parse(Int, match(r"\d+", val["uid"]).match)+1, to_bus = parse(Int, match(r"\d+", val["to_bus"]).match)+1, - fr_bus = parse(Int, match(r"\d+", val["fr_bus"]).match)+1, b_sr = -x / (x^2 + r^2), s_max_ctg = val["mva_ub_em"], u_on=uc["on_status"][t], t=t, dt = dt[t])) - flat_jtk_xf += 1 - end - end - end + for rows in ctg_ac_survivors.xf + for t in periods + for r in rows + haskey(uc_xf_lookup, r.uid) || continue + uc = uc_xf_lookup[r.uid] + push!(jtk_xf_flattened, (flat_jtk_xf=flat_jtk_xf, ctg=r.ctg, j=r.j_xf + L_J_ln, j_ac=r.j_xf + L_J_ln, j_xf=r.j_xf, + to_bus=r.to_bus, fr_bus=r.fr_bus, b_sr=r.b_sr, s_max_ctg=r.s_max_ctg, u_on=uc["on_status"][t], t=t, dt=dt[t])) + flat_jtk_xf += 1 end end end - jtk_dc_flattened = Vector{@NamedTuple{flat_jtk_dc::Int, ctg::Int, j::Int, j_dc::Int, to_bus::Int, fr_bus::Int, t::Int, dt::Float64}}() - flat_jtk_dc = 1 - for ctg in data_json["reliability"]["contingency"], t in periods - for component in ctg["components"] - for val in values(data.dc_line_lookup) - if val["uid"] != component - push!(jtk_dc_flattened, (flat_jtk_dc=flat_jtk_dc, ctg = parse(Int, match(r"\d+", ctg["uid"]).match)+1, j = parse(Int, match(r"\d+", val["uid"]).match)+1+ L_J_ac, - j_dc = parse(Int, match(r"\d+", val["uid"]).match)+1, to_bus = parse(Int, match(r"\d+", val["to_bus"]).match)+1, - fr_bus = parse(Int, match(r"\d+", val["fr_bus"]).match)+1, t=t, dt = dt[t])) - flat_jtk_dc += 1 - end - end - end - end + jtk_dc_flattened = [(flat_jtk_dc = r.flat_jtk_dc, ctg = r.ctg, j = r.j_dc + L_J_ac, j_dc = r.j_dc, to_bus = r.to_bus, fr_bus = r.fr_bus, t = r.t, dt = r.dt) for r in scd.dc_contingency_flows] empty_vpd = Vector{NamedTuple{(:j, :j_ac, :j_xf, :phi_min, :phi_max, :t), Tuple{Int64, Int64, Int64, Float64, Float64, Int64}}}() empty_fpd = Vector{NamedTuple{(:j, :j_ac, :j_xf, :phi_o, :t), Tuple{Int64, Int64, Int64, Float64, Int64}}}() empty_vwr = Vector{NamedTuple{(:j, :j_ac, :j_xf, :tau_min, :tau_max, :t), Tuple{Int64, Int64, Int64, Float64, Float64, Int64}}}() empty_fwr = Vector{NamedTuple{(:j, :j_ac, :j_xf, :tau_o, :t), Tuple{Int64, Int64, Int64, Float64, Int64}}}() + # Reactive capability row types. A typed comprehension yields `Vector{Row}` even + # when the filter selects nothing, so these are the element type for both the + # populated and the empty case; no separate empty sentinel is needed. `u_on` is + # the UC status and the sum2_T_* lookups are Float64 by their zeros(...) sources, + # so the declarations pin what the comprehension would otherwise infer per case. + PrPqBoundsRow = NamedTuple{(:j, :jprcs, :j_pr, :u_on, :sum2_T_supc_pr_jt, :sum2_T_sdpc_pr_jt, :beta_max, :beta_min, :q_max_p0, :q_min_p0, :t), Tuple{Int64, Int64, Int64, Int64, Float64, Float64, Float64, Float64, Float64, Float64, Int64}} + PrPqeRow = NamedTuple{(:j, :jprcs, :j_pr, :u_on, :sum2_T_supc_pr_jt, :sum2_T_sdpc_pr_jt, :beta, :q_p0, :t), Tuple{Int64, Int64, Int64, Int64, Float64, Float64, Float64, Float64, Int64}} + CsPqBoundsRow = NamedTuple{(:j, :jprcs, :j_cs, :u_on, :sum2_T_supc_cs_jt, :sum2_T_sdpc_cs_jt, :beta_max, :beta_min, :q_max_p0, :q_min_p0, :t), Tuple{Int64, Int64, Int64, Int64, Float64, Float64, Float64, Float64, Float64, Float64, Int64}} + CsPqeRow = NamedTuple{(:j, :jprcs, :j_cs, :u_on, :sum2_T_supc_cs_jt, :sum2_T_sdpc_cs_jt, :beta, :q_p0, :t), Tuple{Int64, Int64, Int64, Int64, Float64, Float64, Float64, Float64, Int64}} sc_time_data = ( ; periods = periods, - c_p = [data.violation_cost["p_bus_vio_cost"]], - c_q = [data.violation_cost["q_bus_vio_cost"]], - c_s = [data.violation_cost["s_vio_cost"]], - c_e = [data.violation_cost["e_vio_cost"]], + c_p = [scd.violation_cost.p_bus], + c_q = [scd.violation_cost.q_bus], + c_s = [scd.violation_cost.s], + c_e = [scd.violation_cost.e], busarray = [(;b..., t=t, dt=dt[t]) for b in sc_data.bus, t in periods], - k_busarray = [(;b..., t=t, k=k) for b in sc_data.bus, t in periods, k in 1:length(data_json["reliability"]["contingency"])], + k_busarray = [(;b..., t=t, k=k) for b in sc_data.bus, t in periods, k in 1:K], shuntarray = [ (;s..., t=t, u_sh = uc["step"][t]) for s in sc_data.shunt, t in periods for uc in uc_data["time_series_output"]["shunt"] if s.uid == uc["uid"] ], - k_shuntarray = [(;b..., t=t, k=k) for b in sc_data.shunt, t in periods, k in 1:length(data_json["reliability"]["contingency"])], + k_shuntarray = [(;b..., t=t, k=k) for b in sc_data.shunt, t in periods, k in 1:K], preservearray = [(;n=r.n, n_p=r.n_p, uid=r.uid, c_rgu=r.c_rgu, c_rgd=r.c_rgd, c_scr=r.c_scr, c_nsc=r.c_nsc, c_rru=r.c_rru, c_rrd=r.c_rrd, @@ -878,7 +261,7 @@ function parse_sc_data(data, uc_data, data_json) qreservearray = [(;n=q.n, n_q=q.n_q, uid=q.uid, c_qru=q.c_qru, c_qrd=q.c_qrd, q_qru_min=q.q_qru_min[t], q_qrd_min=q.q_qrd_min[t], t=t, dt = dt[t]) for q in sc_data.reactive_reserve, t in periods], - k_prarray = [(;j_prcs=b.j_prcs, j_pr=b.j_pr, bus = b.bus, uid=b.uid, t=t, k=k) for b in sc_data.prod, t in periods, k in 1:length(data_json["reliability"]["contingency"])], + k_prarray = [(;j_prcs=b.j_prcs, j_pr=b.j_pr, bus = b.bus, uid=b.uid, t=t, k=k) for b in sc_data.prod, t in periods, k in 1:K], prarray = [(;j=p.j, j_prcs=p.j_prcs, j_pr=p.j_pr, bus=p.bus, uid=p.uid, c_on=p.c_on, c_sd=p.c_sd, c_su = p.c_su, p_ru=p.p_ru, p_rd=p.p_rd, p_ru_su=p.p_ru_su, p_rd_sd=p.p_rd_sd, c_rgu=p.c_rgu[t], c_rgd=p.c_rgd[t], c_scr=p.c_scr[t], c_nsc=p.c_nsc[t], c_rru_on=p.c_rru_on[t], c_rru_off=p.c_rru_off[t], c_rrd_on=p.c_rrd_on[t], c_rrd_off=p.c_rrd_off[t], c_qru=p.c_qru[t], c_qrd=p.c_qrd[t], p_rgu_max=p.p_rgu_max, @@ -890,43 +273,41 @@ function parse_sc_data(data, uc_data, data_json) for uc in uc_data["time_series_output"]["simple_dispatchable_device"] if p.uid == uc["uid"]], - prarray_pqbounds = isempty(val for val in values(data.sdd_lookup) if is_pr(val["uid"], L_J_pr, L_J_cs, producers_first) && val["q_bound_cap"]==1) ? - empty_data = Vector{NamedTuple{(:j, :jprcs, :j_pr, :u_on, :sum2_T_supc_pr_jt, :sum2_T_sdpc_pr_jt, :beta_max, :beta_min, :q_max_p0, :q_min_p0, :t), Tuple{Int64, Int64, Int64, Int64, Int64, Int64, Float64, Float64, Float64, Float64, Int64}}}() : [ - (;j = parse(Int, match(r"\d+", val["uid"]).match) + L_J_br + 1, - j_prcs=get_j_prcs(val["uid"], L_J_pr, L_J_cs, producers_first), - j_pr=get_j_pr(val["uid"], L_J_pr, L_J_cs, producers_first), + prarray_pqbounds = PrPqBoundsRow[ + (;j = p.j, + jprcs=p.j_prcs, + j_pr=p.j_pr, u_on = uc["on_status"][t], - sum2_T_supc_pr_jt=sum2_T_supc_pr[p.j_pr, t], - sum2_T_sdpc_pr_jt=sum2_T_sdpc_pr[p.j_pr, t], - beta_max = val["beta_ub"], - beta_min = val["beta_lb"], - q_max_p0 = val["q_0_ub"], - q_min_p0 = val["q_0_lb"], + sum2_T_supc_pr_jt=sum2_T_supc_pr[p.j_pr, t], + sum2_T_sdpc_pr_jt=sum2_T_sdpc_pr[p.j_pr, t], + beta_max = p.beta_ub, + beta_min = p.beta_lb, + q_max_p0 = p.q_0_ub, + q_min_p0 = p.q_0_lb, t=t ) - for val in values(data.sdd_lookup), t in periods - if is_pr(val["uid"], L_J_pr, L_J_cs, producers_first) && val["q_bound_cap"]==1 + for p in sc_data.prod, t in periods + if p.q_bound_cap == 1 for uc in uc_data["time_series_output"]["simple_dispatchable_device"] if p.uid == uc["uid"]], - prarray_pqe = isempty(val for val in values(data.sdd_lookup) if is_pr(val["uid"], L_J_pr, L_J_cs, producers_first) && val["q_bound_cap"]==1) ? - empty_data = Vector{NamedTuple{(:j, :jprcs, :j_pr, :u_on, :sum2_T_supc_pr_jt, :sum2_T_sdpc_pr_jt, :beta, :q_p0, :t), Tuple{Int64, Int64, Int64, Int64, Int64, Int64, Float64, Float64, Int64}}}() : [ - (;j = parse(Int, match(r"\d+", val["uid"]).match) + L_J_br + 1, - j_prcs=get_j_prcs(val["uid"], L_J_pr, L_J_cs, producers_first), - j_pr=get_j_pr(val["uid"], L_J_pr, L_J_cs, producers_first), + prarray_pqe = PrPqeRow[ + (;j = p.j, + jprcs=p.j_prcs, + j_pr=p.j_pr, u_on = uc["on_status"][t], - sum2_T_supc_pr_jt=sum2_T_supc_pr[p.j_pr, t], - sum2_T_sdpc_pr_jt=sum2_T_sdpc_pr[p.j_pr, t], - beta = val["beta"], - q_p0 = val["q_0"], + sum2_T_supc_pr_jt=sum2_T_supc_pr[p.j_pr, t], + sum2_T_sdpc_pr_jt=sum2_T_sdpc_pr[p.j_pr, t], + beta = p.beta, + q_p0 = p.q_p0, t=t ) - for val in values(data.sdd_lookup), t in periods - if is_pr(val["uid"], L_J_pr, L_J_cs, producers_first) && val["q_linear_cap"]==1 + for p in sc_data.prod, t in periods + if p.q_linear_cap == 1 for uc in uc_data["time_series_output"]["simple_dispatchable_device"] if p.uid == uc["uid"]], - k_csarray = [(;j_prcs=b.j_prcs, j_cs=b.j_cs, bus = b.bus, uid=b.uid, t=t, k=k) for b in sc_data.cons, t in periods, k in 1:length(data_json["reliability"]["contingency"])], + k_csarray = [(;j_prcs=b.j_prcs, j_cs=b.j_cs, bus = b.bus, uid=b.uid, t=t, k=k) for b in sc_data.cons, t in periods, k in 1:K], csarray = [(;j=p.j, j_prcs=p.j_prcs, j_cs=p.j_cs, bus=p.bus, uid=p.uid, c_on=p.c_on, c_sd=p.c_sd, c_su=p.c_su, p_ru=p.p_ru, p_rd=p.p_rd, p_ru_su=p.p_ru_su, p_rd_sd=p.p_rd_sd, c_rgu=p.c_rgu[t], c_rgd=p.c_rgd[t], c_scr=p.c_scr[t], c_nsc=p.c_nsc[t], c_rru_on=p.c_rru_on[t], @@ -939,39 +320,37 @@ function parse_sc_data(data, uc_data, data_json) for uc in uc_data["time_series_output"]["simple_dispatchable_device"] if p.uid == uc["uid"]], - csarray_pqbounds = isempty(val for val in values(data.sdd_lookup) if !is_pr(val["uid"], L_J_pr, L_J_cs, producers_first) && val["q_bound_cap"]==1) ? - empty_data = Vector{NamedTuple{(:j, :jprcs, :j_cs, :u_on, :sum2_T_supc_cs_jt, :sum2_T_sdpc_cs_jt, :beta_max, :beta_min, :q_max_p0, :q_min_p0, :t), Tuple{Int64, Int64, Int64, Int64, Int64, Int64, Float64, Float64, Float64, Float64, Int64}}}() : [ - (;j = parse(Int, match(r"\d+", val["uid"]).match) + L_J_br + 1, - j_cs=get_j_cs(val["uid"], L_J_pr, L_J_cs, producers_first), - j_prcs=get_j_prcs(val["uid"], L_J_pr, L_J_cs, producers_first), + csarray_pqbounds = CsPqBoundsRow[ + (;j = p.j, + jprcs=p.j_prcs, + j_cs=p.j_cs, u_on = uc["on_status"][t], - sum2_T_supc_cs_jt=sum2_T_supc_cs[p.j_cs, t], - sum2_T_sdpc_cs_jt=sum2_T_sdpc_cs[p.j_cs, t], - beta_max = val["beta_ub"], - beta_min = val["beta_lb"], - q_max_p0 = val["q_0_ub"], - q_min_p0 = val["q_0_lb"], + sum2_T_supc_cs_jt=sum2_T_supc_cs[p.j_cs, t], + sum2_T_sdpc_cs_jt=sum2_T_sdpc_cs[p.j_cs, t], + beta_max = p.beta_ub, + beta_min = p.beta_lb, + q_max_p0 = p.q_0_ub, + q_min_p0 = p.q_0_lb, t=t ) - for val in values(data.sdd_lookup), t in periods - if !is_pr(val["uid"], L_J_pr, L_J_cs, producers_first) && val["q_bound_cap"]==1 + for p in sc_data.cons, t in periods + if p.q_bound_cap == 1 for uc in uc_data["time_series_output"]["simple_dispatchable_device"] if p.uid == uc["uid"]], - csarray_pqe = isempty(val for val in values(data.sdd_lookup) if !is_pr(val["uid"], L_J_pr, L_J_cs, producers_first) && val["q_bound_cap"]==1) ? - empty_data = Vector{NamedTuple{(:j, :jprcs, :j_cs, :u_on, :sum2_T_supc_cs_jt, :sum2_T_sdpc_cs_jt, :beta, :q_p0, :t), Tuple{Int64, Int64, Int64, Int64, Int64, Int64, Float64, Float64, Int64}}}() : [ - (;j = parse(Int, match(r"\d+", val["uid"]).match) + L_J_br + 1, - j_cs=get_j_cs(val["uid"], L_J_pr, L_J_cs, producers_first), - j_prcs=get_j_prcs(val["uid"], L_J_pr, L_J_cs, producers_first), + csarray_pqe = CsPqeRow[ + (;j = p.j, + jprcs=p.j_prcs, + j_cs=p.j_cs, u_on = uc["on_status"][t], - sum2_T_supc_cs_jt=sum2_T_supc_cs[p.j_cs, t], - sum2_T_sdpc_cs_jt=sum2_T_sdpc_cs[p.j_cs, t], - beta = val["beta"], - q_p0 = val["q_0"], + sum2_T_supc_cs_jt=sum2_T_supc_cs[p.j_cs, t], + sum2_T_sdpc_cs_jt=sum2_T_sdpc_cs[p.j_cs, t], + beta = p.beta, + q_p0 = p.q_p0, t=t ) - for val in values(data.sdd_lookup), t in periods - if !is_pr(val["uid"], L_J_pr, L_J_cs, producers_first) && val["q_linear_cap"]==1 + for p in sc_data.cons, t in periods + if p.q_linear_cap == 1 for uc in uc_data["time_series_output"]["simple_dispatchable_device"] if p.uid == uc["uid"]], @@ -989,10 +368,10 @@ function parse_sc_data(data, uc_data, data_json) for uc in uc_data["time_series_output"]["ac_line"] if b.uid == uc["uid"]], - fpdarray = isempty(sc_data.fpd) ? empty_data = empty_fpd : [(;b..., t=t) for b in sc_data.fpd, t in periods], - fwrarray = isempty(sc_data.fwr) ? empty_data = empty_fwr : [(;b..., t=t) for b in sc_data.fwr, t in periods], - vpdarray = isempty(sc_data.vpd) ? empty_data = empty_vpd : [(;b..., t=t) for b in sc_data.vpd, t in periods], - vwrarray = isempty(sc_data.vwr) ? empty_data = empty_vwr : [(;b..., t=t) for b in sc_data.vwr, t in periods], + fpdarray = isempty(sc_data.fpd) ? empty_fpd : [(;b..., t=t) for b in sc_data.fpd, t in periods], + fwrarray = isempty(sc_data.fwr) ? empty_fwr : [(;b..., t=t) for b in sc_data.fwr, t in periods], + vpdarray = isempty(sc_data.vpd) ? empty_vpd : [(;b..., t=t) for b in sc_data.vpd, t in periods], + vwrarray = isempty(sc_data.vwr) ? empty_vwr : [(;b..., t=t) for b in sc_data.vwr, t in periods], dclinearray = [(;b..., t=t) for b in sc_data.dc_branch, t in periods], p_jt_fr_dc_max = [dc.pdc_max for dc in sc_data.dc_branch, t in periods], @@ -1019,7 +398,7 @@ function parse_sc_data(data, uc_data, data_json) T_w_en_min_pr=T_w_en_min_pr, T_w_en_min_cs=T_w_en_min_cs, - tk_index = [(t=t, k=k) for t in periods, k in 1:length(data_json["reliability"]["contingency"])], + tk_index = [(t=t, k=k) for t in periods, k in 1:K], p_jtm_flattened_pr=p_jtm_flattened_pr, p_jtm_flattened_cs=p_jtm_flattened_cs, @@ -1031,19 +410,19 @@ function parse_sc_data(data, uc_data, data_json) ) - lengths = (L_J_xf, L_J_ln, L_J_ac, L_J_dc, L_J_br, L_J_cs, - L_J_pr, L_J_cspr, L_J_sh, I, L_T, L_N_p, L_N_q, L_W_en_min_pr, L_W_en_min_cs, L_W_en_max_pr, L_W_en_max_cs, K) + # Append the model-owned energy-window lengths to PowerIO's static lengths, + # which already carry the contingency count. + lengths = merge(lengths, (; L_W_en_min_pr, L_W_en_min_cs, L_W_en_max_pr, L_W_en_max_cs)) return sc_time_data, lengths, producers_first end function save_go3_solution(uc_filename, solution_name, result, vars, lengths, producers_first) uc_data = JSON.parsefile(uc_filename) - (L_J_xf, L_J_ln, L_J_ac, L_J_dc, L_J_br, L_J_cs, - L_J_pr, L_J_cspr, L_J_sh, I, L_T, L_N_p, L_N_q, L_W_en_min_pr, L_W_en_min_cs, L_W_en_max_pr, L_W_en_max_cs, K) = lengths + (; L_J_pr, L_J_cs, L_T) = lengths #Update simple dispatchable devices for line in uc_data["time_series_output"]["simple_dispatchable_device"] - raw_uid = parse(Int, match(r"\d+", line["uid"]).match) + raw_uid = _uidnum(line["uid"]) solution_index = raw_uid + 1 #This corresponds to j_prcs if !is_pr(raw_uid, L_J_pr, L_J_cs, producers_first) #This section corresponds to consuming devices @@ -1083,7 +462,7 @@ function save_go3_solution(uc_filename, solution_name, result, vars, lengths, pr end #Update two winding transformers for line in uc_data["time_series_output"]["two_winding_transformer"] - solution_index = parse(Int, match(r"\d+", line["uid"]).match) + 1 #This corresponds to j_xf + solution_index = _uidnum(line["uid"]) + 1 #This corresponds to j_xf line["tm"] = Array(solution(result, vars.τ_jt_xf))[solution_index,:] line["ta"] = Array(solution(result, vars.φ_jt_xf))[solution_index,:] end @@ -1091,7 +470,7 @@ function save_go3_solution(uc_filename, solution_name, result, vars, lengths, pr #Update DC lines for line in uc_data["time_series_output"]["dc_line"] - solution_index = parse(Int, match(r"\d+", line["uid"]).match) + 1 #This corresponds to j_dc + solution_index = _uidnum(line["uid"]) + 1 #This corresponds to j_dc line["qdc_fr"] = Array(solution(result, vars.q_jt_fr_dc))[solution_index,:] line["pdc_fr"] = Array(solution(result, vars.p_jt_fr_dc))[solution_index,:] #pdc_to is implied from energy conservation line["qdc_to"] = Array(solution(result, vars.q_jt_to_dc))[solution_index,:] @@ -1099,7 +478,7 @@ function save_go3_solution(uc_filename, solution_name, result, vars, lengths, pr #Update buses for line in uc_data["time_series_output"]["bus"] - solution_index = parse(Int, match(r"\d+", line["uid"]).match) + 1 #This corresponds to i + solution_index = _uidnum(line["uid"]) + 1 #This corresponds to i line["vm"] = Array(solution(result, vars.v_it))[solution_index,:] line["va"] = Array(solution(result, vars.θ_it))[solution_index,:] end diff --git a/test/Project.toml b/test/Project.toml index b7e63a3..908dcbe 100644 --- a/test/Project.toml +++ b/test/Project.toml @@ -5,6 +5,7 @@ CUDSS = "45b445bb-4962-46a0-9369-b4df9d0f772e" ExaModels = "1037b233-b668-4ce9-9b63-f9f681f55dd2" ExaModelsCompiler = "3d1e9a26-5b74-4f0c-9a2b-7c8f4e11d3a7" ExaModelsPower = "2fff4b78-0b6c-428d-bac8-85ccea8c4bdf" +ExaPowerIO = "14903efe-9500-4d7f-a589-7ab7e15da6de" Ipopt = "b6b21f68-93f8-5de0-b562-5493be1d77c9" JuMP = "4076af6c-e467-56ae-b986-b466b2749572" KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" @@ -12,6 +13,7 @@ MadNLP = "2621e9c9-9eb4-46b1-8089-e8c72242dfb6" MadNLPGPU = "d72a61cc-809d-412f-99be-fd81f4b8a598" NLPModels = "a4795742-8479-5a88-8948-cc11e1c8c1a6" NLPModelsJuMP = "792afdf1-32c1-5681-94e0-d7bf7a5df49e" +PowerIO = "05ed8b54-f668-4096-9d0d-e8c3dd9dc169" PowerModels = "c36e90e8-916a-50a6-bd94-075b64ef4655" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" diff --git a/test/powerio_parser_tests.jl b/test/powerio_parser_tests.jl new file mode 100644 index 0000000..ce7e826 --- /dev/null +++ b/test/powerio_parser_tests.jl @@ -0,0 +1,134 @@ +import ExaPowerIO +import PowerIO + +_case_path(name) = joinpath(@__DIR__, "..", "data", name) + +_matches(lhs::Real, rhs::Real) = isapprox(lhs, rhs; rtol = 1e-9, atol = 1e-10, nans = true) +_matches(lhs, rhs) = lhs == rhs + +function _test_matching_rows(actual, expected) + @test length(actual) == length(expected) + for (a, e) in zip(actual, expected), field in propertynames(e) + @test _matches(getproperty(a, field), getproperty(e, field)) + end +end + +function _test_matches_exapowerio(actual, expected) + @test actual.baseMVA == [expected.baseMVA] + for table in (:bus, :gen, :branch, :arc, :storage) + _test_matching_rows(getproperty(actual, table), getproperty(expected, table)) + end +end + +# Backend-free: everything here runs on the serial path, so `runtests` calls it from +# one slice rather than letting it repeat in every CI job. +function powerio_parser_tests() + @testset "PowerIO parser backend" begin + matpower_cases = [ + "pglib_opf_case3_lmbd.m", + "pglib_opf_case5_pjm.m", + "pglib_opf_case14_ieee.m", + "pglib_opf_case3_lmbd_mod.m", + "pglib_opf_case5_pjm_mod.m", + ] + + for case in matpower_cases + path = _case_path(case) + expected = ExaPowerIO.parse_matpower(Float64, path) + actual = ExaModelsPower.parse_ac_power_data(path, Float64) + _test_matches_exapowerio(actual, expected) + end + + # Every model here is built from the parse, and a single abstract field in it + # leaves `ExaModel(CORE, data)` unresolved under `--trim=safe`. The row types + # must also be isbits, or the GPU backends refuse the arrays built from them. + # + # Broken against PowerIO 0.9.0: its table accessors return the JSON3 value + # union, so containers built from them infer as `Any`, and `T` arrives as a + # keyword-typed `Type{<:Real}` that nothing downstream can specialize on. The + # rows ARE concrete at run time, which the isbits checks below assert; only + # inference cannot prove it. Flips to a failure when PowerIO pins them. + let path = _case_path("pglib_opf_case14_ieee.m") + @test_broken isconcretetype( + Base.infer_return_type(ExaModelsPower.parse_ac_power_data, (String, Type{Float64})), + ) + p = ExaModelsPower.parse_ac_power_data(path, Float64) + for table in (:bus, :gen, :branch, :arc) + @test isbitstype(eltype(getproperty(p, table))) + end + end + + # The multiperiod busarray is built immutably from the LoadSeries; its element + # type must stay concrete/isbits so the GPU kernels accept it (mirrors the + # SCOPF boundary test, and surfaces a PowerIO regression without a GPU runner). + let mp_net = ExaModelsPower.parse_mp_network(_case_path("pglib_opf_case3_lmbd.m")) + mp_series = PowerIO.LoadSeries(mp_net, [1.0, 0.95]; T = Float64) + mp_data = ExaModelsPower.parse_mp_power_data(mp_net, mp_series, 2, 0.1, Float64) + @test isconcretetype(eltype(mp_data.busarray)) + @test isbitstype(eltype(mp_data.busarray)) + + # A horizon longer than the series is a clear error rather than a + # BoundsError from inside the comprehension. + @test_throws DimensionMismatch ExaModelsPower.parse_mp_power_data( + mp_net, mp_series, 3, 0.1, Float64) + end + + # A load curve scales the LOADS. A fixed bus shunt is fixed: case14 carries + # bs = 19.0 at bus 9, and it is the same in every period. + let net = ExaModelsPower.parse_mp_network(_case_path("pglib_opf_case14_ieee.m")) + series = PowerIO.LoadSeries(net, [1.0, 0.5]; T = Float64) + d = ExaModelsPower.parse_mp_power_data(net, series, 2, 0.1, Float64) + shunt = [b.b.bs for b in d.busarray[:, 1]] + @test any(!iszero, shunt) + @test shunt == [b.b.bs for b in d.busarray[:, 2]] + @test [b.b.pd for b in d.busarray[:, 2]] ≈ 0.5 .* [b.b.pd for b in d.busarray[:, 1]] + end + + mktempdir() do dir + matpower = _case_path("pglib_opf_case3_lmbd.m") + psse_path = joinpath(dir, "case3.raw") + powerworld_path = joinpath(dir, "case3.aux") + powermodels_path = joinpath(dir, "case3.json") + + write(psse_path, first(PowerIO.convert_file(matpower, "psse"))) + write(powerworld_path, first(PowerIO.convert_file(matpower, "powerworld"))) + write(powermodels_path, first(PowerIO.convert_file(matpower, "powermodels-json"))) + + for path in (psse_path, powerworld_path) + data = ExaModelsPower.parse_ac_power_data(path, Float64) + @test length(data.bus) == 3 + @test length(data.branch) == 3 + @test length(data.gen) == 3 + end + + pm_data = ExaModelsPower.parse_ac_power_data( + powermodels_path, + Float64; + from = "powermodels", + ) + @test length(pm_data.bus) == 3 + @test length(pm_data.branch) == 3 + @test length(pm_data.gen) == 3 + + @test !isnothing(ac_opf_model(psse_path; form = Polar())[1]) + @test !isnothing(ac_opf_model(powerworld_path; form = Rect())[1]) + @test !isnothing(dcopf_model(psse_path)[1]) + @test !isnothing( + mpopf_model( + powermodels_path, + [1.0, 0.95]; + from = "powermodels", + )[1], + ) + + # Passing only one of pd/qd is a clear error, not a MethodError from a + # `nothing` reaching PowerIO.LoadSeries. Both are read from file, or both + # are supplied as matrices; the files here are never read (the error is + # raised before load construction). + @test_throws ArgumentError mpopf_model( + matpower, "unused.Pd", "unused.Qd"; pd = zeros(3, 2)) + @test_throws ArgumentError mpopf_model( + matpower, "unused.Pd", "unused.Qd"; qd = zeros(3, 2)) + end + end +end diff --git a/test/runtests.jl b/test/runtests.jl index 6fe9b99..1954ad5 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -8,6 +8,7 @@ import NLPModels include("opf_tests.jl") include("recipe_tests.jl") +include("powerio_parser_tests.jl") # CI runs each backend, and the GOC3 smoke test, as a separate job, so the wall clock is # the slowest of them rather than their sum (they were 13.0, 14.8, 21.5 and 74.9 min in run @@ -29,6 +30,9 @@ SELECTION in ("all", "nothing") && push!(CONFIGS, nothing) SELECTION in ("all", "cpu") && push!(CONFIGS, CPU()) SELECTION in ("all", "cuda") && CUDA.has_cuda_gpu() && push!(CONFIGS, CUDABackend()) const RUN_GOC3 = SELECTION in ("all", "goc3") +# The parser tests are backend-free, so they belong to exactly one slice rather than +# repeating in all four. The serial slice is the cheapest of them. +const RUN_PARSER = SELECTION in ("all", "nothing") isempty(CONFIGS) && !RUN_GOC3 && error("EMP_TEST_SELECTION=$(SELECTION) selected no tests") @@ -125,6 +129,7 @@ function runtests() # The PowerModels/Ipopt and JuMP/MadNLP reference solutions do not depend on the # backend, so compute them once per case/form and reuse them. static_ref_cache = Dict{Tuple{String,String},Any}() + dcopf_ref_cache = Dict{String,Any}() # case3 and case5 exercise the same code with different data, so the multi-period # sections keep case3 only. Every backend runs the same set: with one job per @@ -137,6 +142,8 @@ function runtests() # BOTH formulations — # that is the whole guarantee the split is for, and it is backend-free, # so it runs once rather than per backend. + RUN_PARSER && powerio_parser_tests() + if SELECTION in ("all", "nothing") for (filename, case, _) in test_cases, (form_str, form, _, _) in static_forms @testset "$case, recipe == eager, $form_str" begin @@ -244,11 +251,28 @@ function runtests() # DCOPF for (filename, case, _) in test_cases + m32, _, _ = dcopf_model(filename; T=Float32, backend = backend) + m64, v64, _ = dcopf_model(filename; T=Float64, backend = backend) + @testset "$case, DCOPF, $backend" begin - m32, _, _ = dcopf_model(filename; T=Float32, backend = backend) - m64, _, _ = dcopf_model(filename; T=Float64, backend = backend) test_callbacks(m32, m64, backend) end + + # Evaluating the callbacks says nothing about the answer, so DCOPF gets + # the same carve-out as static AC: the smallest case is solved against + # the PowerModels reference, and every other case is callbacks only. + if solving && case == solve_case + result64 = exasolve(m64, backend; print_level = MadNLP.ERROR) + + result_pm = get!(dcopf_ref_cache, filename) do + nlp_solver = JuMP.optimizer_with_attributes(Ipopt.Optimizer, "tol"=>Float64(result64.options.tol), "print_level"=>0) + solve_opf(filename, DCPPowerModel, nlp_solver) + end + + @testset "$case, DCOPF solve, $backend" begin + test_dcopf_case(result64, result_pm, v64.pg, v64.pf) + end + end end # User callbacks