From f0c1dc96c7502a6a1c429d3bc9a44465c16fa227 Mon Sep 17 00:00:00 2001 From: samtalki <10187005+samtalki@users.noreply.github.com> Date: Tue, 18 Aug 2026 05:27:54 -0400 Subject: [PATCH 1/6] Read a zero line rating as no limit, and say which case formats are accepted MATPOWER, PSS/E and PowerWorld all read `rate_a = 0` as an unrated branch, and real cases lean on it: every arc of stock case14, case57, case118 and case13659pegase, 4924 of 25412 in case_ACTIVSg10k, 44104 of 208242 in case_SyntheticUSA. Nine of the twenty four MATPOWER cases in the powerio test corpus carry at least one. Read literally, the rating became a bound of exactly zero on the flow and a thermal limit of `p^2 + q^2 <= 0`, so stock case14 came back INFEASIBLE_PROBLEM_DETECTED instead of solved. An unrated branch now gets an infinite flow bound and an infinite upper bound on its thermal limit rows. The rating stays inside the thermal expression rather than being replaced by infinity there, so the residual and its derivatives stay finite. case14, case57 and case118 now solve and agree with PowerModels/Ipopt to 4.2e-11, 1.4e-12 and 1.5e-13 relative. Rated cases are untouched: their bounds are the rating and their thermal upper bound is zero, exactly as before. The README said nothing about which case files the package reads, and imported GOC3Benchmark, which has not been a dependency since the GOC3 parser moved to PowerIO. It now names the formats, the `from` keyword for the ones an extension cannot identify, the PGLib-OPF name lookup, and the MW convention on the .Pd and .Qd files. `from` is documented on opf_args, opf_model and mpopf_model. --- README.md | 23 +++++++++++++++++++- src/mpopf.jl | 16 +++++++++----- src/opf.jl | 29 +++++++++++++++++++------ test/powerio_parser_tests.jl | 41 ++++++++++++++++++++++++++++++++++++ 4 files changed, 97 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 2606dba..5783f8b 100644 --- a/README.md +++ b/README.md @@ -7,10 +7,25 @@ ExaModelsPower.jl is an optimal power flow models using ExaModels.jl [![doc](https://img.shields.io/badge/docs-dev-blue.svg)](https://madsuite.org/ExaModelsPower.jl/dev/) [![codecov](https://codecov.io/gh/MadNLP/ExaModelsPower.jl/graph/badge.svg?token=ybOObxcXhB)](https://codecov.io/gh/MadNLP/ExaModelsPower.jl) +## Case files + +Every model constructor takes a path. Case files are read through +[PowerIO](https://github.com/eigenergy/PowerIO.jl), so MATPOWER (`.m`), PSS/E raw +(`.raw`), PowerWorld aux (`.aux`), PowerModels JSON, PSLF (`.epc`), pandapower JSON, +egret and GOC3 JSON all work. The format is inferred from the extension; pass `from` when +it cannot be, as for a `.json` file: + +```julia +model, vars, cons = ac_opf_model("case118.json"; from = "powermodels") +``` + +A name that is not a path on disk is looked up in the bundled PGLib-OPF library, which is +what `"pglib_opf_case118_ieee.m"` below resolves through. + ## Usage ### Static optimal power flow ```julia -using ExaModelsPower, MadNLP, MadNLPGPU, CUDA, ExaModels, GOC3Benchmark, JSON +using ExaModelsPower, MadNLP, MadNLPGPU, CUDA, ExaModels, JSON model, vars, cons = ac_opf_model( @@ -60,6 +75,12 @@ result = madnlp(model; tol=1e-4) ``` ### Multi-period optimal power flow + +The `.Pd` / `.Qd` files hold **MW**, one row per bus in the case's own bus order and one +column per period; they are converted to per unit on the case's base MVA. To pass the same +matrices in memory rather than on disk, give both `pd` and `qd` as keywords — one without +the other is an error rather than a silent half-applied load. + ```julia model, vars, cons = mpopf_model( "pglib_opf_case118_ieee.m", # static network data diff --git a/src/mpopf.jl b/src/mpopf.jl index 2a71d78..849ace5 100644 --- a/src/mpopf.jl +++ b/src/mpopf.jl @@ -30,7 +30,9 @@ function parse_mp_power_data(net, series, N, corrective_action_ratio, ::Type{T}) 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], - branch_rate_a = [br.rate_a for br in raw.branch], + rate_a = unlimited_rate.(raw.rate_a, T), + branch_rate_a = [unlimited_rate(br.rate_a, T) for br in raw.branch], + branch_thermal_ucon = [thermal_ucon(br.rate_a, T) for br in raw.branch], Δp = corrective_action_ratio .* (raw.pmax .- raw.pmin) ) @@ -106,10 +108,10 @@ end function add_thermal_mp!(core, ::Union{Polar,Rect}, data, F) @add_con(core, c_from_thermal_limit, c_thermal_limit(b, F.p[b.f_idx, t], F.q[b.f_idx, t]) for (b, t) in data.barray; - lcon = data.rep.ninf_b) + lcon = data.rep.ninf_b, ucon = data.rep.thermal_ucon_b) @add_con(core, c_to_thermal_limit, c_thermal_limit(b, F.p[b.t_idx, t], F.q[b.t_idx, t]) for (b, t) in data.barray; - lcon = data.rep.ninf_b) + lcon = data.rep.ninf_b, ucon = data.rep.thermal_ucon_b) return core, (; c_from_thermal_limit, c_to_thermal_limit) end add_thermal_mp!(core, ::DC, data, F) = (core, (;)) @@ -192,6 +194,7 @@ function _mp_narrow(d, N, ::Type{T}) where {T} pdmax = repeat(d.pdmax, 1, N), pcmax = repeat(d.pcmax, 1, N), dp = repeat(d.Δp, 1, N - 1), ndp = repeat(-d.Δp, 1, N - 1), ninf_b = fill(T(-Inf), size(d.barray)), + thermal_ucon_b = repeat(d.branch_thermal_ucon, 1, N), zero_stor = zeros(T, size(d.storarray)), inf_stor = fill(T(Inf), size(d.storarray)), ninf_stor = fill(T(-Inf), size(d.storarray)), @@ -585,8 +588,10 @@ Construct a multi-period AC optimal power flow (MPOPF) model using different for - `filename::String`: Path to the network data file (e.g., MATPOWER). - `curve::AbstractVector`: A time series of demand multiplier values. -- `active_power_data::String`: Path to a matrix of active power loads (Pd) per bus and time. -- `reactive_power_data::String`: Path to a matrix of reactive power loads (Qd). +- `active_power_data::String`: Path to a matrix of active power loads (Pd) per bus and time, + in MW, rows in the case's bus order. Pass `pd`/`qd` to supply both matrices in memory + instead; one without the other is an error. +- `reactive_power_data::String`: Path to a matrix of reactive power loads (Qd), same layout. - `discharge_func::Function`: (Optional) A function specifying battery discharge losses. ## Keyword Arguments @@ -595,6 +600,7 @@ Construct a multi-period AC optimal power flow (MPOPF) model using different for - `corrective_action_ratio::Float64`: Ratio of corrective power action allowed (default = 0.1). - `backend`: Optimization solver backend (deault = nothing). - `form::OPFForm`: the formulation — `Polar()` (default), `Rect()` or `DC()`. +- `from`: the case format, when it cannot be inferred from the file extension. - `T::Type`: Floating-point type for numeric variables (default = `Float64`). - `storage_complementarity_constraint::Bool`: Whether to enforce complementarity for storage (only for some methods, default = false). - `user_callback`: User function that extends the model diff --git a/src/opf.jl b/src/opf.jl index 946b5d8..e1c887d 100644 --- a/src/opf.jl +++ b/src/opf.jl @@ -78,6 +78,13 @@ _default_start(::Type{T}) where {T} = _resolve_start(f, data) = f(data) _resolve_start(v::Union{Number,AbstractVector,Base.Generator}, data) = v +# A zero line rating means "no limit" in every format read here. Read literally +# it bounds the flow at zero and asks for `p^2 + q^2 <= 0`. The rating stays in +# the thermal expression and the slack goes into its upper bound, so an +# unlimited branch keeps a finite residual. +unlimited_rate(r, ::Type{T}) where {T} = iszero(r) ? T(Inf) : T(r) +thermal_ucon(r, ::Type{T}) where {T} = iszero(r) ? T(Inf) : zero(T) + """ opf_args(filename; T = Float64, backend = nothing, start = (;)) -> (data,) @@ -85,6 +92,9 @@ _resolve_start(v::Union{Number,AbstractVector,Base.Generator}, data) = v Return the argument tuple that closes [`opf_recipe`](@ref) — the parsed case together with everything the recipe cannot compute from a placeholder. +`from` names the case format when the file extension cannot say it, as for a `.json` file +that could be PowerModels, pandapower or GOC3. + `start` overrides any of the starting points `va`, `vm`, `vr`, `vim`, `pg`, `qg`, `p`, `q`. Each entry may be a scalar, a vector, a `Base.Generator`, or a function of the parsed data (`d -> d.vm0` to warm-start from the case's own @@ -127,14 +137,15 @@ function opf_args(filename, ::Type{T}, backend = nothing, start = (;), from = no pmin = p.pmin, pmax = p.pmax, qmin = p.qmin, qmax = p.qmax, angmin = p.angmin, angmax = p.angmax, - rate_a = p.rate_a, + rate_a = unlimited_rate.(p.rate_a, T), # Per BRANCH, not per arc. `dcopf`'s `pf` is a branch-length block and # was bounded by the arc-length `rate_a`; that lands on the right # values only because the first `nbranch` arcs happen to be the # from-arcs in branch order (measured identical, 0 differences, on # case14, case118 and case9241_pegase). Correct by construction rather # than by that coincidence. - branch_rate_a = [br.rate_a for br in p.branch], + branch_rate_a = [unlimited_rate(br.rate_a, T) for br in p.branch], + branch_thermal_ucon = [thermal_ucon(br.rate_a, T) for br in p.branch], # Broadcasting a placeholder is refused by design, so the rectangular # form's squared voltage bounds are computed here, beside the parse. vmin2 = p.vmin .^ 2, @@ -286,17 +297,21 @@ end function add_extras!(core, ::Polar, d, V, F) @add_con(core, c_from_thermal_limit, - c_thermal_limit(b, F.p[b.f_idx], F.q[b.f_idx]) for b in d.branch; lcon = d.branch_ninf) + c_thermal_limit(b, F.p[b.f_idx], F.q[b.f_idx]) for b in d.branch; + lcon = d.branch_ninf, ucon = d.branch_thermal_ucon) @add_con(core, c_to_thermal_limit, - c_thermal_limit(b, F.p[b.t_idx], F.q[b.t_idx]) for b in d.branch; lcon = d.branch_ninf) + c_thermal_limit(b, F.p[b.t_idx], F.q[b.t_idx]) for b in d.branch; + lcon = d.branch_ninf, ucon = d.branch_thermal_ucon) return core, (; c_from_thermal_limit, c_to_thermal_limit) end function add_extras!(core, ::Rect, d, V, F) @add_con(core, c_from_thermal_limit, - c_thermal_limit(b, F.p[b.f_idx], F.q[b.f_idx]) for b in d.branch; lcon = d.branch_ninf) + c_thermal_limit(b, F.p[b.f_idx], F.q[b.f_idx]) for b in d.branch; + lcon = d.branch_ninf, ucon = d.branch_thermal_ucon) @add_con(core, c_to_thermal_limit, - c_thermal_limit(b, F.p[b.t_idx], F.q[b.t_idx]) for b in d.branch; lcon = d.branch_ninf) + c_thermal_limit(b, F.p[b.t_idx], F.q[b.t_idx]) for b in d.branch; + lcon = d.branch_ninf, ucon = d.branch_thermal_ucon) @add_con(core, c_voltage_magnitude, c_voltage_magnitude_rect(V.vr[b.i], V.vim[b.i]) for b in d.bus; lcon = d.vmin2, ucon = d.vmax2) @@ -372,6 +387,8 @@ definition rather than two. - `form`: the formulation, an [`OPFForm`](@ref) instance — `Polar()` (default), `Rect()` or `DC()`. - `user_callback`: User function that extends the model - `start`: Starting-point overrides; see [`opf_args`](@ref). +- `from`: the case format, when it cannot be inferred from the extension — `"powermodels"`, + `"psse"`, `"powerworld"`, `"matpower"`, `"pandapower"`, `"egret"`, `"pslf"`. - `kwargs...`: Additional keyword arguments passed to the model builder. # Returns diff --git a/test/powerio_parser_tests.jl b/test/powerio_parser_tests.jl index ce7e826..135f195 100644 --- a/test/powerio_parser_tests.jl +++ b/test/powerio_parser_tests.jl @@ -84,6 +84,47 @@ function powerio_parser_tests() @test [b.b.pd for b in d.busarray[:, 2]] ≈ 0.5 .* [b.b.pd for b in d.busarray[:, 1]] end + # A zero line rating means "no limit" in every format PowerIO reads, and real + # cases use it: every arc of stock MATPOWER case14, case57 and case118. Read + # literally it bounds the flow at exactly zero and asks for p^2 + q^2 <= 0, + # which made those cases INFEASIBLE_PROBLEM_DETECTED rather than solved. + mktempdir() do dir + src = read(_case_path("pglib_opf_case14_ieee.m"), String) + zeroed = joinpath(dir, "case14_norate.m") + open(zeroed, "w") do io + inbranch = false + for l in split(src, '\n') + if !inbranch && occursin(r"^\s*mpc\.branch\s*=\s*\[", l) + inbranch = true + elseif inbranch && occursin(r"^\s*\];", l) + inbranch = false + elseif inbranch + f = split(l, '\t') + length(f) > 6 && (f[7] = " 0.0") + l = join(f, '\t') + end + println(io, l) + end + end + + d = ExaModelsPower.opf_args(zeroed; T = Float64)[1] + @test all(isinf, d.rate_a) + @test all(isinf, d.branch_rate_a) + @test all(isinf, d.branch_thermal_ucon) + + for form in (Polar(), Rect()) + m, _, _ = ac_opf_model(zeroed; form = form) + @test all(isfinite, NLPModels.cons(m, m.meta.x0)) + r = madnlp(m; print_level = MadNLP.ERROR, tol = 1e-8) + @test r.status == MadNLP.SOLVE_SUCCEEDED + end + + # The rated case is untouched: every bound is the rating itself. + rated = ExaModelsPower.opf_args(_case_path("pglib_opf_case14_ieee.m"); T = Float64)[1] + @test all(isfinite, rated.rate_a) + @test all(iszero, rated.branch_thermal_ucon) + end + mktempdir() do dir matpower = _case_path("pglib_opf_case3_lmbd.m") psse_path = joinpath(dir, "case3.raw") From 424054e0884b3357e2d8f403b85a94156dd34a02 Mon Sep 17 00:00:00 2001 From: samtalki <10187005+samtalki@users.noreply.github.com> Date: Tue, 18 Aug 2026 05:33:53 -0400 Subject: [PATCH 2/6] Assert PowerIO's own parse inference, not only this package's wrapper The wrapper forwards T as a keyword, so its inference stays unresolved even once PowerIO pins its return type; only a positional `::Type{T}` method resolves it. Asserting both separates the two halves: the PowerIO assertion flips as soon as the library is fixed, the wrapper assertion flips when the call site here follows. --- test/powerio_parser_tests.jl | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/test/powerio_parser_tests.jl b/test/powerio_parser_tests.jl index 135f195..6513da4 100644 --- a/test/powerio_parser_tests.jl +++ b/test/powerio_parser_tests.jl @@ -43,12 +43,17 @@ function powerio_parser_tests() # 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. + # Both assertions are 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 `Type{<:Real}` keyword that nothing downstream specializes on. + # The rows ARE concrete at run time, which the isbits checks assert; only + # inference cannot prove it. The first flips when PowerIO pins the return type; + # the second needs that plus a positional `::Type{T}` method to forward `T` + # through, since a keyword forward stays unresolved either way. let path = _case_path("pglib_opf_case14_ieee.m") + @test_broken isconcretetype( + Base.infer_return_type(PowerIO.parse_ac_power_data, (String,)), + ) @test_broken isconcretetype( Base.infer_return_type(ExaModelsPower.parse_ac_power_data, (String, Type{Float64})), ) From 6556ea42ae79241324fa1f2f74ec432513d1f5ab Mon Sep 17 00:00:00 2001 From: samtalki <10187005+samtalki@users.noreply.github.com> Date: Thu, 20 Aug 2026 13:22:25 -0400 Subject: [PATCH 3/6] Read every GOC3 index off PowerIO's rows PowerIO 0.9 carries document order ordinals on the SCOPF instance rows, `j_dev` within the device class and `j_sdd` in the canonical producers then consumers stacking, and the initial on status on the device, ac line and transformer rows. Every index this package derived from a uid string is now a field read: `_uidnum`, `get_j_pr`, `get_j_cs`, `get_j_prcs`, `is_pr` and the `producers_first` threading are deleted, the stacked variable numbering is arithmetic on the ordinals, and the rows that reference a device from another table (energy windows, price blocks) map through per class dictionaries built from the instance rows. The suffix rule read the digits in a uid as the device's position in its class, so any file that does not follow the competition uid convention was misindexed, including GOC's own 14 bus validation case; PowerIO warned and continued. On C3E4N00073D1_scenario_303 the two agree everywhere: no row differs across 154 producers, 51 consumers, the active reserve set rows, 105 ac lines, 15 transformers, 1 dc line and 73 buses. `parse_sc_data` takes the GOC3 document text and returns the data and the lengths. `goc3_scopf_data` types PowerIO's parse of it, so the periods and the interval durations come off the instance instead of a second raw parse, and the three `goc3_add_status_flags!` calls take typed rows in place of the raw lookup dictionaries. `save_go3_solution` takes the case file, rebuilds the uid to index tables from the instance and maps every solution row through them. Its old signature could not be called: it asked for `producers_first`, which `goc3_model` never returned, and it had no call sites. Renaming every uid in the case and the unit commitment document, so the digits the retired rule would have read run in reverse of document order, must move neither the model nor the written solution. The regression asserts both: same variable count, same objective and constraints at x0, and every written field equal to the rename of the original, uid for uid. Verified against PowerIO on the companion `v09/scopf-instance-consumers` branch: the goc3 slice and the full suite pass. Co-Authored-By: Claude Opus 5 --- src/goc3.jl | 3 +- src/sc_parser.jl | 127 ++++++++++++++++++++++------------------------ test/opf_tests.jl | 64 +++++++++++++++++++++++ test/runtests.jl | 4 ++ 4 files changed, 130 insertions(+), 68 deletions(-) diff --git a/src/goc3.jl b/src/goc3.jl index c9cc67a..fa2722b 100644 --- a/src/goc3.jl +++ b/src/goc3.jl @@ -10,8 +10,7 @@ function goc3_model( uc_data = JSON.parsefile(uc_filename) - data = PowerIO.parse_goc3_json(filename) - sc_data, lengths, producers_first = parse_sc_data(data, uc_data) + sc_data, lengths = parse_sc_data(read(filename, String), uc_data) @info "parsed data" (; L_J_xf, L_J_ln, L_J_ac, L_J_dc, L_J_br, L_J_cs, diff --git a/src/sc_parser.jl b/src/sc_parser.jl index c17ec16..0e50f27 100644 --- a/src/sc_parser.jl +++ b/src/sc_parser.jl @@ -1,23 +1,9 @@ -# 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 - -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)) - parse(Int, match(r"\d+", uid_str).match) + 1 + offset -end - -function get_j_cs(uid_str::String, L_J_pr::Int, L_J_cs::Int, producers_first::Bool) - offset = Int64(producers_first ? (-L_J_pr) : 0) - parse(Int, match(r"\d+", uid_str).match) + 1 + offset -end - -_uidnum(s) = parse(Int, match(r"\d+", s).match) +# PowerIO returns the general GOC3 topology and time-series rows, keyed by uid +# and per-class document-order ordinals (j_dev within the class, j_sdd in the +# canonical producers-then-consumers stacking). 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 threaded on here — +# as arithmetic on the ordinals, never as a read of a uid spelling. # Shutdown power capability p_sdpc[j_prcs, t, t_prime]. Model-specific: it is # indexed in this model's stacked producer/consumer variable space. @@ -81,16 +67,13 @@ function goc3_shutdown_power_cap_sums!(sum_p, sum_u, devices, commitment, period return nothing end -function parse_sc_data(data, uc_data) +function parse_sc_data(scopf_text, 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) + # `scopf_text` is the GOC3 document itself (read the file at the call site). + scd = PowerIO.goc3_scopf_data(scopf_text) 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 @@ -98,9 +81,9 @@ function parse_sc_data(data, uc_data) (; 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)) + # rows: arithmetic on the document-order ordinals the rows carry. + _stack_pr(r) = (j = r.j_sdd + L_J_br, j_prcs = r.j_sdd, j_pr = r.j_dev) + _stack_cs(r) = (j = r.j_sdd + L_J_br, j_prcs = r.j_sdd, j_cs = r.j_dev) sc_data = ( bus = sc_data.bus, shunt = [(j = s.j_sh + L_J_br + L_J_cspr, s...) for s in sc_data.shunt], @@ -111,18 +94,23 @@ function parse_sc_data(data, uc_data) 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], + prod = [(; _stack_pr(p)..., p...) for p in sc_data.prod], + cons = [(; _stack_cs(c)..., c...) for c 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], + active_reserve_set_pr = [(i = r.i, _stack_pr(r)..., n = r.n_p, n_p = r.n_p) for r in sc_data.active_reserve_set_pr], + active_reserve_set_cs = [(i = r.i, _stack_cs(r)..., n = r.n_p, n_p = r.n_p) for r in sc_data.active_reserve_set_cs], + reactive_reserve_set_pr = [(i = r.i, _stack_pr(r)..., n = r.n_q + L_N_p, n_q = r.n_q) for r in sc_data.reactive_reserve_set_pr], + reactive_reserve_set_cs = [(i = r.i, _stack_cs(r)..., n = r.n_q + L_N_p, n_q = r.n_q) for r in sc_data.reactive_reserve_set_cs], ) - periods = data.periods - dt = Float64.(data.dt) + # Stacked indices by device uid, for the rows that reference a device from + # another table (energy windows, price blocks). + pr_stack = Dict(p.uid => (j = p.j, j_prcs = p.j_prcs, j_pr = p.j_pr) for p in sc_data.prod) + cs_stack = Dict(c.uid => (j = c.j, j_prcs = c.j_prcs, j_cs = c.j_cs) for c in sc_data.cons) + + periods = 1:L_T + dt = scd.dt # 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. @@ -130,9 +118,9 @@ function parse_sc_data(data, uc_data) 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) + PowerIO.goc3_add_status_flags!(uc_data["time_series_output"]["ac_line"], scd.static.acl_branch) + PowerIO.goc3_add_status_flags!(uc_data["time_series_output"]["two_winding_transformer"], scd.static.acx_branch) + PowerIO.goc3_add_status_flags!(sdd_uc, vcat(scd.static.prod, scd.static.cons)) # 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) @@ -166,14 +154,14 @@ function parse_sc_data(data, uc_data) # 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] + W_en_max_pr = [(w_en_max_pr_ind = r.w_en_max_pr_ind, pr_stack[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, cs_stack[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, pr_stack[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, cs_stack[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, pr_stack[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, cs_stack[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, pr_stack[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, cs_stack[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) L_W_en_max_cs = length(W_en_max_cs) L_W_en_min_pr = length(W_en_min_pr) @@ -181,8 +169,8 @@ function parse_sc_data(data, uc_data) 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] + p_jtm_flattened_pr = [(flat_k = r.flat_k, pr_stack[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, cs_stack[r.uid]..., t = r.t, m = r.m, c_en = r.c_en, p_max = r.p_max) for r in pb_cs] # Post-contingency surviving AC branches. PowerIO enumerates the pure survivor # rows per contingency; here we attach the UC on_status and expand over @@ -414,21 +402,30 @@ function parse_sc_data(data, uc_data) # 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 + return sc_time_data, lengths end -function save_go3_solution(uc_filename, solution_name, result, vars, lengths, producers_first) +function save_go3_solution(case_filename, uc_filename, solution_name, result, vars, lengths) + # The writer maps every solution row back to a variable index through the + # instance's uid tables, so a uid can spell anything. Rebuilding the + # instance here keeps the function self-contained (one extra parse per + # solution write). + scd = PowerIO.goc3_scopf_data(read(case_filename, String)) + st = scd.static + pr_index = Dict(r.uid => r.j_dev for r in st.prod) + cs_index = Dict(r.uid => r.j_dev for r in st.cons) + xf_index = Dict(r.uid => r.j_xf for r in st.acx_branch) + dc_index = Dict(r.uid => r.j_dc for r in st.dc_branch) + bus_index = Dict(r.uid => r.i for r in st.bus) + uc_data = JSON.parsefile(uc_filename) - (; L_J_pr, L_J_cs, L_T) = lengths + (; L_T) = lengths #Update simple dispatchable devices for line in uc_data["time_series_output"]["simple_dispatchable_device"] - 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) + uid = String(line["uid"]) + if haskey(cs_index, uid) #This section corresponds to consuming devices - if producers_first - solution_index -= L_J_pr - end + solution_index = cs_index[uid] line["p_syn_res"] = Array(solution(result, vars.p_jt_scr_cs))[solution_index,:] line["p_ramp_res_up_online"] = Array(solution(result, vars.p_jt_rru_on_cs))[solution_index,:] line["p_nsyn_res"] = zeros(L_T) @@ -443,9 +440,7 @@ function save_go3_solution(uc_filename, solution_name, result, vars, lengths, pr line["p_ramp_res_down_offline"] = Array(solution(result, vars.p_jt_rrd_off_cs))[solution_index,:] else #Producing devices - if !producers_first - solution_index -= L_J_cs - end + solution_index = pr_index[uid] line["p_syn_res"] = Array(solution(result, vars.p_jt_scr_pr))[solution_index,:] line["p_ramp_res_up_online"] = Array(solution(result, vars.p_jt_rru_on_pr))[solution_index,:] line["p_nsyn_res"] = Array(solution(result, vars.p_jt_nsc_pr))[solution_index,:] @@ -462,15 +457,15 @@ 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 = _uidnum(line["uid"]) + 1 #This corresponds to j_xf + solution_index = xf_index[String(line["uid"])] line["tm"] = Array(solution(result, vars.τ_jt_xf))[solution_index,:] - line["ta"] = Array(solution(result, vars.φ_jt_xf))[solution_index,:] + line["ta"] = Array(solution(result, vars.φ_jt_xf))[solution_index,:] end #ac line flows can be inferred from voltage and angle levels #Update DC lines for line in uc_data["time_series_output"]["dc_line"] - solution_index = _uidnum(line["uid"]) + 1 #This corresponds to j_dc + solution_index = dc_index[String(line["uid"])] 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,:] @@ -478,7 +473,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 = _uidnum(line["uid"]) + 1 #This corresponds to i + solution_index = bus_index[String(line["uid"])] line["vm"] = Array(solution(result, vars.v_it))[solution_index,:] line["va"] = Array(solution(result, vars.θ_it))[solution_index,:] end diff --git a/test/opf_tests.jl b/test/opf_tests.jl index 930e9c9..c08f0e4 100644 --- a/test/opf_tests.jl +++ b/test/opf_tests.jl @@ -86,6 +86,70 @@ end # GOC3 is a smoke test of the parser and the model constructor. Solving it cost 32 of the # 47 min this section took in CI, for one iteration of a 139502-variable problem, so build # the model and evaluate its callbacks instead of solving. +# The model may not depend on uid spellings. Rename every uid so the digits +# the retired suffix rule would have read run in reverse of document order; +# the model built from the renamed pair must be the one built from the +# original. This is the regression for the misindexing that rule caused on +# files that do not follow the competition uid convention. +function sc_uid_invariance_tests(filename, backend, T) + case_path = filename * ".json" + uc_path = filename * "_solution.json" + case = JSON.parsefile(case_path) + uc = JSON.parsefile(uc_path) + uids = String[] + for section in values(case["network"]) + section isa Vector || continue + for item in section + item isa Dict && haskey(item, "uid") && push!(uids, String(item["uid"])) + end + end + n = length(uids) + mapping = Dict(uid => "renamed $(n - i) ($uid)" for (i, uid) in enumerate(uids)) + rename(x::Dict) = Dict(k => rename(v) for (k, v) in x) + rename(x::Vector) = [rename(v) for v in x] + rename(x::String) = get(mapping, x, x) + rename(x) = x + dir = mktempdir() + renamed_case = joinpath(dir, "case.json") + renamed_uc = joinpath(dir, "case_solution.json") + open(renamed_case, "w") do io + JSON.print(io, rename(case)) + end + open(renamed_uc, "w") do io + JSON.print(io, rename(uc)) + end + m0, _, vars0, lengths0, _ = ExaModelsPower.goc3_model(case_path, uc_path; backend = backend, T = T) + m1, _, vars1, lengths1, _ = ExaModelsPower.goc3_model(renamed_case, renamed_uc; backend = backend, T = T) + x0 = m0.meta.x0 + @test m1.meta.nvar == m0.meta.nvar + @test NLPModelsJuMP.obj(m1, x0) ≈ NLPModelsJuMP.obj(m0, x0) + @test Array(NLPModelsJuMP.cons(m1, x0)) ≈ Array(NLPModelsJuMP.cons(m0, x0)) + + # The solution writer maps every row back to a variable index through the + # instance's uid tables. Write the same variable vector against both + # documents; each written row must carry the values its original carries. + x = collect(x0) + S = typeof(x) + result = ExaModels.SolverCore.GenericExecutionStats{eltype(x),S,S,Any}(solution = x) + written = joinpath(dir, "written.json") + written_renamed = joinpath(dir, "written_renamed.json") + ExaModelsPower.save_go3_solution(case_path, uc_path, written, result, vars0, lengths0) + ExaModelsPower.save_go3_solution(renamed_case, renamed_uc, written_renamed, result, vars1, lengths1) + w0 = JSON.parsefile(written)["time_series_output"] + w1 = JSON.parsefile(written_renamed)["time_series_output"] + @test Set(keys(w0)) == Set(keys(w1)) + for (section, rows) in w0 + by_uid = Dict(String(r["uid"]) => r for r in w1[section]) + @test length(by_uid) == length(rows) + for row in rows + renamed_row = by_uid[rename(String(row["uid"]))] + for (field, value) in row + @test renamed_row[field] == rename(value) + end + end + end +end + function sc_tests(filename, backend, T) uc_filename = filename*"_solution.json" filename = filename*".json" diff --git a/test/runtests.jl b/test/runtests.jl index 1954ad5..2ff9e33 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -1,4 +1,5 @@ using Test, ExaModelsPower, MadNLP, MadNLPGPU, KernelAbstractions, CUDA, CUDSS, PowerModels, Ipopt, JuMP, ExaModels, NLPModelsJuMP +import ExaModelsPower.JSON as JSON # Import only `CNLPModel`, not all of CNLPModels: it exports `solution` and so # does ExaModels, and a name exported by two loaded packages resolves to # neither -- which took out 24 tests that call `solution` unqualified. @@ -295,6 +296,9 @@ function runtests() @testset "GOC3, Float64, nothing" begin sc_tests("../data/C3E4N00073D1_scenario_303", nothing, Float64) end + @testset "GOC3 uid invariance" begin + sc_uid_invariance_tests("../data/C3E4N00073D1_scenario_303", nothing, Float64) + end end end end From f0e9e7f6033634b99a9d469d5f88d982170736b0 Mon Sep 17 00:00:00 2001 From: samtalki <10187005+samtalki@users.noreply.github.com> Date: Thu, 20 Aug 2026 13:22:37 -0400 Subject: [PATCH 4/6] Forward the element type positionally so the parse infers PowerIO's `T` keyword is a value of an abstract `Type{<:Real}`, so forwarding the wrapper's static parameter through it dropped the specialization: the result inferred as an unparameterized NamedTuple and every field read off it widened to `AbstractArray{BusRow{T}} where T`. Forwarding positionally keeps the static parameter, which is what the wrapper's own comment says its `::Type{T}` signature exists for. Both inference assertions now hold and stop being broken. PowerIO 0.9 pins its own return type, which flips the first, and this call site follows it, which is what the second was waiting on. A single abstract field in the parse leaves `ExaModel(CORE, data)` unresolved under `--trim=safe`, so the assertions are the guard against that regressing. EMP_TEST_SELECTION=all: 6713 passed, 0 failed, 0 broken, 13m39s. Co-Authored-By: Claude Opus 5 --- src/parser.jl | 6 ++++-- test/powerio_parser_tests.jl | 14 +++++--------- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/src/parser.jl b/src/parser.jl index ce6074d..1e7ee99 100644 --- a/src/parser.jl +++ b/src/parser.jl @@ -18,11 +18,13 @@ _case_path(filename) = # 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. +# it is a static parameter and the whole chain stays concrete. The forward has +# to be positional for the same reason: PowerIO's `T` keyword is a value of an +# abstract `Type{<:Real}`, so a keyword forward drops the static parameter. parse_ac_power_data(filename) = parse_ac_power_data(filename, Float64) 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) + return PowerIO.parse_ac_power_data(_case_path(filename), T; from = from) end # Resolve a case name to a parsed network. The same network feeds both the diff --git a/test/powerio_parser_tests.jl b/test/powerio_parser_tests.jl index 6513da4..592699f 100644 --- a/test/powerio_parser_tests.jl +++ b/test/powerio_parser_tests.jl @@ -43,18 +43,14 @@ function powerio_parser_tests() # 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. # - # Both assertions are 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 `Type{<:Real}` keyword that nothing downstream specializes on. - # The rows ARE concrete at run time, which the isbits checks assert; only - # inference cannot prove it. The first flips when PowerIO pins the return type; - # the second needs that plus a positional `::Type{T}` method to forward `T` - # through, since a keyword forward stays unresolved either way. + # Both halves hold as of PowerIO 0.9: the library pins its return type, and the + # wrapper forwards `T` positionally so the static parameter survives the call. + # Either one regressing widens the rows back to an abstract element type. let path = _case_path("pglib_opf_case14_ieee.m") - @test_broken isconcretetype( + @test isconcretetype( Base.infer_return_type(PowerIO.parse_ac_power_data, (String,)), ) - @test_broken isconcretetype( + @test isconcretetype( Base.infer_return_type(ExaModelsPower.parse_ac_power_data, (String, Type{Float64})), ) p = ExaModelsPower.parse_ac_power_data(path, Float64) From 8ec05e181524b82e5758e2e70c8e7fa52b829e48 Mon Sep 17 00:00:00 2001 From: samtalki <10187005+samtalki@users.noreply.github.com> Date: Thu, 20 Aug 2026 15:52:16 -0400 Subject: [PATCH 5/6] Keep PowerIO multiperiod parsing concrete Pass the element type positionally through every PowerIO parse and load series call so the multiperiod argument function has one exact inferred return type. Restrict PGLib fallback resolution to bare case names, and run the compiled library check as a self-contained CI slice with a private output directory. --- .github/workflows/ci.yml | 6 ++--- README.md | 5 ++-- src/mpopf.jl | 9 +++---- src/parser.jl | 15 ++++++++--- test/powerio_parser_tests.jl | 32 ++++++++++++++++++++-- test/recipe_tests.jl | 52 +++++++++++++++++++----------------- test/runtests.jl | 30 +++++++++++---------- 7 files changed, 94 insertions(+), 55 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0c002ea..08db621 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,9 +30,9 @@ jobs: fail-fast: false matrix: julia-version: ['1'] - # Each backend, and the GOC3 smoke test, run as their own job so that the wall - # clock is the slowest slice rather than the sum of all of them. - selection: ['nothing', 'cpu', 'cuda', 'goc3'] + # Each backend, GOC3, and AOT run as their own job so that the wall clock is the + # slowest slice rather than the sum of all of them. + selection: ['nothing', 'cpu', 'cuda', 'goc3', 'aot'] steps: - name: Checkout repository uses: actions/checkout@v4 diff --git a/README.md b/README.md index 5783f8b..eff0126 100644 --- a/README.md +++ b/README.md @@ -19,8 +19,9 @@ it cannot be, as for a `.json` file: model, vars, cons = ac_opf_model("case118.json"; from = "powermodels") ``` -A name that is not a path on disk is looked up in the bundled PGLib-OPF library, which is -what `"pglib_opf_case118_ieee.m"` below resolves through. +A bare name that is not a file in the working directory is looked up in the bundled +PGLib-OPF library, which is what `"pglib_opf_case118_ieee.m"` below resolves through. +Paths with a directory component are passed to PowerIO unchanged. ## Usage ### Static optimal power flow diff --git a/src/mpopf.jl b/src/mpopf.jl index 849ace5..4ac5ce5 100644 --- a/src/mpopf.jl +++ b/src/mpopf.jl @@ -8,7 +8,7 @@ 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} - raw = PowerIO.parse_ac_power_data(net; T = T) + raw = PowerIO.parse_ac_power_data(net, T) _check_periods(series, N) # No empty-storage ternary: its two branches had DIFFERENT types (a vector @@ -53,9 +53,9 @@ end # 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) + return PowerIO.read_load_series(net, pd_path, qd_path, T) elseif pd !== nothing && qd !== nothing - return PowerIO.LoadSeries(net, pd, qd; T = T) + return PowerIO.LoadSeries(net, pd, qd, T) end throw( ArgumentError( @@ -174,7 +174,7 @@ mpopf_args(filename, curve; N = length(curve), T = Float64, backend = nothing, 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, + d = parse_mp_power_data(net, PowerIO.LoadSeries(net, curve, T), N, corrective_action_ratio, T) return (convert_data(_mp_narrow(d, N, T), backend),) end @@ -711,4 +711,3 @@ function mpopf_model( return build_mpopf(data, Nbus, Np, discharge_func, form,user_callback, backend = backend, T = T, kwargs...) end - diff --git a/src/parser.jl b/src/parser.jl index 1e7ee99..b80bd86 100644 --- a/src/parser.jl +++ b/src/parser.jl @@ -9,10 +9,17 @@ 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) +# A bare case name that is not a file in the working directory is looked up in +# the bundled PGLib-OPF directory, which is the one thing ExaPowerIO is still +# here for. A path with a directory component stays a path: rebasing a missing +# `cases/foo.m` below the PGLib artifact hides the path the caller actually +# supplied and makes relative paths depend on the artifact layout. +function _case_path(filename::AbstractString) + path = String(filename) + isfile(path) && return path + isempty(dirname(path)) || return path + return joinpath(ExaPowerIO.get_path(:pglib), path) +end # `T` is a TYPE PARAMETER, not a value of type `Type`. As a plain positional # argument it arrives typed `Type` — abstract — and then the parse cannot diff --git a/test/powerio_parser_tests.jl b/test/powerio_parser_tests.jl index 592699f..fa190b5 100644 --- a/test/powerio_parser_tests.jl +++ b/test/powerio_parser_tests.jl @@ -39,6 +39,14 @@ function powerio_parser_tests() _test_matches_exapowerio(actual, expected) end + # Only bare names use the PGLib fallback. An explicit path must reach + # PowerIO unchanged even when it is missing, so its error names the + # caller's path rather than a fabricated path inside the artifact. + let missing = joinpath("missing-cases", "case.m") + @test ExaModelsPower._case_path(missing) == missing + @test isfile(ExaModelsPower._case_path("pglib_opf_case3_lmbd.m")) + 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. @@ -63,7 +71,7 @@ function powerio_parser_tests() # 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_series = PowerIO.LoadSeries(mp_net, [1.0, 0.95], 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)) @@ -74,10 +82,30 @@ function powerio_parser_tests() mp_net, mp_series, 3, 0.1, Float64) end + # The exact multiperiod argument type is part of the compiled library + # boundary. Concrete rows at run time are not enough: juliac needs to + # infer the same closed type before it emits the library. + let path = _case_path("pglib_opf_case3_lmbd.m"), curve = [1.0, 0.95] + args = (path, curve, 2, Float64, nothing, 0.1, nothing) + actual = ExaModelsPower.mpopf_args(args...) + signature = Tuple{ + String, + Vector{Float64}, + Int, + Type{Float64}, + Nothing, + Float64, + Nothing, + } + inferred = Base.infer_return_type(ExaModelsPower.mpopf_args, signature) + @test isconcretetype(inferred) + @test inferred === typeof(actual) + 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) + series = PowerIO.LoadSeries(net, [1.0, 0.5], 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) diff --git a/test/recipe_tests.jl b/test/recipe_tests.jl index 8f5d5ee..4763c40 100644 --- a/test/recipe_tests.jl +++ b/test/recipe_tests.jl @@ -61,32 +61,34 @@ function test_solution_handles(filename, form) @test total == m.meta.nvar end -# Compiling costs ~90 s per form and needs ExaModelsC, which is not a test -# dependency, so it is opt-in: EMP_TEST_AOT=1. -# Compiling is minutes, so this is opt-in and runs ONCE for the whole suite -# rather than once per case and formulation: the plain default call a user -# makes, then a few properties of what comes back. `obj`/`cons` are checked -# away from x0, so a library that returned constants -- or that ignored the -# case it was handed -- would fail rather than agree trivially. +# Compiling takes minutes, so CI gives it one dedicated slice instead of +# repeating it for every backend. `EMP_TEST_AOT=1` also adds it to a local +# full run. The test makes the plain default call a user makes, then checks a +# few properties of what comes back. `obj`/`cons` are checked away from x0, so +# a library that returned constants -- or ignored its case -- would fail. function test_aot() - r = compile_all(ExaModelsPower) - @test isfile(r.libpath) - @test Set(Symbol.(r.prefixes)) == Set((:acp, :acr, :dcp, :mpacp, :mpacr, :mpdcp)) + mktempdir() do dir + # A test must not require a caller-owned CNLPMODELS_PATH. Install the + # library in its private directory and remove it with the directory. + r = compile_all(ExaModelsPower; path = joinpath(dir, "emp")) + @test isfile(r.libpath) + @test Set(Symbol.(r.prefixes)) == Set((:acp, :acr, :dcp, :mpacp, :mpacr, :mpdcp)) - case = "pglib_opf_case14_ieee.m" - m = CNLPModel(r.libpath, :acp, case) - ref, _, _ = ac_opf_model(case) - @test (m.meta.nvar, m.meta.ncon) == (ref.meta.nvar, ref.meta.ncon) - @test collect(m.meta.x0) == collect(ref.meta.x0) - x = [0.9 + 0.02sin(i) for i = 1:m.meta.nvar] - @test NLPModels.obj(m, x) == NLPModels.obj(ref, x) - @test collect(NLPModels.cons(m, x)) == collect(NLPModels.cons(ref, x)) + case = "pglib_opf_case14_ieee.m" + m = CNLPModel(r.libpath, :acp, case) + ref, _, _ = ac_opf_model(case) + @test (m.meta.nvar, m.meta.ncon) == (ref.meta.nvar, ref.meta.ncon) + @test collect(m.meta.x0) == collect(ref.meta.x0) + x = [0.9 + 0.02sin(i) for i = 1:m.meta.nvar] + @test NLPModels.obj(m, x) == NLPModels.obj(ref, x) + @test collect(NLPModels.cons(m, x)) == collect(NLPModels.cons(ref, x)) - # The property the recipe rewrite exists for: a network size the library - # was never compiled against. - m3 = CNLPModel(r.libpath, :mpdcp, "pglib_opf_case3_lmbd.m") - ref3, _, _ = mpopf_model("pglib_opf_case3_lmbd.m", - ExaModelsPower.MPOPF_DEFAULT_CURVE; - form = ExaModelsPower.DC()) - @test (m3.meta.nvar, m3.meta.ncon) == (ref3.meta.nvar, ref3.meta.ncon) + # The property the recipe rewrite exists for: a network size the + # library was never compiled against. + m3 = CNLPModel(r.libpath, :mpdcp, "pglib_opf_case3_lmbd.m") + ref3, _, _ = mpopf_model("pglib_opf_case3_lmbd.m", + ExaModelsPower.MPOPF_DEFAULT_CURVE; + form = ExaModelsPower.DC()) + @test (m3.meta.nvar, m3.meta.ncon) == (ref3.meta.nvar, ref3.meta.ncon) + end end diff --git a/test/runtests.jl b/test/runtests.jl index 2ff9e33..bee2ca4 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -11,12 +11,12 @@ 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 -# 30814411004). EMP_TEST_SELECTION names the slice; it defaults to everything, so a plain -# local `Pkg.test()` still runs the whole suite. +# CI runs each backend, GOC3, and AOT as separate jobs, so the wall clock is the +# slowest of them rather than their sum. EMP_TEST_SELECTION names the slice; it +# defaults to the runtime suite, so a plain local `Pkg.test()` runs every model +# test without compiling the shared library. const SELECTION = get(ENV, "EMP_TEST_SELECTION", "all") -const VALID_SELECTIONS = ("all", "nothing", "cpu", "cuda", "goc3") +const VALID_SELECTIONS = ("all", "nothing", "cpu", "cuda", "goc3", "aot") SELECTION in VALID_SELECTIONS || error("EMP_TEST_SELECTION must be one of $(join(VALID_SELECTIONS, ", ")), got $(repr(SELECTION))") @@ -31,11 +31,15 @@ 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") +# AOT has its own CI slice because it compiles all six models and does not need +# a GPU. Keep EMP_TEST_AOT as the local opt-in for a full `Pkg.test()` run. +const RUN_AOT = SELECTION == "aot" || haskey(ENV, "EMP_TEST_AOT") # 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") +isempty(CONFIGS) && !RUN_GOC3 && !RUN_AOT && + error("EMP_TEST_SELECTION=$(SELECTION) selected no tests") test_cases = [("../data/pglib_opf_case3_lmbd.m", "case3", test_case3), ("../data/pglib_opf_case5_pjm.m", "case5", test_case5), @@ -145,6 +149,12 @@ function runtests() # so it runs once rather than per backend. RUN_PARSER && powerio_parser_tests() + if RUN_AOT + @testset "compile_all, then the models it returns" begin + test_aot() + end + end + if SELECTION in ("all", "nothing") for (filename, case, _) in test_cases, (form_str, form, _, _) in static_forms @testset "$case, recipe == eager, $form_str" begin @@ -154,14 +164,6 @@ function runtests() test_solution_handles(filename, form) end end - - # Once for the whole suite, not once per case and formulation: - # `compile_all` is minutes of juliac. - if haskey(ENV, "EMP_TEST_AOT") - @testset "compile_all, then the models it returns" begin - test_aot() - end - end end for backend in CONFIGS From a6ee67277d6d8e0b0ca05b3408654a1e2b289e4b Mon Sep 17 00:00:00 2001 From: samtalki <10187005+samtalki@users.noreply.github.com> Date: Fri, 21 Aug 2026 02:58:58 -0400 Subject: [PATCH 6/6] Parse through PowerIO's typed live path `parse_file(BalancedNetwork, ...)` returns the concrete network type rather than one inferred from the call, and `Val(:live)` selects the method that keeps the handle out of the AOT call graph. Every parse and LoadSeries route takes both, so the row element types stay isbits and `ExaModel(CORE, data)` resolves under `--trim=safe`. Co-Authored-By: Claude Opus 5 (1M context) --- src/mpopf.jl | 8 ++++---- src/parser.jl | 5 +++-- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/mpopf.jl b/src/mpopf.jl index 4ac5ce5..bd0371d 100644 --- a/src/mpopf.jl +++ b/src/mpopf.jl @@ -8,7 +8,7 @@ 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} - raw = PowerIO.parse_ac_power_data(net, T) + raw = PowerIO.parse_ac_power_data(net, T, Val(:live)) _check_periods(series, N) # No empty-storage ternary: its two branches had DIFFERENT types (a vector @@ -53,9 +53,9 @@ end # 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) + return PowerIO.read_load_series(net, pd_path, qd_path, T, Val(:live)) elseif pd !== nothing && qd !== nothing - return PowerIO.LoadSeries(net, pd, qd, T) + return PowerIO.LoadSeries(net, pd, qd, T, Val(:live)) end throw( ArgumentError( @@ -174,7 +174,7 @@ mpopf_args(filename, curve; N = length(curve), T = Float64, backend = nothing, 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), N, + d = parse_mp_power_data(net, PowerIO.LoadSeries(net, curve, T, Val(:live)), N, corrective_action_ratio, T) return (convert_data(_mp_narrow(d, N, T), backend),) end diff --git a/src/parser.jl b/src/parser.jl index b80bd86..4f2ebac 100644 --- a/src/parser.jl +++ b/src/parser.jl @@ -31,7 +31,8 @@ end parse_ac_power_data(filename) = parse_ac_power_data(filename, Float64) 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), T; from = from) + net = PowerIO.parse_file(PowerIO.BalancedNetwork, _case_path(filename); from = from) + return PowerIO.parse_ac_power_data(net, T, Val(:live)) end # Resolve a case name to a parsed network. The same network feeds both the @@ -39,5 +40,5 @@ end # 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) + return PowerIO.parse_file(PowerIO.BalancedNetwork, _case_path(filename); from = from) end