Dynamic operating envelopes API
Functions for specifying connection points, allocating import or export limits, and testing the resulting envelopes. The worked study shows allocation and verification over specified scenarios. The DOE guide defines the equations, units and interpretation of the results; the literature review explains the underlying assumptions.
Connections, fairness, and control recourse
PowerOptLab.ConnectionPoint — Type
ConnectionPoint(; id, bus, export_max=0.0, import_max=0.0, kwargs...)An active connection point whose positive operating-envelope capacity is calculated by solve_operating_envelope.
export_max/import_maxare the connection's active-power nameplate limits (W, both non-negative). Select which one is used withdirectionon the solve.ibr_id=nothingretains a single-phase unity-PF port, stamped directly atbususing onephase_terminalsentry andneutral.ibr_id="pv1"binds the envelope to an existing BMOPFToolsibr. This is the recommended representation for PV and batteries: the IBR keeps its prescribed Volt-VAr/Volt-Watt or fixed-power-factor control law, apparent/current limits, phase topology, and DC coupling while the DOE controls active power only. Each IBR may bind only one participant. The declared phases and neutral must match itsterminal_mapphase order and the engine's reference conductor.requestedis an optional requested/forecast capacity (W), used byFairnessPolicy(normalization=:request).normalizationis an optional custom fairness reference (W), used byFairnessPolicy(normalization=:custom).
PowerOptLab.FairnessPolicy — Type
FairnessPolicy(; kind=:equal, normalization=:none, weights=Dict(),
alpha=1.0, epsilon=1e-6)Parameterized policy for allocating active-power envelope capacity.
normalization defines the reference in xᵢ = capacityᵢ/referenceᵢ:
:none— absolute watts (the reference is 1 W);:capacity— the connection's export/import nameplate for this direction;:request—ConnectionPoint.requested;:custom—ConnectionPoint.normalization.
Supported kind values:
:equal— require equal normalized allocations and maximize their level;:max_total— maximize the weighted sum of normalized allocations;:proportional— weighted proportional fairness,Σwᵢ log(xᵢ+ε);:alpha— weighted alpha fairness (alpha=0is weighted sum andalpha=1is proportional fairness);:max_min— maximize the minimum normalized allocation, then maximize total allocation while retaining that locally optimal minimum;:equal_curtailment— require equal normalized curtailment from nameplate and minimize it.
weights is keyed by connection-point id and defaults to one. All weights must be finite and strictly positive. epsilon regularizes logarithmic/negative-power utilities at zero; it does not create physical capacity.
PowerOptLab.DOEScenario — Type
DOEScenario(; id, network, role=:unspecified, weight=nothing, kwargs...)One network realization with explicit uncertainty provenance. role is one of :train, :calibration, :validation, :test, :stress, or :unspecified. weight is an optional positive relative probability weight; a scenario set must either weight every scenario in an interval or none of them.
source, generation_method, seed, timestamp, and metadata describe how the realization was obtained. They do not themselves establish calibration or independence.
PowerOptLab.DOEScenarioSet — Type
DOEScenarioSet(intervals; dataset_id, metadata=Dict())Typed scenario ensemble. Pass a vector of DOEScenario for one interval or a vector of non-empty scenario vectors for multiple intervals. Scenario IDs must be unique within each interval. Optional weights must be complete within an interval; they are treated as relative weights and normalized only when a coverage statistic is calculated.
PowerOptLab.DOEUncertaintySample — Type
DOEUncertaintySample(; id, parameters, weight=nothing,
timestamp=nothing, metadata=Dict())One realization in a typed uncertainty sample set. parameters may contain numeric uncertainty draws or categorical/model-candidate values; interpretation is delegated explicitly to materialize_doe_scenarios.
PowerOptLab.DOEUncertaintySampleSet — Type
DOEUncertaintySampleSet(samples; parameter_names, generation_method,
seed=nothing, metadata=Dict(), diagnostics=Dict())Reproducible collection of typed uncertainty samples. Every sample must contain exactly the declared parameter names. sample_set_id hashes the declarations, samples, weights, timestamps, and metadata; derived diagnostics are deliberately excluded from the identity.
PowerOptLab.select_doe_scenarios — Function
Return a typed subset containing scenarios whose role is in roles.
PowerOptLab.DOEScenarioTimeSplit — Type
DOEScenarioTimeSplitChronological calibration/test split returned by split_doe_scenarios_by_time. Scenarios between calibration_end and test_start are excluded as a leakage-control gap and listed explicitly.
PowerOptLab.split_doe_scenarios_by_time — Function
split_doe_scenarios_by_time(scenarios;
calibration_end, test_start=calibration_end, split_name="time_block",
group_key=nothing, group_overlap_policy=:error)Create a chronological calibration/test split for a one-interval typed scenario ensemble. Timestamps before calibration_end are assigned :calibration; timestamps on or after test_start are assigned :test; the intervening gap is excluded. Every scenario must have a timestamp and each retained block must be non-empty.
Set group_key to a scenario-metadata key such as "site_id" or "weather_event_id" to assess cross-block group leakage. The default group_overlap_policy=:error rejects overlapping groups. :exclude_test removes overlapping test scenarios, while :allow retains and reports them for longitudinal designs where group reuse is intentional.
The one-interval restriction is deliberate in this first slice: it avoids silently confusing forecast intervals with statistical sample time. Build one split per forecast interval when their historical samples differ.
PowerOptLab.DOEControlRegistration — Type
DOEControlRegistration(; component, id, quantity, handle, kwargs...)Register a control exposed by a BMOPFTools public OpfModelKey so that a DOE policy can audit and link it without inspecting JuMP variable names.
native_classification is :free, :fixed_data, :local_law, or :envelope. For a local law, provide automatic_law and immutable controller provenance in metadata. model_to_canonical_scale converts the registered scalar model value to canonical_unit; it must be identical for every context represented by this registration. Native IBR powers and transformer taps are registered by the solver automatically.
PowerOptLab.DOEControlRule — Type
DOEControlRule(; component, id, quantity, stage)Override the information stage of one DOE control family. Rules currently use the stable device-level identity (component, id, quantity) and apply to every phase or regulator position belonging to that device.
Supported native identities are transformer :tap and IBR :active_power / :reactive_power. A stage is one of:
:issue— one value is shared by every scenario and utilisation context;:scenario— one value is shared by the utilisation contexts within each scenario;:local_law— the value is determined by a prescribed automatic controller;:context— independent pointwise recourse (perfect information).
The solver rejects a rule that attempts to replace a prescribed local law or the envelope's own active-power allocation with a different information stage.
PowerOptLab.DOEControlPolicy — Type
DOEControlPolicy(; name=:custom, default_stage=:context,
rules=DOEControlRule[], registrations=DOEControlRegistration[],
on_unclassified=:error)Information structure for controllable assets in a DOE formulation. default_stage applies to discovered free controls that have no explicit rule. on_unclassified=:error fails closed when the model contains a free native control that the current implementation cannot link safely; on_unclassified=:context retains it as pointwise recourse and reports it.
Use PerfectRecourse to reproduce anticipative formulations and IssuePlusLocalLaws for an operational policy in which free setpoints are issued before uncertainty while prescribed automatic laws still respond locally.
PowerOptLab.PerfectRecourse — Function
Policy preset retaining independent controls in every scenario/utilisation context.
PowerOptLab.IssueFixedControls — Function
Policy preset fixing all discovered free setpoints at DOE issue time.
PowerOptLab.IssuePlusLocalLaws — Function
Operational preset: issue-time free setpoints plus prescribed local control laws.
Study specification and evidence records
PowerOptLab.DOEStudySpec — Type
DOEStudySpecImmutable top-level provenance record for a reproducible DOE experiment. Use the network-aware constructor DOEStudySpec(nets, connection_points; kwargs...) and serialize doe_study_manifest beside research outputs.
PowerOptLab.DOEScenarioCalibrationAudit — Type
DOEScenarioCalibrationAuditProvenance and leakage audit returned by audit_doe_scenario_calibration. It summarizes calibration and evaluation ensembles and records which disjointness requirements were actually checked. It is not a probability-calibration or distribution-shift test.
PowerOptLab.DOECovariateShiftResult — Type
DOECovariateShiftResultDeclared-metadata covariate comparison returned by test_doe_covariate_shift. Descriptive feature effects are always available. p_value is missing unless the caller explicitly asserts the exchangeability required by the selected permutation design.
PowerOptLab.DOEProbabilityObservation — Type
DOEProbabilityObservation(; id, predicted_violation_probability,
observed_violation, weight=1.0, timestamp=nothing, group_id=nothing,
metadata=Dict())One probability forecast paired with its later binary DOE-verification outcome. observed_violation=nothing records an unresolved outcome rather than silently labelling it safe. The probability must have been produced before observing the outcome; this temporal ordering is a caller-supplied scientific assertion.
PowerOptLab.DOEProbabilityCalibrationResult — Type
DOEProbabilityCalibrationResultReliability and proper-score diagnostics returned by evaluate_doe_probability_calibration. Empty-bin rows are retained so different studies can use an identical bin declaration. Concentration intervals are present only when observation independence is explicitly asserted.
PowerOptLab.doe_study_manifest — Function
Return a serialization-friendly dictionary for a DOEStudySpec.
PowerOptLab.doe_uncertainty_manifest — Function
Return a serialization-friendly manifest for a DOEUncertaintySampleSet.
PowerOptLab.doe_benchmark_rows — Function
doe_benchmark_rows(spec, result; method_label="DOE")Return stable, tidy interval rows for a DOE allocation. The rows retain the study identity, formulation labels, solver evidence, capacity, and claim boundary without embedding full network snapshots.
PowerOptLab.doe_context_benchmark_rows — Function
doe_context_benchmark_rows(spec, verification; method_label="verification")Return one tidy row per interval/scenario/utilization context, including replay status and minimum-margin summaries.
PowerOptLab.OperatingEnvelopeResult — Type
OperatingEnvelopeResultResult of solve_operating_envelope. Capacities are positive SI watts for the selected direction.
snapshots[t] is the first scenario at the all-active upper corner. When an interval has no feasible primal solution it contains only status metadata and all capacities for that interval are NaN; infeasible solver iterates are never published as envelopes.
total_export is retained as a backward-compatible alias of total_capacity. For a new import study use total_capacity and inspect direction.
fairness_metrics reports allocation and curtailment metrics for the published capacity at each interval. schedule records the issue/validity metadata and whether a non-optimised fallback was published.
PowerOptLab.OperatingEnvelopeVerification — Type
OperatingEnvelopeVerificationResult of verify_operating_envelope. Each interval reports whether a fixed, already-issued allocation was locally feasible at every requested utilisation point and forecast/model scenario. This is a verification result, not a new allocation.
PowerOptLab.OperatingEnvelopeContextResult — Type
OperatingEnvelopeContextResultEvidence for one forecast scenario and participant-utilisation point in an operating-envelope solve or verification. feasible records raw local evidence: true is a published feasible witness, false a local infeasibility candidate, and nothing unresolved numerical or joint-model evidence. Time/iteration limits are unresolved even if they return an infeasible iterate. None of these statuses is a global infeasibility certificate. In verification, consult diagnostics["verification_verdict"] for usable evidence after shared-policy compatibility and any requested fixed-control replay have been considered.
PowerOptLab.OperatingEnvelopeSearchResult — Type
OperatingEnvelopeSearchResultResult of search_operating_envelope_utilizations. outcome is :search_stable, :candidate_counterexample, or :inconclusive. Search-stable means only that every generated point passed the configured local AC verification; global_certificate remains false.
PowerOptLab.DOEAdversarialSearchResult — Type
DOEAdversarialSearchResultResult of search_operating_envelope_adversarial. The search starts from a deterministic coverage set and performs coordinate refinement around the utilization points with the smallest normalized network-constraint headroom. It retains every joint verification round and the final score for each tested point.
This is a black-box falsification heuristic. outcome=:search_stable means no counterexample was found within the recorded budget; it is not a continuous-set or global-optimality certificate.
PowerOptLab.DOECounterexampleConfirmationResult — Type
DOECounterexampleConfirmationResultMultistart replay evidence returned by confirm_operating_envelope_counterexample. outcome is :repeated_candidate, :not_reproduced, or :inconclusive. Repeated local infeasibility is stronger numerical evidence than one failed solve, but remains distinct from a globally certified physical violation.
PowerOptLab.DOECoverageResult — Type
DOECoverageResultHeld-out scenario evaluation returned by evaluate_operating_envelope_coverage. scenario_rows contains one safe/unsafe/unresolved record per selected interval/scenario, while metrics reports empirical context and scenario rates. A confidence bound is present only when the caller explicitly declares the selected scenarios i.i.d.
PowerOptLab.DOECoverageCurveResult — Type
DOECoverageCurveResultCapacity-scaling sensitivity returned by evaluate_operating_envelope_coverage_curve. Each element of coverages is a full held-out evaluation at the corresponding scale. The curve is finite numerical evidence, not a continuous security certificate.
PowerOptLab.DOECoverageShiftResult — Type
DOECoverageShiftResultDescriptive comparison returned by compare_doe_coverage_shift. metric_deltas are shifted minus reference. This record can reveal a change in observed performance, but does not constitute a statistical distribution-shift test.
PowerOptLab.DOEUncertaintyModelSensitivityResult — Type
DOEUncertaintyModelSensitivityResultDescriptive comparison returned by compare_doe_uncertainty_models. rows contains one coverage-curve record per uncertainty model and capacity scale. pairwise_rows contains every model-pair delta and, where stable scenario identities or timestamps permit, paired outcome-discordance counts.
Pairing improves attribution of observed finite-sample differences but does not by itself establish a causal uncertainty-model effect or authorize a significance claim.
PowerOptLab.AdversarialSearchStableOperatingEnvelopeResult — Type
AdversarialSearchStableOperatingEnvelopeResultEvidence from solve_adversarial_search_stable_operating_envelope, including every allocation and adaptive falsification search. envelope is the last allocation and utilization_points is the final accumulated finite set.
PowerOptLab.SearchStableOperatingEnvelopeResult — Type
SearchStableOperatingEnvelopeResultResult of solve_search_stable_operating_envelope. It retains the final allocation, every utilization-screening round, and the accumulated test set. outcome=:search_stable is a finite-search result rather than a global robust certificate.
PowerOptLab.OperatingEnvelopeMultistartResult — Type
OperatingEnvelopeMultistartResultCollection returned by solve_operating_envelope_multistart. selected is the best publishable run under the declared selection rule; all starts and capacity spreads remain available for branch-sensitivity reporting.
Solvers and verification
PowerOptLab.audit_doe_scenario_calibration — Function
audit_doe_scenario_calibration(calibration, evaluation;
group_key=nothing, require_disjoint_ids=true,
require_unique_networks=true, require_group_disjoint=group_key !== nothing,
require_chronological_order=false)Audit whether declared calibration and evaluation scenario sets satisfy chosen separation requirements. The result reports ID reuse, exact network-realization reuse, timestamp ordering, optional metadata-group overlap, provenance completeness counts, interval counts, and weighted effective sample sizes.
group_key may identify a site, feeder, customer cohort, weather event, or any other caller-defined blocking unit. Set require_group_disjoint=false for an intentional longitudinal design. Exact network reuse is rejected by the audit outcome by default but can likewise be made descriptive with require_unique_networks=false.
An outcome of :no_declared_leakage_detected is limited to the checks and metadata supplied here. It does not establish probabilistic calibration, representativeness, independence, or absence of distribution shift.
PowerOptLab.sample_doe_gaussian_uncertainty — Function
sample_doe_gaussian_uncertainty(mean, covariance;
parameter_names, count, seed, sample_prefix="gaussian",
timestamps=nothing, metadata=Dict(), psd_tolerance=sqrt(eps()))Draw a reproducible typed sample set from a declared multivariate normal model. The covariance may be positive semidefinite; eigenvalues within psd_tolerance of zero are clipped and the retained rank is reported. Larger negative eigenvalues, asymmetry, non-finite inputs, and dimension mismatches are rejected.
The result records the full declared mean/covariance, empirical sample moments, generator, Julia version, and seed. It does not establish that a Gaussian model is appropriate, and its support is unbounded: physical truncation, rejection, or transformation must be declared separately rather than applied silently.
PowerOptLab.sample_doe_box_truncated_gaussian_uncertainty — Function
sample_doe_box_truncated_gaussian_uncertainty(mean, covariance;
parameter_names, lower, upper, count, seed, draw_budget,
sample_prefix="truncated-gaussian", timestamps=nothing,
metadata=Dict(), psd_tolerance=sqrt(eps()))Draw from a multivariate Gaussian conditioned on the componentwise box lower .<= x .<= upper using rejection sampling. Accepted draws are not clipped or projected. The returned sample set records the draw budget, stopping index, empirical acceptance rate, bounds, underlying Gaussian declaration, and whether the requested count was reached.
draw_budget is a required scientific/computational stopping rule. The function throws when the budget cannot supply count accepted samples. Rejection sampling is exact conditional on the declared Gaussian model and box, but a low acceptance rate is evidence of an inefficient or poorly aligned proposal—not validation of either model.
PowerOptLab.sample_doe_empirical_residual_bootstrap — Function
sample_doe_empirical_residual_bootstrap(residuals;
parameter_names, block_count, seed, block_length=1,
center=nothing, circular=false, source_timestamps=nothing,
timestamps=nothing, require_regular_spacing=false,
sample_prefix="residual-bootstrap", metadata=Dict())Resample rows from a declared residual library. With block_length=1, this is an ordinary empirical bootstrap. Longer blocks preserve contiguous row order; circular=true permits blocks to wrap from the last library row to the first. Each returned parameter equals center + residual, with a zero center by default.
The output is flattened in block-major order and every sample records its block, position, source row, optional source timestamp, and whether a circular wrap occurred. The complete residual library and its timestamps participate in a stable library hash even when some rows are not sampled. Optional timestamps describe output/target samples and therefore remain distinct from source times.
Moving-block validity generally requires a defensible ordered, approximately stationary residual process and a justified block length. This function records but does not establish those assumptions, residual calibration, block independence, physical support, or out-of-sample validity.
PowerOptLab.materialize_doe_scenarios — Function
materialize_doe_scenarios(base_network, sample_set, materialize!;
dataset_id, materializer_id, role=:unspecified,
source="uncertainty sample materialization", metadata=Dict(),
scenario_metadata=Dict())Deep-copy base_network for each typed uncertainty sample, then call materialize!(network, sample). The callback may mutate the copy and return nothing, or return a replacement Dict{String,Any} network. The base network is never intentionally mutated.
materializer_id is required because function bodies cannot be serialized into the study identity; use a committed method/version identifier. Parameters, sample-set identity, base-network hash, generation method, seed, timestamp, and materializer identity are propagated into scenario provenance. The callback is responsible for units, physical transforms, topology validity, and any rejection or truncation rule.
PowerOptLab.test_doe_covariate_shift — Function
test_doe_covariate_shift(reference, shifted;
features, exchangeability_assumption=false, permutation_unit=:scenario,
group_key=nothing, permutations=999, seed=0, alpha=0.05)Compare numeric scenario-metadata covariates using pooled-scale multivariate energy distance and per-feature mean differences, standardized mean differences, and empirical-CDF distances. features is an explicit list of metadata keys; the function never guesses covariates from network dictionaries.
With the default exchangeability_assumption=false, the result is descriptive and p_value is missing. Set it to true only when labels are exchangeable under the null. permutation_unit=:scenario assumes scenario-level exchangeability. :group permutes whole, disjoint metadata groups identified by group_key; it is suitable only when those groups, rather than observations within them, are exchangeable. Neither design is automatically valid for time series.
A rejected test concerns only the declared metadata covariates. It does not by itself establish concept shift, changed violation risk, or general distribution shift in the full network state.
PowerOptLab.test_doe_time_series_covariate_shift — Function
test_doe_time_series_covariate_shift(reference, shifted;
features, circular_shift_invariance_assumption=false,
shifts=999, seed=0, alpha=0.05, require_regular_spacing=true)Compare chronologically separated metadata-covariate series while preserving contiguous serial structure. All scenarios need unique timestamps, every reference timestamp must precede every shifted timestamp, and regular spacing is required by default. Descriptive energy-distance and per-feature effects are always returned.
With circular_shift_invariance_assumption=true, the original reference window is compared with contiguous windows obtained by circularly shifting the cut through the pooled ordered series. This is stronger than ordinary stationarity: it asserts that cyclic placement, including the artificial last-to-first boundary, is valid under the null. Up to shifts alternative cuts are sampled without replacement; all cuts are used when their count is smaller.
The test concerns only the declared metadata covariates and does not establish changed violation risk or concept shift. Seasonal structure, trends, irregular sampling, overlapping windows, or a non-exchangeable intervention boundary need a different resampling design.
PowerOptLab.doe_probability_observations — Function
doe_probability_observations(coverage;
probability_key, group_key=nothing, use_scenario_weights=false)Convert scenario rows from a DOECoverageResult into probability- calibration observations. probability_key names scenario metadata containing a violation-probability forecast made before evaluation. Candidate violations map to true, passed scenarios to false, and unresolved scenarios to nothing.
Scenario weights are ignored by default because relative scenario weights are not automatically observation-frequency weights. Set use_scenario_weights only when that interpretation is scientifically justified.
PowerOptLab.evaluate_doe_probability_calibration — Function
evaluate_doe_probability_calibration(observations;
bins=10, unresolved=:exclude, independence_assumption=false,
confidence=0.95)Evaluate forecasts of DOE candidate-violation probability against later binary outcomes. The result includes weighted Brier and logarithmic scores, calibration-in-the-large, weighted expected/maximum calibration errors, a Brier decomposition for bin-mean forecasts with an explicit remainder for the original forecasts, and reliability-bin rows. bins is either a positive equal-width bin count or explicit edges spanning [0, 1].
unresolved must be :exclude, :violation, or :pass; the default preserves uncertainty rather than labelling unresolved nonlinear solves. Simultaneous bin-wise and overall weighted Hoeffding intervals are returned only with independence_assumption=true. This asserts conditional independence of outcomes given the forecast design, with weights, bin rules, and retained observations fixed independently of those outcomes. It is not inferred from timestamps, groups, scenario weights, or provenance. Overall and simultaneous-bin intervals have separate confidence guarantees; they are not one joint family. Their target is the weighted mean conditional event probability minus the weighted forecast, not a pointwise calibration function. Outcome-dependent exclusion of unresolved cases does not satisfy the assertion. Recoding them targets the recoded event.
These are diagnostics, not a binary declaration that a forecast is calibrated. Reliability diagrams depend on bin choice, and temporal/group dependence, forecast selection, and post-hoc reuse require study-specific treatment.
PowerOptLab.solve_operating_envelope — Function
solve_operating_envelope(nets, connection_points; kwargs...)
-> OperatingEnvelopeResultCalculate active-power operating-envelope capacity for each interval.
nets accepts three shapes:
- one network
Dict— one interval, one forecast scenario; Vector{Dict}— several intervals, one scenario each (backward compatible);Vector{Vector{Dict}}— several intervals, each containing one or more forecast/model scenarios. One capacity allocation is shared by every scenario in an interval;DOEScenarioSet— the same interval/scenario structure with typed IDs, train/calibration/validation/test roles, optional weights, timestamps, generation method, seeds, and provenance metadata.
Important keywords:
direction=:exportor:import; returned capacities are positive magnitudes;fairness=:equal, the legacy symbols:sum/:proportional, or aFairnessPolicy;security=:bound_pointenforces only simultaneous full utilisation;security=:cornersembeds all2^Nzero/full-utilisation corners for every scenario. It is deliberately capped bymax_exact_corners=10and is reported as local AC feasibility at tested points, not a global robust certificate;control_policy=nothingretains the historical pointwise-perfect-recourse formulation and reports it as a legacy default. PassPerfectRecourseexplicitly for published-work replication, orIssuePlusLocalLawsto share free setpoints across all scenario/utilisation contexts while retaining prescribed automatic IBR laws;utilizations=nothingmay instead be an explicit collection of participant utilisation vectors in[0,1]^N. This supports reproducible adaptive or counterexample-guided studies and is reported as an explicit test set;context_hook! = nothingmay register research-extension variables through BMOPFTools publicOpfModelKeys before the control policy is applied. Pair those handles withDOEControlRegistration;start_hook! = nothingreceives the completed OPF contexts immediately before optimization and can set reproducible JuMP start values;volt_var_watt_eps=2e-3controls the engine's smooth approximation of mandatory IBR Volt-VAr/Volt-Watt curve corners.
Loads retain their known P/Q from each network snapshot. Connection-bound IBRs retain their prescribed Q-V law. Other network devices, including BMOPFTools STATCOM IBRs, remain available to the OPF; comparing otherwise identical nets with and without a STATCOM therefore quantifies its impact on active-power DOEs. Network voltage, phase-to-neutral, negative-sequence (vneg_max), branch thermal, neutral-current, and device limits declared by BMOPFTools remain in force.
Diagnostics label the result as a local nonlinear solve, never as a global certificate. They also record whether uncertainty is represented by one declared snapshot or a finite scenario set, the selected control policy, and a per-control audit of shared, automatic, fixed, and context-adaptive variables. Connection-bound prescribed IBR controls remain enforced.
PowerOptLab.solve_operating_envelope_multistart — Function
solve_operating_envelope_multistart(nets, connection_points;
start_scales=(1.0, 0.9, 1.1), base_start_hook! = nothing, kwargs...)Run the same DOE formulation from several deterministic perturbations of the native registered-variable starting point. Among runs with feasible primals, selection compares the requested fairness objectives in chronological interval order, with primary then secondary objectives for max-min policies. Primary max-min differences within max_min_tolerance are treated as ties; exact ties retain the earlier run. Equal-curtailment objectives are minimized. Diagnostics retain objective keys, every termination status, and capacity spread.
This is a branch-sensitivity diagnostic, not a proof of global optimality. base_start_hook!, when supplied, runs before each scale perturbation. Remaining keywords are forwarded to solve_operating_envelope.
PowerOptLab.compare_operating_envelope_policies — Function
compare_operating_envelope_policies(nets, connection_points, policies; kwargs...)Solve the same DOE study under several fairness policies. policies is a dictionary or vector of label => fairness pairs. The returned dictionary maps each label to an OperatingEnvelopeResult, whose fairness_metrics make the capacity/fairness trade-off directly comparable.
PowerOptLab.verify_operating_envelope — Function
verify_operating_envelope(nets, connection_points, capacities; kwargs...)
-> OperatingEnvelopeVerificationCheck an already-issued capacity trajectory without optimising it. The active power capacities are fixed and the normal network physics, including prescribed Q-V IBR controls and any STATCOM model present in the network, is solved at every requested scenario and utilisation point. utilizations is :bound_point, :corners, or explicit vectors in [0, 1]^N.
The same local-solve and finite-test-set semantics as solve_operating_envelope apply. control_policy also applies during verification, so an issued envelope can be checked under the same information structure used to quantify it. Custom vectors are reported as security_scope=:explicit_utilization_points. When capacities is an OperatingEnvelopeResult, its direction, control policy, per-unit base, smoothing settings and registered context hook are inherited unless overridden. Connection bindings must match. Scenario controls match stable IDs and network hashes (unique network hashes for untyped inputs); changed information states require replay_control_stages=(:issue,) to allow new scenario recourse. An explicit different policy is a re-optimization comparison, recorded in control_reoptimization and issued_control_replay_source. Under the same policy, replay_issued_controls=true fixes its recorded :issue and :scenario control values during verification. A capacity dictionary has no such issuance record and is labelled accordingly.
PowerOptLab.doe_dropout_utilizations — Function
doe_dropout_utilizations(participant_count, depth=1)Utilization vectors on the hypercube faces adjacent to the simultaneous bound point: every way of dropping 1..depth participants to zero while the remainder stay at their issued limit, ordered by the number dropped.
This is the family in which published partial-utilization counterexamples occur — a customer whose export falls below its allocation can raise the voltage of another phase through mutual and neutral coupling — and it grows as sum(binomial(n, k) for k in 1:min(depth, n)): polynomial for fixed depth, but 2^n - 1 at full depth. Pass the result as utilizations to verify_operating_envelope to trace how a violation depends on the number of participants that back off.
PowerOptLab.search_operating_envelope_utilizations — Function
search_operating_envelope_utilizations(nets, connection_points, capacities;
samples=16, sequence_offset=0, include_zero=true,
include_bound=true, include_corners=false, dropout_depth=0,
halton_scramble_seed=nothing, kwargs...)Screen an issued operating envelope at a deterministic Halton low-discrepancy set of continuous participant-utilisation vectors. The generated set is solved jointly, so the selected DOEControlPolicy and its non-anticipativity constraints apply across the search points.
The result is deliberately labelled :search_stable, :candidate_counterexample, or :inconclusive; this finite local-NLP search is not a robust-feasibility certificate. sequence_offset makes disjoint, reproducible batches possible.
dropout_depth additionally seeds every point that drops 1..dropout_depth participants to zero while the remainder stay at their issued limit; it defaults to 0 here so that the screening sequence stays the documented space-filling set. Digit scrambling is reproducible but cannot compensate for an inadequate sample budget. diagnostics["halton_seed_stratified"] reports only measured marginal first-digit coverage of the actual offset sequence, not joint coverage or a safety guarantee. Remaining keywords are forwarded to verify_operating_envelope.
PowerOptLab.search_operating_envelope_adversarial — Function
search_operating_envelope_adversarial(
nets, connection_points, capacities;
seed_samples=8, dropout_depth=1, refinement_rounds=3, restarts=3,
initial_step=0.25, step_decay=0.5, kwargs...)Search for unsafe partial utilization using deterministic Halton seeds and bound-point dropout faces, followed by coordinate refinement around points with the least normalized voltage, thermal, or negative-sequence headroom. Every round jointly verifies the full accumulated point set, preserving the selected control-recourse policy and its non-anticipativity constraints.
The score is the negative of the smallest declared normalized constraint margin, maximized over intervals and scenarios for each utilization point. An individually infeasible context receives an infinite candidate score; unresolved contexts remain unscored and make the outcome inconclusive. Because each AC verification and the outer point search are local and finite, this function is a falsification heuristic, not the continuous violation-maximizing oracle or a robust certificate.
Reachability of the coordinate refinement
Refinement moves one coordinate at a time and the step shrinks geometrically, so from the simultaneous bound point the deepest single-coordinate excursion it can ever reach is
1 - initial_step / (1 - step_decay)which is 0.5 at the defaults. Vertices in which a participant backs off completely are therefore unreachable by refinement alone, and published partial-utilization counterexamples are of exactly that form. dropout_depth seeds those faces directly — every way of dropping 1..dropout_depth participants to zero, sum(binomial(n, k) for k in 1:dropout_depth) points — and defaults to 1 because falsification is this function's purpose. Raise initial_step, lower step_decay, or use include_corners when the interior between those faces also matters.
halton_scramble_seed reproducibly permutes every digit, including trailing zeros. It does not ensure coverage with a small budget. The diagnostic halton_seed_stratified measures only marginal first-digit coverage of the actual offset sequence, not joint stratification or a safety guarantee.
PowerOptLab.confirm_operating_envelope_counterexample — Function
confirm_operating_envelope_counterexample(
nets, connection_points, capacities, utilization;
start_scales=(1.0, 0.9, 1.1), kwargs...)Repeat one candidate utilization point from deterministic perturbations of the registered OPF starting values. If capacities is an OperatingEnvelopeResult, recorded issue-time/scenario controls are replayed by default through verify_operating_envelope.
:repeated_candidate means every start produced at least one individually infeasible context; :not_reproduced means at least one start verified every interval/scenario; all other combinations are :inconclusive. None is a global infeasibility certificate.
PowerOptLab.evaluate_operating_envelope_coverage — Function
evaluate_operating_envelope_coverage(
scenarios, connection_points, capacities;
roles=(:test,), utilizations=:bound_point,
iid_assumption=false, confidence=0.95, kwargs...)Evaluate an issued envelope on a role-selected subset of a typed DOEScenarioSet. A scenario is a candidate violation when any tested utilization context is individually infeasible, unresolved when numerical or joint-policy evidence cannot classify every context, and passed otherwise.
Empirical context/scenario rates are always returned. A one-sided Hoeffding upper bound is returned only when iid_assumption=true; that flag is an explicit scientific assertion by the caller, not something inferred from metadata. Issue-time controls from an OperatingEnvelopeResult are replayed, while scenario-stage controls may adapt to each newly observed held-out scenario.
PowerOptLab.evaluate_operating_envelope_coverage_curve — Function
evaluate_operating_envelope_coverage_curve(
scenarios, connection_points, capacities;
scales=(0.5, 0.75, 1.0), kwargs...)Evaluate the same selected held-out scenarios over an ascending sequence of capacity multipliers. When capacities is an OperatingEnvelopeResult, its recorded issue-time controls are retained at every scale; they are not silently re-optimized after test scenarios are observed. Other coverage keywords, including roles, utilizations, and iid_assumption, are forwarded to evaluate_operating_envelope_coverage.
The first scale with a candidate violation is a finite-grid diagnostic only. Candidate-count reversals are reported rather than hidden: they can reflect physical non-monotonicity, discrete/control effects, or local-solver behavior.
PowerOptLab.compare_doe_coverage_shift — Function
compare_doe_coverage_shift(reference, shifted;
reference_label="reference", shifted_label="shifted", tolerance=0.0)Compare two already evaluated held-out ensembles descriptively. Deltas are shifted - reference; the outcome uses the conservative scenario-frequency delta so unresolved cases are not treated as safe. This function deliberately does not infer that the scenario distributions differ. Establishing covariate, concept, or temporal distribution shift requires a separately declared test and assumptions appropriate to the data-generating process.
PowerOptLab.compare_doe_uncertainty_models — Function
compare_doe_uncertainty_models(models, connection_points, capacities;
scales=(0.5, 0.75, 1.0), pairing=:auto, pair_key=nothing,
tolerance=0.0, kwargs...)Evaluate the same issued capacities, utilization declaration, control policy, solver settings, and scale grid against two or more labelled typed scenario sets. models is a dictionary or vector of label => DOEScenarioSet pairs. Coverage keywords such as roles, utilizations, and iid_assumption are forwarded unchanged to every model.
pairing=:auto requires a nonempty pairing_namespace string in every scenario's metadata, matching across paired rows. Within that declared scope it tries uncertainty-sample IDs, unique timestamps, then interval/scenario IDs. Coincident local IDs alone never establish pairing. Declare a shared namespace only for the same underlying experimental units or deliberately coupled draws. Use scenario_metadata=Dict("pairing_namespace" => "study-draws-v1") when materializing a reused sample set. Independent ensembles should use distinct namespaces or none. Alternatively select :uncertainty_sample_id, :timestamp, :scenario_id, or :metadata explicitly to assert that the selected keys identify matching units; explicit pairing does not check namespaces. Metadata pairing also requires pair_key. pairing=:none disables matching. Paired and partially paired comparisons report conservative status discordance, counting unresolved outcomes as candidate violations.
The result is descriptive finite-ensemble sensitivity evidence. It does not test that distributions differ, establish that the uncertainty model caused an observed difference, or verify that capacities were selected independently of the evaluation ensembles. Pairwise deltas are comparison - reference in the provided model order, and outcome summarizes conservative-frequency differences at the largest declared scale. Prefer a vector of pairs when that directional order is part of the experimental design.
PowerOptLab.solve_adversarial_search_stable_operating_envelope — Function
solve_adversarial_search_stable_operating_envelope(
nets, connection_points; initial_utilizations=:bound_point,
max_rounds=3, solve_keywords=NamedTuple(),
search_keywords=NamedTuple())Allocate on an accumulated finite utilization set, run search_operating_envelope_adversarial against the actual recorded issue/scenario controls, add all discovered points, and repeat. Every allocation and search is retained. A final reallocation is performed when the search budget is exhausted so the returned envelope represents every accumulated point, although that final allocation has not itself passed another adaptive screen.
Outcomes are :search_stable, :budget_exhausted, :inconclusive, or :allocation_failed. They remain finite local-NLP evidence and never a global certificate.
PowerOptLab.solve_search_stable_operating_envelope — Function
solve_search_stable_operating_envelope(nets, connection_points;
initial_utilizations=:bound_point, samples_per_round=16,
max_rounds=3, solve_keywords=NamedTuple(),
verification_keywords=NamedTuple(), kwargs...)Counterexample-guided research wrapper for a box DOE. Each round allocates capacity on the accumulated utilization set, screens that allocation on an increasing deterministic low-discrepancy set, and adds the full screened set to the next allocation when a candidate violation or joint-policy conflict is found.
The result is :search_stable, :budget_exhausted, or :allocation_failed. No outcome is a global certificate: this procedure improves finite tested-point coverage while retaining local nonlinear-solver limitations. Put fairness and other allocation-only options in solve_keywords; put replay/solver options used only for screening in verification_keywords.