toc: true title: Strom: Smart Heating Optimisation
Smart Heating Optimisation · Barcelona
Take one Barcelona apartment, a little physics, a linear programme, and a €15 smart plug. Against tomorrow's electricity prices and the weather forecast, it continuously re-plans the cheapest way to heat the flat, without ever letting it get uncomfortable. Staying in the comfort band isn't a target it aims for; it's a hard rule it's not allowed to break.
- 27% lower electricity cost over two years versus a plain thermostat: €152 that stayed in Jan's pocket, with no loss of comfort.
- Zero comfort violations across more than 17,500 hours and two full heating seasons. The comfort band is a hard LP constraint.
- Shoulder seasons dominate. Mild spring and autumn months save the most (up to ~80%), while deep winter drops to 14–22%, since the heater then runs nearly full-time regardless of price.
- Buying more can cost less. Over the second half of November the optimizer drew more total energy than the thermostat (190 kWh vs 170 kWh) yet paid 35% less that fortnight. The savings come from timing, not from heating less. (The 27% above is the blended two-year figure; individual cheap stretches do far better.)
- Thermal mass is the storage medium. The wall's 7-day time constant ($\tau_{wall} \approx 7\ \text{days}$) lets the optimizer pre-charge the house and coast through expensive hours with no discomfort.
0. The Story
After switching to a dynamic electricity tariff, my friend Jan noticed that the price of electricity changes every hour: cheap at 3 a.m., painfully expensive through the morning rush. He also owns an electric plug-in heater, which was his main cost, so we wondered: Could we smartly heat the flat when electricity is cheap, before he feels cold? And could we do it without checking an app every hour, using available weather and price forecasts?
The result is a full-stack system with four parts: it pulls price and weather forecasts from APIs, models the building's thermal behaviour, solves for the cheapest schedule that stays comfortable, and sends the on/off commands to a smart plug. Forecast in, decisions out.
1. The Business Perspective
Electricity is perishable in a way most goods are not: the grid has to match supply and demand at every instant, with almost no buffer in between. That is the real reason cheap power at 3 a.m. is hard to use at 9 a.m.: you cannot simply set it aside. Renewables have sharpened the problem: when the sun is out, generation can be so abundant that wholesale prices fall to near zero, or even turn negative. But because it is weather-bound, that cheap power is volatile and fleeting. The grid's usual answer is storage: batteries, pumped hydro, hydrogen, and, less obviously, the thermal mass of the buildings we already live in.
That last form of storage is what this project exploits, through load shifting: buy energy when it's cheap, not at the moment you happen to need it. A building comes with the slack to make this work: a few degrees of comfort and a few hours of thermal inertia stand between "heat now" and "too cold." That slack is the room to maneuver, and the whole job of the optimizer is to use it deliberately instead of letting it go to waste.
Stated plainly, the objective is almost boring: spend as little as possible on electricity while keeping the indoor temperature inside a comfort band at all times. Let's look into a standard model for how a building stores and dissipates thermal energy, one that, as we'll see, also points to an efficient way to find the optimal strategy for when to heat and when to cool.
2. How the Building Works as a Battery
Section 1 called the building "thermal storage." Here is what that means in practice. Heat the walls and the air while power is cheap, and the structure holds that warmth and gives it back over the following hours; the building itself becomes the battery, storing energy as temperature rather than charge. To use that battery well we need to know how it charges and discharges, and each part of the building obeys the same physics, Newton's law of cooling:
| Symbol | Meaning | Units |
|---|---|---|
| Heat capacity: energy needed to raise temperature by 1°C | kWh/°C | |
| Thermal resistance: how hard heat flows between two regions | °C/kW | |
| Temperature (interior, exterior, etc.) | °C | |
| Timescale: time to halve a temperature gap | h | |
| Net thermal power injected into the interior | kW |
The injected power
where
So far we have treated the house as a single lump of mass, but that hides the mechanism that makes the whole scheme work. A home is really a shell: a thin envelope of air (the part we actually want to keep comfortable) wrapped inside far heavier walls. The heater warms the air, the air warms the walls, and only then does heat slowly leak outside.
That leaves us two lumps worth tracking, and they live on completely different clocks. The air heats and cools in minutes; the walls take days to fully charge or discharge. Between them sits a thermal resistance measuring how readily heat crosses from one to the other, and a second resistance to the outside.
And it is the wall, not the indoor air, that does the heavy lifting. Pre-heating that slow, massive reservoir is what buys the long coasting time inside the comfort zone, the stretch when the heater is off and the room stays warm anyway. That single fact is what the rest of this project is built to exploit.
3. The Physical Model
3.0 Which Model to Use?
Once we commit to lumped masses, two natural options present themselves:
| Model | What it captures | The trade-off |
|---|---|---|
| 1R1C | Single air+wall lump | Simple and useful for grid-scale aggregation, but misses the air/wall split: it cannot tell how warm people actually feel inside |
| 2R2C | Air + wall | Two time constants, still linear; captures the heat-battery effect that drives both comfort and cost |
Beyond lumped models lie full spatial simulations: FEM tools like EnergyPlus that resolve geometry and every localized heat leak. They are more accurate and far more expensive, which makes them the right tool for design and certification and the wrong one for a controller that has to re-solve every few minutes.
2R2C is the smallest model that still tells us what we need: by separating the fast-responding air from the slow thermal reservoir, it captures the one effect that comfort and cost both hinge on. It is also linear, which is what will allow the cost-minimization in §4 to be solved exactly, with the comfort band as a hard constraint.
3.1 Two Equations
The model almost writes itself once we follow the heat in and out of each part. Any lump warms up when more heat arrives than leaves, at a rate set by its heat capacity: Newton's law of cooling, applied part by part. Doing that for the air and the wall gives one differential equation each.
For the air:
For the wall:
Read them as a pair of flows: the air node takes the net injection from heater and cooler (both with non-negative duty cycles
3.2 Matrix Form
Stacked into a single system:
| Symbol | What it is |
|---|---|
| The two temperatures (the system's state) | |
| Heater and cooler duty cycles | |
| How temperatures drive each other; off-diagonals are heat pathways, diagonals are loss rates | |
| Input-gain matrix. Only the air row is excited by the current actuators | |
| Exterior temperature forcing |
With the actual parameter values:
The two diagonal entries differ by a factor of about 70. That is the matrix restating, in its own language, something we already suspected from standing in a cold room: the air responds roughly 70 times faster than the wall behind it.
3.3 Parameters and Timescales
The parameters are not invented; they come from Péan et al. (2018)[^pean2018], identified for a multi-family apartment in Barcelona, close enough to Jan's flat to be a fair stand-in.
| Parameter | Value | Units | What it measures |
|---|---|---|---|
| 0.26 | kWh/°C | Energy needed to heat the air by 1°C | |
| 19.1 | kWh/°C | Same for the wall, 73× larger | |
| 0.42 | °C/kW | Resistance between air and wall | |
| 8.86 | °C/kW | Insulation from outside | |
| 2.0 | kW | Heater nominal power | |
| 2.0 | kW | Cooler nominal power | |
| 18 / 24 | °C | Comfort band |
The two timescales:
: air responds in minutes : wall holds heat for nearly a week
At full heater power and no cooling, the air settles about 0.84°C warmer than the wall in steady state, a small but real gap you can spot in the plots further down:
4. The Optimisation
Now the actual task: choose heater and cooler duty cycles
Why not just a thermostat? It heats when the room is cold and stops when it's warm, and it has no idea whether electricity costs 5 cents or 50 at that moment. Blind to the price ahead, it can't pre-heat, and pre-heating is where every euro of savings in this project comes from.
Why not reinforcement learning? RL can learn genuinely sophisticated policies, but it can't promise you anything. A temperature limit handed to it as a soft penalty stays soft. One cold night is all it takes for someone to rip an automated system off the wall.
Why a linear programme, then? Because everything here is already linear: the building dynamics, the cost (power × price), and the constraints (comfort band, duty-cycle bounds). That lets an LP find the exact global optimum, with the comfort band as a hard wall, not a polite suggestion.
To get these continuous dynamics inside the LP, we discretize: each ODE step becomes a linear equality constraint via forward Euler with
The step size is not arbitrary; it is set by stability. Forward Euler stays stable only when
5. Tools
| Tool | What it does here |
|---|---|
| Python + CVXPY | Formulates the LP; chunked monthly solves stitch a two-year horizon |
| CLARABEL | Interior-point conic solver: lightweight, robust, and well-suited to LPs of this size |
| pandas / numpy | Time-series alignment, resampling, and per-month accounting |
| ENTSO-E API | Day-ahead wholesale electricity prices for the historical backtest and the live forecast |
| OpenWeatherMap API | Historical and forecast exterior temperatures |
| python-kasa | Sends ON/OFF commands to the TP-Link smart plug in the live loop |
6. Results
Throughout, the thing we measure against is a deadband thermostat: heat below
24–25 November 2024
Two representative winter days. The optimiser front-loads its heating into the cheapest pre-dawn hours and then coasts, sidestepping the expensive early-evening peaks, and the flat never once leaves the comfort band while it does.
November 2024 (second half)
Those days weren't cherry-picked. The same shape recurs wherever the price schedule opens a cheap window: 35% savings over the fortnight, again while buying more total energy (190 kWh vs 170 kWh). November is heating-dominated, so the optimizer spends most of its time hugging the lower edge of the comfort band, climbing above it only to pre-charge ahead of a price spike. In summer the picture flips entirely: cooling becomes the dominant cost, the optimizer hugs the upper edge, and it pre-cools toward the lower bound when overnight prices fall.
Two-year backtest: March 2023 to March 2025
Running the full two years as one LP isn't practical: at 5-minute steps that's 210,000 timesteps in a single solve. So we cut it at the seams: each calendar month is solved on its own, with the final temperatures of month
The optimizer spends less while using more energy. Every euro saved comes from when it buys, not how much.
That blended 27% hides three quite different regimes:
- Free-coast months (March 2023, October 2023, June 2024): the exterior temperature stays inside the comfort band, so no heating or cooling is called for at all. These aren't wins so much as sanity checks: they confirm the optimizer does nothing when nothing needs doing.
- Shoulder seasons (spring and autumn, plus the cooling months): wide price swings and ample comfort-band slack are the ideal conditions, and the optimizer saves anywhere from ~20% to nearly 80%, on bills ranging from a few euros to ~€30.
- Deep winter (December, January, February): the heater runs nearly flat-out just to keep pace with heat loss, leaving almost no slack to shift around. Savings fall to 14–22%. But these are also the months that dominate the absolute bill, so in euros they matter most.
There's a side effect worth naming, because it points beyond this one flat. Buying when the price is near zero means buying surplus: the solar overproduction and low-demand overnight hours the grid would otherwise have to spill or curtail. For a single household that's a footnote. Multiply it across a fleet and optimizers like this one begin to act as distributed flexibility, soaking up exactly the renewable energy the grid can't otherwise place.
One last detail: comfort is more than just "inside the band." Per-step temperature changes stay below 0.7°C / 5 min, so nothing ever lurches. Peak-to-peak swings within the band average about 1°C, with a 95th percentile near 2°C; only on a handful of days does the optimizer use the full 6°C, and only when prices make it genuinely worth it.
7. Conclusion
The path from "automate my heating" to a working system runs through four layers: a physical model of the building, a linear programme that exploits it, an API pipeline that feeds it forecasts, and an MPC loop that turns its output into action. The layers are stacked on purpose. The model is linear, which is what keeps the LP fast; the LP is fast, which is what keeps the MPC loop tractable; and a tractable MPC loop is what turns a weather forecast into a plug command every five minutes.
And that same linearity buys something a bigger model would not: you can read the answer. The schedule comes out line by line, every move with a reason attached: it pre-heats at 02:00 because that's when power is cheapest, and coasts through the 09:00 peak because the heat banked in the wall is enough to stay comfortable. A black-box controller gives you a number. This gives you a reason.
8. Future Work
- Coordinating multiple devices or households, using the same LP structure with a larger state space
- Handling price and weather uncertainty explicitly, instead of treating day-ahead forecasts as ground truth
- V2G energy management
- Identifying the apartment-specific RC parameters from real measurements rather than literature defaults
- A rate constraint on
to cap rare large swings; current per-step changes can reach ~0.7°C / 5 min - Roller shutters as a new control input: they modulate solar gain linearly, so the LP stays intact
9. References
[^pean2018]: Péan, T., Salom, J., & Costa-Castelló, R. (2018). Configurations of model predictive control to exploit energy flexibility in building thermal loads. In Proc. 57th IEEE Conference on Decision and Control (CDC), Miami, FL, USA, pp. 3177–3182. DOI: 10.1109/CDC.2018.8619095.