Overview
Week 12 built a twin that follows the library through its data. A twin is also a model that can run ahead of its building and run alternatives that nobody has tried yet. This week asks the twins of the campus two kinds of questions. What-if questions compare decisions, such as two heating schedules, before any of them is applied. Prognostic questions ask when a part will reach the end of its life, so that maintenance can be planned in time [1].
flowchart LR A["What-if analysis"] --> B["Many possible weeks"] B --> C["Remaining useful life"] C --> D["Uncertainty and the order"] D --> S["The campus microgrid, stage 13"] S --> FT["In the field: The capacity test"] FT --> H["Learning machines"]
Every method on this page is also written as Python code in the Colab notebook of the week. Its code is divided into numbered sections. Each orange box on this page names the section whose code carries out what the text above the box explains. The box says what to run and what to look at in that section, and its button opens the Colab notebook at that place. The virtual laboratories, the practice parts and the self-assessment of the week are in the interactive lab. Each blue box opens one part of the interactive lab. The part ends with a link back to its box on this page, and the Colab notebook is always opened from the orange boxes here.
Python step 13: Scenarios and Monte Carlo
Python code in the Colab notebook, right after Section 0 (setup). Open the Colab notebook and run this step cell by cell: It consists of short pieces of Python code with their explanations, a quick check and three exercises. Topics: Loops over scenarios · Random numbers with NumPy · Probabilities from many random runs.
The step runs one model for a few named scenarios with a loop over a dictionary. It then draws random numbers with the generator of NumPy and turns many random runs into a probability [2]. This is the Monte Carlo method of the week. Students who have never programmed start with the start-here notebook of the course.
Weeks 1 to 11 modelled, measured, controlled, scheduled, connected, optimised, forecast and defended the campus. Week 12 calibrated a twin of the library that follows the building and notices when it changes.
This week asks that twin and a new twin of the battery questions about decisions and about the future.

What-if analysis with the twin
The library is too cold when it opens. Its thermostat holds 17 °C at night and heats to 21 °C from 6:00 on weekdays and from 8:00 at weekends. In the observed week of February, the library was still below 20 °C for 11 of its opening hours, all of them in the morning. The facility manager asks two questions: Which schedule keeps the library warm at opening, and what does it cost?
A what-if analysis answers such questions with the twin instead of the building. The calibrated twin of Week 12 runs in a closed loop with a model of the thermostat. The thermostat switches the 60 kW of the heating on below its setpoint minus 0.5 K and off above its setpoint plus 0.5 K. Two numbers judge a schedule. The heating energy of the week counts the cost. The comfort deficit counts the degrees below 20 °C during the opening hours, multiplied by their duration:
Before the twin answers what-if questions, it must reproduce what happened. With the current schedule, the twin needs 5730 kWh in the observed week, against the 5693 kWh of the heat meter. Its comfort deficit is 8.79 K h, against 9.85 K h of the library. The twin thus also knows that the library is cold in the morning.
An earlier start helps only a little: Starting at 4:00 still leaves 4.13 K h. A warmer night of 19 °C almost removes the deficit, but it needs 6075 kWh, 6.0 percent more. A third option is the optimal start. Each morning the controller asks the twin how long the heating needs to reach 20.5 °C with full power. It starts the heating when this time reaches the time left before opening. The formula is the warm-up time of Week 2:
A worked example. At 3:00 the twin stands at 17.20 °C with 1.00 °C outside. With full power the library would settle at \(T_{ss} = 1.00 + 60 \times 0.44 = 27.40\) °C, and \(R\,C = 0.44 \times 30.41 = 13.38\) h. Reaching 20.5 °C takes \(t_{need} \)\({}= 13.38 \ln(10.20/6.90) \)\({}= 13.38 \times 0.391 \)\({}= 5.23\) h. The library opens in 5 hours, less than the 5.23 hours needed, so the heating must start at once.
With the optimal start, the night setpoint no longer costs comfort. A deep setback of 13 °C with the optimal start keeps the library above 20 °C at every opening hour of the observed week and needs 5760 kWh. That is only 0.5 percent more than the cold schedule of today.
Animation. The heating schedule. Choose the setpoint at night and the start of the heating, or switch on the optimal start. The twin of the library then runs over Monday and Tuesday of the observed week. The readouts give the energy and the comfort of the whole week next to the current schedule.

Check your understanding. Why does the twin first run the current schedule over the observed week?
Interactive lab, Part A. The plant room in 3D: The plate heat exchanger of the district heating, the supply and return pipes, the circulation pump, the heat meter and the heating controller. Try schedules on the observed week and on 300 possible weeks. The results can be copied into the Colab notebook.
Python code in the Colab notebook, Section 1. Open Section 1 of the Colab notebook and run it. The function schedule_twin runs the twin in a closed loop with the thermostat and returns the energy and the comfort deficit of the week. The code compares the current schedule with the library and prints the table of 25 schedules. It then draws the observed week with two of them.
- The twin says that 13 °C at night with the optimal start keeps the library warm. What would you check in the library before switching the real controller?
- Who should decide the schedule: The facility manager, the library or the twin?
Uncertainty: Many possible weeks
The observed week is one week out of many. Next week may be colder, cloudier or fuller, and a schedule that works in one week may fail in another. The Monte Carlo method runs the model over many random inputs and counts the outcomes [3]. Each possible week here draws a daily level of the outdoor temperature, a cloud factor and a factor of the visitors:
Here \(\varepsilon\) are standard normal random numbers, so neighbouring days resemble each other. The estimated probability \(\hat{p}\) of a comfort deficit above 1 K h is a share of the \(n\) weeks. Its standard error \(\sigma_{\hat{p}}\) shrinks with the square root of \(n\).
A worked example. With 13 °C at night and the optimal start, 19 of 300 possible weeks have a comfort deficit above 1 K h. The estimate is \(\hat{p} = 19/300 = 0.063\), and \(\sigma_{\hat{p}} \)\({}= \sqrt{0.063 \times 0.937 / 300} \)\({}= \sqrt{0.000197} \)\({}= 0.014\). An interval of two standard errors around the estimate, from 0.035 to 0.091, covers the true probability with a confidence of about 95 percent.
Over the 300 weeks, the current schedule always leaves a deficit above 1 K h, with a mean of 7.59 K h. A warmer night of 19 °C brings the probability down to 0.067 but needs 5698 kWh per week on average. The deep setback with the optimal start reaches a similar probability, 0.063, with 5420 kWh, 4.9 percent less. The 90 percent quantile of its energy, 6092 kWh, gives the energy office the budget of a cold week.
| Schedule | Mean energy (kWh) | 90 percent quantile (kWh) | Mean deficit (K h) | P(deficit > 1 K h) |
|---|---|---|---|---|
| 17 °C at night, start 6:00 (today) | 5340.9 | 6001.5 | 7.593 | 1.000 |
| 19 °C at night, start 6:00 | 5697.9 | 6390.0 | 0.292 | 0.067 |
| 17 °C at night, optimal start | 5556.9 | 6285.0 | 0.106 | 0.033 |
| 15 °C at night, optimal start | 5446.6 | 6151.5 | 0.128 | 0.037 |
| 13 °C at night, optimal start | 5420.4 | 6091.5 | 0.222 | 0.063 |
Someone who packs for a week in the mountains does not pack for the forecast of a single day. They think of the warm days and the cold ones and pack so that most weeks will be fine. The 300 possible weeks are such a list of weather, worked through with the twin instead of in the head.

Check your understanding. Why does each possible week get its own seed of the random generator?
Python code in the Colab notebook, Section 2. Open Section 2 of the Colab notebook and run it. The function weather(seed) draws one possible week with the random generator of the interactive lab, and monte_carlo runs a schedule over 300 such weeks. The code prints the table above. Paste the results of Part A into MY_SCHEDULES, and the code repeats each of your runs. It then draws the energy and the deficit of the weeks.
- The standard error of 0.014 came from 300 weeks. How many weeks would halve it, and what would that cost?
- The weather model draws temperatures, clouds and visitors. Which uncertainty of the library does it leave out?
Predictive maintenance and the remaining useful life
Jardine and colleagues describe how maintenance moved from repairs after a breakdown to work at fixed intervals. It then moved to decisions based on the measured condition, with diagnostics and prognostics [4]. Four strategies result. Corrective maintenance repairs after a failure. Preventive maintenance replaces parts at fixed intervals, whether they are worn or not. Condition-based maintenance acts when a measured condition crosses a limit. Predictive maintenance forecasts when the condition will cross the limit and plans the work before that.
| Strategy | When the work is done | On the campus |
|---|---|---|
| Corrective | After a failure | A street light is replaced when it goes dark |
| Preventive | At fixed intervals | The air filters of the library are changed every six months |
| Condition-based | When a measured condition crosses a limit | A pump is serviced when its vibration exceeds an alarm limit |
| Predictive | Before the predicted crossing, with time to prepare | New battery modules are ordered before the battery reaches its end of life |
The remaining useful life (RUL) is the time from now until a part can no longer do its job [5]. Si and colleagues stress that the RUL is random, so its estimate needs a distribution and not just one number. For a battery, the job ends by convention when the capacity falls to 80 percent of its rated value. For the battery of the campus that is 400 of 500 kWh.
The capacity of a battery in operation is known in two ways. At the end of every month, the battery management system estimates the usable capacity from the energy of a full discharge in daily operation, corrected to a reference temperature. Once a year, a capacity test checks this estimate: The battery is charged fully, rests and is discharged at its rated power down to its lower limit. The battery of the campus has 36 monthly estimates since its commissioning.
Inside a lithium-ion cell, many physical and chemical mechanisms wear it down. Birkl and colleagues group their effects into the loss of lithium inventory and the loss of active material of the two electrodes [6]. Seen from outside, the battery ages in two ways. Calendar ageing goes on with time, even when the battery rests, and cycle ageing grows with every charge and discharge. Xu and colleagues combine a calendar part and a cycle part in a model of the ageing of grid batteries [7]. A simple model of that kind describes the lost share of the capacity with the age \(t\) in years and the equivalent full cycles \(N\):
\(Q\) is the capacity and \(Q_0 = 500\) kWh the rated capacity. The square root describes a calendar ageing that slows down with time, and \(n\) is the number of cycles per day from now on. The model is linear in \(a\) and \(b\), so least squares fits it directly to the monthly capacity estimates. With \(x = \sqrt{t_{end}}\), the end of life is the positive root of a quadratic equation.
After three years, the battery has made 1078.3 cycles, and its capacity is 460.0 kWh. The fit gives \(a = 0.0236\) per square root of a year and \(b = 0.0000412\) per cycle, with a root mean square error of 1.48 kWh. A straight line in time fits the estimates worse, with 3.21 kWh. It also predicts the end of life after 6.44 years, in April 2030, more than two years before the 8.70 years of the model with both kinds of ageing. The straight line mistakes the fast early calendar ageing for a constant rate.
→ This formula with numbers, step by step: Lab Part B, calculator, steps 1 to 5.
A worked example. With one cycle per day from now on, the cycle ageing per year is \(k = b \times 365.25 = 0.01505\). The constant term is \(c_0 \)\({}= b\,(1078.3 - 365.25 \times 3) \)\({}- 0.2 \)\({}= -0.20072\). The quadratic equation \(k x^2 + a x + c_0 = 0\) has the discriminant \(0.0236^2 \)\({}+ 4 \times 0.01505 \times 0.20072 \)\({}= 0.01264\). Its positive root is \(x \)\({}= (-0.0236 + 0.11243)/0.0301 \)\({}= 2.9512\). The end of life comes after \(x^2 = 8.71\) years, in July 2032, so the remaining useful life is 5.71 years.

Check your understanding. Why does the linear model predict the end of life too early?
Interactive lab, Part B. The calculator of the week computes the end of life of the battery step by step: The yearly cycle ageing, the quadratic equation, its root and the remaining useful life.
Python code in the Colab notebook, Section 3. Open Section 3 of the Colab notebook and run it. The functions fit_linear and fit_ageing fit the two models with least squares, and end_of_life solves the quadratic equation. The code prints both fits with their errors and the end of life for 1, 1.25 and 1.5 cycles per day. It then draws the estimates with both models.
- Which devices of the campus would you leave to corrective maintenance, and why is that not careless?
- What does the battery management system need to measure so that a prognosis of its end of life is possible?
The uncertainty of the remaining useful life
Thirty-six estimates with a noise of 1.5 kWh do not fix \(a\) and \(b\) exactly. Least squares also returns their covariance, and the two are strongly correlated: A larger calendar ageing comes with a smaller cycle ageing. A Monte Carlo simulation draws 2000 pairs of parameters from this uncertainty and computes an end of life for each pair:
\(\Sigma\) is the covariance of the fit, \(L\) its Cholesky factor, and \(z\) are standard normal numbers. New modules take six months to arrive, so an order placed \(M\) months from now arrives in time if the end of life comes later than that. The latest safe order is the largest \(M\) with a probability of at least 0.95.
At one cycle per day, 90 percent of the futures reach the end of life between January 2032 and March 2033, with the median in July 2032. Modules ordered within 56 months, by July 2031, arrive in time with a probability of 0.952. The campus also considers frequency regulation, which would add half a cycle per day. Xu and colleagues assessed the ageing that such a service causes [7]. For the battery of the campus, the median end of life moves forward to December 2030, and the order must be placed within 37 months, by December 2029.
A worked example. At 1.5 cycles per day, an order placed 37 months from now, in December 2029, arrives in June 2030. Of the 2000 futures, 1952 reach the end of life after that. The probability that the modules arrive in time is \(1952/2000 = 0.976\). One month later the probability drops below 0.95.
Scene: A fan of futures. The battery of the campus loses capacity every month. A chart stands on the table like a glass board. It shows the monthly capacity estimates of three years and the model of calendar and cycle ageing. One hundred possible futures are spread in depth, and the end of life lies at 400 kWh. The five buttons follow the prognosis up to the order of new modules. The views Front and From the side show the chart from two sides.

Check your understanding. The prognosis gives a distribution of the end of life. Which quantile decides the latest order?
Interactive lab, Part C. The battery container in 3D: The open container with its racks of modules and the inverter, the cabinet of the battery management system and a pallet of new modules. Predict the end of life with both models and plan the order for frequency regulation. The results can be copied into the Colab notebook.
Python code in the Colab notebook, Section 4. Open Section 4 of the Colab notebook and run it. The function futures draws 2000 parameter pairs with the random generator of the interactive lab, and latest_order searches the latest safe order. The code prints the distribution of the end of life and the order for three duties. Paste the results of Part C into MY_ORDERS, and the code repeats each of your plans.
- Frequency regulation earns money every year but brings the replacement forward by about a year and a half. Which numbers would the finance office need to decide?
- The prognosis will change with every new test. How often would you repeat it, and who should see the result?
Development templates of the week
The folder templates/ of the repository collects small working programs that carry out the methods of the course. Week 13 adds two of them, each with a description, its inputs and outputs and an example run.
| Template | What it does |
|---|---|
whatif_scenarios.py | A first-order thermal twin in a closed loop with an on and off thermostat, schedules with a fixed or an optimal start, and a Monte Carlo comparison over random weeks of weather; the example is the library of the campus |
remaining_useful_life.py | A fit of calendar and cycle ageing to monthly capacity estimates, the end of life from a quadratic equation, a Monte Carlo distribution of the end of life and the latest safe order of spare parts; the example is the battery of the campus |
The engineering side: From prediction to decision
A prognosis helps only when it changes a decision in time. Tao and colleagues build the prognostics and health management of a wind turbine around its digital twin, which fuses the physical model with the measured data [1]. The same chain applies to the campus: Measure the condition, update the model, predict with the uncertainty and plan the work.
| Practice | Why it matters on the campus |
|---|---|
| Agree on the limits with the operators and the makers | The end of life at 80 percent is a convention of the warranty, not a law of physics |
| Store every prediction with its date and its data | Comparing old predictions with what happened shows how far the model can be trusted |
| Repeat the prognosis after every new test | Each test narrows the distribution of the end of life |
| Plan with the lead times of the spare parts | Modules that take six months must be ordered before the median end of life |
| State the probability, not only the date | A plan that is in time in 95 percent of the futures differs from one that is in time on average |
| Let a person approve the decision | The twin supports the decision, and the responsibility stays with people |
- The twin predicted July 2032 three years ago, and the battery is now ahead of that prediction. What would you check first?
- Which prognosis of the campus would you publish to the students who use the library and the chargers?
The campus microgrid, stage 13: Asking the twin
Stage 13 asks the twins of the campus what-if questions. The twin of the library compares heating schedules over the observed week and over 300 possible weeks. The twin of the battery predicts its end of life with the uncertainty and plans the order of new modules.
| Question | Result | Method |
|---|---|---|
| Current schedule, observed week | 5730 kWh and a comfort deficit of 8.79 K h; the library: 5693 kWh and 9.85 K h | Twin in a closed loop |
| 13 °C at night with the optimal start, observed week | 5760 kWh, no comfort deficit | Warm-up time of Week 2 |
| 300 possible weeks, current schedule | P(deficit above 1 K h) = 1.000 | Monte Carlo |
| 300 possible weeks, 13 °C with the optimal start | P = 0.063 with 5420 kWh on average; 19 °C at night: P = 0.067 with 5698 kWh | Monte Carlo |
| End of life of the battery, linear model | 6.44 years: April 2030 | Least squares |
| End of life, calendar and cycle model | 8.70 years: July 2032; 90 percent between January 2032 and March 2033 | Least squares and Monte Carlo |
| Latest order of new modules | Within 56 months at 1 cycle per day, within 37 months with frequency regulation | Probability of 0.95 |
The stage turns the twins of the campus from mirrors into advisers. They compare decisions before anyone takes them and put a probability on every date. Week 14 asks the opposite question: How can the campus show that its cyber-physical system is safe, even when parts fail?

Check your understanding. Why does the optimal start allow a deep setback at night without a loss of comfort?
Interactive lab, Part D. Stage 13 by hand: The capacity of the battery after six years, the mean energy of five possible weeks and the share of the weeks above a budget.
Python code in the Colab notebook, Section 5. Open Section 5 of the Colab notebook and run it. The code collects the results of stage 13 in the dictionary STAGE13 and draws the trade-off of the schedules and the orders of the battery.
In the field: The yearly capacity test
The monthly estimates of this lecture come from daily operation, and once a year a capacity test checks them. The International Electrotechnical Commission (IEC) defines the parameters of a storage system, such as its energy capacity, and the methods that test them in IEC 62933-2-1 [8]. On site, the test takes the battery out of service for most of a day. The energy management system (EMS) must not dispatch it meanwhile, and the racks must lie within the temperatures that the test procedure of the maker asks for.
The battery is charged fully and rests for an hour, so that the voltages of its cells settle. It is then discharged at its rated power of 250 kW down to its lower limit, while a meter counts the energy. The relative deviation from the estimate of the battery management system (BMS) tells whether its estimates can be trusted:
For example, a test that delivers 452.0 kWh against an estimate of 460.0 kWh gives \(\delta = 452.0/460.0 - 1 = -0.0174\), or -1.74 percent.
Interactive lab, Part E. The field task: The service software of the battery container. Run the capacity test in its order and evaluate it against the estimate.
Your application
Wherever a condition degrades step by step, the same steps predict the remaining useful life. The Colab notebook holds an application switch with six systems. They are a cooling water pump, the street lights, the solar plant, the air filter of the library, the brake pads of a tram and the fans of a server.
Python code in the Colab notebook, Section 6. Open Section 6 of the Colab notebook, set APP to one of the six names in the comment and run the cell. The function app_rul fits the degradation of the system, draws its parameters from their uncertainty and prints the distribution of the remaining useful life.
Learning machines for prognostics
The model of this week knows the shape of the ageing: A square root for the calendar and a straight line for the cycles. Learning machines can find such relations in data without that knowledge. Severson and colleagues cycled 124 commercial lithium-ion cells with cycle lives from 150 to 2300 cycles [9]. From the discharge voltage curves of the early cycles, before the capacity had faded, their best models predicted the cycle life with a test error of 9.1 percent.
A learned prognosis carries the conditions of its training data. The cells of that study were charged fast in a laboratory, while the battery of the campus cycles slowly with the sun. A learned model needs data from batteries like the one it judges, and its uncertainty must be stated as clearly as that of a physical model.
Suppose that the maker of the battery collects the capacity estimates of a thousand containers in the field. A network trained on them could predict the end of life of a new container from its first year, long before the model of this week becomes certain. The twin of the campus would then compare the two predictions and trust the learned one only where the container resembles the ones it learned from.
- The model of this week has two parameters, a network may have thousands. When is each of them the better choice?
- How would you check that a learned prognosis fits the battery of the campus?
Review cards
Select a card to turn it over.
References
[1] Tao, F., Zhang, M., Liu, Y., & Nee, A. Y. C. (2018). Digital twin driven prognostics and health management for complex equipment. CIRP Annals, 67(1), 169-172. https://doi.org/10.1016/j.cirp.2018.04.055
[2] Harris, C. R., Millman, K. J., van der Walt, S. J., Gommers, R., Virtanen, P., Cournapeau, D., Wieser, E., Taylor, J., Berg, S., Smith, N. J., Kern, R., Picus, M., Hoyer, S., van Kerkwijk, M. H., Brett, M., Haldane, A., Fernández del Río, J., Wiebe, M., Peterson, P., Gérard-Marchant, P., Sheppard, K., Reddy, T., Weckesser, W., Abbasi, H., Gohlke, C., & Oliphant, T. E. (2020). Array programming with NumPy. Nature, 585(7825), 357-362. https://doi.org/10.1038/s41586-020-2649-2
[3] Metropolis, N., & Ulam, S. (1949). The Monte Carlo method. Journal of the American Statistical Association, 44(247), 335-341. http://links.jstor.org/sici?sici=0162-1459%28194909%2944%3A247%3C335%3ATMCM%3E2.0.CO%3B2-3
[4] Jardine, A. K. S., Lin, D., & Banjevic, D. (2006). A review on machinery diagnostics and prognostics implementing condition-based maintenance. Mechanical Systems and Signal Processing, 20(7), 1483-1510. https://doi.org/10.1016/j.ymssp.2005.09.012
[5] Si, X.-S., Wang, W., Hu, C.-H., & Zhou, D.-H. (2011). Remaining useful life estimation – A review on the statistical data driven approaches. European Journal of Operational Research, 213(1), 1-14. https://doi.org/10.1016/j.ejor.2010.11.018
[6] Birkl, C. R., Roberts, M. R., McTurk, E., Bruce, P. G., & Howey, D. A. (2017). Degradation diagnostics for lithium ion cells. Journal of Power Sources, 341, 373-386. https://doi.org/10.1016/j.jpowsour.2016.12.011
[7] Xu, B., Oudalov, A., Ulbig, A., Andersson, G., & Kirschen, D. S. (2018). Modeling of lithium-ion battery degradation for cell life assessment. IEEE Transactions on Smart Grid, 9(2), 1131-1140. https://doi.org/10.1109/TSG.2016.2578950
[8] International Electrotechnical Commission. (2017). Electrical energy storage (EES) systems - Part 2-1: Unit parameters and testing methods - General specification (IEC 62933-2-1:2017, Edition 1.0). IEC.
[9] Severson, K. A., Attia, P. M., Jin, N., Perkins, N., Jiang, B., Yang, Z., Chen, M. H., Aykol, M., Herring, P. K., Fraggedakis, D., Bazant, M. Z., Harris, S. J., Chueh, W. C., & Braatz, R. D. (2019). Data-driven prediction of battery cycle life before capacity degradation. Nature Energy, 4(5), 383-391. https://doi.org/10.1038/s41560-019-0356-8