-
-
Notifications
You must be signed in to change notification settings - Fork 6
cost function math
This document provides the complete mathematical formulation of the HSEM cost function
(planner/cost_function.py). It is the source of truth for all cost calculations.
The cost function returns two distinct aggregates for every plan:
| Aggregate | Symbol | Contents | Used for |
|---|---|---|---|
| total_cost | Real money terms only | Auditing, bill comparison | |
| score |
|
Candidate selection |
The selector picks the plan with the lowest score, not the lowest money cost.
Where
The cost function prices actual grid energy drawn, not stored energy. If the battery stores
$x$ kWh and charge efficiency is$e$ , the grid import is$x/e$ , which includes conversion losses implicitly.
Where
Revenue is subtracted from total cost. Negative export prices (curtailment penalties) increase total cost.
Where
The cycle cost counts the maximum of charge and discharge per slot, not
their sum. This matches the MILP formulation where
The 2× denominator accounts for one full round-trip (charge + discharge = 2 ×
usable_kwh throughput per cycle). With this factor, charging
Where
The conversion loss term prices the energy lost as heat during charge/discharge at the average of import and export price — an opportunity-cost proxy.
When separate charge/discharge efficiencies are configured:
Where
An optional per-slot fixed tariff cost, typically zero unless the user configures grid tariff fees.
These are soft guards — the SoC simulation already hard-clamps at hardware limits, so violations are rare. The quadratic form heavily penalises large deviations while tolerating tiny numerical rounding errors.
Past-slot exclusion: Slots with time_passed recommendation are excluded
from SoC penalty calculation. The SoC simulator writes estimated_battery_soc = 0.0
as a sentinel on past slots, which would otherwise generate a false penalty of
Where
Where
Where:
-
$E_{initial}$ = stored battery energy above the discharge floor at the start of the horizon (kWh) -
$E_{final}$ = stored battery energy above the discharge floor at the end of the horizon (kWh) -
$p_{replacement}$ = replacement price per kWh (minimum future import price)
Sign convention:
The replacement price uses the minimum future import price across the horizon because:
- It represents the marginal cost of re-purchasing one stored kWh at the cheapest opportunity
- Using the average (including expensive peak prices) over-values stored energy during high-price periods and biases against discharging
The cost function skips any slot whose recommendation is time_passed:
- All energy-flow fields (
grid_import_kwh,batteries_charged, etc.) are zero on past slots - Including them would only affect the SoC penalty (bogus
$w_{low} \cdot soc_{min}^2$ ) - Skipping past slots does not change the winner (the bogus penalty is identical across candidates) but keeps the reported cost clean
For every planner run:
-
$C_{total} = C_{import} - R_{export} + C_{cycle} + C_{loss}$ (exact) - No synthetic penalty enters
$C_{total}$ -
$S = C_{total} + P_{soc} + P_{grid} + P_{override} + V_{terminal}$ (exact) - When all penalties = 0 and terminal-SoC is disabled:
$S = C_{total}$ - Selector picks minimum
$S$ , not minimum$C_{total}$ -
$score_{winner} = score_{final_output}$ (no post-selection mutation) - Two identical plans, one ending with more stored energy → lower
$V_{terminal}$ → lower$S$
- Home — User-facing overview: features, FAQ, working modes, battery schedules, excess export, consumption sensors
- Battery Charging Economics — How to calculate the minimum charging price for a battery schedule
- Architecture Overview — System context, layered architecture, module map, planning pipeline
- Planner Specification — Normative — all planner invariants, rules, and constraints
- Planner Technical Guide — How the planner works with worked examples
- Cost Function Math — Complete mathematical formulation of the 8-term cost function
- Energy Accounting — Physical energy flow model, SoC simulation, efficiency math
- Candidate Generation — How candidates are generated, assumptions, partial-SoC
- MILP Optimization — Full LP formulation, variable layout, constraints, and solver pipeline
- Consumption Prediction — Weighted-average model, IQR outlier detection, spike suppression
- Safety Modes — Degraded mode, read-only gate, write-verify applier, runtime resolver
- Price Scaling — EDS price scaling, eds_share conversion factor
- Services Reference — All 4 HSEM services with examples
- Sensors Reference — Complete entity reference: all sensor, select, switch, number, and time entities
- Dashboard Setup — Step-by-step ApexCharts dashboard with full YAML, layout reference, and troubleshooting
- Config Flow Reference — Every config/options flow step and field
- EV Charge Plan Setup — EV planned load configuration guide
- EV Surplus Charging Automation — Wire your physical EV charger (go-e, Easee, Zaptec) to follow HSEM surplus recommendations
- EV Optimal Charging Template — Legacy Home Assistant template sensor for cost-optimal EV charging
- Forecast Accuracy Tracking — Forecast vs actual tracking system
- Huawei Entities — Canonical HA entity ID reference
- Troubleshooting Guide — Diagnose and fix common problems: missing data, wrong prices, write failures, battery behaviour
- Quality Checks — Static quality tools and CI configuration