Hard data for heat pumps

A massive proportion of UK carbon emissions are from heating our homes^1 - so I decided to do the right thing and consider a heat pump to replace our domestic gas boiler. Heat pumps use electricity to take tiny amounts of heat from the outside air, and scavenge enough to actually heat your house. No more gas. And (if your electricity is sustainably sourced) then much reduced carbon emissions.

My energy supplier, Octopus, were on a mission to roll out heat pumps and had offered me a survey. Hurrah! But then they told me I couldn’t have one. Booo!

Most people might have left it there. Instead, I set about a year of data collecting and number crunching, so that I could do my own maths…

Why Octopus said “no”

After they made a very detailed survey of my house, measuring every room, their calculations said that I needed a 15kW capacity heat pump. This means that by their calculations, my house is losing 15kW of heat power to the outside world on a cold winter’s day.

If “15kW” doesn’t make sense to you yet, don’t worry. Just know that 15kW is a huge amount of heating, and too big for Octopus’s largest heat pump to cope with. So they said I couldn’t have one, and (incredibly promptly to their credit) refunded me my survey fee.

Why I knew their maths was amiss

I have our gas meter linked in to my home automation, so have a complete record of gas usage figures for every 30 seconds over the last 4 years. If I pick a really cold January day in the past, when the heating has been on full, here’s my gas usage:

Graph showing winter gas at 8kW

Other than the odd spike in the data, it shows in the worst case we put 8kW of heat into the house. But Octopus calculated 15kW of heat would be escaping the house. Without bandying around any laws of thermodynamics, it’s obvious that we can’t be creating energy from nothing. If 8 is what’s going in, then at most 8 is escaping to the outside.

But this was just a quick reckoning using one day of data. Admittedly a worst-case day, but still a very small sample. How could I use some hard data to properly prove this? How can I prove Octopus wrong? As Mark Watney would say in The Martian: “I’m gonna have to science the shizz out of this.”

Setting our hypotheses

There are at least two ways that Octopus could have over-calculated my heat loss. I need to do some science on each.

1. I’m running the house colder than they expect.

This is partly true, because currently we only heat the parts of the house that we’re using at that time. Like only heating bedrooms during the evening, and letting the overall temperature drop during the daytime if we’re out at work. Heat pumps don’t work so well with that approach because they can’t rapidly heat a room, so you need to have a higher baseline temperature.

I can answer this by simulating what would happen if I had higher temperatures in each room consistently, by building a physics model for it.

2. The house is better insulated than they expect.

This is definitely true, because (at time of writing) Octopus seems to use a simplification of grouping all houses into either:

  • built in 2001 onwards, or
  • anything before 2000

…and assume an average insulation based on which group you’re in. My house built in 1999 has an insulation rating that’s around 80% as good as the latest UK building regulations. But Octopus lump me in with the same calculation as for Victorian buildings that lose significantly more heat. And heat loss is your energy cost.

I had a thought, though.

I can determine a more accurate insulation level by measuring how fast each room heats up and cools down for an amount of heat input, and fitting a mathematical model to it.

STEM to the rescue

Picture of a smart heating thermostat on a wall

I’m a big advocate of STEM for getting people excited about the world around them - bringing different skills together to solve interesting problems. In our case:

  • Science. Mostly some basic physics, like the fact that heat moves from a hot place to a colder one. And this happens faster when the temperature difference is greater - so you lose more heat from the house when it’s colder outside. This is intuitively true, right? For your gas bill, cold days cost more.

  • Technology. We can use readily-available home automation tech to record the room temperatures.

  • Engineering. In this case, software engineering. We can write some computer programs to collect and process the data, and run simulations on them.

  • Maths. Maths is everywhere! We’ll use it for our simulations.

This is what we’re going to do:

Diagram showing approach to models

  1. Create a theoretical model of the house, with the room dimensions, assumed insulation values, radiator sizes, and some maths to work out the heating required.
  2. Create an empirical model of the house and its thermal losses, by recording real data on the room heating over several months.
  3. Combine the above to produce an accurate simulation of what amount of heat pump energy would heat the house.

Science: the theoretical physics model

I found an amazing open-source project called HeatLossJS^2 which implements a physics simulation for heat loss in a building. This is likely similar to the software Octopus used when they surveyed my house.

You enter lots of details about room sizes, radiators, building insulation, and then get answers about how much heat power (now we’re back to kW again) you’ll need. It’s very comprehensive:

HeatLossJS web application showing parameters and heat calculation

You can see though, this is very easy to get wrong. If you put in the wrong insulation ratings (called “U-values”), either by using an assumed Victorian-era figure (Octopus!) or by guessing from UK building regulations (me) then the numbers will be all over the place.

Here’s why it’s important:

Older house Modern house
Insulation value (lower is better) 2.4 0.2
Heat power needed (yearly average) 4 kW 0.36 kW
Yearly heating cost £2,400 £200

How can we make sure our parameters are right? Well, we can take measurements of the real heat performance of the house, and use those to “tune” the physics model until it matches reality. This is called developing an empirical model. Let’s do that.

Technology: the empirical model

To find out how heat is being gained and lost for each room in the house, we need to take some measurements. I have some smart home tech that’s useful here:

  • Gas smart-meter. I have a smart In-Home Display from Hildebrand^3 that sends a gas usage reading to my Home Assistant software every 30 seconds. This tells me the whole gas use for the house, but I need it calculated per-room. Which leads on to…
  • Radiator smart valves. I can monitor how much hot water is being let into each radiator, from 0% to 100%, because they have smart TRVs from Tado^4 which are integrated into Home Assistant. TRV positions are crude, but combined with the gas input they’re a good enough proxy for how the heat splits between rooms.
  • Room smart thermostats. Each room has wall-mounted thermostats, also Tado, which means that Home Assistant is recording the room temperatures. This is needed for telling how fast the rooms heat up. But also, less obviously, calculating the heat produced (i.e. gas used) by radiators needs the temperature difference between the radiator and the room’s current air temperature. This corrects the basic ΔT50 rating into real emitted heat power (you can look that up elsewhere).

So I recorded heating and temperature for every room, every five minutes, for a year. Along with the gas power every 30 seconds. That’s 9 rooms × 2 sensors × 288 readings per day × 365 days = nearly 2 million points of real data.

Engineering (software)

To bring this all together, I built a computer program called HeatPlan. It combines the theoretical and empirical models, tunes one to match the other, and then simulates whatever I ask it to. (The full details are in a section for the nerds at the end.)

And for fun, I can drive it all using AI - in my case, Claude. Important to stress that the AI isn’t doing the computation. It’s just a convenient way to run the program and interpret the results.

Back to the meter

A model is fine, but we need to tie it back to an absolute truth: the gas meter itself. From December 2025 to February 2026 it averaged about 87 kWh per day. A few of those are for hot water, but most is heating - and my old energy bills agreed.

HeatPlan fitted all the rooms’ heating and cooling together, anchored to that meter reading. Then it adjusted the U-values in the theoretical model until its losses matched the real ones:

Part of the house U-value (lower is better)
External walls 0.31
Loft (fixed) 0.16
Sloping roof (fixed) 0.35
Ground floor 0.53
Windows (double glazed) 2.79

Look at those walls. 0.31 is typical of Building Regulations from around 2005, and better than the 0.45 required when the house was built. A long way from the Victorian 2.4 in the table earlier. Hypothesis 2 is looking healthy.

Add it all up, and for every degree warmer it is inside than outside, the house leaks about 310-320 Watts. So on a frosty day, when it’s 20 degrees warmer indoors than out, that’s a bit over 6kW. Remember that number.

In plain English

I now have a model of my house which correctly predicts the heating that’s needed for each room, for a given outdoor temperature. So now I can ask it “what if?” questions.

First question: what if every room was kept properly warm, all the time? I used the standard temperatures that heat pump installers design to (21°C in living rooms, 18°C in bedrooms) and a chilly -3°C outside.

The answer is 6.4kW.

That’s hypothesis 1 dealt with. Even if we heat the whole house, it needs less than half of Octopus’s 15kW.

A second opinion

A year after the Octopus survey, I tried another company that’s got a reputation for decent heat pump surveying. This gave me a table of their calculated heat loss for every room in my house - which I could compare with my own.

And the headline? They said it was possible to heat my house with a 7kW heat pump. Which is what my model said too. Hurrah!

But we differed on how. They recommended no radiator changes at all, and instead just running the water hotter. That works, but as heat pumps are less efficient when making hotter water, it’s more expensive to run. They didn’t give me any hard numbers on how much more expensive that would be, though.

Which got me wondering. Could I do some modelling, and see what the effect would be if I upgraded certain radiators?

Leaky buckets

For asking lots of “what if” scenarios for real-world costs, I needed a “digital twin”: a pretend version of my house that I can experiment on without anybody getting cold.

In my HeatPlan software, I added this feature as a stock and flow simulation. If that’s new to you, picture a leaky bucket:

  • The stock is the water in the bucket. In our case, it’s the heat stored in each room: the air, walls, floors and furniture.
  • The flows are water poured in and water leaking out. Here that’s heat arriving from the radiators, and heat escaping through walls, windows and draughts.

The water level is the room temperature. Pour in more than leaks out, and it rises. Pour in less, and it falls.

My house is seven leaky buckets (the stairs and both landings count as one), which also leak into each other through the internal walls. And some buckets are bigger than others. A big room full of concrete takes ages to warm up, but holds on to its heat for ages too.

One hour at a time

Now we set time running. The simulator takes a year of real local weather^5 (November 2025 to October 2026) and steps forward through it one hour at a time. All 8,760 of them. In every hour it goes around this loop:

next hour
Outside temperature and room temperatures
Heat leaking from each room
Heat each room is asking for
Water temperature the neediest radiator needs
Heat delivered, within the heat pump's limit
Electricity used, and what it cost
New room temperatures

In words:

  1. What’s leaking? Using the tuned model, work out the heat each room is losing right now.
  2. What does each room want? Replace what’s leaking, plus a bit extra if it’s below its target temperature (spread over three hours, so we don’t ask for the impossible). Then knock off some free heat from people and appliances.
  3. How hot must the water be? For each room, find the water temperature at which its radiators can deliver that much. The highest answer wins.
  4. Can the heat pump manage it? If not, reduce the water temperature until it can.
  5. What did that cost? Work out the electricity based on that heat pump’s characteristics, and price it at that hour’s tariff.
  6. Where did the rooms end up? Update every temperature, and go round again.

Step 5 hides the crucial bit. A heat pump might give you 4 units of heat for every unit of electricity when making lukewarm water, but only 2.5 when making it hot. That ratio is called the “coefficient of performance” or COP. Cooler radiators mean cheaper heating.

Running this simulation for a year, here’s the whole year in one picture. Don’t worry about the detail: darker blue in the electricity panel means more power, and in the bottom panel green is efficient and red is less so.

A year of simulated electricity use, water temperature and efficiency, hour by hour

What temperature do we actually want?

Earlier I used the heat pump installer’s standard room temperatures, which follow UK MCS accreditation guidelines. They’re a sensible starting point, but they aren’t how we want to live. So from here on, my digital twin uses the temperatures I eventually settled on:

Room Installer standard What I settled on
Downstairs 21°C 21°C
Upstairs lounge 21°C 21°C
Study 21°C 20°C
Bedroom 18°C 20°C
Small bedroom 18°C 19°C
Spare room 18°C 20°C
Stairs 18°C 17°C

(How I settled on them is part of the story, so for now the stairs start out at 18°C.)

The hungriest room

There’s a catch. A house has one water temperature for all its radiators, and it has to be hot enough for the neediest room. Every other room just turns its valve down.

My neediest room was downstairs, where the existing radiators would need water averaging 59.8°C on a -3°C day. Running the year like that, with no radiator changes, came to £1,670 in electricity. That’s our starting line.

With heat pumps, it’s well known that more radiator area gets the heat out more easily. That means a lower water temperature, and therefore less cost.

So which radiators should I change? There are hundreds of possibilities. With a digital twin you can try them all:

Replace lots of them? My full radiator plan gave the lowest water temperature. But it needs new pipework, so would be very expensive. Rejected.

Upgrade a few small rooms? I tried bigger radiators in some of the smaller rooms. Running cost saving: nothing. Downstairs was still demanding hot water, so every radiator in the house still got it.

Fix the hungriest room? Adding just one new large radiator downstairs (about 2kW) dropped that room’s requirement from 59.8°C to 47.8°C. It was by far the biggest win from any radiator: well over £200 a year.

One radiator!

Whack-a-mole

But the house as a whole only dropped to 57.2°C. Because as soon as downstairs was happy, the stairs became the neediest room.

I could add a radiator on the stairs. Or… I could just have the stairs one degree cooler, at 17°C instead of 18°C. That took the house down to 52.1°C, for free.

A couple of thousand winters

One simulated year answers one question. The real fun starts when you can run another. And another.

Change one thing, replay the same weather, and compare the totals. By the time I’d finished, I’d run about two thousand simulated years. Each one takes HeatPlan only seconds.

By trying different combinations of radiator upgrades and room temperatures, I could see how everything was connected. I could stop asking “what does this setup cost?” and start asking “why does it cost that?”

Who’s in charge?

Remember that the neediest room sets the water temperature for everyone. Which room is that? It turns out the answer depends on the weather.

Which room sets the water temperature at each outside temperature, and how close the others are to taking over

The top graph shows how hot the water needs to be (the average temperature in the radiators), coloured by whichever room is in charge. In the middle graph, each line shows how many degrees warmer a room could be before it takes charge. Any line below zero is the current boss.

Three rooms take turns:

  • The stairs when it’s freezing, up to about 0°C outside.
  • The spare room from about 1°C to 3°C.
  • Downstairs from 4°C upwards.

Now look at the bottom graph. Most of my heat for the year is used when it’s around 6°C outside. So the room in charge on the coldest day isn’t the one in charge for most of the bill. Downstairs is.

The price of a degree

Next, the question every household argues about: what does one more degree cost?

I took one room at a time, moved its target from three degrees cooler to four degrees warmer, and simulated a full year at every step. That’s about fifty years for one graph.

Change in yearly cost as each room is set cooler or warmer, one room at a time

(A “K” on the graph is simply one degree of difference.)

The solid lines show what the simulation says it costs. The dashed lines show what you’d expect if you only paid for the extra heat. Where a solid line bends sharply upwards, that room has taken charge, and now the whole house is paying to run hotter.

Here’s the price of the first extra degree in each room, per year (give or take a pound of rounding):

Room One degree warmer …of which extra heat …of which lost efficiency
Downstairs £134 £60 £74
Spare room £60 £10 £50
Stairs £34 £20 £13
Bedroom £18 £19 -£1
Upstairs lounge £15 £20 -£5
Small bedroom £7 £9 -£2
Study £7 £8 -£1

Look at the spare room. Only £10 of its £60 is heat for the spare room. The rest is the price of making every radiator’s water hotter.

Whereas in the study, turn it up. It barely matters.

(Yes, some of those efficiency figures are negative. Nudge up a room that isn’t in charge, and the house as a whole gets very slightly more efficient.)

It works in reverse too, but not equally. A degree off downstairs saves about £100 a year. Turning the spare room down by three degrees saves barely £25.

Where the money goes

Last one, for the keen. This splits the cost of that extra degree by the weather outside at the time.

The yearly cost of one extra degree in each room, split by outside temperature into extra heat and lost efficiency

The grey bars are the extra heat. The coloured bars are the efficiency penalty. And the penalty only really piles up where a room is in charge, or close to it (the shaded areas). The “who’s in charge” graph and the bill agree with each other.

The warmer-is-cheaper surprise

My favourite result was in the bedrooms. Had I left two of them at the installer’s 18°C, the house would have needed water at 53.7°C. Making them warmer is part of how it gets down to 52.1°C, for about £2 a year. At 18°C they’d been quietly drawing heat through the internal walls from the stairs and spare room, which were the very rooms setting the water temperature. (This one relies on my internal wall figures, which I haven’t tuned against real data, so I hold it a bit more loosely.)

You wouldn’t find that one room at a time on the back of an envelope. You need all the buckets leaking into each other.

Should we turn it down at night?

Everyone knows you save money by turning the heating down when you don’t need it. So I tested it.

Our electricity tariff is 6.6p per kWh overnight and 34.95p in the day. I tried turning rooms down overnight or during the day, and I also tried the opposite: turning the whole house up by one degree between 11:30pm and 5:30am.

The boost won. It stores cheap heat in the fabric of the house. The heat pump is actually a bit less efficient, because it’s working harder overnight, but the electricity is so much cheaper that it doesn’t matter: £1,401 a year became £1,161.

And turning it down? With a quick three-hour warm-up afterwards, my biggest setbacks pushed the bill up to nearly £2,000, because the heat pump has to run very hot to recover. Even with a gentle 24-hour recovery they didn’t beat the boost.

A bigger boost of two degrees saved only another £37, so I stuck with one.

So which heat pump?

Putting it all together. Every row uses my settled room temperatures (with the stairs at 18°C until the third row):

Step (each adds to the one above) Average radiator water temperature at -3°C Cost per year
Heat pump with today’s radiators 59.8°C £1,670
One tall radiator downstairs 57.2°C £1,438
Stairs at 17°C 52.1°C £1,401
One degree overnight boost 52.1°C £1,161

That final design means the heat pump sends out water at about 55°C on the coldest design day. (Why not 52.1? Because that’s the average water temperature needed, so it has to start off at the heat pump a little bit warmer than that.)

And how much heat does the house need? Still about 6.4kW at -3°C with my settled temperatures (the warmer bedrooms and the cooler stairs and study nearly cancel out). Take off the free heat from people and appliances, and the heat pump has to supply about 6kW.

So why not a 6kW heat pump, or the second surveyor’s 7kW? Because the number on the box isn’t what you get. The heat pump I’m looking at is sold as “8kW”, but at these water temperatures it delivers just under 7kW. That’s the headroom I want.

What if it gets colder? At -5°C it only just keeps up, with next to nothing to spare. But that’s rare here: on average about 3 hours a year. I know this from my accurate historic data. (We also have 2kW of electric underfloor heating that we could use if there’s extreme cold.)

So, an 8kW heat pump. Not 15.

For the tech nerds

(Everyone else: you can start reading again at the next heading.)

Here’s how my HeatPlan software fits together:

Diagram of HeatPlan: measurements and Home Assistant readings feed a heat transfer model and a tuner; the tuned model goes into a simulator, which I drive through an API, an MCP server and Claude

  • The model is my own rebuild of HeatLossJS in .NET. It knows which rooms share walls, floors and ceilings, so heat can move between them.
  • The tuner is a separate service. It fits all the rooms to a winter of readings, then nudges the insulation values (U-values) and air change rates until the physics agrees.
  • The simulator bundles up the tuned model, so I can change one thing at a time and replay the weather.
  • The API and MCP server put the simulator within Claude’s reach. MCP (Model Context Protocol) is a standard way of giving an AI tools to use.

That last part became my method for trying things out. I’d ask a question in plain English, Claude would set up the runs, HeatPlan would do the sums, and then I’d ask the next question.

Being fair to Octopus

I admire the way Octopus go about things. They lead the field in being innovative - I can attest first-hand having attended their tech summit last year. They have a real desire to help us reduce carbon emissions. They’ve got nice open APIs so nerds like me can connect Home Assistant to them.

And when it comes to heat pumps, they’re doing it at scale. I reckon this means following an 80/20 rule: focus on the 80% that are easy to do, and get them done quickly. For the 20% where houses are a bit awkward - mine is one of them - it’s not worth sacrificing the speed of the whole rollout. A quick, cautious rule of thumb makes sense when you’ve got thousands of homes to get through.

I’ve only got one home to get through. So I could afford to science the shizz out of it.

Fancy a survey of your own?

I’d recommend both of the companies in this story. They each have their advantages.

Octopus Energy are rolling out heat pumps at scale. If your house is one of the straightforward ones, they’re a great place to start. And when mine wasn’t, they refunded my survey fee incredibly promptly. If you switch to Octopus, use my referral link and we’ll both get £50.

Heat Geek is how I booked my second survey, with one of their installers. I got a room-by-room table of heat loss, and a way to heat my slightly awkward house with a 7kW heat pump. If you’d like to try them, use my referral code ODI4E0MA to get £100 off your survey. (The first letter is an “oh”, and the sixth is a “zero”.) In the interests of fairness: I get £100 too, so we both win.

What next?

This is, for now, all just a prediction. I’ll do another post after we’ve had a year of the heat pump running - and compare its actual performance to the theory.

Collections, Classes, Clocks

Here’s a talk I did at a local tech meet-up event. This blog post is, unashamedly, NET 8 for the Nerds.

I was meant to be speaking about the new Microsoft .NET 8 release, but decided to be rebellious and talk lots about Python instead. Partly, my excuse was that tech meet-ups are more fun if there are different technologies.

But, struggling for a better excuse, I decided to talk about new language features that are moving C# closer towards the convenience of Python. Read on to be unconvinced.

0. Tech we’ll be using

  • .NET 8 and C# 12: new language and runtime features
  • Python: hugely convenient, can C# learn from it?
  • Jupyter Notebooks: markdown and code OK the talk used Jupyter but I can’t do that in a blog post

I’ve grouped the talk into 3 parts: Collections, Classes, Clocks.

1. Collections

Collections are the mainstay of most applications. After all, what’s ever been achieved by processing a single datapoint on its own?

Everyone has their favourite. IEnumerable<T> or IList<T> or just plain arrays. They’re a bit faffy to initialise though, aren’t they? It all depends on the method you’re calling, and what type that expects:

1
2
3
4
ProcessData(new int[] { 1, 2, 3 }); // If you're lucky.
ProcessData(new int[] { 1, 2, 3 }.ToList()); // If you're unlucky.
ProcessData(Enumerable.Empty<int>()); // Or even if you even just want to do nothing.
ProcessData(Array.Empty<int>()); // ...unless it needs an Array, in which case it's this.

This is even more of a pain if you change the method signature to a more derived type. Even your empty array calls don’t compile any more!

Before we start, let’s talk about Python!

Python rightly has a reputation for being quick to develop code. The syntax is really simple and doesn’t have any of that unnecessary faff:

1
ProcessData([1,2,3])

Can we get close to Python in .NET 8 with C# 12?

1
2
3
4
5
6
// Let's try...
ProcessData([1,2,3]);

// Or even...
int[] others = [9,8];
ProcessData([1, 2, ..others, 3]);

So yes we can! If you compare the Python example to that first C# 12 block above, you’ll see they’re literally identical.

(in fact, when I gave this talk live, I used a Jupyter notebook and ran that “Python” code sample inside a C# .NET interpreter block, because the syntax was identical. Except I hid a semicolon on the next line. I know right? What a trickster!)

So what’s going on?

A new language feature: collection expressions^1. Lots of magic under the hood. Some neat features:

  • If the target type changes (e.g. a method used to take IEnumerable but now takes Array) the compiler finds the most appropriate initialiser.
  • All sorts of performance optimisations internally; better than most people would hand-roll. Example^2

2. Classes

Let’s create a class that processes some data and returns a calculated result.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using MathNet.Numerics.Statistics;

public class Stats
{
public Stats(IEnumerable<double> data)
{
_data = data;
}

private readonly IEnumerable<double> _data;

public (double Average, double Deviation) Calculate()
{
return (_data.Average(), _data.StandardDeviation());
}
}


var result = new Stats([1,2,3]).Calculate();

Console.WriteLine($"{result.Average}, {result.Deviation}");

You’ll see that this takes some data, does two calculations on it (average and stdev) and returns the result.

(NB I have taken liberties here and enumerated the same IEnumerable more than once. This is usually a Bad Thing (TM) and I’ve done it for artistic license. Don’t do it in your production systems!)

Can we learn much from Python?

1
2
3
4
5
6
7
8
9
10
import statistics

class Stats:
def __init__(self, data):
self._data = data

def calculate(self):
return (statistics.mean(self._data), statistics.stdev(self._data))

avg, dev = Stats([1, 2, 3]).calculate()

So yes, Python has simplified this in a few ways:

  • Eliminated the explicit declaration of the private readonly variable for _data
  • Enables de-structuring the result directly into two variables

Let’s see what we can do with C# 12 and .NET 8

1
2
3
4
5
6
7
8
9
10
using MathNet.Numerics.Statistics;

public class Stats(IEnumerable<double> data)
{
public (double Average, double Deviation) Calculate() => (data.Average(), data.StandardDeviation());
}

var (avg, dev) = new Stats([1,2,3]).Calculate();

Console.WriteLine($"{avg}, {dev}");

Hang on. That’s shorter than the Python equivalent!

What’s going on?

Some magic syntax coming from the new C# 12 specification. We used a few recent-ish features from prior C# specifications too:

  • C# 12: Primary Constructors^3. A bit like we see in the recent record class definitions we gained in C# 10. (although record classes expose the field publicly, whereas classes with primary constructors don’t.)
  • C# 10: Destructuring of objects into variables (since C# 7 with some restrictions)
  • C# 6: Expression-bodied members

3. Clocks

To be fair I’ve dropped the Python rebellion pretence now, but I do want to talk about the most significant new feature to appear in .NET for many a long year.

Let’s talk time.

So you’re not afraid of working with time?

Time is one of the most difficult concepts in programming. Need persuading? If you live somewhere with a summertime timezone offset, just start with that. Can you think of any unsafe assumptions people typically make?

TL;DR: If you’re not Unit Testing your time calcs, your code isn’t production-ready.

What happens when we try to Unit Test our time calculations, usually? Let’s create a class that does some basic time calcs.

1
2
3
4
5
public class UntestableTimeCode()
{
private readonly DateTimeOffset _createdOn = DateTimeOffset.Now.Date;
public bool IsItTomorrowYet() => DateTimeOffset.Now.Date > _createdOn.Date;
}

Completely fictional obviously, but this code would store today’s date when you initialise it, and then you could repeatedly ask it “Is it tomorrow yet”. Until it is.

The clue’s in the name here: it’s not really testable. But if we really really had to test that class, could we do it in a hacky creative way?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using Xunit;

public class TimeTest1
{
[Fact]
public async Task TestIf_IsItTomorrowYet_ReturnsTrueTomorrow()
{
var untestable = new UntestableTimeCode();

// Umm...?
await Task.Delay(TimeSpan.FromHours(24));

Assert.True(untestable.IsItTomorrowYet());
}
}

…yes. But you can see the problem here. Your unit test would take 24 hours to run. FAIL.

.NET 8 secret sauce

So. We need some way to modify the system clock. Or rather, de-couple our code from the system clock, and use an abstraction that we can control in a test.

1
2
3
4
5
6
7
8
public class TestableTimeCode(TimeProvider timeProvider)
{
private readonly DateTimeOffset _createdOn = timeProvider.GetUtcNow().Date;
public bool IsItTomorrowYet() => timeProvider.GetUtcNow().Date > _createdOn.Date;
}

// In normal use, we pass the current System time provider into the constructor:
var myTimeCode = new TestableTimeCode(TimeProvider.System);

OK, so we have now de-coupled from the System clock by adding a dependency. How does this make Unit Tests possible?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using Microsoft.Extensions.Time.Testing;

public class TimeTest2
{
[Fact]
public void TestIf_IsItTomorrowYet_ReturnsTrueTomorrow()
{
var fakeTime = new FakeTimeProvider(startDateTime: DateTimeOffset.UtcNow.Date);
var untestable = new TestableTimeCode(fakeTime);

// await Task.Delay(TimeSpan.FromHours(24)); --not any more!
fakeTime.Advance(TimeSpan.FromHours(24));

Assert.True(untestable.IsItTomorrowYet());
}
}

Amazing! We can artificially advance the system clock to suit our whim.

TimeProvider is our new best friend!

Remember, take a TimeProvider dependency into all your time-based code.

You can then use FakeTimeProvider in lots of powerful ways:

  • Advance time immediately (like above)
  • Timezone changes e.g. summertime
  • Other countries’ timezones

Horizon

Why should you care?

Post Office Horizon. Another failed £1bn government IT project. So what? OK it’s a waste of money, but plus ça change?

Here’s why.

Because this failure is associated with:

  • 4,000 people falsely accused of fraud or mismanagement
  • 700 people prosecuted
  • 200 people sent to prison
  • 3 people’s deaths

I use the word “people” 4 times, deliberately. Because this is about people. The people affected; and the people responsible.

What’s Horizon?

Horizon is a £1bn IT system enabling UK Government departments to make social security payments. Development began in 1996 and lasted 20 years.

It was designed for the UK Government benefits agency and the state-owned Post Office. Post Offices are run in a franchise-like way by “Sub Postmasters” (SPMs). These are people who ran their Post Offices quietly and successfully for many years prior to Horizon.

Problems

When Horizon was rolled out to Sub Postmasters they began noticing financial errors. Money was going missing.

Important context: Horizon had already “failure[d] to meet the first milestone [which] cannot but cause concern in a project with such a chequered history”. This is a quote from the Parliamentary Select Committee report^1 in 1999. The same report tells us the UK benefits agency had pulled out of the project by 1999, leaving Post Office as sole client (and primary financier) of Horizon.

So Horizon as a project was already on the back foot, reputationally and financially, with Post Office now the de-facto responsible party. Rather than investigating their new IT system for financial errors, Post Office robustly turned the problem back on the Sub Postmasters; requiring them to make-good the shortfalls without opportunity for dispute (Hamilton v Post Office, judgment, 2021)^2.

If SPMs didn’t repay the shortfalls, Post Office auditors brought prosecutions against them. They were wrongfully pressured (Fraser J, Judgment No 3)^3 into admitting charges of mismanagement, under the threat that they would otherwise risk prison if they denied wrongdoing.

Many lost their homes due to the incurred debt. Others went to prison. Some died.

What can you do about this?

Help share this knowledge in some small way. Play your part in improving the collective knowledge of society, to prevent a similar disaster happening again.

Collective knowledge works; it’s how society is beginning to scrutinise institutions on climate action. Knowledge leads to well-informed scrutiny.

Read on, and I’ll describe 5 failures. I’ll separate out the technical detail so you can skip over those bits if they’re not of interest. The rest is a human story.

Failure #1: Transparency and disclosure

When SPMs called the Horizon helpline to report errors, Fujitsu staff recorded errors in a “Known Error Log”. This would have been useful as evidence in Court. But these errors were not widely disclosed by Post Office during any of its legal proceedings against SPMs. They maintained that Horizon was robust, without providing evidence.

The next failure was during counter claims by SPMs against Post Office. The Government and Members of Parliament instigated independent inquiries; but Post Office aggressively withheld evidence^9 in an attempt to protect their trusted brand from reputational damage. Prosecutions continued.

In all these cases transparency would have enabled the focus to be put back onto Horizon’s bugs, and innocent people kept out of prison.

Failure #2: Acquisition due-diligence

The media has reported Fujitsu as the developer of Horizon, and much of the public anger is directed at them.

Fujitsu is unimaginably huge. Annually they generate net income of $1.2bn, from $22bn revenue. Most of the public hadn’t heard of them - until now, when their first impression of Fujitsu is as the creator of a £1bn failed IT system that has ruined thousands of lives. It was even dramatised as a TV series recently, watched by 20% of the UK population^13 who all now directly link Fujitsu with this tragedy.

But, Fujitsu are subject to reputational and financial penalty for an IT system they didn’t directly create.

Horizon was actually developed by ICL, which originated from the ashes of the 1960s British computer industry. Fujitsu wholly acquired ICL in 1998, by which time Horizon was already a failing project and subject to Parliamentary review.

Fujitsu didn’t adequately assess the Horizon IT project before completing the ICL acquisition. This due diligence failure is presenting itself now, 25 years later, as a possible $1bn financial liability and incalculable reputational damage^10 ^11 ^12.

There’s an additional irony here, post-acquisition, when Horizon continued as an ICL branded project. There’s suggestion that the emerging poor reputation of Horizon had damaged the ICL brand, contributing to Fujitsu ending the ICL brand name and Horizon becoming a Fujitsu-branded product.

Fujitsu - and its directors personally - have mortgaged their whole public reputation on the failing of ICL.

Failure #3: Software DevOps

Software DevOps is an industry term that includes how software is rolled out to the users, and how it’s supported and maintained by technical staff.

An important principle of DevOps is that technical staff should never have unrestricted access to the data in a live system. But in Horizon it was routine^3 for support staff to “fix” data errors in SPM’s accounts, without any proper controls. And worse, without proper logs of what data they’d changed.

Good DevOps practices are also closely aligned with how a system is tested. There was very little evidence in the Court expert witness statements of anything that a modern software developer would consider “good”. For the minimal system errors that Post Office reported, there was no focus on how the fixes were formally tested.

Another principle is “observability and monitoring” of a system: it should continuously and thoroughly log data about how well it’s functioning. Court proceedings have subsequently showed there wasn’t enough logging for fault to be attributed correctly.

Technical thoughts

  • It’s dangerous, directly editing data in a production system. Especially the methods that Horizon staff were using, which was to use SQL CLI commands; bypassing many of the checks and balances that written into the software. Privileged user access by support staff was widespread used as a regular method of solving application issues, and without logging their actions. There was a “Transaction Correction Tool” script but its usage was not logged either.^6

  • Errors in data are almost always due to a software problem further upstream. By simply fixing the data, it takes the focus away from helping to identify the root-cause. Even worse, it can destroy key information that would help the bug to be properly investigated.

  • Testing is vital. Horizon was in development for over a decade, with many changes to add new features and fix bugs. Whenever part of a system is modified, there needs to be “regression testing” of the parts of the system that sit around that. This might be a combination of manual test plans; synthetic test data; automated test scripts… None of this was mentioned in the Court proceedings that I’ve seen.

Failure #4: Software and Integration

The name “Horizon” is an umbrella covering several different systems, all developed by different teams. The Horizon system is made up of:

  • Databases, for storing the data
  • Software, for manipulating the data
  • Integrations, which connect the various software and database components together.

Much of the Court evidence given by the Post Office expert witness^8 was on the robustness and reliability of just the database system within Horizon. And while his technical description of database systems is true, I’d suggest it’s not useful. It focused attention away from where most software bugs occur: in the software. Not the database.

The expert witness didn’t offer expertise on the challenges (and scope for error) arising from how the systems are integrated, or from the software algorithms that sit above the database.

Technical thoughts

  • The expert witness talked at length about the inherent safety of double-entry bookkeeping in accountancy, and how this forms the basis of Horizon’s claimed robustness. He went into great detail explaining how relational databases work, including referential integrity and transaction blocks, and that this is proof of robustness. It is not. The wider system is where the complexity arises.

  • One of the proven errors in the pivotal Bates v Post Office was a bug when the same SPM user logged on to two computer terminals at the same time. This is a classic “integration testing” failure. The software was never built to cope with the same user logging on twice, because (in theory) it wasn’t possible. The complexity of the two systems together - the computer terminal and the Horizon system - caused the error.

Failure #5: Legal

The early prosecutions of SPMs relied on a (then legally valid) assumption that:

computer[s] operate correctly unless there is explicit evidence to the contrary.
Law Commission Presumption, 1997

Put another way, the SPMs had no defence because Horizon was legally presumed to be functioning correctly. SPMs could claim there was a bug, but without any good error logging or relevant testing (see Failure #3) there was literally no evidence to the contrary. They were found guilty and prosecuted.

The legal system’s presumption of computer systems was simplistic, and not aligned with the reality of large-scale software systems. Thankfully, this presumption has now been recognised by a Law Commission article^4 as not “reflect[ing] the reality of general software-based system behaviour.”

Citing the article, Parliamentary Justice Committee evidence^5 has recommended mandatory training for all lawyers on the complexities of software development.

Much of that improved legal thinking comes from a landmark legal case; one where SPMs received justice for the first time. This is “Bates v Post Office”^3 presided over by Justice Fraser, examining 29 bugs^7 that had been involved in falsely prosecuting SPMs. Justice Fraser’s analysis is highly astute. One of his findings states it was extremely difficult for the experts to make categorical negative statements of the form “X or Y never happened”; and even where there is some evidence then it would be too complex to disentangle. Perhaps his most damning assessment is:

This approach by the Post Office has amounted, in reality, to bare assertions and denials that ignore what has actually occurred, at least so far as the witnesses called before me in the Horizon Issues trial are concerned. It amounts to the 21st century equivalent of maintaining that the earth is flat.
Bates v Post Office, judgment No 6, paragraph 929^6

I recommend you read a few pages of Justice Fraser’s findings. It’s a rare uplifting part of the Horizon story.

Technical thoughts

  • It’s almost incomprehensible that the expert witness for the Post Office portrayed software as inherently robust. Any software professional will tell you this is never the case. You need to write test cases to test the code for bugs. Anything not covered by a well-defined test case cannot be claimed as bug-free or robust.

  • Modern software development places huge emphasis on testing and monitoring. When errors occur, the system should have logged enough data that the software team can reproduce the bug by testing for it in a controlled environment. Then they modify the software to fix it, and then re-test to validate the bug goes away. Horizon didn’t follow this.

  • There was insufficient system logging to determine cause of errors, let alone to determine it was the fault of SPMs. Technical support staff created standard code scripts and tooling for fixing errors that happened often, but even these tools didn’t log that they had been used.

  • We think of making software “observable and monitorable” because, as software professionals, it makes our lives easier. We can catch problems early; and we can find bugs more easily. But since reading about Horizon, I realise that if a software vendor ends up in Court, they need to have evidence (e.g. system logs) to prove or disprove culpability.

Ivory Towers

I need to put my hand up and admit it’s easy to criticise.

In my corner of the software industry, I’m incredibly fortunate to work directly with client organisations. I feel the problems first-hand, because I’m working almost as an extension of the client organisation. This makes it easier to see the organisation as people and to become invested in any problems they’re experiencing.

But typical of a large system, Horizon’s software professionals and technical support were far removed from the client at a human level. This is why it’s vital to follow good software development practices, and to educate software professionals so they understand the benefits.

I’m also lucky that I get the opportunity to learn and apply the latest thinking in software development practices. I’m not talking about new technologies necessarily (although I’m lucky I get to do that too). Rather, I’m talking about the human practices around how to successfully develop software. With a system like Horizon, which has a decades-long gestation, development practices are often stuck in the past. It’s harder to keep evolving the culture.

Good software development is as equally about human culture and practices, as it is about technology.

Maybe even more so.

Timeline

To round this off, I thought I’d try illustrating the sheer size of the Horizon project by showing how long it took to build… And how long Sub Postmasters waited for justice.

GovernmentBenefits_AgencyPost_OfficeICLFujitsuProcurement (1995)Trial roll-out (1995)Bugs reported (1995)Fujitsu acquire ICL (1998)National roll-out (1999)Widespread prosecutions (1999-)Cancelled (1999)Parliamentary review (1999)Widespread prosecutions of SPMs (1999)ICL rebrand as Fujitsu (2001)Full roll-out (2001)Media reports SPM mistreatment (2009)Parliamentary orders a review (2012)Review cancelled before publication (2015)SPMs bring legal action (2017)

Further reading

Judiciary reports from Bates v Post Office: https://www.judiciary.uk/judgments/bates-others-v-post-office/

Why planes don't crash

A380 aircraft at airport

Best start with two caveats.

First, yes, planes sometimes do crash. And second, there’s lots of reasons why they mostly don’t.

I recently discovered a simple human design factor that contributes to aircraft safety—and realised I could borrow the same idea for the user interface design in my home automation.

What are my odds?

Racing odds

It’s often said that commercial air travel is one of the safest things you can do; but it’s so incredibly safe that the odds are hard to comprehend. If you took a commercial jet airliner flight in 2022, your chance of a fatal crash was 1 in 5.8 million^1.

It’s 1 in 5.8 million because only 1 jet crashed from a total of 5.8 million flights. There’s no such thing as “half a jet,” so it’s pretty hard to get much lower than that. Other than absolutely zero. (Mathematicians: you can start reading again now.)

People problems

Aircraft safety isn’t just from good engineering or technology. The biggest risk is the people operating the aircraft, and that’s why commercial flying is so safe: iteratively honing the human processes to the point where they’re near-infallible.

Added to this, very few airliner crashes are due to a single factor. Usually two things have to go wrong at the same time^2. Perhaps a smaller initial issue distracts the pilot from a secondary one. The distraction means that their situational awareness becomes reduced.

How do you improve situational awareness? Let’s think about the simplest electronic device in an aircraft: plain old switches.

Switching mindset

Switches are really simple: something’s either On or Not. What’s to go wrong?

Big switch

Obviously the complexity comes from the quantity of switches. It’s easy to spot that one switch is “On” where it should be “Off”. If there are hundreds, then less so.

This challenge was addressed by the European aerospace manufacturer, Airbus. They have pioneered a principle to make hundreds of switches simpler for a pilot to understand. It’s called “Dark Cockpit,” and we can demonstrate it here.

First, let’s look at some cockpit switches from the other big name in airliner manufacturer—the one everyone’s heard of. I’ve deliberately set some of these switches incorrectly. Can you spot the mistake? Well no, probably not…

Boeing 747 cockpit

Of course a pilot will spot the mistake. But the point is, if they’re already distracted by another failure, then their situational awareness is reduced and they might not spot this.

Now let’s look at a similar invalid switch configuration, but this time in the Airbus cockpit.

Airbus A320neo cockpit

Much more easily noticed: the left “Tank Pumps” are set to OFF, which has also caused “GEN 1” and “PACK 1” to go into “FAULT” because, well, the engine has stopped. (Pilots: you can start reading again now.)

Even if you know nothing about flying this aircraft, you could have a good guess what’s not right. The “Dark Cockpit” principle^3 means that only the abnormal switches are lit up, and anything that’s in its nominal position is “dark.“

Problem #2 averted. Airbus pilot now has more situational awareness available for problem #1, whatever that was.

Here are these two opposite approaches shown together, with the relevant incorrect switch settings highlighted on the Boeing and then the Airbus. See how much easier the “Dark Cockpit” principle is.

A320 vs Boeing 747 cockpit

What’s the link to Home Automation?

I hope this has persuaded you really simple changes, like changing a switch, can contribute enormously to usability. We can take those principles and apply them more widely.

In my case I’ve applied the Airbus principles to my home automation control screens. This is because it’s all getting a bit too complicated for people to run the house… It’s OK for me—usually—because I built it. But it’s becoming unintelligible for anyone else.

So now, I’ve built a control panel as per Dark Cockpit:

Home Assistant control panel

The Dark Cockpit principle means everything is always dark when it’s “normal”. Only things that require your attention are lit-up, and they follow the same design principles as Airbus too:

Yellow is where you’ve pushed a switch, but “might be of concern, so be aware of it.“

Green hints you might want to push that switch, but it’s not essential.

Blue says you’ve pushed a switch, and it will stay activated for a short period until it resets.

Dark is where it’s nominal. E.g. above, the “Spare power” mode is ON, which is the default and therefore is dark.

If I was to push the “Spare power” switch, I’d be disabling spare power (potentially a bad thing) and the button lights up yellow to warn me:

Home Assistant control panel

I’m definitely going to consider this approach when I’m developing software user interfaces, too. Airliner-spec buttons for everyone!

dark
sans