Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 23 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,26 @@ 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 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
```julia
using ExaModelsPower, MadNLP, MadNLPGPU, CUDA, ExaModels, GOC3Benchmark, JSON
using ExaModelsPower, MadNLP, MadNLPGPU, CUDA, ExaModels, JSON


model, vars, cons = ac_opf_model(
Expand Down Expand Up @@ -60,6 +76,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
Expand Down
3 changes: 1 addition & 2 deletions src/goc3.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
25 changes: 15 additions & 10 deletions src/mpopf.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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, Val(:live))
_check_periods(series, N)

# No empty-storage ternary: its two branches had DIFFERENT types (a vector
Expand All @@ -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)
)

Expand All @@ -51,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, Val(:live))
elseif pd !== nothing && qd !== nothing
return PowerIO.LoadSeries(net, pd, qd; T = T)
return PowerIO.LoadSeries(net, pd, qd, T, Val(:live))
end
throw(
ArgumentError(
Expand Down Expand Up @@ -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, (;))
Expand Down Expand Up @@ -172,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, Val(:live)), N,
corrective_action_ratio, T)
return (convert_data(_mp_narrow(d, N, T), backend),)
end
Expand All @@ -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)),
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -705,4 +711,3 @@ function mpopf_model(

return build_mpopf(data, Nbus, Np, discharge_func, form,user_callback, backend = backend, T = T, kwargs...)
end

29 changes: 23 additions & 6 deletions src/opf.jl
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,23 @@ _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,)

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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
24 changes: 17 additions & 7 deletions src/parser.jl
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,36 @@ 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
# 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)
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
# 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)
return PowerIO.parse_file(PowerIO.BalancedNetwork, _case_path(filename); from = from)
end
Loading
Loading