User-Defined Constraints — Syntax Reference
GTOpt supports user-defined linear constraints that are added directly to the LP formulation. Constraints are expressed in an AMPL-inspired syntax that references power system elements and their LP variables, with optional domain restrictions over scenarios, stages, and blocks.
Table of Contents
- Quick Start
- Syntax Overview
- Element Types and Attributes
- Element Identification
- Aggregation with sum()
- Domain Specifications
- Comments
- Examples
- External Constraint Files
- Formal Grammar (BNF)
- Error Diagnostics
- Constraint Directives
- Comparison with AMPL
- Best Practices
- See Also
1. Quick Start
Add a user_constraint_array to the system section of your JSON case file:
{ "system": { "bus_array": [...], "generator_array": [...], "user_constraint_array": [ { "uid": 1, "name": "gen_pair_limit", "expression": "generator('G1').generation + generator('G2').generation <= 300" } ] } }
This adds a constraint to the LP: the sum of generation from G1 and G2 must not exceed 300 MW in every scenario, stage, and block.
2. Syntax Overview
A constraint expression has three parts:
<linear_expression> <operator> <rhs> [, for(<domain>)]
| Part | Description | Example |
|---|---|---|
| Linear expression | Sum of coefficient * element.attribute terms | 2 * generator('G1').generation - demand('D1').load |
| Operator | Comparison: <=, >=, or = | <= |
| RHS | Right-hand side: number or another linear expression | 300 |
| Domain (optional) | Index restriction: for(stage in ..., block in ...) | for(stage in {1,2,3}, block in 1..24) |
Arithmetic and operator precedence
Linear expressions support the standard arithmetic operators with C/Python-style precedence (highest to lowest):
| Precedence | Operators | Associativity | Notes |
|---|---|---|---|
| 1 (tightest) | ( ) | — | Grouping subexpressions |
| 2 | unary -, unary + | right | -(a - b) distributes the sign |
| 3 | *, / | left | Division is by numeric literals only |
| 4 (loosest) | binary +, - | left | Term addition/subtraction |
Parentheses let you factor out a shared coefficient or divisor:
2 * (generator('G1').generation + generator('G2').generation) <= 300
(generator('G1').generation + generator('G2').generation) / 4 <= 25Constant folding. Any subexpression that contains only numeric literals is folded at parse time, so (2 + 3) * x, 2 * 3 * x and 6/2 * x all resolve to a coefficient of 5, 6, and 3 respectively.
Linearity is enforced. The parser keeps constraints linear and rejects two classes of non-linear expressions:
- Product of two variable-bearing expressions:
generator('G1').generation * generator('G2').generation→ error. - Division by a variable or parameter:
generator('G1').generation / generator('G2').generation→ error. Division by zero is also rejected at parse time.
At least one side of every * must collapse to a constant; every / divisor must collapse to a nonzero constant.
Range constraints
Range constraints bound an expression from both sides:
100 <= generator('G1').generation <= 500This creates a single LP row with both lower and upper bounds.
Nonlinear shortcuts (auto-linearized)
The parser accepts three convex nonlinear shortcuts and lowers them into plain LP rows behind the scenes. You can use them in any single-sided constraint (range constraints are not supported for these). Arguments may be arbitrary linear expressions.
abs(expr) — absolute value
abs(generator('G1').generation - 50) <= 50is lowered as:
t >= 0
generator('G1').generation - 50 - t <= 0
-(generator('G1').generation - 50) - t <= 0
+ t -- replaces abs(...) in the original rowConvexity rules. c · abs(x) must appear on the convex side: c > 0 with <=, or c < 0 with >=. Any other combination (e.g. abs(x) >= k) is non-convex and is rejected with a diagnostic at LP construction time. Nested abs(abs(...)) is rejected at parse time.
max(e1, e2, ...) and min(e1, e2, ...)
max(generator('G1').generation, generator('G2').generation) <= 80
min(generator('G1').generation, generator('G2').generation) >= 5are lowered into one free auxiliary variable t plus one row per argument:
-- max(...) <= : t - t bounds free, arg_i - t <= 0 ∀ i -- min(...) >= : same shape with t - arg_i <= 0
The outer coefficient is preserved, so -3 * max(a, b) >= k rewrites to the equivalent convex <= form. At least two arguments are required. A max/min on the wrong side of the inequality is non-convex and is rejected with a diagnostic.
If every argument is a constant, the expression is folded at parse time (max(3, 7) → 7).
if cond then A else B — data-only conditional
if stage = 1 then (generator('G1').generation)
else (generator('G1').generation * 0.5)
<= 60The condition is evaluated per domain instance at LP-construction time against the loop coordinates — scenario, stage, and block — so only one of the two branches is emitted into the LP row for each (scenario, stage, block). The condition never produces an LP variable; it is pure data.
Supported atoms:
| Form | Meaning |
|---|---|
stage = 2 | Stage UID equality |
stage != 2 | Inequality |
stage in {1, 2, 3} | Set membership (integers and a..b ranges) |
block > 12 | <, <=, >, >= on integer UIDs |
Multiple atoms can be joined with and / &&:
if stage = 1 and block in {1..12} then ... else ... <= 60The else branch is optional; an omitted else means the LP row contains only the constant RHS when the condition is false.
Time-coupling: prev() and block.duration
Two constructs let a per-block constraint reference time, which together make it possible to write a storage/reservoir balance entirely in user-constraint text (see Example 23).
prev(<element_ref>) — the lagged value of an element attribute at the previous chronological block:
prev(decision_variable('vol').value) -- vol at the block before this one- At block
b > 0of a stage it resolves to blockb − 1(the stage must set"chronological": true). - At the first block of a stage it resolves to the cross-stage / cross-phase incoming value — for a
block_statedecision variable that is the previous stage's end-of-stage value (or theinitial_valueon the very first stage). This is what carries a reservoir's storage across stages and, undermethod=sddp, across phases. prev(...)may not be nested and takes a single element reference (nosum, no numeric argument).
<attr>_prev (e.g. generator('G').generation_prev) is the lagged column of an ordinary LP attribute:
- inside a chronological stage: the same attribute at block
b − 1; - at the first block of a stage whose previous stage is in the same phase (same LP) and chronological: the previous stage's last block. This is
model_options.prev_stage_link = "stage"(default);"none"restores the legacy constant 0 at every stage start after the first; - at the first block of a periodic stage (
Stage.periodic: a typical day / week repeated in a cycle, at least 2 blocks) undermodel_options.prev_stage_link = "period": the last block of the same stage — the period wraps (also at the horizon start and at a later-phase start, where no initial value or 0 is used); - at the first block of the horizon (no previous stage): the constant
initial_<attr>when the element defines it —Generator.initial_generationforgeneration_prev(PLEXOS Initial Generation) — folded into the row, sogen − gen_prev ≤ 60withinitial_generation: 80readsgen ≤ 140; otherwise 0; - at the first block of a later phase (SDDP / cascade): 0 — the plain attribute carries no cross-phase state, and the horizon initial value is never reused there. See the known limitation below.
Known limitation — _prev across a phase boundary. Each phase is its own LP, and an ordinary attribute such as generation is not an SDDP state variable, so at the first block of phase 2, 3, … x_prev is the constant 0. A ramp row gen − gen_prev ≤ R then reads gen ≤ R there. That is tighter than the physics when the unit was running at the end of the previous phase (possibly infeasible with pmin > R), and a ramp-down row gen_prev − gen ≤ R is vacuous there. The LP build logs one WARN per affected constraint:
user_constraint 'PANGUEramp': 3 `_prev` term(s) at the first block of a later phase read 0 — the previous phase's value is not carried across phases …
Single-phase runs (monolithic with one phase, the usual PCP / unit-commitment setup) are not affected. Workarounds today: put the ramp-coupled horizon in one phase, or model the coupled quantity as a block_state decision_variable, whose prev(...) is carried across phases.
Proposed fix (not implemented). Register the last-block value of every column that a _prev term references at a phase start as an SDDP state variable, exactly as block_state decision variables and reservoir volumes already are:
- While lowering user constraints, collect the
(class, uid, attribute)triples whose_prevterm falls on a later-phase start (the same test that triggers the WARN). - In the producing phase, register the attribute's column at the last block of the last stage as a state source (
StateVariablewith the element/attribute key). - In the consuming phase, create an incoming column
x_in(bounded by the attribute's own bounds, e.g.[0, pmax]). The_prevterm resolves to it, and it is linked to the source as a state target. The forward pass fixes it to the trial value, and the backward pass returns its reduced cost as the cut coefficient, like any other state. - The monolithic solver with several phases, and cascade, chain the same pair through their existing state-propagation paths.
- Keep it behind an option (e.g.
prev_stage_link = "phase"extendingstage), because every such state adds a cut dimension.
block.duration — a singleton scalar giving the current block's duration Δt (hours). Unlike stage.duration (the whole-stage total), it varies block to block, so it converts a per-block rate (power, flow) into the energy / volume it contributes over the block:
generator('g').generation * block.duration -- MWh drawn over the blockDuration trap. A per-block term is a rate, not an energy:
generator('g').generationis power (MW), and GTOpt does not auto-multiply it by Δt. A storage balance written without* block.durationis only correct when every block is exactly 1 hour long. For multi-hour blocks you must write the explicit* block.durationfactor — this mirrors the native reservoir, whose energy balance scales each flow column by the block duration. (block.durationis the only scalar allowed to multiply a variable; all other products of a parameter and a variable are rejected as non-linear.)
State variables: state()
state(<element_ref>) asserts that the wrapped reference is a cross-phase state column (a DecisionVariable with "state": true / "block_state": true). It is a typing hint that documents intent and is checked during resolution; it does not change the LP value.
Decision variables: scope and where a column is visible
A DecisionVariable (decision_variable('X').value) gets one LP column per cell of its scope. A user constraint of any scope may reference it; every row resolves to the column of the cell that contains the row's (scenario, stage, block):
DV scope | Columns | Visible from |
|---|---|---|
block (default) | one per (scenario, stage, block) | that block only |
stage | one per (scenario, stage) | every block of that stage, same scenario |
phase | one per (scene, phase) LP | every block, stage and scenario of the phase |
global | one per (scene, phase) LP | every block, stage and scenario of the phase |
block: N selector | one, on block N of each (scenario, stage) | block N only |
So x <= decision_variable('g').value written as an ordinary per-block constraint with a global g bounds x on every block by the same single column: the cell column is built before any block or stage row.
Non-anticipative (here-and-now) decisions. A phase/global column is shared by all scenarios of a scene, so it cannot adapt to the scenario: it is a first-stage decision in the stochastic-programming sense. Put the scenarios in one scene (the default when scene_array is omitted) and give the decision scope: "global" — no nonanticipative flag is needed. When the scenarios are split into several scenes (e.g. one scene per hydrology), add "nonanticipative": true (see Nonanticipative across scenes below). A stage (or block) column is per scenario (wait-and-see). A probability- weighted cost (cost_type: "energy" / "power") on a shared column is weighted by the scene's total probability, not one scenario's.
Limits of a "global" column.
- Across scenes: each scene is a separate LP, so each scene has its own copy. Non-anticipativity holds within a scene, but not across scenes — unless the variable sets
"nonanticipative": true(below). Across phases (SDDP, cascade, multi-phase monolithic): each phase LP has its own copy, and gtopt chains them so a
globalvariable is still ONE value for the whole horizon. Without an explicitstate, aglobalvariable in a run with more than one phase is carried as an implicit state variable ("state": true, "link": true): phase p's copy is linked to phase p−1's, the forward pass pins it to the first phase's value (equality coupling), and SDDP carries it in every cut like a reservoir volume. Itscost(andobj_constant) is charged once, in the first phase. An explicit"state": truekeeps the user's own state + link (cost charged per phase LP, as for any state column). An explicit"state": falseopts out: each phase gets an independent copy and a warning is logged — sayscope: "phase"to request per-phase copies without the warning. The FutureCost user α (use_user_alpha+user_alpha_uid) is exempt: its per-phase copy is the per-phase cost-to-go. The same rule applies to the variables bundled in aUserModel.Method notes: under SDDP the first-phase decision sees the later phases through the cuts, so the converged bound equals the single-LP monolithic optimum. Multi-phase monolithic solves the phases in sequence without cuts, so the first phase decides myopically (later phases still share its value).
Example — an LNG cargo calendar decided once. The number of cargoes (or a delivery schedule) must be fixed before the weather and hydrology are known and cannot be revised later in the horizon:
"decision_variable_array": [ { "uid": 1, "name": "cargo", "lower_bound": 0, "upper_bound": 100, "cost": 1.0, "scope": "global" } ], "user_constraint_array": [ { "uid": 1, "name": "lng_cap", "expression": "generator('lng').generation <= decision_variable('cargo').value" } ]
With all hydrology scenarios in one scene, cargo is shared by every scenario (non-anticipative) and, through the implicit state, by every phase: one here-and-now decision that SDDP optimises against the expected cost of all scenarios and phases.
Nonanticipative across scenes ("nonanticipative": true). A global variable with this flag is ONE value for every scene: a here-and-now decision taken before the scene (the hydrology, …) is known. gtopt then builds the active scenes as one extensive-form LP per phase: the scenes are folded into a single LP scene whose scenarios are the union of theirs. Each scenario keeps its own data, probability and state columns (reservoirs, batteries, …), so the dispatch still adapts per scenario; only the variable is a single shared column. A probability-weighted cost (cost_type: "energy") uses the total probability mass and is charged once; a raw cost is charged once at face value (the anticipative run charges it once per scene). One INFO line names the merged scenes: nonanticipative decision variable(s) 'cargo': scenes [1 'wet', 2 'dry'] merged into one LP scene (uid 1, 2 scenarios) — one shared value across them.
"scene_array": [ { "uid": 1, "name": "wet", "first_scenario": 0, "count_scenario": 1 }, { "uid": 2, "name": "dry", "first_scenario": 1, "count_scenario": 1 } ], "decision_variable_array": [ { "uid": 1, "name": "cargo", "lower_bound": 0, "upper_bound": 100, "cost": 50.0, "cost_type": "energy", "scope": "global", "nonanticipative": true } ]
What changes with the merge:
- Everything scene-level is shared. Every other
phase/globalvariable and the capacity-expansion columns (one per scene LP) also become one column across the merged scenes, i.e. nonanticipative too. - Output. Element results still come out per original scene (
scene=<uid>partition /_s<uid>CSV shard), each holding only its own scenarios' rows; stage-only streams are written to every original scene. The shared variable itself is one column: its value and cost are written once, in the shard of the first merged scene.solution.csvhas one row per phase for the merged LP (uid of the first merged scene). - Monolithic. Exact for one phase. With several phases monolithic is sequential (myopic, see the method notes above), but every phase still uses one value shared by all scenes.
- SDDP / cascade. Supported with the deterministic backward pass (no apertures): the merged LP is re-solved, so the cuts are exact over the joint state of every scenario and the first-phase value is carried to later phases as the implicit state. Every combination that cannot honour the merge is a hard error before anything is solved (see the table).
- Errors (hard, naming the variable): the flag on a non-
globalscope; on the FutureCost user α (α is a per-scene cost-to-go); a run with FutureCost boundary cuts (the cut α of a scene LP is tied to its first scenario's state, so the other scenarios' future cost would be lost); and active scenes whose scenarios are not one contiguous range ofscenario_array. "state": falsekeeps its meaning: one independent copy per phase, each shared by all the merged scenes.
nonanticipative × method / option. "Error" rows fail fast with an InvalidInput error naming the variable and the option (cascade: also the level), each covered by a test. "Supported" rows are covered by a test that checks the optimum, except those marked "generic" (no merge-specific code path; not separately tested).
| Method / option | Status | Why |
|---|---|---|
| monolithic, one phase | supported | exact extensive form |
| monolithic, several phases | supported | sequential (myopic), one shared value per phase |
monolithic mip_start / MIP | supported (generic) | the merged LP is an ordinary LP/MIP |
SDDP, no apertures (apertures: [], num_apertures: 0, or no aperture_array) | supported | deterministic backward pass re-solves the merged LP |
Phase.apertures without aperture_array | supported | inert (no aperture pool) |
backward apertures: aperture_array, sddp_options.apertures, num_apertures > 0, aperture_selection_mode, aperture_chunk_mode | error | the aperture pass perturbs only a scene's first scenario |
cascade level_array[N].sddp_options.apertures / num_apertures > 0 (e.g. default L1 = 8); num_apertures = 0 is supported | error | same, checked for every level before level 0 runs |
cut_sharing_mode = none / multicut | supported | one scene: sharing is a no-op |
cut_sharing_mode = markov | error | markov_states has one entry per original scene |
forward_sampling_mode = resampled | supported | one scene: no-op |
scene probabilities (probability_factor) | supported | each scenario keeps its own weight |
multi-phase "state": false | supported | independent per-phase copies, each shared by all scenes |
low_memory_mode = compress | supported | per-cell snapshots, unchanged |
basis_cross_mode | supported | per-cell basis reuse, unchanged |
elastic_mode, feasibility cuts, update_lp_skip, simulation_mode without loaded cuts | supported (generic) | act on the merged LP's own columns |
FutureCost boundary cuts (cuts_file, boundary_cuts_file) | error | one cut α tied to the first scenario's state |
hot start: cuts_input_file, cut_recovery_mode under --recover | error | cut files store (class, variable, uid) without the scenario |
cascade transition.inherit_optimality_cuts ≠ 0 (incl. --recover resume) | error | same cut-file round trip |
| cascade without cut inheritance | supported | every level re-merges the same scenes |
SDDP investment master (solve_investment_master) | error | one master α per original scene |
FutureCost user α marked nonanticipative | error | α is a per-scene cost-to-go |
non-global scope; non-contiguous active scenes | error | see above |
lp_debug_scene_min/max, per-scene SDDP logs | supported (generic) | address the merged scene (uid of the first merged scene) |
Unreachable columns. If a term names a scope-restricted variable that has no column at the row's (scenario, stage, block) — e.g. a block: 1 variable referenced on block 2, or a coarse variable whose anchor stage is inactive — the term is NOT treated as an implicit 0. strict/debug mode aborts with ... has no LP column at (scenario s, stage t, block b) — the decision_variable has single-block selector (block 1), so its column is not reachable from this row; normal mode logs that warning once per term and drops the term. (The implicit-0 rule still applies to elements whose column is omitted because the element is idle, e.g. a generator with pmax = 0 on that block.)
Terms with no column: implicit 0 vs. mismatch. The same distinction applies to every element class. When a known element/attribute has no LP column at a row's block, gtopt classifies why:
| Reason | Example | Handling |
|---|---|---|
| inactive element | active: [1, 0], referenced in stage 2 | implicit 0 |
| zero capacity | generator pmax = 0 (or demand lmax = 0, line tmax_ab = tmax_ba = 0) on that block | implicit 0 |
| no column at this block | per-block omission inside a stage that has the column on other blocks | implicit 0 |
prev at first block | prev(x) / x_prev on a stage's first block with no incoming value | implicit 0 (but see x_prev below) |
| attribute not built | e.g. line.lossp on a lossless line, a generator with pmax = 0 on every block | implicit 0 |
| suppressed by mode | line(...) under use_single_bus, bus.theta without Kirchhoff | implicit 0 |
| scope mismatch | the element is active with capacity here and its column was registered at an earlier stage of the same LP, but not at this one (e.g. a reserve_provision.up whose zone is inactive in this stage) | strict/debug: error; normal: warning once per term, term dropped |
Implicit-0 drops are counted per constraint and reported once, at the end of the LP build, as one INFO line per constraint: user_constraint 'X': N term occurrence(s) contribute 0 — the element has no LP column there by design (inactive element: 3, zero capacity: 12). An explicit id inside sum(...) that names no known element/attribute (sum(generator('g1', 'typo').generation)) logs a warning once per id and contributes 0 (a single-term typo still aborts).
Scope-restricted DecisionVariables follow the same rule: one that is inactive at the row's stage is an implicit 0 (not a scope error), and sum(decision_variable(all).attr) over a mix of scopes skips the members with no column at that block (counted as scope-restricted member of sum(all) in the INFO summary). An explicit reference — single term or listed id — to an active single-block / coarse-scope variable that is not reachable from the row is still the error described above.
Integer decision variables
A DecisionVariable with "integer": true creates integer LP columns (a MIP). With bounds exactly [0, 1] they are binary; with other bounds they are general integers. The flag works at every scope:
scope | Integer columns |
|---|---|
block (default) | one per (scenario, stage, block) |
stage | one per (scenario, stage) |
phase / global | one per (scene, phase) cell |
"relax": true keeps the columns continuous over their bounds, like Commitment.relax. A continuous phase (Phase.continuous, model_options.continuous_phases, or the --no-mip CLI flag) also relaxes them. The effective rule is relax || phase.continuous.
A coarse "state": true variable may be integer: its column is then both a cross-phase state and an integer column. For a "block_state": true variable only the per-block volume columns are integer. The incoming value_in column is a pinned copy of the previous phase's state, so it stays continuous.
{ "uid": 7, "name": "units_on", "lower_bound": 0, "upper_bound": 3, "integer": true }
Integer columns need a MIP-capable solver (CPLEX, HiGHS, CBC, Gurobi, …); CLP solves only the LP relaxation.
Element references
Elements are referenced by type and identifier (name or UID):
generator('TORO').generation -- by name
generator('uid:23').generation -- by UID3. Element Types and Attributes
| Element type | Attributes | LP variable meaning |
|---|---|---|
generator | generation | Generator power output (MW) |
generator | cost | Generation cost contribution ($/h) |
demand | load | Served demand (MW) |
demand | fail | Unserved demand / load curtailment (MW) |
line | flow | Active power flow on transmission line (MW) |
line | flowp | Positive-direction power flow (MW) |
line | flown | Negative-direction power flow (MW) |
line | lossp | Positive-direction line losses (MW) |
line | lossn | Negative-direction line losses (MW) |
battery | energy | Battery state of energy (MWh); scaled by energy scale from variable_scales |
battery | charge | Battery charging power (MW) |
battery | discharge | Battery discharging power (MW) |
battery | spill | Battery energy spillway / curtailment (MW); also accepts drain |
converter | charge | Converter charging power (MW) |
converter | discharge | Converter discharging power (MW) |
reservoir | volume | Reservoir water volume (dam³); also accepts energy; scaled by energy scale from variable_scales |
reservoir | extraction | Water extraction from reservoir (m³/s); scaled by energy scale from variable_scales |
reservoir | spill | Reservoir spillway discharge (m³/s); also accepts drain; scaled by energy scale from variable_scales |
bus | theta | Voltage angle at bus (radians); also accepts angle; scaled by 1/scale_theta |
waterway | flow | Water flow through waterway (m³/s) |
turbine | generation | Turbine power output (MW) |
junction | drain | Junction drain/spill variable (m³/s) |
flow | flow | Water discharge into junction (m³/s); also accepts discharge |
filtration | flow | Filtration flow variable (m³/s); also accepts filtration |
reserve_provision | up | Up-reserve provision variable (MW reserved up); also accepts uprovision, up_provision |
reserve_provision | dn | Down-reserve provision variable (MW reserved down); also accepts dprovision, dn_provision, down |
reserve_zone | up | Up-reserve requirement variable (MW of up-reserve); also accepts urequirement, up_requirement |
reserve_zone | dn | Down-reserve requirement variable (MW of down-reserve); also accepts drequirement, dn_requirement, down |
gas_node | pi | Squared pressure π = p² at the node (bar²) |
gas_supply | flow | Gas injection rate (km³/h) |
gas_demand | fail | Shed gas (km³/h); only when the demand has a fail_cost |
gas_demand | served | Served gas load − fail (km³/h); no LP column, the scheduled load rides on the RHS |
gas_pipe | flow | Pipe flow (km³/h); with linepack: true the mean (flow_in + flow_out)/2 |
gas_pipe | flow_in / flow_out | Inlet / outlet flow of a line-pack pipe (km³/h) |
gas_pipe | linepack | Gas stored in a line-pack pipe (km³) |
gas_compressor | flow | Throughput (km³/h) |
gas_compressor | fuel | Fuel gas burnt (km³/h); fuel_model: saldarriaga only |
gas_compressor | power | Electric drive power (MW); drive: electric only |
gas_turbine | generation | Output of the linked generator (MW) — same column as generator(...).generation |
gas_turbine | fuel | Gas burnt heat_rate · generation (km³/h); no LP column |
lng_terminal | volume | Tank level (m³); also accepts energy |
lng_terminal | delivery | Scheduled LNG inflow rate (m³/h) |
lng_terminal | drain | Venting (m³/h); also eini, efin (stage tank levels) |
lng_terminal | fuel | LNG drawn by the linked generators Σ heat_rate · generation (m³/h); no LP column |
hydrogen_demand | load | Hydrogen offtake per block |
Element parameters
Besides LP variables, an expression may reference an element's input parameters; they resolve to constants at the (stage, block) of the row, e.g. gas_pipe('S_A').flow <= 0.8 * gas_pipe('S_A').fmax. An unset optional parameter is an error, not a silent zero. Parameters of the gas network, the LNG terminal and the hydrogen demand:
| Element type | Parameters |
|---|---|
gas_node | pmin, pmax (bar), pressure_cost |
gas_supply | fmin, fmax (km³/h), cost ($/km³), volume (km³ per stage) |
gas_demand | load (scheduled, km³/h), fail_cost |
gas_pipe | fmax |
gas_compressor | fmax, max_ratio, power_max |
gas_turbine | heat_rate (km³/MWh) |
lng_terminal | emin, emax (m³), ecost, delivery (m³ per stage) |
hydrogen_demand | lmax, lmin, price, min_energy, max_energy |
Variable Scaling
Some LP variables are internally scaled to improve solver numerical conditioning. User constraints are written in physical units; the constraint resolver automatically applies the appropriate scale factor so that the LP constraint is dimensionally correct.
| Variable | Scale factor (physical = LP × scale) | Default |
|---|---|---|
reservoir.volume / reservoir.energy | energy scale (from variable_scales) | 1000 |
reservoir.extraction | flow scale (from variable_scales) | 1000 |
reservoir.spill / reservoir.drain | flow scale (from variable_scales) | 1000 |
battery.energy | energy scale (from variable_scales) | 1.0 |
battery.spill / battery.drain | flow scale (from variable_scales) | 1.0 |
bus.theta / bus.angle | 1 / scale_theta (θ_LP = scale_theta · θ) | 3·median(X/V²) |
| All other variables | 1.0 (no scaling) | — |
For example, reservoir("R1").volume >= 5000 (in dam³) is automatically translated to the LP constraint scale × volume_LP ≥ 5000, accounting for the fact that the LP variable stores volume_physical / scale.
4. Element Identification
Elements can be referenced by name (single-quoted string) or by numeric UID (bare integer):
# By name (single-quoted string)
generator('TORO').generation
demand('D1').load
line('L1_2').flow
# By explicit UID prefix (single-quoted string)
generator('uid:23').generation
# By bare numeric UID (integer — automatically treated as uid:N)
generator(3).generation -- equivalent to generator('uid:3')
demand(7).load -- equivalent to demand('uid:7')
battery(1).energy -- equivalent to battery('uid:1')Mixing name and UID references in the same expression is allowed:
generator('G1').generation + generator(5).generation <= 3005. Aggregation with sum()
The sum() function aggregates a variable across multiple elements of the same type, inspired by AMPL's sum{...} syntax. This avoids listing each element individually.
Syntax
sum( element_type ( id_list ) . attribute )
Where id_list is one of:
- Explicit list:
'G1', 'G2', 'G3'or1, 2, 3or mixed - All elements:
all
Examples
# Sum generation over specific generators (by name)
sum(generator('G1', 'G2', 'G3').generation) <= 500
# Sum generation over specific generators (by UID)
sum(generator(1, 2, 3).generation) <= 500
# Mixed name and UID references
sum(generator('G1', 2, 'uid:3').generation) <= 500
# Sum over ALL generators in the system
sum(generator(all).generation) <= 1000
# Sum with a coefficient
0.5 * sum(demand('D1', 'D2').load) <= 200
# Combined: sum + individual elements
sum(generator('G1', 'G2').generation) + demand('D1').load <= 1000
# Balance constraint: total generation minus total demand
sum(generator(all).generation) - sum(demand(all).load) = 0Filtering sum(all) with predicates
sum(type(all : ...).attribute) restricts the aggregate to elements whose metadata matches a conjunction of predicates. Predicates are separated by and (or &&) and all must hold (AND semantics):
# All thermal generators
sum(generator(all : type = 'thermal').generation) <= 150
# Thermal generators on bus 1
sum(generator(all : type = 'thermal' and bus = 1).generation) <= 150
# AC lines (anything not of type "dc")
sum(line(all : type != 'dc').flowp) <= 1000
# Numeric comparisons on metadata
sum(generator(all : bus >= 10).generation) <= 300
# Set membership
sum(generator(all : type in {'hydro', 'solar'}).generation) <= 500Supported operators: =, ==, != / <>, <, <=, >, >=, and in { … }. String values are double- or single-quoted; bare numbers compare numerically (node / bus / generator keys hold the element uid, e.g. gas_supply(all : gas_node = 3)). Predicates consult per-element metadata that each element registers during LP assembly; currently available keys:
| element | metadata keys |
|---|---|
| generator | type, bus |
| demand | type, bus |
| line | type, bus_a, bus_b |
| battery | type |
| bus | type |
| gas_node | type |
| gas_supply, gas_demand | type, gas_node |
| gas_pipe | type, gas_node_a, gas_node_b |
| gas_compressor | type, gas_node_in, gas_node_out |
| gas_turbine | type, gas_node, generator |
Elements without a registered metadata key for the predicate's attribute (or without any metadata at all) are silently excluded from the sum — the predicate is treated as unsatisfied. The legacy shortcut sum(generator(all, type='thermal').generation) still parses and lowers to a single-predicate filter.
AMPL comparison
| GTOpt | AMPL equivalent |
|---|---|
sum(generator('G1','G2').generation) | sum{g in {"G1","G2"}} generation[g] |
sum(generator(all).generation) | sum{g in GENERATORS} generation[g] |
sum(generator(all : type = 'thermal').generation) | sum{g in GENERATORS : type[g] = 'thermal'} generation[g] |
0.5 * sum(demand(all).load) | 0.5 * sum{d in DEMANDS} load[d] |
6. Domain Specifications
By default, a constraint applies to every scenario, stage, and block. Use a for(...) clause to restrict the domain:
Dimension names
| Dimension | Meaning |
|---|---|
scenario | Scenario index |
stage | Stage (investment period) index |
block | Block (operating hour) index |
Index set forms
| Form | Meaning | Example |
|---|---|---|
all | Every index | stage in all |
N | Single value | stage = 3 |
N..M | Range (inclusive) | block in 1..24 |
{N, M, ...} | Explicit set | stage in {1, 3, 5} |
{N, M..P, Q} | Mixed values and ranges | block in {1, 5..10, 20} |
Syntax variants
Both in and = are accepted:
for(stage in {1,2,3}) -- using 'in'
for(stage = 1) -- using '=' (single value)Unspecified dimensions default to all:
for(block in 1..24) -- all scenarios, all stages, blocks 1-24
7. Comments
Expressions support line comments using # or //. Everything after the comment marker to the end of the line is ignored:
generator('G1').generation <= 100 # limit gen output
generator('G1').generation // first gen
+ generator('G2').generation // second gen
<= 300Multi-line expressions with comments are useful for documenting complex constraints:
# Total system generation capacity constraint sum(generator(all).generation) # MW total <= 1000 # system-wide limit , for(block in 1..24) # applies to all 24 blocks
8. Examples
Example 1 — Simple generation cap
Limit generator G1 to 100 MW:
{ "uid": 1, "name": "g1_cap", "expression": "generator('G1').generation <= 100" }
Example 2 — Joint generation limit
The sum of two generators must not exceed 300 MW:
{ "uid": 2, "name": "gen_pair_limit", "expression": "generator('TORO').generation + generator('uid:23').generation <= 300, for(stage in {4,5,6}, block in 1..30)" }
Example 3 — Minimum generation requirement
Generator G1 must produce at least 50 MW:
{ "uid": 3, "name": "min_gen", "expression": "generator('G1').generation >= 50" }
Example 4 — Line flow limit
Restrict flow on line L1_2 to 200 MW:
{ "uid": 4, "name": "flow_limit", "expression": "line('L1_2').flow <= 200" }
Example 5 — Generation-load balance
Generator G1 output must equal demand D1 load:
{ "uid": 5, "name": "gen_demand_balance", "expression": "generator('G1').generation = demand('D1').load" }
Example 6 — Range constraint
Generator output must be between 50 and 250 MW:
{ "uid": 6, "name": "gen_range", "expression": "50 <= generator('G1').generation <= 250" }
Example 7 — Weighted sum with coefficients
Partial contributions from two generators:
{ "uid": 7, "name": "weighted_cap", "expression": "0.8 * generator('G1').generation + 0.5 * generator('G2').generation <= 200" }
Example 8 — Cross-element CHP coupling
Model combined heat-and-power relationship (generation proportional to load):
{ "uid": 8, "name": "chp_coupling", "expression": "generator('CHP').generation - 1.5 * demand('HeatLoad').load = 0" }
Example 9 — Battery energy limit during peak hours
Limit battery state of energy during peak blocks:
{ "uid": 9, "name": "bess_peak_limit", "expression": "battery('BESS1').energy <= 400, for(block in {18, 19, 20, 21})" }
Example 10 — Scenario-specific constraint
Different limit in scenarios 1 and 2 only:
{ "uid": 10, "name": "scenario_limit", "expression": "generator('G1').generation <= 150, for(scenario in {1, 2})" }
Example 11 — Inactive constraint (disabled)
A constraint that is defined but not active:
{ "uid": 11, "name": "maintenance_limit", "active": false, "expression": "generator('G1').generation <= 10" }
To enable a constraint only in some stages, give a per-stage schedule in active_stages (one 0/1 entry per stage, or a file field). A stage with 0 emits no row at all, which is better for LP numerics than a huge never-binding right-hand side. Both active and active_stages must allow the stage:
{ "uid": 11, "name": "dated_limit", "active_stages": [0, 1, 1], "expression": "generator('G1').generation <= 10" }
Example 12 — Zero unserved energy requirement
Force no load curtailment on demand D1:
{ "uid": 12, "name": "no_curtailment", "expression": "demand('D1').fail = 0" }
Example 13 — Generator referenced by numeric UID
Use the bare integer syntax instead of 'uid:3':
{ "uid": 13, "name": "gen_uid_limit", "expression": "generator(3).generation <= 200" }
Example 14 — Sum over all generators (budget constraint)
Limit total system generation using sum():
{ "uid": 14, "name": "total_gen_cap", "expression": "sum(generator(all).generation) <= 1000" }
Example 15 — Sum over specific generators
Constrain a subset of generators:
{ "uid": 15, "name": "thermal_limit", "expression": "sum(generator('G1', 'G2', 'G3').generation) <= 500, for(block in 1..12)" }
Example 16 — Sum with coefficient (weighted budget)
Weighted sum of demand served:
{ "uid": 16, "name": "weighted_demand", "expression": "0.5 * sum(demand('D1', 'D2').load) <= 200" }
Example 17 — Balance: total generation equals total demand
System-wide power balance using two sum() terms:
{ "uid": 17, "name": "system_balance", "expression": "sum(generator(all).generation) - sum(demand(all).load) = 0" }
Example 18 — Reservoir volume constraint
Limit reservoir volume during dry season:
{ "uid": 18, "name": "reservoir_min_vol", "expression": "reservoir('RES1').volume >= 1000, for(stage in {3, 4})" }
Example 19 — Converter charge/discharge limit
Limit total converter throughput:
{ "uid": 19, "name": "converter_limit", "expression": "converter('CV1').charge + converter('CV1').discharge <= 100" }
Example 20 — Expression with comments
Use # or // for inline documentation (useful in external files):
{ "uid": 20, "name": "documented_limit", "expression": "generator('G1').generation + generator('G2').generation <= 300 # peak capacity" }
Example 21 — Reserve provision limit
Limit up-reserve provision of a specific provider:
{ "uid": 21, "name": "up_reserve_limit", "expression": "reserve_provision('RP1').up <= 50" }
Example 22 — Reserve zone total up-reserve
Constrain total up-reserve in a zone across all provisions:
{ "uid": 22, "name": "zone_up_reserve_min", "expression": "reserve_zone('RZ1').up >= 100" }
Example 23 — A reservoir modeled in user-constraint text
A hydro reservoir can be expressed entirely in user-constraint text — no native reservoir element — using a block_state decision variable (the per-block volume) plus a balance and a terminal target. The block_state variable creates one volume column per block, an incoming column reachable as the first-block prev(...), and registers the last block as the cross-phase SDDP state, so the same machinery the native reservoir uses carries storage across stages and phases. The release here is a hydro generator; the * block.duration factor turns its power into the volume drawn over each block (required whenever blocks are not exactly 1 hour — see the duration trap in §2).
{ "system": { "decision_variable_array": [ { "uid": 101, "name": "vol", "scope": "block", "lower_bound": 0, "upper_bound": 1000, "link": true, "block_state": true, "initial_value": 600 } ], "user_constraint_array": [ { "uid": 201, "name": "vol_balance", "expression": "decision_variable('vol').value - prev(decision_variable('vol').value) + generator('HYDRO').generation * block.duration = inflow * block.duration" }, { "uid": 202, "name": "vol_terminal", "expression": "decision_variable('vol').value >= 150, for(stage in {12})" } ] } }
Here inflow is a named user parameter (per the Constraint Directives params section); set it to 0 for a pure-drawdown reservoir. The terminal vol >= 150 plays the role of the native reservoir's efin. Stages carrying multiple blocks must set "chronological": true so the within-stage prev(...) lag is well-defined.
9. External Constraint Files
When there are many constraints, store them in a separate file.
JSON format
{ "system": { "bus_array": [...], "user_constraint_file": "constraints.json" } }
External JSON file (constraints.json):
[ { "uid": 1, "name": "gen_limit", "expression": "generator('G1').generation <= 100" }, { "uid": 2, "name": "flow_limit", "expression": "line('L1').flow <= 200" } ]
PAMPL format
PAMPL (pseudo-AMPL) files provide a more readable syntax with named constraints, parameters, and comments:
# System constraints param pct_elec = 35; param seasonal[month] = [0,0,0,100,100,100,100,100,100,100,0,0]; constraint gen_limit "Combined generation limit": generator('G1').generation + generator('G2').generation <= 300; constraint seasonal_limit: generator('G1').generation <= pct_elec * seasonal[month];
Optional header clauses go between the name (or description) and the colon, in any order:
| Clause | Effect |
|---|---|
penalty <value> | Soft constraint with a per-unit slack cost (UserConstraint.penalty) |
rhs [v0, v1, ...] | Per-block scheduled right-hand side (UserConstraint.rhs) |
scope block\|stage\|phase\|global | Row granularity (UserConstraint.scope); stage emits one row per (scenario, stage) and per-block terms must be wrapped in sum{b in stage} |
# Stage-average cap: mean of q over the stage <= mean of qmax constraint avg_cap "stage-average cap" scope stage: sum{b in stage} dur[b] * flow_right('q').flow - sum{b in stage} dur[b] * flow_right('qmax').flow <= 0;
PAMPL files are loaded automatically when referenced:
{ "system": { "user_constraint_file": "constraints.pampl" } }
Multiple external files
Use user_constraint_files (plural, array) to load multiple files independently. Each file is parsed with auto-incremented UIDs to avoid collisions:
{ "system": { "user_constraint_files": [ "laja.pampl", "maule.pampl" ] } }
This keeps each constraint set self-contained and avoids combining files. Both user_constraint_file (singular) and user_constraint_files (plural) can coexist — all sources are accumulated.
Combining inline and external
Both user_constraint_array and external files can be used simultaneously. Constraints from all sources are accumulated:
{ "system": { "user_constraint_array": [ {"uid": 1, "name": "inline_limit", "expression": "..."} ], "user_constraint_files": ["more_constraints.pampl"] } }
Multi-file merge
When loading from multiple JSON files (the standard GTOpt pattern), constraints from all files are accumulated via System::merge():
gtopt base.json overrides.json
10. Formal Grammar (BNF)
constraint := expr comp_op expr [',' for_clause]
| number comp_op expr comp_op number [',' for_clause]
expr := add_expr
add_expr := mul_expr (('+' | '-') mul_expr)*
mul_expr := unary (('*' | '/') unary)*
unary := ('+' | '-') unary
| primary
primary := number
| '(' add_expr ')'
| sum_expr
| abs_expr -- F5: absolute value
| minmax_expr -- F7: min / max envelope
| if_expr -- F8: data-only conditional
| prev_expr -- previous-block / incoming lag
| state_expr -- state-column typing assertion
| element_ref
| scalar_ref -- options.X / system.X / stage.X / block.duration
| IDENT -- bare parameter reference
-- Linearity rules (enforced at parse time):
-- * At least one operand of every '*' must fold to a numeric constant,
-- EXCEPT `block.duration` which may multiply a single variable term
-- (recorded as a per-block Δt weight).
-- * The right operand of every '/' must fold to a nonzero constant.
-- * Any subexpression made of numeric literals is constant-folded.
-- * abs / max / min / if are not allowed inside a RANGE constraint
-- (`lo <= expr <= hi`): only single-sided `<=` / `>=` are convex.
-- * prev(...) and state(...) take a single element_ref and do not nest.
element_ref := element_type '(' element_id ')' '.' IDENT
scalar_ref := ('options' | 'system' | 'stage' | 'block') '.' IDENT
prev_expr := 'prev' '(' element_ref ')'
state_expr := 'state' '(' element_ref ')'
sum_expr := 'sum' '(' element_type '(' id_list ')' '.' IDENT ')'
abs_expr := 'abs' '(' add_expr ')'
minmax_expr := ('max' | 'min') '(' add_expr (',' add_expr)+ ')'
if_expr := 'if' if_cond 'then' '(' add_expr ')'
[ 'else' '(' add_expr ')' ]
if_cond := if_atom (('and' | '&&') if_atom)*
if_atom := index_dim if_cmp_op number
| index_dim 'in' '{' number_or_range (',' number_or_range)* '}'
if_cmp_op := '=' | '==' | '!=' | '<>' | '<' | '<=' | '>' | '>='
number_or_range := number
| number '..' number
id_list := 'all'
| element_id (',' element_id)*
element_id := STRING -- name: 'G1' or 'uid:3'
| number -- bare UID: 3 → uid:3
element_type := 'generator' | 'demand' | 'line' | 'battery'
| 'converter' | 'reservoir' | 'bus'
| 'waterway' | 'turbine'
| 'junction' | 'flow' | 'filtration'
| 'reserve_provision' | 'reserve_zone'
comp_op := '<=' | '>=' | '='
for_clause := 'for' '(' index_spec (',' index_spec)* ')'
index_spec := index_dim ('in' | '=') index_set
index_dim := 'scenario' | 'stage' | 'block'
index_set := 'all'
| '{' index_values '}'
| number '..' number
| number
index_values := index_value (',' index_value)*
index_value := number
| number '..' number
comment := ('#' | '//') <anything to end of line>
STRING := '"' <characters> '"' | "'" <characters> "'"
IDENT := [a-zA-Z_][a-zA-Z0-9_]*
number := [0-9]+ ('.' [0-9]+)?Reserved keywords. The tokens abs, max, min, if, then, else, and, in, all, sum, for, scenario, stage, and block are reserved by the grammar above — they cannot appear as element names or parameter names inside an expression.
11. Error Diagnostics
When a constraint expression fails to parse, the parser throws a gtopt::ConstraintParseError (which derives from std::invalid_argument for backward compatibility). The error's what() includes:
- A column indicator (1-based) pointing at the offending token.
- The original source line.
- A caret (
^) under the exact column. - An optional
hint:line suggesting a fix.
For example, the non-linear product generator('G1').generation * generator('G2').generation <= 100 yields:
Parse error at column 29: Non-linear product: both sides of '*' contain
variables or parameters; only scalar-by-expression products are allowed
generator('G1').generation * generator('G2').generation <= 100
^
hint: at least one operand of '*' must be a constantDivision by zero, division by a variable, unterminated string literals, stray characters, missing attributes after ., unknown for-clause dimensions, and malformed index sets are all reported with the same caret + hint format.
The ConstraintParseError type also exposes its components programmatically:
try { auto expr = ConstraintParser::parse(...); } catch (const gtopt::ConstraintParseError& e) { std::cerr << e.what(); // formatted caret + hint e.message(); // raw diagnostic text e.hint(); // suggestion (may be empty) e.column(); // 0-based byte offset into the source }
Because ConstraintParseError inherits from std::invalid_argument, existing catch (const std::invalid_argument&) handlers continue to work unchanged.
constraint_mode — runtime error policy
Some user-constraint errors only surface at LP-construction time, not at parse time. Examples:
- Non-convex
abs(x) >= k(wrong side of the inequality) - Non-convex
c * max(…)with a sign that violates convexity - Nested
abs/min/max/ifinside another wrapper (v1 limit) - Unknown user parameter name referenced from an expression
The constraint_mode option in PlanningOptions (alongside demand_fail_cost, scale_objective, etc.) controls how these runtime errors are treated:
| Value | Behavior |
|---|---|
normal | Log a warning/error and silently drop the offending constraint. |
strict | (Default.) Abort the LP build with a diagnostic. |
debug | Same as strict, plus verbose per-row lowering trace at info. |
Example:
"options": { "constraint_mode": "debug" }
Running in debug mode is the recommended way to author a new user constraint — it prints the lowered rows so you can sanity-check which LP columns were picked up.
Tip. Non-convex / unknown-parameter errors are only recoverable in
normalmode because the constraint is dropped entirely. If you want a non-strict build and also want the author to notice the problem, grep the logs fornon-convexorunknown parameter.
Resolver-time source-location diagnostics
Resolver-time errors (e.g. unknown generator name 'GX') also report the offending token's source column, derived from ConstraintTerm::column (parser-stamped, 1-based). Example for generator('g1').generation + generator('does_not_exist').generation <= 100:
user_constraint 'X' at column 30: cannot resolve element reference 'generator(does_not_exist).generation' (block 1) — unknown generator name 'does_not_exist' — did you mean: g1?
The at column 30 clause indexes into the expression string (not a file path) — column 30 points to the start of the second generator token. For a long composite LHS the column lets you jump straight to the bad ref without re-scanning the string by eye. Same shape as the parse-time Parse error at column N reports above.
Note. Today the column is populated for bare element refs, singleton scalars (
system.scale_objective), and bare parameter names. Wrapper-shape terms (sum(...),abs(...),min/max(...),if-then-else,state(...)) carry an outer term withcolumn = 0(the "unset" sentinel); the inner element refs nested inside them DO get their own columns through recursive parsing, so failures inside a wrapper still surface a source location pointing at the exact inner ref.
12. Constraint Directives
A directive is typed metadata attached to a UserConstraint that classifies its family and carries a policy payload (soft-penalty tier, aggregation scope, gating, …). The directive is a JSON sibling field on the UserConstraint, NOT part of the expression string — so the expression stays pure math and the policy lives in one auditable place.
Directives replace the legacy practice of detecting constraint families by name regex inside converters (_RegRange_, Gas_MaxOpDay\d+_, …) and assigning soft-penalty tiers via Python constants. With a directive present the JSON self-describes:
{ "uid": 1337, "name": "csflw_regrange_e1", "expression": "... commitment + reserve_provision ...", "directive": { "kind": "regrange", "penalty": 1000.0 } }
The gtopt-side UserConstraint::directive picks it up; UserConstraintLP::effective_penalty() makes the directive's penalty win over the scalar penalty field at LP-build time, so the directive is the single source of truth for soft-tier policy.
12.1 Discriminator (kind)
The kind string is the family discriminator — lowercase canonical name, ASCII case-insensitive on read.
kind | Valid payload fields | Implies |
|---|---|---|
regrange | penalty (optional) | — |
reserve_prov_sum | penalty (optional) | — |
daily_budget | penalty, scope (both optional) | daily_sum = true |
hydro_floor | scope (optional gate-ref tag) | — |
max_starts_window | window_hours (required, > 0) | daily_sum = true iff window_hours == 24 |
Validation at JSON-load time: ConstraintDirective::valid_for_kind() rejects payloads that populate fields outside the discriminator's allowed set. See include/gtopt/constraint_directive.hpp for the C++ schema.
12.2 regrange — PLEXOS regulation-range UC
PLEXOS *_RegRange_e1 / _e2 constraints couple commitment(g).status to reserve_provision(g, .).{up|dn}. Under LP-relax their tight implied-bounds chain renders the LP structurally infeasible at continuous status values; the directive's penalty (typically 1000.0) converts the infeasibility into a finite-cost slack that LP-relax can absorb.
{ "name": "uc_regrange_e1", "expression": "α * commitment(\"g\").status - reserve_provision(\"g\", ResUp).up - reserve_provision(\"g\", ResDn).dn >= 0", "directive": { "kind": "regrange", "penalty": 1000.0 } }
12.3 reserve_prov_sum — pure reserve aggregator
Σ reserve_provision(g, R).{up|dn} ≥ requirement shape (3+ reserve_provision refs, no commitment / generator / battery / line), plus the *Calculation definitional rows that define per-zone requirements. Same soft-tier rationale as regrange.
{ "name": "csf_lw_minprov", "expression": "reserve_provision(\"p1\").up + reserve_provision(\"p2\").up + reserve_provision(\"p3\").up >= 10", "directive": { "kind": "reserve_prov_sum", "penalty": 1000.0 } }
12.4 daily_budget — per-day cumulative cap
Per-day cumulative budget on a Σ aggregator (typical scope tags: fuel:GAS, owner:CSF, gas_maxopday:<suffix>). The directive implies daily_sum = true at LP-build time without requiring the field to be set explicitly. For PLEXOS Gas_MaxOpDay the converter stamps the directive on the consolidator's output so the JSON self-describes which PLEXOS fuel-owner group the row consolidates.
{ "name": "Gas_MaxOpDay_Enel", "expression": "sum(generator(all: fuel=\"GAS\").generation) <= 800", "daily_sum": true, "constraint_type": "energy", "directive": { "kind": "daily_budget", "scope": "gas_maxopday:Enel" } }
12.5 hydro_floor — gated reservoir floor
Reserved for the P2 follow-up. A reservoir floor that should only bind when a referenced commitment binary is active (e.g. reservoir.volume >= 50 only when the unit is on). The scope tag carries the gating element ref. Step 1 honours the directive's presence in the JSON schema; LP-build currently treats it as a pass-through (no gate semantics yet — needs P2 ordered-time primitives).
12.6 max_starts_window — rolling startup count cap
Σ_{τ ∈ window(N h)} commitment(g).startup ≤ MaxStarts(g) shape. Required field window_hours carries the rolling-window length in hours; 24 is the canonical daily alias (the directive implies daily_sum = true in that case), 168 the canonical weekly window.
{ "name": "max_starts_per_day_G1", "expression": "sum(commitment(\"uc_G1\").startup) <= 5", "directive": { "kind": "max_starts_window", "window_hours": 24 } }
Wider rolling windows (e.g. window_hours: 48 for a 2-day rolling cap) are wired in the schema but the LP-build path needs P2 to emit the right shape — for now they fall through to the same daily aggregator as the 24 case. Tagged for Step 4b v2 / P2.
12.7 Backwards compatibility
directive is OPTIONAL on every UserConstraint. JSON written before the scaffold landed (UserConstraint.directive == std::nullopt) is treated exactly as before — UserConstraintLP falls through to the scalar penalty and explicit daily_sum fields. Converters can add directives incrementally: any constraint without one keeps behaving identically.
13. Comparison with AMPL
AMPL equivalents
# ── gtopt: simple capacity constraint ── # generator('G1').generation <= 100 # AMPL: subject to g1_cap: generation["G1"] <= 100; # ── gtopt: sum over element group ── # sum(generator('G1','G2','G3').generation) <= 500, for(block in 1..12) # AMPL: subject to thermal_limit {b in 1..12}: sum{g in {"G1","G2","G3"}} generation[g,b] <= 500; # ── gtopt: budget constraint (sum over all) ── # sum(generator(all).generation) <= 1000 # AMPL: subject to budget_constraint: sum{g in GENERATORS} generation[g] <= 1000; # ── gtopt: cross-element balance ── # sum(generator(all).generation) - sum(demand(all).load) = 0 # AMPL: subject to balance: sum{g in GENERATORS} generation[g] - sum{d in DEMANDS} load[d] = 0; # ── gtopt: weighted sum with domain ── # 0.8 * generator('G1').generation + 0.5 * generator('G2').generation <= 200, # for(stage in {4,5,6}, block in 1..30) # AMPL: subject to weighted_cap {s in STAGES, b in BLOCKS: s in {4,5,6} and b >= 1 and b <= 30}: 0.8 * generation["G1",s,b] + 0.5 * generation["G2",s,b] <= 200;
Key differences from AMPL
| Aspect | AMPL | GTOpt |
|---|---|---|
| Element access | generation["G1",s,b] | generator('G1').generation |
| Element by UID | Not applicable | generator(3).generation |
| Sum syntax | sum{g in SET} expr | sum(element_type(list).attr) |
| Index sets | {s in STAGES: s >= 4} | for(stage in {4,5,6}) |
| Constraint name | subject to name: | "name": "..." field |
| Comments | # only | # and // |
| File format | .mod text file | JSON field or external file |
| Scope | Full modeling language | LP constraints only |
| Set definitions | Explicit set GENERATORS; | Implicit from system model |
Design philosophy
The GTOpt constraint language is intentionally narrower than AMPL:
- No set definitions needed: Element sets are implicit from the system model.
sum(generator(all).generation)automatically sums over all generators in the system, without requiring aset GENERATORS;declaration. - Element-centric: Variables are accessed via element references (
generator('G1').generation) rather than indexed arrays (generation["G1",s,b]). This is more natural for power system engineers. - JSON-native: Constraints live in JSON files alongside the rest of the case definition, enabling programmatic generation from scripts and GUIs.
14. Best Practices
- Name constraints meaningfully: use descriptive names like
gen_pair_limitornight_battery_reserve, notc1ortest. - Start without domain restrictions: let the constraint apply to all time steps first, then narrow with
for(...)as needed. - Use UIDs for stability:
generator('uid:5')orgenerator(5)is stable across name changes;generator('TORO')breaks if the generator is renamed. - Prefer
sum()over manual expansion: usesum(generator(all).generation)instead of listing every generator individually — it's shorter, self-documenting, and auto-adapts when generators are added or removed. - Use comments to document intent: add
# ...or// ...comments to explain why a constraint exists, not just what it does. - Set
active: falsefor debugging: disable a constraint without removing it from the file. - Use external files for large constraint sets: when you have more than ~10 constraints, move them to a separate file referenced by
user_constraint_file. - Validate with
use_single_bus: truefirst: check that your constraints are feasible in a simple model before adding network constraints. - Check LP feasibility: if adding user constraints makes the problem infeasible (
status != 0), checkoutput/Demand/fail_sol.csvfor unserved demand.
15. See Also
- Irrigation Agreements — Laja and Maule agreement modeling, FlowRight/VolumeRight entities, PLP comparison
- Input Data Reference — Full JSON input format specification (§3.18 for UserConstraint fields)
- Mathematical Formulation — LP/MIP formulation details
- Planning Guide — Step-by-step planning guide
- Usage Guide — Command-line options and output interpretation