State estimation API
Select an estimator using the state estimation overview and comparison. The legacy WLS and constrained NLLS guides describe the network assumptions, measurement equations and convergence criteria.
Legacy WLS estimator
PowerOptLab.Measurement — Type
Measurement(; kind, bus, value, sigma, terminal="1", reference=missing)A single scalar measurement for solve_state_estimation. value and sigma are SI (volts for :vr, :vi, :vmag, watts for :pinj, vars for :qinj); sigma is the measurement standard deviation (WLS weight 1/sigma²), and must be finite and strictly positive.
kind::Symbol—:vr,:vi, or:vmag(a rectangular component or the magnitude of the voltage across(bus, terminal)→reference),:pinj(active power injected into the network at that terminal pair), or:qinj(reactive power injection).bus::String,terminal::String="1"— the measured conductor.reference— the return terminal the quantity is referenced to.missing(the default) inherits the solve'sneutral; aStringnames an explicit return terminal on the same bus;nothingreferences terminal-to-ground. Each voltage reading selects its own reference; P/Q for one customer must share a return path. A smart-meter reading is usually phase-to-neutral.
Construction validates kind, finiteness, sigma > 0, and non-empty identifiers; it does not check that the identifiers exist in a particular net.
PowerOptLab.solve_state_estimation — Function
solve_state_estimation(net, measurements; kwargs...) -> StateEstimationResultEstimate the network state of net — a physics-only BMOPFTools net (buses, lines, transformers, shunts, and a voltage source; no loads, generators, IBRs, or operational limits) — that best fits measurements in a weighted-least-squares sense.
The network is treated as a contract and validated up front (see allow_operational). Every non-source phase terminal must be either a measured injection (a :pinj+:qinj pair) or declared in zero_injection; an un-declared, un-measured bus is an error, never a silent zero injection.
Keywords
neutral="n"— default return terminal for injection measurements, free injections, and voltage references. Passnothingif phase terminals are referenced directly to ground.zero_injection=String[]— buses (or(bus, terminal)pairs) known to carry no injection. A bare bus id expands over its phase terminals.allow_operational=false— whentrue, downgrade the network-contract check to a warning instead of an error (estimate against loads/limits deliberately).check_observability=true— compute a local identifiability diagnostic.per_unit=true,s_base=1e6— engine unit handling; measurements stay SI.optimizer=Ipopt.Optimizer,verbose=false,solver_options=().
Observability
The returned observability NamedTuple reports a LOCAL numerical check: the exact KCL Jacobian and whitened measurement Jacobian with respect to rectangular node voltages are formed at the returned point (reusing ybus_passive). Measurement rank is evaluated on the feasible tangent space, after profiling individual-customer powers at merged nodes. observable = rank == n_states, where rank combines exact and tangent measurement ranks. redundancy excludes fitted individual-customer power allocations. The smallest singular value and condition number describe the reduced voltage information. This detects local rank deficiency / critically-weak measurement sets; it is not a global uniqueness proof, and solver convergence alone never establishes one.
Returns
A StateEstimationResult; its bus voltages are NaN unless solve_status(result).publishable is true.
PowerOptLab.StateEstimationResult — Type
StateEstimationResultResult of solve_state_estimation.
Fields
termination_status::String,primal_status::String— the solver's termination status and primal-point status. Trust the estimate only whensolve_status(result).publishableis true (termination and primal feasibility).objective::Float64— the optimal weighted-residual sum∑ (z−h)²/σ²(NaNif no feasible point was found).bus::Dict{String,Any}— the estimated SI bus voltages (vr,vi,vm,vaper terminal).NaNthroughout when the result is not publishable — an unconverged solver iterate is not an estimate.residuals::Vector{NamedTuple}— per input measurement, in order:(kind, bus, terminal, reference, measured, estimated, residual, standardized)withresidual = measured − estimatedandstandardized = residual/σ.standardizedis the σ-normalised RAW residual, not the classical leverage-adjusted normalised residual (rᴺ = r / √(Sᵢᵢ)) used for bad-data identification; it is a scale-free residual, not a χ²/rᴺ test statistic.observability::NamedTuple— a LOCAL numerical identifiability diagnostic(observable, n_states, rank, redundancy, min_singular, cond, tangent_dimension)from the measurement Jacobian at the returned point. Exact KCL equations are ranked in their own units; measurement rank, redundancy,min_singular, andcondare computed from the whitened measurement Jacobian on the feasible tangent space. Thus1/min_singularis the local worst-case estimate standard deviation under the stated Gaussian model (seesolve_state_estimation).
Compiled constrained estimator
PowerOptLab.TerminalConnection — Type
One oriented device branch: current is positive from positive to negative. Also declares an unknown injection's physical path through compile_state_estimator(...; injection_connections=[...]), without stipulating a current or power law. negative=nothing denotes earth.
PowerOptLab.ExactInjectionSpecification — Type
ExactInjectionSpecificationMarker hierarchy for information which is genuinely exact. Meter readings and forecasts are intentionally absent: they belong in the stochastic residual model, not in this hierarchy.
PowerOptLab.ConstantPowerDevice — Type
Exact constant-power branches; positive power denotes consumption.
PowerOptLab.ConstantCurrentDevice — Type
ConstantCurrentDevice(connections, currents; angle_reference=:earth)Exact current branches; positive current flows into the device. :earth fixes an absolute phasor. :voltage fixes magnitude and power factor relative to the connection voltage: I=currents[k]*V/abs(V). Its angle is undefined at zero V unless the current coefficient is zero.
PowerOptLab.ZIPDevice — Type
Exact ZIP branches: conj(S/V) + I + YV, all in SI branch quantities.
PowerOptLab.ExactDeviceEquation — Type
ExactDeviceEquation(model)Wrap an exact device model so its terminal KCL equations enter c(x)=0. Use only for a device law known exactly; uncertain load/generation information belongs in measurements or priors.
PowerOptLab.BranchMeasurement — Type
A scalar telemetry reading on one end/conductor of a named BMOPF line.
PowerOptLab.NetInjectionMeasurement — Type
NetInjectionMeasurement(; kind, bus, terminal="1", reference=nothing, value, sigma)Net current (:ire, :iim, :imag) or power (:pinj, :qinj) into the passive network at one conductor. Unlike customer Measurement powers this observes the total at a merged node and declares no unknown injection path. Declare physical paths with injection_connections independently of telemetry. Power uses terminal-to-reference voltage; current is reference-independent. Ideal-ground reaction currents require element telemetry, not reduced Ybus.
PowerOptLab.TransformerMeasurement — Type
TransformerMeasurement(; kind, transformer, variant, port=1, terminal,
reference=nothing, value, sigma)Current (:ire, :iim, :imag) or power (:pflow, :qflow) into a finite transformer port. The id is looked up across BMOPF subtypes; optional variant disambiguates a duplicated id. Ordinary transformers use port 1 (from) or 2 (to); a center-tap's port 2 contains both secondary legs and neutral. For n_winding, port is the winding-list index. Power is referenced to earth unless a terminal on the selected port's bus is named explicitly. Shared original nodes in n-winding ports cannot be disaggregated by Yprim.
PowerOptLab.ShuntMeasurement — Type
ShuntMeasurement(; kind, shunt, terminal, reference=nothing, value, sigma)Current or power entering a named finite BMOPF shunt, including a neutral grounding electrode. Current is positive from the conductor into the shunt; positive power is absorbed by it. Uses the shunt's full coupled admittance. The kinds and voltage-reference convention match BranchMeasurement.
PowerOptLab.FunctionalMeasurement — Type
FunctionalMeasurement(; name, nodes, prediction, gradient=nothing, value, sigma)A pure scalar measurement function of selected SI conductor voltages. Its input is [real(V[nodes]); imag(V[nodes])], retaining duplicates and grounded zeros. prediction(z) returns one finite real number; supply gradient(z) or support ForwardDiff dual numbers for automatic first derivatives. Values/sigmas may change through SEParameters; functions, node order and captured constants belong to the compiled pattern. Callbacks must be pure and must not mutate inputs or captured data. They add no injection paths or exact equations. All three shared-model solvers use this same function and Jacobian.
PowerOptLab.SEPreflightFinding — Type
One machine-readable estimator preflight finding (:error, :warning, or :info).
PowerOptLab.SEPreflightReport — Type
SEPreflightReportElectrical support inventory for one snapshot. supported means the input can be represented by the compiled model, not that it is observable or that a solve will converge. elements records representation and fixed taps; omitted records network injections and operating limits not used by this estimator. Sources, declared perfect grounds, measurement references, and exact-equation requests are recorded separately. Compilation retains the report in s.preflight.
PowerOptLab.SEUnsupportedNetwork — Type
Compilation error carrying an inspectable SEPreflightReport.
PowerOptLab.state_estimator_preflight — Function
state_estimator_preflight(net, measurements=[]; neutral="n", zero_injection=[],
exact_devices=[], injection_connections=nothing)Inspect the supported electrical interpretation before compiling. Ideal and warning-producing transformer primitives are rejected, never regularised or silently skipped. Fixed taps are data, not estimated controls. This report does not certify observability, model accuracy, or convergence. Pass injection_connections to declare unknown injection paths independently of P/Q telemetry; the default infers them from the measurements.
PowerOptLab.initial_state_estimator — Function
initial_state_estimator(structure, parameters)Return the load-free voltage state using current source phasors and compiled finite admittances. This respects fixed transformer ratios and phase shifts. When unknown-current states are present, seed them from precision-weighted customer P/Q and the corresponding complex connection voltage. It is an initial guess, not telemetry or a state estimate. Reference-deficient networks may have arbitrary null-space components; callers should supply a physical warm start when that matters. Throws if there is no nonzero reference.
PowerOptLab.injection_state_indices — Function
injection_state_indices(structure)Map original unknown customer terminals to (real, imag) SI current-state indices. Empty for the eliminated voltage formulation. Voltage-state indices remain in free_state_map; current entries follow all voltage entries.
PowerOptLab.SEStructure — Type
SEStructure{Ti}Compiled structure for the voltage/current four-wire state-estimation formulation. It imports BMOPFTools' passive, conductor-to-earth Ybus exactly once. free_state_map maps a free conductor to its position in the rectangular state's leading [real(V_free); imag(V_free)] entries; explicit unknown-current entries follow when needed, indexed by injection_state_indices. Ideal-source conductors are held in the parameter vector instead. Closed ideal switches are already represented by the node aliases in ybus_passive.
The evaluator supports terminal voltage components/magnitudes and terminal active/reactive injection measurements, exact zero-injection equations, and connection-aware exact constant-power, constant-current, and ZIP devices. Explicit injection_connections (or power-measurement references by default) declare injection return paths: the sum of terminal currents on each connected, non-source, non-earth return component is exactly zero, independently of the noisy power readings. Distinct original terminals that alias to one node retain separate customer powers. The default uses explicit currents when customer powers cannot safely be eliminated; formulation=:voltage retains the optimized power profile for eligible connections. Repeated readings of one original terminal share its power. Only numerical solver-proof caches are mutable; topology and patterns are fixed. Line telemetry is compiled from the same passive primitives.
PowerOptLab.SEParameters — Type
SEParametersMutable numerical data paired with an SEStructure. Updating the measurement values, standard deviations, or fixed source phasors does not alter terminal ordering or symbolic sparsity. Standard deviations are the diagonal whitening factors for this first implementation.
Construct parameter updates with the same measurement kinds, locations, references, and row order used at compilation. Exact device kinds and oriented connections must also match. Only their numerical readings, uncertainties, and device values may change; a changed pattern requires recompilation.
magnitude_epsilon (volts) and current_epsilon (amperes) smooth :vmag and :imag residuals respectively. They are deliberately separate scalars: a magnitude derivative is undefined at zero for both, but the two are different physical quantities and a mixed :vmag/:imag dataset has no single meaningful smoothing value. Size each below the resolution of the instrument it applies to.
voltage_min_model (volts) bounds the domain of physical constant-power laws and merged-customer power profiling. At zero connection voltage individual customer powers cannot be recovered from their sum using finite currents.
PowerOptLab.SEEvaluation — Type
Values of the compiled residual/constraint model at one voltage/current state.
PowerOptLab.compile_state_estimator — Function
compile_state_estimator(net, measurements=Measurement[];
neutral="n", zero_injection=String[], exact_devices=[],
injection_connections=nothing) -> SEStructureCompile the voltage/current evaluator. The network is represented by BMOPFTools' passive I = YV relation in SI units. Every source terminal with a specified phasor is eliminated from the state; ungrounded neutrals and floating conductors remain explicit states, so gauge/reference deficiencies are visible to the later rank diagnostics rather than silently grounded.
injection_connections is a vector of TerminalConnections for unknown injections, independent of their telemetry; omit it to infer paths from P/Q measurements. Preserve declarations when channels drop out. Each power meter must match a declared original positive terminal and electrical return. The default formulation=:auto adds explicit currents for merged customers, overlapping paths and partially exact shared conductors. :current always uses unknown current states; :voltage requires the narrower elimination contract.
PowerOptLab.evaluate_state_estimator — Function
evaluate_state_estimator(structure, parameters, x) -> SEEvaluationEvaluate SI phasors, whitened stochastic residuals (h(x)-z)/σ, and exact zero-injection, device, and return-current KCL residuals. The constraint vector is never whitened or otherwise softened.
PowerOptLab.residual_jacobian — Function
Sparse analytic Jacobian of whitened measurement and prior residuals. Use collect(Float64, H) if a downstream routine requires a dense matrix.
PowerOptLab.constraint_jacobian — Function
Sparse analytic Jacobian of exact zero-injection, device, and return-current constraints.
PowerOptLab.ConstrainedStateEstimationResult — Type
ConstrainedStateEstimationResultResult from the dense composite-step reference solver. status distinguishes a numerically converged but underobserved estimate from failure to establish the exact equations. history records the scaled trust-region radius, merit value, measurement objective, and exact-constraint norm at accepted iterates.
PowerOptLab.solve_compiled_state_estimator — Function
solve_compiled_state_estimator(structure, parameters, x0; kwargs...)
-> ConstrainedStateEstimationResultDense reference implementation of the plan's equality-constrained Gauss–Newton method. It uses a scaled Byrd–Omojokun composite step: a normal least-squares step for exact-equation violation, followed by a null-space tangential measurement step. An exact-penalty merit function globalises both quantities; rejected nonlinear constraint steps receive one trust-region-limited second-order correction before the radius contracts.
This intentionally transparent solver is for small-system verification. It uses dense SVD rank/null-space diagnostics; the compiled evaluator preserves the sparsity used by solve_sparse_state_estimator, the sparse Hachtel-system implementation for larger networks.
PowerOptLab.SparseConstrainedStateEstimationResult — Type
SparseConstrainedStateEstimationResultResult from solve_sparse_state_estimator. constraint_multipliers are recovered directly from the final Hachtel system, in the same row order as evaluation.constraints; they are useful for ranking suspicious exact zero-injection or device equations.
PowerOptLab.solve_sparse_state_estimator — Function
solve_sparse_state_estimator(structure, parameters, x0; kwargs...)
-> SparseConstrainedStateEstimationResultSparse augmented-system implementation for larger compiled networks. Each iteration solves the scaled Hachtel system using SuiteSparse QR, retaining the residual and constraint operators rather than explicitly forming H' * H or a dense null-space basis. The dense SVD helper is used only for the small final rank diagnostic/status; it is not part of the linear step.
The trust-region acceptance uses the same exact-penalty merit function as the dense reference solver. damping is a small scaled primal regulariser used only to select a stable representative in rank-deficient linear systems.
PowerOptLab.IpoptStateEstimationResult — Type
Outcome of solve_ipopt_state_estimator. state and evaluation use the same SI model as the dense and sparse solvers. Optimizer statuses are retained separately from checked physical feasibility, stationarity, curvature and rank. Use solve_status(result).publishable, not an Ipopt termination code alone. constraint_rows identifies the physical equations sent to Ipopt after removing verified coefficient identities. evaluation.constraints always retains every physical equation; diagnostics report both counts.
PowerOptLab.solve_ipopt_state_estimator — Function
solve_ipopt_state_estimator(structure, parameters, x0; kwargs...)Classic Ipopt nonlinear-programming solve over the same compiled model as the dense and sparse constrained estimators. All measurement functions, transformers, grounding, exact devices, priors and profiled customer powers therefore have identical semantics. This does not invoke the legacy BMOPF OPF wrapper or impose its complete P/Q coverage contract.
Uses analytic/automatic first derivatives, voltage/current scaling, compiled sparse derivative patterns and Gauss–Newton curvature H' * H. Residual and nonlinear constraint second derivatives are omitted. Evaluations and individual Jacobians are cached at each iterate. Final rank checks remain dense; tested feeder sizes do not establish general scaling. State-independent dependencies are checked using passive/device affine coefficients and independent nonlinear branch-current incidences. Only a verified basis is sent to Ipopt; final checks retain all original equations. An initially rank-deficient Jacobian alone never permits dropping an equation. solver_options accepts Ipopt attribute pairs or a NamedTuple; the supplied curvature approximation uses Ipopt's hessian_approximation="exact" callback mode. Final physical feasibility and reduced stationarity are checked independently of the optimizer's status. Internal homotopy stages remain nonpublishable.
PowerOptLab.ContinuationStateEstimationResult — Type
Result and per-stage diagnostics from constant-power continuation.
PowerOptLab.solve_with_continuation — Function
solve_with_continuation(structure, parameters, x0; alphas=0:0.25:1, kwargs...)Advance exact constant-power/ZIP constraints from the regularised internal model (α=0) to their physical, unregularised equations (α=1). Each stage warm starts the dense constrained solver. A returned :power_flow_initialization_failed status means a stage could not establish feasibility; no final estimate is claimed unless the last stage is at α=1. Intermediate converged stages report :converged_regularized and are not publishable. Failure or an exception restores the caller's original alpha; successful continuation leaves it at one.
PowerOptLab.SEObservability — Type
Local tangent-space observability diagnostic for a compiled estimator.
PowerOptLab.observability_diagnostics — Function
observability_diagnostics(structure, parameters, x) -> SEObservabilityReport local identifiability on the feasible tangent space. include_prior=true includes prior information; set it to false to report measurement-only rank. Uses H*Z where C*Z = 0. This is deliberately not the rank of the unconstrained measurement Jacobian. The current dense diagnostic is intended for small/reference cases; the sparse solver uses it only after convergence, not in its linear step. With no feasible free direction, min_singular=Inf and condition_number=1.0 by convention.
PowerOptLab.unobservable_directions — Function
unobservable_directions(structure, parameters, x; count=nothing)Generate requested local unobservable state directions on demand. No basis is stored in SEStructure; callers that only need ranks should use observability_diagnostics instead.
PowerOptLab.selected_state_covariance — Function
selected_state_covariance(structure, parameters, x, indices)Return only the requested covariance block of the rectangular voltage state. The measurement residual Jacobian is already whitened, so this is the local Gauss–Newton covariance under the diagonal covariance model. It throws for a quantity that depends on an unobservable tangent direction. Identifiable quantities retain finite local covariance even when other state directions are unobservable; this is a first-order statement, not global identifiability.
PowerOptLab.derived_covariance — Function
derived_covariance(structure, parameters, x, jacobian)Return the local covariance of selected derived quantities. jacobian has one row per requested quantity and one column per state variable.
PowerOptLab.StatePrior — Type
A stochastic prior on selected SI voltage or branch-current state entries.
PowerOptLab.set_state_prior! — Function
Replace the stochastic state prior without recompiling network structure.
PowerOptLab.TimeSeriesStateEstimationResult — Type
Outcome of sequential estimation over one unchanged compiled topology.
PowerOptLab.solve_time_series_state_estimator — Function
solve_time_series_state_estimator(structure, parameters, x0;
previous_state_sigma=nothing, solver=:sparse, kwargs...)Solve successive snapshots without rebuilding terminal maps, Ybus structure, or measurement/device incidence. parameters contains one mutable SEParameters per snapshot; callers update its numerical measurements, covariances, sources, and device values in place before calling. Each snapshot warm-starts from the preceding result. When previous_state_sigma is supplied, that preceding state becomes a whitened stochastic prior for the next snapshot, not an exact equation. Supply a scalar or one standard deviation per state in SI units (volts for voltage entries, amperes for explicit-current entries).
solver is :sparse (default), :dense, or :ipopt. The result preserves every per-snapshot result and stops at the first non-converged snapshot, reporting :time_series_stalled without claiming later estimates. Use solver_kwargs=(dense=(...), sparse=(...), ipopt=(...)) for backend-specific settings; shared kwargs must apply to the selected solver.