Skip to content

Network optimization overview

HAEO uses linear programming to optimize energy flows across your network. This page explains the high-level architecture and mathematical foundations.

Layered architecture

HAEO separates user configuration from mathematical modeling through a layered architecture:

Device Layer (user-configured): Elements like Battery, Grid, Solar, and Load that users configure through Home Assistant. Each Device Layer element may create multiple Model Layer elements and multiple devices with sensors. See Device Layer.

Model Layer (optimization): The mathematical building blocks that form the linear programming problem. These elements define decision variables, constraints, and cost terms. See Model Layer.

This separation enables composition flexibility—a single Device Layer element can create multiple Model Layer elements to achieve complex behavior (e.g., Battery creates both a battery model for SOC tracking and a connection model for power flow).

Linear programming overview

Linear programming finds optimal values for decision variables that minimize (or maximize) an objective function subject to linear constraints.

Standard LP form:

\[ \begin{align} \text{minimize} \quad & c^T x \\ \text{subject to} \quad & Ax \leq b \\ & A_{\text{eq}} x = b_{\text{eq}} \\ & l \leq x \leq u \end{align} \]

Where:

  • \(x\): Decision variables (what the optimizer chooses)
  • \(c\): Objective coefficients (costs/prices)
  • \(A\), \(b\): Inequality constraint matrices
  • \(A_{\text{eq}}\), \(b_{\text{eq}}\): Equality constraint matrices
  • \(l\), \(u\): Variable bounds

Linearity requirement: All relationships must be linear. No quadratic terms (\(x^2\)), products (\(xy\)), or nonlinear functions (\(\sin(x)\), etc.).

Why linear programming?

LP fits home energy systems because power balances, costs, and most device constraints are linear. It delivers a global optimum when a feasible solution exists and scales well as you extend the horizon or add elements.

Pure LP first; MILP as a last resort

HAEO optimizes with pure linear programming (LP) wherever possible—fast solves over the multi-resolution horizon, with power policies compiled into the LP.

Mixed-integer programming (MILP) is a tool of last resort: we look for linear encodings first (penalties, slacks, forecast-shaped loads) and add integers only when LP cannot deliver the same outcome. Deferrable loads follow that approach: a deferrable load is pure LP, with each window's requirement settled at its end and any shortfall priced rather than enforced. Loads that need a discrete run-now decision, such as fixed-power appliances that cannot modulate, are still fixed or forecast consumption, or scheduled externally (for example via EMHASS) and passed in as inputs.

Mathematical model structure

HAEO formulates energy system optimization as a network where elements contribute to a unified linear program. Each element defines its own decision variables, constraints, and cost terms. The network aggregates these contributions into a single optimization problem.

Model aggregation

The complete optimization problem is built by combining contributions from all elements:

Decision variables: Each element introduces variables representing its behavior (power flows, energy states, etc.). The complete variable set is the union of all element variables.

Constraints: Each element contributes constraints governing its operation. The complete constraint set is the union of all element constraints plus network-wide power balance constraints.

Objective function: Each element contributes cost terms. The objective minimizes the sum of all element costs.

Solution process

Optimization is lexicographic: the plan has the lowest cost, and among equally cheap plans, the lowest secondary time-preference objective. The secondary breaks ties among cost-equivalent solutions by preferring earlier energy transfers.

Both are reached with a single blended solve of primary + weight * secondary, which warm-starts efficiently and gives shadow prices from the plan's own basis. On the first optimization, a binary search finds the largest blend weight whose plan is still cost-optimal, and the weight starts a quarter of a decade below it. A larger weight gives the secondary objective more influence, producing better tie-breaking in degenerate regions.

No single weight suits every input: too large and the secondary trades away cost, too small and its differences fall below the solver's tolerance, leaving ties unresolved. Each blended plan is therefore checked at its basis. The reduced costs there are the slopes of an objective along each way of moving away from the plan. The cost is priced at the plan's basis without any simplex iterations, which leaves the plan and its basis unchanged. If some move would lower the cost, the weight is too large and is lowered, half a decade (a factor of \(\sqrt{10}\)) at a time. Otherwise, the moves that leave the cost unchanged lead to equally cheap plans, and if one of them lowers the secondary, the weight is too small and is raised. The secondary needs no pricing of its own: at a fixed basis reduced costs are linear in the objective, so its reduced costs are the blended solve's minus the cost's, divided by the weight. The weight is never raised to a weight already found too large for the cost in that optimization, so the cheapest plan always comes first. Between a weight known too small and one known too large, the weight is bisected, and the blended solve is repeated from the same basis. The weight settled on is kept for later solves, and since inputs change, no weight is ruled out for good. If no weight puts the plan in order without failing the cost, the cost-optimal plan is kept; if none is cost-optimal at all, the cost alone is solved.

The primary objective is priced last, so its dual values at the plan's basis are the shadow prices: the blended duals without the secondary's contribution.

The secondary's reduced costs are scaled by the small blend weight, so the solver runs with feasibility tolerances of \(10^{-9}\) rather than the HiGHS default of \(10^{-7}\). At the default, tie-breaking differences can fall below the tolerance and leave equally cheap plans unresolved.

Solution outcomes

  • Optimal solution: Satisfies all constraints with minimum total cost and deterministic tie-breaking
  • Infeasible: No solution exists that satisfies all constraints simultaneously

Infeasibility does not depend on the objective, so the first infeasible solve ends the search for a blend weight. HiGHS then finds an irreducible infeasible subsystem: a smallest set of constraint rows that cannot all hold, which the error names by element, constraint, and period.

When the hub relaxes impossible plans, HiGHS instead finds the smallest weighted violation of the constraint rows that makes the model feasible. Variable bounds never give way. A power balance row weighs 1 and every other row 1000, so a shortfall lands at a balance point, as energy no source could supply or nothing could absorb, unless only a limit can give way. The violated rows are widened to the values the relaxation found, the model is solved for cost as usual, and the rows are restored. The relaxation does not see the cost, so the violation is minimal but where it falls is not chosen by cost.

Network structure

HAEO models energy systems as directed graphs:

  • Elements: Vertices that produce, consume, or store energy
  • Connections: Directed edges that transfer power between elements
  • Nodes: Balance points where power flows must sum to zero
graph LR
    Grid((Grid)) <-->|Connection| Node((Node))
    Solar((Solar)) -->|Connection| Node
    Battery((Battery)) <-->|Connection| Node
    Node -->|Connection| Load((Load))

    class Node emphasis

Element registration

When a connection is added to the network, it registers itself with its source and target elements. This allows elements to track their incoming and outgoing connections for constraint generation.

Network validation

Before optimization, the network validates its structure:

  • All connection endpoints reference valid elements
  • No connection has another connection as an endpoint
  • All element dependencies are satisfied

This validation ensures the network forms a valid directed graph before attempting optimization.

Time discretization

The optimization horizon is divided into \(T\) discrete periods (time steps) whose durations can vary. The horizon is defined by its \(T + 1\) period boundaries, which come from the hub's planning horizon setting:

  • Presets cover 2 to 7 days with 1-minute periods near-term, growing to 5, 30, and 60 minutes further out. Each change in period length is aligned to a clock boundary of the next length.
  • Forecast sensors list the boundaries directly, so a forecast with \(T + 1\) points defines \(T\) periods of any lengths.

Fine near-term periods give precise control over immediate decisions, while coarse distant periods keep the problem small across a multi-day lookahead. Each decision variable exists for every time step, but interval durations vary.

Power and energy discretization

HAEO distinguishes between two types of measurements across the optimization horizon:

Power variables represent average power over each period. These are interval measurements—the "fences" in the fence post analogy. With \(T\) periods, power variables have \(T\) values indexed as \(t \in \{0, 1, \ldots, T-1\}\).

Energy variables represent instantaneous stored energy at time boundaries. These are point measurements—the "posts" in the fence post analogy. With \(T\) periods, energy variables have \(T+1\) values indexed as \(t \in \{0, 1, \ldots, T\}\).

gantt
    title Power and Energy Variable Timing
    dateFormat X
    axisFormat %s
    section Variables
        E0 :milestone, 0, 0s
        P0 :active, 1s
        E1 :milestone,
        P1 :active, 1s
        E2 :milestone,
        P2 :active, 1s
        E3 :milestone,

Energy values (milestones) are measured at 4 time boundaries: \(E(0), E(1), E(2), E(3)\)

Power values (bars) are measured over 3 time intervals: \(P(0), P(1), P(2)\)

This distinction matters for cost calculations. Prices apply to average power over intervals, which is then converted to energy:

\[ \text{Energy consumed} = P(t) \times \Delta t_t \]
\[ \text{Cost} = P(t) \times \Delta t_t \times \text{price}(t) \]

Where \(\Delta t_t\) is the duration of interval \(t\) in hours (varies across the horizon).

Decision variables and constraints

The complete optimization problem includes decision variables and constraints from all network elements.

Variable structure

Power variables represent average power over each time period. These are interval measurements spanning the optimization horizon with \(T\) values.

Energy variables represent instantaneous stored energy at time boundaries. These are point measurements with \(T+1\) values.

Each element contributes its own variables based on its physical role (power flows, energy storage, curtailment decisions).

Constraint structure

Element constraints govern individual element behavior (capacity limits, efficiency losses, operating bounds).

Network constraints ensure power balance at connection points (Kirchhoff's law).

The complete constraint set ensures physically feasible operation while allowing optimization across the network.

Objective function

The optimization uses a lexicographic two-objective formulation.

Primary objective: minimize cost

\[ \text{minimize} \sum_{\text{elements}} \sum_{t=0}^{T-1} C_{\text{element}}(t) \]

Where:

  • \(T\): Number of time periods
  • \(C_{\text{element}}(t)\): Cost contribution from each element at time \(t\)

Each element defines its own cost terms based on its role:

  • Elements that interact with external systems (grids) contribute costs based on prices
  • Elements with artificial costs (batteries, curtailment) guide optimizer behavior
  • Elements without direct costs (loads, nodes) affect costs indirectly through energy balance

See individual element pages for specific cost formulations.

Secondary objective: time preference

When multiple solutions achieve the same minimum cost, the optimizer prefers earlier energy transfers. Each connection contributes a time-preference term to the secondary objective:

\[ \text{minimize} \sum_{\text{connections}} \sum_{t=0}^{T-1} w_{p,t} \cdot E_c(t) \]

Where \(p\) is the connection's priority, \(w_{p,t} = p \cdot T + (t + 1) + \tfrac{1}{2} u_{p,t}\) assigns monotonically increasing weights by connection and time step, and \(E_c(t)\) is the energy transferred through connection \(c\) at time \(t\). Each connection has its own priority, so connections receive non-overlapping weight ranges. The small fixed offset \(u_{p,t} \in [0, 1)\), the fractional part of the square root of a distinct prime per connection and period, breaks exact ties between equally cheap plans, which would otherwise be decided by the order of the solver's rows. See connection for why it is needed.

The secondary objective does not affect the optimal cost. It only selects among cost-equivalent solutions for deterministic, physically intuitive schedules.

Solver

HAEO uses HiGHS as its LP solver:

  • Open source: MIT licensed
  • Fast: State-of-the-art performance
  • Robust: Handles large-scale problems reliably
  • Alpine Linux compatible: Provides Python wheels that run on Home Assistant's Alpine Linux base
  • Actively maintained: Continuous improvements

HiGHS is the only supported solver and cannot be changed via configuration.

Units

HAEO uses consistent units for numerical stability:

  • Power: kilowatts (kW)
  • Energy: kilowatt-hours (kWh)
  • Time: hours (h)
  • Cost: dollars ($)

This keeps values in similar numerical ranges, improving solver performance. See units documentation for details.

Next steps