KERNEL2.1.0-alpha.1 ‹ Website

KERNEL 2

kiloWatt Energy Resources Network Estimation Library. KERNEL finds the cheapest way to run the flexible equipment on a site (batteries, electric vehicles, heat pumps and air conditioners, rooftop PV) against the site's tariff, while keeping every device inside its limits and every occupant comfortable. It is a library for C, C++, Python and Java on Windows and Linux.

You describe a site in one JSON file: its load, its tariff, its equipment and what you want optimised. KERNEL can also forecast the load, PV, EV charging and heating or cooling from the site's history. KERNEL builds a mathematical program, solves it to proven optimality and returns the schedule, the costs, and a comparison with running the site without optimisation.

{
  "horizon": { "start": "2026-11-16T00:00-05:00", "duration": "48h" },
  "data": { "load": "load.csv" },
  "tariff": "ontario_tou",
  "batteries": [
    { "id": "home_battery", "capacity_kwh": 13.5, "power_kw": 5, "round_trip_eff": 0.9,
      "soc_init_pct": 50, "soc_min_pct": 10, "soc_max_pct": 100 }
  ]
}
$ cediskernel solve site.json -o results.xlsx
status: optimal
  total_cost                                 6.6403 CAD
  baseline_total_cost                        8.6652 CAD
  savings                                    2.0248 CAD
  ...
written: results.xlsx

What it does

Feature In short Read more
Batteries Any number of units, separate charge and discharge efficiencies, self-discharge, end-of-horizon targets Batteries
Battery wear Off, throughput cost, or cycle-depth cost with calendar ageing; switched on per battery Battery wear
EV charging Plug-in sessions with energy or state-of-charge targets, minimum charging power, vehicle-to-grid EV charging
HVAC Heating and cooling with a thermal model of the building, comfort bands by time of day, heat-pump efficiency that follows the weather, on/off or modulating units HVAC
PV and the grid PV generation, optional curtailment, import and export limits Grid and PV
Tariffs Time-of-use (the default), flat, tiered, real-time prices, critical peak, demand charges, export credit, fixed charges; Ontario presets Tariffs
Ancillary services Regulation, reserves and your own products, symmetric or one-sided; demand-response events Ancillary services
Optimisation Deterministic, or stochastic over load and PV scenarios with a risk measure (CVaR) Optimisation
Solvers HiGHS (default) and SCIP built in; Gurobi and CPLEX used when installed Solvers
Data CSV (default), Excel and JSON; any sample step, resampled to the model step (default 15 minutes) Time and data
Results Schedule, costs, device and EV-session tables; CSV (default), Excel or JSON, at any output step (default 15 minutes) Results
Forecasting Demand, PV, EV charging and HVAC load from history, with ranges; the building's thermal model fitted from data; forecasts feed the optimisation directly Forecasting
Metrics MAE, WAPE, skill, peak and energy errors, CRPS, coverage; backtests to compare methods Metrics

Choose your starting point

How it fits together

KERNEL architecture Python, Java and C++ call the C interface, which calls the C++ core; the core uses HiGHS, SCIP, Gurobi or CPLEX. Python Java (FFM) C++ header cediskernel CLI C interface — cedis/kernel.h (stable ABI) C++20 core — configuration, data, tariffs, site model, results HiGHS SCIP Gurobi CPLEX
Every language uses the same C interface, so results are identical from Python, Java, C++ and the command line. HiGHS and SCIP are linked in; Gurobi and CPLEX (dashed) are loaded at run time when installed.

Status

This is 2.1.0-alpha.1, a pre-release. The site model, the solvers, forecasting and the four language bindings are complete and tested. See the roadmap.

KERNEL 2 is released under the Apache License 2.0; see the LICENSE and NOTICE files. It is developed at CEDIS Lab.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

Install

KERNEL is built from source with CMake. One build gives you the C library, the C++ header, the command-line tool cediskernel and, if you ask for it, the Python module. The Java package uses the same library.

Requirements

What Version
CMake 3.28 or newer
C++ compiler GCC 12+, Clang 16+, or Visual Studio 2022 17.8+ (workload "Desktop development with C++")
Git any recent version (CMake uses it to fetch the dependencies)
Python (optional) 3.11 or newer
Java (optional) JDK 22 or newer; 25 LTS recommended. Maven 3.9+ to build the jar

Supported systems: Windows 10/11 and Linux (glibc 2.28 or newer), on x86-64 and arm64.

The first configure downloads the dependencies (HiGHS, SCIP, SoPlex, nlohmann/json, miniz, pugixml) and links them statically, so the finished library has no run-time dependencies.

Build the library and the command-line tool

cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build --parallel
ctest --test-dir build --output-on-failure
./build/bin/cediskernel version

MultiThreaded links the Microsoft C runtime statically, so cediskernel.dll runs on machines without the Visual C++ redistributable.

To build and run every test suite and example in one go, use scripts/test.sh (Linux) or scripts\test.ps1 (Windows); see TESTING.md in the repository.

Build options

CMake option Default Meaning
KERNEL_WITH_SCIP ON Bundle the SCIP solver (with SoPlex). OFF gives a smaller library and a much faster build; HiGHS is always included.
KERNEL_BUILD_PYTHON OFF Build the Python module in place (python/cedis_kernel/), for development
KERNEL_BUILD_TESTS ON at top level C and C++ tests
KERNEL_BUILD_EXAMPLES ON at top level C and C++ examples
KERNEL_BUILD_CLI ON at top level the cediskernel command-line tool
KERNEL_USE_SYSTEM_HIGHS OFF Use an installed HiGHS (find_package(highs)) instead of downloading it
KERNEL_HIGHS_TAG, KERNEL_SCIP_TAG, KERNEL_SOPLEX_TAG v1.15.1, v10.1.0, v8.1.0 Dependency versions

Offline builds

Point CMake at local copies of the dependency sources:

cmake -S . -B build \
  -DFETCHCONTENT_SOURCE_DIR_HIGHS=/src/HiGHS \
  -DFETCHCONTENT_SOURCE_DIR_SCIP=/src/scip -DFETCHCONTENT_SOURCE_DIR_SOPLEX=/src/soplex \
  -DFETCHCONTENT_SOURCE_DIR_NLOHMANN_JSON=/src/json \
  -DFETCHCONTENT_SOURCE_DIR_MINIZ=/src/miniz -DFETCHCONTENT_SOURCE_DIR_PUGIXML=/src/pugixml

Install for use from other C or C++ projects

cmake --install build --prefix /opt/cedis-kernel

This installs the library, the headers cedis/kernel.h and cedis/kernel.hpp, the command-line tool and a CMake package:

find_package(CedisKernel 2 REQUIRED)
target_link_libraries(my_app PRIVATE cedis::cediskernel)

Python

From the repository root:

python -m pip install .
python -c "import cedis_kernel as ck; print(ck.__version__, ck.solvers())"

pip builds a wheel with scikit-build-core, which runs the same CMake build. For pandas output (Result.to_pandas()), install pandas as well.

For development, build the module in place and point PYTHONPATH at it:

cmake -S . -B build-py -DKERNEL_BUILD_PYTHON=ON -DCMAKE_BUILD_TYPE=Release
cmake --build build-py --parallel
PYTHONPATH=python python -m unittest discover -s python/tests -v

Java

The Java package org.cedislab.kernel calls the C library through the Foreign Function & Memory API, which is final in Java 22. Build the C library first, then:

cd java
mvn verify -Dcedis.kernel.library=$PWD/../build/src/libcediskernel.so      # Linux
mvn verify "-Dcedis.kernel.library=$PWD\..\build\bin\Release\cediskernel.dll"  # Windows

Run your application with native access enabled:

java --enable-native-access=ALL-UNNAMED -cp cedis-kernel-2.1.0-alpha.1.jar:. MyApp        # class path
java --enable-native-access=org.cedislab.kernel -p cedis-kernel-2.1.0-alpha.1.jar -m my.app   # module path

The library is found in this order: the system property cedis.kernel.library (a file path), a copy bundled in the jar under native/<os>-<arch>/ (release jars built by CI carry all four platforms), then the system library path (PATH on Windows, LD_LIBRARY_PATH on Linux).

Commercial solvers (optional)

KERNEL can use Gurobi or CPLEX if you have them installed and licensed. Nothing is needed at build time: the library is loaded when a site asks for that solver. See Solvers for how KERNEL finds them, and check with:

$ cediskernel solvers
  highs    available (bundled, 1.15.1)
  scip     available (bundled, 10.1.0)
  gurobi   not found (set GUROBI_HOME or KERNEL_GUROBI_LIBRARY)
  cplex    not found (set CPLEX_STUDIO_DIR<version> or KERNEL_CPLEX_LIBRARY)

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

Your first site

This walk-through builds a site step by step: a house with a home battery, then an electric car, then a heat pump, and finally a forecast with uncertainty. Each step is one small change to the configuration. The finished files are in the repository under examples/sites/first_site/.

You need the command-line tool cediskernel (Install). Each step also works from Python, Java or C++.

1. The load data

KERNEL needs to know how much power the site draws. Make a folder and save this as load.csv: one row per hour for Monday 16 and Tuesday 17 November 2026, in kW (the full file has 48 rows).

timestamp,load_kw
2026-11-16T00:00-05:00,0.62
2026-11-16T01:00-05:00,0.55
2026-11-16T02:00-05:00,0.52
...
2026-11-17T23:00-05:00,0.78

The -05:00 is the UTC offset of Ontario in winter (Eastern Standard Time). Writing it makes the times unambiguous, including across daylight-saving changes. Hourly data is fine: KERNEL resamples every input to the model step, which is 15 minutes unless you choose otherwise (Time and data).

2. A battery on time-of-use prices

Save this as site.json next to load.csv:

{
  "name": "My first site",
  "horizon": { "start": "2026-11-16T00:00-05:00", "duration": "48h", "step": "15min" },
  "data": { "load": { "file": "load.csv", "time": "timestamp", "value": "load_kw" } },
  "tariff": "ontario_tou",
  "batteries": [
    { "id": "home_battery", "capacity_kwh": 13.5, "power_kw": 5, "round_trip_eff": 0.9,
      "soc_init_pct": 50, "soc_min_pct": 10, "soc_max_pct": 100 }
  ]
}
Setting Meaning
horizon Optimise two days from midnight, in 15-minute steps (192 steps)
data.load The load comes from load.csv; time and value name its columns
tariff The Ontario Regulated Price Plan time-of-use prices (off-peak 9.1, mid-peak 14.6, on-peak 18.9 ¢/kWh). Time-of-use is also what you get if you leave tariff out
batteries One 13.5 kWh, 5 kW battery, 90 % round trip, starting half full

Check the file, then solve:

$ cediskernel validate site.json
ok: 192 steps of 900 s

$ cediskernel solve site.json -o results.xlsx
status: optimal
  total_cost                                 6.6403 CAD
  baseline_total_cost                        8.6652 CAD
  savings                                    2.0248 CAD
  savings_pct                               23.3674 %
  energy_cost                                6.6403 CAD
  baseline_energy_cost                       8.6652 CAD
  peak_kw                                    3.8673 kW
  baseline_peak_kw                           3.1000 kW
  import_kwh                                65.0952 kWh
  load_kwh                                  62.5200 kWh
  battery_charged_kwh                       25.7517 kWh
  battery_discharged_kwh                    23.1765 kWh
  battery_losses_kwh                         2.5752 kWh
  ...
written: results.xlsx

The baseline is the same site without optimisation: the battery stays idle, so every kWh of load is bought when it is used. With the battery charging off-peak and discharging on-peak, the two days cost 6.64 instead of 8.67 CAD. The battery ends at least as full as it started, so the saving is not borrowed from the following day.

Note

These are commodity prices only. Real bills add delivery and regulatory charges per kWh; add them with "adder_per_kwh" (see Tariffs).

3. Read the schedule

Open results.xlsx. The Schedule sheet has one row per 15 minutes:

timestamp load_kw grid_import_kw price home_battery.power_kw home_battery.soc_pct
2026-11-16 00:00 0.62 1.636 0.091 1.016 51.79
2026-11-16 00:15 0.62 1.636 0.091 1.016 53.57
…
2026-11-16 07:00 2.10 0 0.189 −2.100 95.90
2026-11-16 07:15 2.10 0 0.189 −2.100 91.80

Battery power is positive when charging and negative when discharging. Overnight it charges at a steady 1.016 kW; when on-peak starts at 07:00 it covers the whole load. The state of charge is at the end of each step. The Summary sheet holds every cost and energy figure, and Devices the figures per battery. Results explains every column.

To get CSV files instead, write -o results with --format csv (or leave -o out and set "output": {"path": "results", "format": "csv"}).

4. Add an electric car

The car comes home at 18:00 with 35 % charge and must reach 80 % by 07:30. Add this to site.json:

  "evs": [
    { "id": "car", "battery_kwh": 75, "charge_max_kw": 7.2, "charge_eff": 0.92,
      "sessions": [ { "arrival": "2026-11-16T18:00", "departure": "2026-11-17T07:30",
                      "soc_arrival_pct": 35, "soc_target_pct": 80 } ] }
  ]
$ cediskernel solve step2_ev.json
status: optimal
  total_cost                                 9.9787 CAD
  baseline_total_cost                       12.7091 CAD
  savings                                    2.7304 CAD
  peak_kw                                    6.9243 kW
  baseline_peak_kw                          10.3000 kW
  ev_energy_kwh                             33.7500 kWh
  ...

The car needs 75 × (80 − 35) % = 33.75 kWh. In the baseline it charges at full power the moment it is plugged in, at the on-peak price and on top of the evening load (10.3 kW). Optimised, it charges after 19:00 when prices drop, and the peak falls to 6.9 kW. The EV sessions sheet confirms each session got its energy:

ev session arrival departure need_kwh delivered_kwh shortfall_kwh
car 1 2026-11-16T18:00:00-05:00 2026-11-17T07:30:00-05:00 33.75 33.75 0

Times without an offset, like "2026-11-16T18:00", use the horizon's offset. EV charging covers sessions from files, minimum charging power and vehicle-to-grid.

5. Add a heat pump

The heat pump keeps the house between 20.5 and 23 °C from 06:30 to 22:00, and between 18 and 24 °C at night. Outside it is −5 °C:

  "hvac": [
    { "id": "heat_pump", "initial_c": 21, "outdoor": -5,
      "thermal": { "ua_kw_per_c": 0.25, "capacitance_kwh_per_c": 3.0 },
      "heating": { "max_kw": 4.0, "cop": { "a": 2.8, "b": 0.05, "min": 1.5 } },
      "comfort": { "min_c": 18, "max_c": 24,
                   "schedule": [ { "days": "all", "from": "06:30", "to": "22:00", "min_c": 20.5, "max_c": 23 } ] } }
  ]

thermal describes the house: it loses 0.25 kW per °C of difference with the outside, and it takes 3 kWh of heat to warm it by 1 °C. The heat pump's efficiency (COP) is 2.8 + 0.05 × outdoor temperature, here 2.55.

$ cediskernel solve step3_heat_pump.json
status: optimal
  total_cost                                23.8995 CAD
  baseline_total_cost                       27.9125 CAD
  savings                                    4.0130 CAD
  hvac_energy_kwh                          115.1893 kWh
  baseline_comfort_violation_ch              3.8185 degC h
  ...

The schedule pre-heats the house to the top of the comfort band before on-peak starts at 07:00, then lets it coast:

timestamp price heat_pump.power_kw heat_pump.indoor_c heat_pump.comfort_min_c
06:15 0.091 4 22.46 18
06:30 0.091 4 22.73 20.5
06:45 0.091 4 23.00 20.5
07:00 0.189 0 22.42 20.5
07:15 0.189 0 21.86 20.5

The baseline thermostat only heats when the house would otherwise get too cold, so it misses the 06:30 step up and is 3.8 °C·h below the band over the two days. The optimised schedule has no comfort violation. See HVAC for cooling, weather data, on/off units and soft comfort limits.

6. Plan for an uncertain forecast

A load forecast is never exact. Tell KERNEL how uncertain it is and ask for a stochastic plan:

  "data": { "load": { "file": "load.csv", "time": "timestamp", "value": "load_kw", "std_pct": 15 } },
  "optimization": { "mode": "stochastic", "stochastic": { "scenarios": 5 } }

KERNEL builds five load scenarios (quantiles of a normal distribution with a 15 % standard deviation) and finds one plan for the first step that is best on average over all of them, adapting later steps to each scenario.

$ cediskernel solve step4_stochastic.json
status: optimal
  total_cost                                23.9020 CAD
  ...
  scenarios                                  5.0000
  cost_min                                  22.2742 CAD
  cost_max                                  25.5349 CAD

The cost is now an expected value, and cost_min / cost_max show the spread across scenarios. Add "risk_weight" to trade expected cost against the cost of the worst scenarios (Optimisation).

Next steps

  • Use real data: weather, PV and prices from CSV, Excel or JSON files (Time and data).
  • Model your own tariff, with demand charges or an export price (Tariffs).
  • Earn revenue from ancillary services (Ancillary services).
  • Turn on battery wear so cycling has a cost (Batteries).
  • Run it from code: Python, Java, C++, C.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

Concepts

A few ideas run through every part of KERNEL. Knowing them makes the configuration reference and the results easy to read.

The site

A site is everything behind one grid connection: its load, its PV, its batteries, EVs and HVAC units, and the tariff it pays. KERNEL decides, for every time step, how much each flexible device charges, discharges, heats or cools, and therefore how much the site imports from or exports to the grid.

The load is the site's demand that KERNEL does not control (lights, appliances, processes), in kW. PV is given separately. Everything KERNEL schedules (batteries, EVs, HVAC) comes on top of the load.

Time: horizon, steps and the three grids

The horizon is the period being optimised, for example 48 hours from midnight. It is cut into equal model steps; the default step is 15 minutes. Power is constant within a step, and states (battery charge, indoor temperature) are tracked at the end of each step.

Data, model and results each have their own time grid:

Input, model and output time grids Input data at 5-minute or hourly samples is resampled to 15-minute model steps, and results can be written hourly or at any other step. inputmodeloutput 15 mine.g. 1 h 5-minute sampleshourly samples step averagelinear (temperature)power: averagestate: end of step
Input data can arrive at any sample step. It is resampled to the model step, the problem is solved there, and the results can be written at another step.
  • Input step. Each data series can have its own sample interval: 1 minute, 5 minutes, 30 minutes, hourly, even irregular. KERNEL takes the typical (median) spacing of the timestamps as the sample interval.
  • Model step (horizon.step, default "15min"). The horizon must be a whole number of steps.
  • Output step (output.step, default: the model step). Any step that divides the horizon, longer or shorter than the model step.

How data are resampled

Quantity Default rule Why
Power (load, PV, gains), prices, other series Step average: the value of a model step is the time-weighted average of the samples it overlaps; each sample holds until the next one Preserves energy: 1 kW for an hour is 1 kWh whatever the step
Temperature Linear: interpolated between samples, then averaged over the step Temperature changes smoothly; holding it in steps would put jumps in the thermal model

Change the rule for any series with "interpolation": "step" or "linear". Every series must cover the whole horizon; KERNEL reports the series and the gap if it does not.

How results are resampled

When output.step differs from the model step:

  • powers and prices (…_kw, price) are averaged over each output step, so energy is preserved;
  • states (…soc_pct, …energy_kwh, …indoor_c, comfort bounds) are the value at the end of each output step, interpolated if the output step is finer than the model step.

Local time and UTC offsets

Tariffs, comfort schedules and service windows are written in local wall clock time ("on-peak from 07:00 to 11:00 on weekdays"). KERNEL keeps every instant as UTC plus the UTC offset in force, so it can apply local rules and still handle daylight-saving changes.

The offset comes from, in order:

  1. horizon.utc_offset, for example "-05:00";
  2. the offset written in horizon.start, for example "2026-11-16T00:00-05:00";
  3. the offsets in the load data's timestamps, step by step. This is the way to cross a daylight-saving change: give timestamps such as 2026-11-01T01:30-04:00 and 2026-11-01T01:30-05:00, and every step gets the right local time;
  4. otherwise, UTC.

A time written without an offset ("2026-11-16T18:00") is read in the horizon's offset. Results carry the offset in their timestamps (2026-11-16T18:00:00-05:00) whenever one was given; see output.timestamps in Results.

Signs and units

Quantity Unit Sign
Power kW battery and EV power: + charging, − discharging; grid: import and export are separate, both ≥ 0; net_grid_kw = import − export
Energy kWh
State of charge % of capacity
Temperature °C
Prices currency per kWh the currency is whatever your tariff uses ("currency": "CAD"); KERNEL does not convert
Demand charges currency per kW of peak
Efficiencies fractions 0.95, not 95; KERNEL rejects 95 with a message
Durations "15min", "1h", "PT15M", "2d" or seconds

Data files can use other units; say which with "unit" ("W", "MW", "cents_per_kwh", "F" …), see Time and data.

Costs, the baseline and savings

KERNEL minimises the site's total cost over the horizon:

total_cost = energy_cost − export_credit + demand_cost + fixed_cost
           + wear_cost + ev_shortfall_penalty + comfort_penalty + dr_penalty
           − service_revenue − dr_revenue

Every term is reported in the results. Penalties are zero unless a target cannot be met (an EV that cannot be charged in time, a room that cannot be kept warm).

The baseline is the same site run without optimisation, under the same tariff:

  • batteries stay idle;
  • EVs charge at full power from the moment they arrive until they have the energy they need;
  • HVAC behaves like a plain thermostat: it heats (or cools) only when the room would otherwise leave the comfort band, and only as much as needed (an on/off unit runs at full power when it runs);
  • PV is used on site, and surplus is exported when export is allowed.

savings = baseline_total_cost − total_cost. The baseline uses the same tariff, so savings show the value of scheduling, not of changing tariff.

Deterministic and stochastic

  • Deterministic (the default) treats the data as known. One schedule is computed.
  • Stochastic treats load and PV (or any series you mark) as uncertain. KERNEL builds scenarios, and finds the decisions for the first step (or the first few hours) that are best across all scenarios, with later decisions adapted to each scenario. Results report the expected values plus the spread. See Optimisation.

Equal-cost schedules and the tie-break

Many schedules often cost exactly the same: charging at 01:00 or at 03:00 when both are off-peak, for example. A solver returns one of them, and which one can change between versions and machines. KERNEL's default smooth tie-break returns a specific one among the cheapest: the one that spreads power evenly and does no pointless cycling. The cost is unchanged. It makes results reproducible across platforms and languages. See The model.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

The configuration file

A site is described by one JSON object. You can keep it in a .json file, build it as a dictionary in Python, or pass JSON text from any language. Only the parts your site needs have to be there; everything else has a default.

Top-level settings

Key Required What it holds Page
kernel no Configuration format version, "2"
name no A name for the site (free text)
horizon see below Start, length and step of the optimisation Time and data
data usually Time series: load, pv, outdoor_temperature, prices, anything a setting refers to by name Time and data
tariff no What energy costs. Default: time-of-use ("ontario_tou") Tariffs
grid no Import and export limits, whether export is allowed Grid and PV
pv no PV curtailment Grid and PV
batteries no List of batteries, each with an optional wear model Batteries
evs no List of electric vehicles and their charging sessions EV charging
hvac no List of heating and cooling units with their building model HVAC
services no Ancillary-service products and demand-response events Ancillary services
optimization no Deterministic or stochastic, solver, time limit, tie-break Optimisation
output no Output step, format, file path, timestamp style Results

horizon.start may be left out when there is load data: the horizon then starts at the first sample and ends after the last one.

A complete example with every section:

{
  "kernel": "2",
  "name": "Ottawa home (example)",
  "horizon": { "step": "15min", "utc_offset": "-05:00" },
  "data": {
    "load": { "file": "data/load.csv", "time": "timestamp", "value": "load_kw", "std_pct": 15 },
    "pv": { "file": "data/pv.csv", "value": "pv_w", "unit": "W", "std_pct": 30 },
    "outdoor_temperature": { "file": "data/weather.xlsx", "sheet": "Weather", "value": "Temperature (C)" }
  },
  "tariff": { "preset": "ontario_tou", "adder_per_kwh": 0.035, "export": { "type": "flat", "price": 0.05 } },
  "grid": { "import_limit_kw": 20, "allow_export": true },
  "batteries": [ { "id": "home_battery", "capacity_kwh": 13.5, "power_kw": 5, "round_trip_eff": 0.9,
                   "wear": { "model": "cycle_depth", "replacement_cost": 12000, "cycle_life": 6000 } } ],
  "evs": [ { "id": "car", "battery_kwh": 75, "charge_max_kw": 7.2,
             "sessions": [ { "arrival": "2026-11-16T18:00", "departure": "2026-11-17T07:30",
                             "soc_arrival_pct": 35, "soc_target_pct": 80 } ] } ],
  "hvac": [ { "id": "heat_pump", "thermal": { "ua_kw_per_c": 0.25, "capacitance_kwh_per_c": 3.0 },
              "heating": { "max_kw": 4.0, "cop": { "a": 2.8, "b": 0.05, "min": 1.5 } },
              "comfort": { "min_c": 20, "max_c": 23 } } ],
  "optimization": { "solver": "highs", "tie_break": "smooth" },
  "output": { "step": "15min", "format": "xlsx" }
}

The full version is examples/sites/ottawa_home/site.json in the repository.

File paths

Data files are found relative to the folder of the configuration file. When the configuration is passed as text or as a dictionary, they are relative to the base_dir argument (or the current folder). Paths may contain any Unicode characters on every platform.

Comments

JSON has no comments, but KERNEL accepts // and /* … */ comments in the configuration. Keys that start with an underscore, such as "_comment" or "_note", are ignored at every level; use them to keep files valid JSON for other tools.

Error messages

KERNEL checks the whole configuration before solving, and every message says where the problem is and what is expected:

error: configuration: unknown setting 'tarrif' (did you mean 'tariff'?)
error: batteries[0]: unknown setting 'power_kv' (did you mean 'power_kw'?)
error: batteries[0].charge_eff: must be a fraction in (0, 1], e.g. 0.95 (not 95)
error: horizon: the horizon (65min) is not a whole number of 15min steps
error: 'load' (load.csv) covers 2026-11-16T00:00:00-05:00 to 2026-11-18T00:00:00-05:00, but the
       horizon runs from 2026-11-16T00:00:00-05:00 to 2026-11-19T00:00:00-05:00
error: bad.csv, line 14, column 2 (load_kw): expected a number for load, found 'n/a'
error: site.json: line 4, column 3: invalid JSON (expected string literal)

Errors are grouped by kind, so programs can react to them:

Kind C status Python exception Java KernelException.Status Example
Invalid argument KERNEL_ERR_INVALID_ARGUMENT InvalidArgumentError INVALID_ARGUMENT unknown setting, value out of range
I/O KERNEL_ERR_IO KernelIOError IO file not found, cannot write
Data KERNEL_ERR_DATA DataError DATA bad number in a file, gap in a series
Infeasible KERNEL_ERR_INFEASIBLE InfeasibleError INFEASIBLE a hard limit cannot be met (import limit below the load)
Solver KERNEL_ERR_SOLVER SolverError SOLVER time limit reached without any schedule, licence missing

To check a configuration and its data without solving, use cediskernel validate site.json, cedis_kernel.validate(...) or Kernel.validate(...).

Reading this reference

Each setting is listed with its type and default. Types:

Type Example
number 13.5
percent 50 (meaning 50 %)
fraction 0.95
duration "15min", "1h", "PT15M", 3600 (seconds)
date-time "2026-11-16T18:00", "2026-11-16 18:00", "2026-11-16T18:00-05:00", "2026-11-16T23:00Z"
clock time "07:00", "7", "24:00"
series a number (constant) or the name of a series in data
time rule { "months": [...], "days": "weekday", "from": "07:00", "to": "19:00" }, see Time rules

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

Time and data

Horizon

"horizon": { "start": "2026-11-16T00:00-05:00", "duration": "48h", "step": "15min" }
Setting Type Default Meaning
start date-time first sample of the load data Start of the first step
end date-time End of the last step. Give one of end, duration or steps
duration duration Length of the horizon, e.g. "24h", "7d"
steps integer Number of model steps
step duration "15min" Model step. The horizon must be a whole number of steps
utc_offset text offset in start, else from the data, else UTC Local time as an offset from UTC, e.g. "-05:00", "+09:00", "Z"

If none of end, duration and steps is given, the horizon ends with the load data (the end of its last sample). A horizon has at most 200,000 steps.

Choosing the step is a trade-off. Shorter steps follow the data more closely and give more room to schedule; they also make the problem larger. 15 minutes suits most sites over one to seven days; 5 minutes suits a day-ahead plan with fast-changing prices; 1 hour suits a month.

Data series

Every time series lives under data, by name. Some names are used automatically:

Name Unit after conversion Used by
load kW the site's demand. Without it the load is zero
pv kW PV generation
outdoor_temperature °C HVAC units (unless they set outdoor)
price per kWh the energy price when there is no tariff, or a tariff of type series
export_price per kWh a tariff whose export type is series

Any other name can be referred to by a setting that takes a series: a heat-pump COP, internal heat gains, a service's capacity price, a real-time price under another name.

A series can be written four ways:

"data": {
  "load": "load.csv",                                 // a file; the time and value columns are found automatically
  "outdoor_temperature": -5,                          // a constant
  "pv": { "file": "pv.xlsx", "sheet": "PV", "time": "Time", "value": "PV (W)", "unit": "W" },
  "load": { "forecast": "demand.json" }                // a forecast, see Forecasting
}

A forecast series is predicted for the horizon by a forecasting model (a model file, or a training configuration that is trained when the site is read), and its quantiles become the series' uncertainty; see Forecasts in a site.

Settings of a series

Setting Type Default Meaning
file path CSV, Excel (.xlsx, .xlsm) or JSON file. The format follows the extension
sheet text first sheet Excel: the worksheet. JSON: the member that holds the table
time text, list or "auto" "auto" The time column: a column name, or ["Year","Month","Day","Hour","Quarter"] for KERNEL 1.x files. "auto" uses the 1.x columns if present, else the first column that holds dates
value text or column number the only numeric column (or a 1.x …Mean column) The value column; numbers count from 1
unit text kW, per kWh, °C Unit of the values; see Units
scale number 1 Multiply every value (after the unit), e.g. 1.1 for 10 % growth
kind power, price, temperature, generic from the name What the series measures; decides units and the default interpolation
interpolation step, linear linear for temperature, else step How samples become model steps; see Concepts
constant number A constant value (same as writing the number)
values, start, step list, date-time, duration Values written inline: {"values": [1.2, 1.4, 1.1], "start": "2026-11-16T00:00-05:00", "step": "1h"}
building, building_column number, text "BuildingIndex" Keep only the rows of one building (KERNEL 1.x result files hold several)
stamp start, end start (KERNEL 1.x files with hour 24: end) Whether each timestamp marks the start or the end of its interval. Meter exports often stamp the end: the reading at 00:15 covers 00:00–00:15
forecast path or object Forecast this series with a model; see Forecasts in a site

The kind is taken from the name when not given: a name containing price is a price, one containing temp is a temperature, and load, pv and names containing _kw or gains are power.

Uncertainty

For stochastic optimisation, a series can say how uncertain it is. In deterministic mode these settings are read and ignored.

Setting Meaning
std_pct Standard deviation as a percentage of each value
std Standard deviation: a column name (file), a list (inline values) or a number (constant)
lower, upper, level Columns with the lower and upper bounds of a central interval, and its probability (default 0.95). The standard deviation is derived assuming a normal distribution
pmf KERNEL 1.x forecast distributions: {"start": "pmfStartIndx", "step": "pmfStep", "bins": "DemandpmfData"} (all optional)
scenarios Columns (file) or lists (inline) that are complete scenarios, used with "method": "provided"

A forecast series carries its quantiles (p10 … p90) as the uncertainty. A forecast written earlier to a file can be read back with its range: {"file": "load.csv", "value": "load", "lower": "load.p10", "upper": "load.p90", "level": 0.8}.

File formats

CSV

Comma-separated, with a header row. Quoted fields may contain commas. UTF-8, with or without a byte-order mark. Numbers use a dot as the decimal point.

timestamp,load_kw,pv_kw
2026-11-16T00:00-05:00,0.62,0
2026-11-16T00:15-05:00,0.60,0

Excel

.xlsx and .xlsm workbooks. The first row of the sheet is the header. Dates may be real Excel dates (any date format) or text. Formulas are read by their last calculated value, so save the workbook in Excel before using it.

JSON

Three layouts are accepted:

{ "timestamp": ["2026-11-16T00:00-05:00", "2026-11-16T00:05-05:00"], "load_kw": [0.62, 0.61] }
[ { "timestamp": "2026-11-16T00:00-05:00", "load_kw": 0.62 },
  { "timestamp": "2026-11-16T00:05-05:00", "load_kw": 0.61 } ]

A KERNEL result file (results.json) can also be read back as data: its timestamps become the timestamp column and every series a column. Use "sheet" to pick a member of a larger JSON document: {"file": "forecast.json", "sheet": "load"}.

Timestamps

Written as Example
ISO 8601 with offset 2026-11-16T18:00-05:00, 2026-11-16T23:00Z, 2026-11-16T18:00:00-05:00
ISO 8601 without offset (read in the horizon's offset) 2026-11-16T18:00, 2026-11-16 18:00, 2026/11/16 18:00
Excel date-time cell any date format
KERNEL 1.x columns Year, Month, Day, Hour, Quarter (or Minute)

Timestamps must increase. A repeated local time during a daylight-saving change is an error unless the timestamps carry offsets; the message says so.

Units

Kind Units accepted
power kW (default), W, MW
price per_kwh (default), per_mwh, cents_per_kwh (also /kWh, /MWh, c/kWh)
temperature C (default), F, K
generic none; use scale
"pv": { "file": "inverter.csv", "value": "ac_power", "unit": "W" },
"price": { "file": "hoep.csv", "value": "price", "unit": "per_mwh" }

Sample steps

Each series is read at its own sample interval (the typical spacing of its timestamps) and resampled to the model step, so a 1-minute meter export, a 5-minute price feed and hourly weather can be used together. A single sample (or a constant) covers the whole horizon. See How data are resampled.

KERNEL 1.x files

The 1.x forecast results (Demand_Results.csv, PV_Results.csv) can be used directly:

"data": {
  "load": { "file": "Demand_Results.csv", "building": 1, "pmf": {} },
  "pv":   { "file": "PV_Results.csv", "building": 3 }
}

Time comes from the Year, Month, Day, Hour, Quarter columns (hour 24 means the file is stamped at the end of each quarter hour), the value from the …Mean column, and with "pmf": {} the forecast distribution becomes the uncertainty for stochastic optimisation. The 1.x storage-only inputs (essConfig.csv, tou.csv, peakprice.csv) are read by the storage scheduler. The 1.x forecast inputs (Demand_LTD.csv, PV_LTD.csv) can be used as forecasting history; see Forecasting and the Benchmark.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

Tariffs

The tariff says what the site pays for energy and power, and what it earns for exporting. KERNEL evaluates it on the model time grid, in local time, and minimises the bill.

The default: time-of-use

Leave tariff out and KERNEL uses time-of-use prices, the Ontario Regulated Price Plan TOU preset ontario_tou, and says so in a warning:

warning: no "tariff" given: using the default time-of-use tariff 'ontario_tou' (set "tariff" to change it)

(If data has a price series and there is no tariff, that series is used instead, as a real-time price.)

Three ways to give a tariff

"tariff": "ontario_ulo"

A preset, by name.

"tariff": { "preset": "ontario_tou", "adder_per_kwh": 0.035, "export": { "type": "flat", "price": 0.05 } }

A preset with changes. The settings you give are merged into the preset; objects merge key by key, so {"preset": "ontario_tou", "energy": {"periods": {"on_peak": 0.2}}} changes one price and keeps the rest. An object without energy or preset also starts from the default ontario_tou.

"tariff": {
  "name": "Example commercial TOU",
  "currency": "CAD",
  "energy": {
    "type": "tou",
    "periods": { "off_peak": 0.085, "mid_peak": 0.125, "on_peak": 0.19 },
    "default": "off_peak",
    "schedule": [
      { "days": "weekday", "from": "07:00", "to": "11:00", "period": "on_peak" },
      { "days": "weekday", "from": "11:00", "to": "17:00", "period": "mid_peak" },
      { "days": "weekday", "from": "17:00", "to": "19:00", "period": "on_peak" }
    ]
  },
  "holidays": "ontario",
  "demand_charges": [ { "name": "daytime_peak", "rate": 12.5, "window": { "days": "weekday", "from": "07:00", "to": "19:00" } } ]
}

A tariff of your own.

Settings

Setting Type Default Meaning
name, currency text "" For reports. currency labels every cost in the results (e.g. "CAD")
preset text Start from this preset
energy object the default preset's The price of imported energy, see below
adder_per_kwh number 0 Added to every imported kWh: delivery, regulatory and other per-kWh charges
holidays text, list or object "none" ("ontario" in the Ontario presets) Which days count as holidays, see Holidays
critical_peak list Critical peak pricing events, see Critical peak
demand_charges list Charges per kW of peak, see Demand charges
export text or object "none" What exported energy earns, see Export
fixed_per_day number 0 Fixed charge per day, pro-rated over the horizon
effective, source text Information only (presets fill them in)

Energy prices

energy.type Settings Meaning
tou periods, default, schedule Time-of-use: named periods with a price each, and a schedule of time rules that pick the period. The first matching rule wins; times no rule matches get the default period
flat price One price for every kWh
tiered tiers, consumed_kwh Block prices by monthly consumption, see Tiered prices
series series (default "price") A price for every step from a data series: real-time or day-ahead prices

type may be left out: periods means tou, tiers means tiered, otherwise flat.

When a step straddles a period boundary (a 1-hour step with a period change at 07:30, say), its price is the time-weighted average of the two. The price of every step is in the result's price series.

Tiered prices

"energy": {
  "type": "tiered",
  "tiers": [ { "up_to_kwh": [1000,1000,1000,1000,600,600,600,600,600,600,1000,1000], "price": 0.112 },
             { "price": 0.132 } ],
  "consumed_kwh": 420
}

Each tier's up_to_kwh is the monthly consumption where it ends, either one number or twelve (January to December). The last tier has no limit. consumed_kwh is what the site has already used this billing month, so the first tier is partly used up. Tier prices must not decrease.

Time rules

Time rules select times of day, days and months. They are used by TOU schedules, comfort schedules, demand-charge windows and service windows.

Setting Type Default Meaning
months list of numbers or names every month [11, 12, 1, 2, 3, 4] or ["nov", "dec", "jan"]
days text or list "all" weekday, weekend, holiday, weekend_holiday, all, mon … sun, or a list of these
from, to clock time "00:00", "24:00" Local time, from inclusive, to exclusive. When to is before from the rule runs past midnight ("23:00" to "07:00"); when they are equal it covers the whole day
start_date, end_date date-time Limit the rule to a date range (local; end exclusive)

Holidays are their own kind of day. On a holiday, weekday does not match; holiday and weekend_holiday do. This is how the Ontario presets make holidays off-peak.

A rule that runs past midnight belongs to the day it starts: {"days": "weekday", "from": "21:00", "to": "07:00"} covers Friday night until Saturday 07:00, but not Sunday night.

Holidays

holidays Meaning
"none" No holidays (the default for your own tariffs)
"ontario" The Ontario Energy Board RPP holidays: New Year's Day, Family Day, Good Friday, Victoria Day, Canada Day, Civic Holiday, Labour Day, Thanksgiving, Christmas Day, Boxing Day. A holiday on a weekend moves to the next weekday that is not itself a holiday
["2026-12-24", "2026-12-31"] These dates only
{"calendar": "ontario", "add": ["2026-12-24"], "remove": ["2026-08-03"]} A calendar with changes

Critical peak

"critical_peak": [
  { "start": "2026-11-18T17:00", "end": "2026-11-18T19:00", "price": 0.9 },
  { "start": "2026-11-25T16:00", "end": "2026-11-25T20:00", "adder": 0.5 }
]

During an event the import price is replaced by price, or raised by adder. Steps partly inside an event are charged in proportion.

Demand charges

"demand_charges": [
  { "name": "monthly_peak", "rate": 9.85 },
  { "name": "on_peak_demand", "rate": 6.2, "window": { "days": "weekday", "from": "07:00", "to": "19:00" },
    "peak_so_far_kw": 182 }
]
Setting Type Default Meaning
rate number required Currency per kW of the highest import in the billing month (within the window)
window time rule or list all times When the peak counts
peak_so_far_kw number 0 The peak already set this billing month. Only what the horizon adds above it costs anything
name text demand_1, … For reports

The peak is the highest step-average import, so with 15-minute steps it is the 15-minute demand most utilities bill. A horizon that crosses into a new month gets a separate peak for each month; peak_so_far_kw applies to the first.

Tip

When the horizon is a small part of the billing month, the full monthly rate applies to the peak set in the horizon. That is right when the horizon is the rest of the month, and conservative when it is one day. Set peak_so_far_kw to the month's peak so far to avoid paying twice for the same peak.

Export

export Meaning
"none" Export earns nothing (the default). Surplus PV still flows to the grid, unpaid, unless the site is set to zero export (grid.allow_export: false)
{"type": "flat", "price": 0.05} A fixed price per exported kWh
"net_metering" (or "same_as_import") Export earns the import price of the same step
{"type": "series", "series": "export_price"} A price per step from a data series

When export can earn more than import costs in the same step, KERNEL adds binary variables so the site cannot import and export at once (see exclusive_import_export).

Adders and fixed charges

adder_per_kwh adds delivery, transmission, regulatory and similar per-kWh charges to every imported kWh. It shifts every price by the same amount, so it changes the bill but rarely the schedule (except against export prices and battery losses). fixed_per_day adds a fixed charge per day.

Presets

Preset What it is
ontario_tou Ontario RPP Time-of-Use
ontario_ulo Ontario RPP Ultra-Low Overnight
ontario_tiered Ontario RPP Tiered, residential
ontario_tiered_nonresidential Ontario RPP Tiered, non-residential
flat One price, 0.10 per kWh (set energy.price)

The Ontario presets carry the Ontario Energy Board's commodity prices effective 1 November 2026, in CAD per kWh, with the OEB holiday calendar. They do not include delivery or regulatory charges; add those with adder_per_kwh. Show any preset in full with cediskernel presets <name> (or cedis_kernel.tariff_preset(name)).

ontario_tou

Period Price Winter (Nov–Apr) weekdays Summer (May–Oct) weekdays
Off-peak 0.091 19:00–07:00 19:00–07:00
Mid-peak 0.146 11:00–17:00 07:00–11:00, 17:00–19:00
On-peak 0.189 07:00–11:00, 17:00–19:00 11:00–17:00

Weekends and holidays are off-peak all day.

ontario_ulo

Period Price When
Ultra-low overnight 0.037 23:00–07:00 every day
Weekend off-peak 0.091 07:00–23:00 weekends and holidays
Mid-peak 0.146 07:00–16:00 and 21:00–23:00 weekdays
On-peak 0.377 16:00–21:00 weekdays

ontario_tiered

Tier Price Monthly limit
Tier 1 0.112 1,000 kWh November–April, 600 kWh May–October (non-residential: 750 kWh all year)
Tier 2 0.132 above the limit

Set energy.consumed_kwh to the consumption so far this month.

Check

Prices change, normally on 1 November each year. Check the OEB's current prices before relying on a preset, and override energy.periods (or energy.tiers) when they change.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

Grid and PV

Grid connection

"grid": { "import_limit_kw": 20, "export_limit_kw": 10, "allow_export": true }
Setting Type Default Meaning
import_limit_kw number no limit Most the site may draw from the grid in any step (breaker, contract or transformer limit)
export_limit_kw number no limit Most the site may send to the grid
allow_export true/false true false means a zero-export site: surplus must be stored, used or curtailed

Import and export are separate, both zero or positive. What export earns is set by the tariff; without an export price it earns nothing but is still allowed, which is how surplus PV normally leaves a house.

An import limit below what the load needs (after batteries and PV) makes the problem infeasible, and KERNEL says so. Batteries, EVs and HVAC all count against the limits, so a limit is also a way to keep the EV and the heat pump from running at full power together.

PV

PV generation is the pv series in data, in kW (or with "unit": "W"):

"data": {
  "load": "load.csv",
  "pv": { "file": "pv.csv", "value": "pv_w", "unit": "W", "std_pct": 30 }
},
"pv": { "curtailable": true }
Setting Type Default Meaning
pv.curtailable true/false false Allow KERNEL to use less PV than is available: needed for zero-export sites, and useful when export prices go negative

PV is used on site first, then charges batteries or is exported, whichever is worth more. Results report pv_kw, and pv_used_kw when PV can be curtailed, plus pv_kwh and pv_curtailed_kwh in the summary.

For stochastic optimisation, give PV an uncertainty (std_pct, std, lower/upper or scenarios); PV scenarios are never below zero.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

Batteries

"batteries": [
  { "id": "home_battery", "capacity_kwh": 13.5, "power_kw": 5, "round_trip_eff": 0.9,
    "soc_init_pct": 50, "soc_min_pct": 10, "soc_max_pct": 100 }
]

Any number of batteries can be listed. Each has its own limits, efficiency and wear model, and KERNEL schedules them together.

Settings

Setting Type Default Meaning
id text battery_1, … Name used in the results (home_battery.power_kw)
capacity_kwh number required Usable energy capacity
power_kw number Charge and discharge limit, kW (the site side)
charge_max_kw, discharge_max_kw number power_kw Separate limits; give power_kw or these
round_trip_eff fraction Round-trip efficiency; split evenly between charging and discharging (√0.9 each for 0.9)
efficiency fraction One-way efficiency used for both directions
charge_eff, discharge_eff fraction 0.95 Separate one-way efficiencies
soc_init_pct percent 50 State of charge at the start
soc_min_pct, soc_max_pct percent 10, 90 Allowed range
self_discharge_pct_per_day percent 0 Energy lost per day while stored
terminal see below "at_least_initial" What the battery must hold at the end
wear object off Battery wear model, see below
services true/false true May provide ancillary services

Energy accounting: charging c kW for one hour stores c × ηc kWh, and taking out d kW for one hour removes d / ηd kWh. Power in the results is at the site's meter: positive when charging.

End of the horizon

terminal Meaning
"at_least_initial" End with at least the starting state of charge (the default). Savings then never borrow energy from after the horizon
"free" End anywhere within the allowed range. The battery will usually end empty, because stored energy has no value after the horizon
{"soc_min_pct": 80} End with at least 80 %

Battery wear

Each battery has its own wear model, switched on or off with wear.model. With wear off, cycling is free apart from its losses, and a battery will do anything that saves a cent. With wear on, every kWh cycled has a cost, so the battery only works when the saving is worth the wear.

wear.model Cost
"off" (default) None. The results can still estimate fade if you give cycle_life
"throughput" A cost per kWh discharged
"cycle_depth" A cost that rises with the depth of each cycle: shallow cycles are cheap, deep ones expensive
Setting Type Default Meaning
model text "off" As above
replacement_cost currency 0 What it costs to replace the battery. Required for cycle_depth, or for throughput without cost_per_kwh
cycle_life number 5000 Full (100 % depth) cycles to end of life
cost_per_kwh number replacement_cost / (cycle_life × capacity_kwh) Throughput model: cost per kWh discharged
dod_exponent number, 0.5–4 1.5 Cycle-depth model: cycle life ∝ depth−k. Larger means deep cycles wear much more
segments integer, 1–50 8 Cycle-depth model: number of depth bands in the piecewise-linear cost
end_of_life_pct percent 80 Remaining capacity at end of life
calendar object Calendar ageing, see below
"wear": {
  "model": "cycle_depth",
  "replacement_cost": 12000,
  "cycle_life": 6000,
  "dod_exponent": 1.3,
  "calendar": { "fade_pct_per_year": 2.0, "at_soc_pct": 50, "fade_pct_per_year_at_full": 2.5 }
}

Throughput

The simplest model: every kWh discharged costs cost_per_kwh. With a 12,000 replacement cost, 6,000 cycles and 13.5 kWh, that is 12000 / (6000 × 13.5) = 0.148 per kWh, so the battery will not cycle for a price spread smaller than that (plus its losses).

Cycle depth

Battery life depends on how deep the cycles are. With cycle life N(δ) = N100 × δ−k for depth δ, a cycle of depth δ uses up δk / N100 of the battery's life. KERNEL divides the state-of-charge range into segments bands and charges each kWh taken from a deeper band at a higher price, which is the piecewise-linear form of this curve (Xu et al., IEEE Transactions on Power Systems, 2018). Shallow cycles near the top are cheap; draining the battery to the bottom is expensive.

Calendar ageing

Batteries also age while they sit, faster when kept full:

Setting Default Meaning
fade_pct_per_year 2.0 Capacity fade per year at at_soc_pct
at_soc_pct 50 The state of charge that rate applies to
fade_pct_per_year_at_full fade_pct_per_year Fade per year at 100 %

Between the two points the fade rate is linear in the state of charge. With a replacement_cost, the fade is priced into the optimisation (so the battery prefers not to sit full) and into the baseline, where the idle battery ages at its starting state of charge.

What the results report

Metric Meaning
wear_cost The wear cost in the objective (summary)
battery.<id>.cycles Equivalent full cycles
battery.<id>.cycle_fade_pct Capacity lost to cycling, by rainflow counting of the state-of-charge path
battery.<id>.calendar_fade_pct Capacity lost to calendar ageing over the horizon

The rainflow estimate is reported whenever wear parameters are given, even with "model": "off", so you can compare schedules with and without a wear cost.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

EV charging

An EV is a battery that is only there part of the time and has to reach a target before it leaves. KERNEL decides when, and how fast, each car charges during each plug-in session, and can discharge it to the site (vehicle-to-grid) if you allow it.

"evs": [
  { "id": "car", "battery_kwh": 75, "charge_max_kw": 7.2, "charge_eff": 0.92,
    "sessions": [
      { "arrival": "2026-11-16T18:00", "departure": "2026-11-17T07:30", "soc_arrival_pct": 35, "soc_target_pct": 80 },
      { "arrival": "2026-11-17T17:30", "departure": "2026-11-18T07:30", "energy_kwh": 20 }
    ] }
]

Settings

Setting Type Default Meaning
id text ev_1, … Name used in the results (car.power_kw)
charge_max_kw number required Charger (or car) limit
charge_min_kw number 0 When charging, at least this much (some chargers cannot go lower than 6 A); adds on/off variables
charge_eff fraction 0.9 Share of the power drawn that reaches the battery
battery_kwh number unknown Battery size; needed for state-of-charge targets and V2G
sessions list or file required When the car is plugged in and what it needs, see below
v2g object off Vehicle-to-grid, see below
shortfall_penalty_per_kwh number 10 × the highest price Cost of each kWh the car leaves without
must_meet true/false false Make the target a hard limit: no shortfall allowed (the problem is infeasible if it cannot be met)
services true/false true May provide ancillary services while plugged in

Sessions

Each session gives an arrival and a departure, and what the car needs, in one of two ways:

Way Settings Meaning
Energy energy_kwh Deliver this many kWh into the battery during the session
State of charge soc_arrival_pct, soc_target_pct The car arrives with this charge and must leave with at least that one. Needs battery_kwh

Times without an offset use the horizon's offset. A session partly outside the horizon is clipped to it, and its need is pro-rated to the part inside (with a warning). Sessions of one car must not overlap.

Sessions from a forecast

"sessions": { "forecast": "ev.json" }

The car's sessions over the horizon are the sessions a forecasting model expects from the car's past sessions: typical arrival and departure times and the typical energy, by day type. The file is a model file or a training configuration; see EV charging forecasts.

Sessions from a file

"sessions": { "file": "sessions.csv" }
ev,arrival,departure,soc_arrival_pct,soc_target_pct
car,2026-11-16T18:00,2026-11-17T07:30,35,80
car,2026-11-17T17:30,2026-11-18T07:30,50,80
van,2026-11-16T19:00,2026-11-17T06:00,,

The file (CSV, Excel with "sheet", or JSON) needs arrival and departure columns, plus energy_kwh or the two state-of-charge columns. With an ev column, each EV takes only its own rows, so one file can serve a whole fleet.

Shortfall

If a car cannot get what it needs (it arrives late, the charger is too small, the import limit is too tight), KERNEL charges it as much as is worth doing and reports the shortfall rather than failing. Each kWh missing costs shortfall_penalty_per_kwh; the default, ten times the highest energy price, makes meeting the need always worth it when it is possible. KERNEL also warns before solving when a session cannot physically be met:

warning: EV car #1 needs 40 kWh but can take at most 32.4 kWh while plugged in; the shortfall will be reported

With "must_meet": true there is no shortfall: either every session is met or the problem is infeasible.

Vehicle-to-grid

"v2g": { "enabled": true, "discharge_max_kw": 7.2, "discharge_eff": 0.9, "soc_min_pct": 30 }
Setting Type Default Meaning
enabled true/false true V2G on
discharge_max_kw number charge_max_kw Discharge limit
discharge_eff fraction 0.9 Share of the energy taken from the battery that reaches the site
soc_min_pct percent 20 V2G never takes the car below this charge (or its arrival charge, if lower)

V2G needs battery_kwh and state-of-charge sessions. The car still leaves with its target; in between, it can supply the site when that saves money.

Results

Series Meaning
<id>.power_kw Charging power at the charger (negative when discharging with V2G)
<id>.energy_kwh Energy in the battery (relative to empty for energy sessions); empty while the car is away
<id>.plugged Share of each step the car is plugged in (0 to 1)

The EV sessions table lists every session with its need, the energy delivered and any shortfall. The summary has ev_energy_kwh, ev_shortfall_kwh and their baseline values; in the baseline every car charges at full power from the moment it arrives.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

HVAC

KERNEL schedules heating and cooling against a thermal model of the building, so it can pre-heat or pre-cool before expensive hours and let the temperature drift within the comfort band when prices are high.

"hvac": [
  { "id": "heat_pump",
    "thermal": { "ua_kw_per_c": 0.25, "capacitance_kwh_per_c": 3.0 },
    "initial_c": 21,
    "heating": { "max_kw": 4.0, "cop": { "a": 2.8, "b": 0.05, "min": 1.5 } },
    "cooling": { "max_kw": 3.0, "cop": 3.2 },
    "comfort": { "min_c": 18, "max_c": 24,
                 "schedule": [ { "days": "all", "from": "06:30", "to": "22:00", "min_c": 20.5, "max_c": 23 } ] } }
]

The building model

Each unit serves one thermal zone, modelled as one thermal resistance and one heat capacity (a 1R1C model):

C dT/dt = (T_out − T) / R + COP_heat × P_heat − COP_cool × P_cool + gains
Symbol Setting Meaning
R thermal.resistance_c_per_kw, or 1 / thermal.ua_kw_per_c How well the zone is insulated: °C of temperature difference per kW of heat loss. ua_kw_per_c is the heat loss per °C (the inverse)
C thermal.capacitance_kwh_per_c Heat needed to warm the zone by 1 °C, kWh/°C
T_out outdoor or data.outdoor_temperature Outdoor temperature, °C
gains gains_kw Internal and solar heat gains, kW of heat

KERNEL integrates this equation exactly over each step (with the step's average outdoor temperature and power), so the result does not depend on the step length. Time constant τ = R × C; with R = 4 °C/kW and C = 3 kWh/°C the zone cools by 63 % of its difference with the outside in 12 hours.

Finding R and C. From a heat-loss calculation: UA (kW/°C) is the design heat loss divided by the design temperature difference. C is roughly 0.03 to 0.1 kWh/°C per m² of floor for houses (light to heavy construction). Or let KERNEL fit them from a few weeks of metered HVAC power, indoor and outdoor temperature (HVAC forecasts), and use the fit directly:

"thermal": { "model": "hvac.json" }

R, C and the gains then come from the fitted model (a model file, or a training configuration trained when the site is read). Any of them can still be set to override the fit, e.g. {"model": "hvac.model.json", "capacitance_kwh_per_c": 4}.

Settings

Setting Type Default Meaning
id text hvac_1, … Name used in the results
thermal object required capacitance_kwh_per_c, and resistance_c_per_kw or ua_kw_per_c; or model, a fitted thermal model
initial_c number 21 Indoor temperature at the start
outdoor number or series name "outdoor_temperature" Outdoor temperature: a constant, or a data series
heating object max_kw (electrical) and cop
cooling object max_kw (electrical) and cop
comfort object required Comfort band, see below
gains_kw number or series name 0 (the fitted gains with thermal.model) Heat gains into the zone (people, appliances, sun), kW of heat
on_off true/false false The unit runs at full power or not at all (a fixed-speed unit). Adds binary variables
services true/false false May provide ancillary services by changing its power

A unit needs heating, cooling, or both.

Efficiency (COP)

cop is how many kW of heat (or cooling) one kW of electricity gives:

cop Meaning
3.2 Constant
"cop_heat" A data series
{"a": 2.8, "b": 0.05, "min": 1.5} Linear in the outdoor temperature: a + b × T_out, never below min (default 1). A heat pump at −15 °C with these numbers has COP 2.05; at 5 °C, 3.05

Electric resistance heating has COP 1.

Comfort

Setting Type Meaning
min_c, max_c number The band at all times not covered by the schedule
schedule list of time rules with min_c and max_c Bands for particular times; the first matching rule wins
penalty_per_c_h number Cost per °C·h outside the band. Default: effectively a hard limit (1000 × the highest energy price)

The band applies to the temperature at the end of each step. With a soft penalty, KERNEL may let the temperature leave the band when keeping it would cost more than the penalty; the results report the violation in °C·h.

On/off units

With "on_off": true each step is either off or at max_kw. This suits fixed-speed equipment, and needs a mixed-integer solve. Modulating (inverter) units should leave it false: the problem stays linear and solves in a fraction of the time.

Note

On a flat price an on/off unit has many equally cheap schedules, and proving which is optimal can take the solver a long time. KERNEL adds a cut that closes most of this gap, but if the solver reaches time_limit_s, the result is feasible and marked status: time_limit with the remaining gap. Prices that vary in time, a shorter horizon, or a modulating model avoid it.

Results

Series Meaning
<id>.power_kw Electrical power, heating plus cooling
<id>.indoor_c Indoor temperature at the end of each step
<id>.comfort_min_c, <id>.comfort_max_c The band

The summary has hvac_energy_kwh, comfort_violation_ch and baseline_comfort_violation_ch. The baseline is a plain thermostat that heats or cools only when the zone would otherwise leave the band.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

Ancillary services

Batteries, EVs and HVAC can earn money by keeping capacity in reserve for the grid operator or an aggregator, as well as by saving on the bill. KERNEL decides, for every step, how many kW to offer in each product, and keeps enough power and energy in reserve to deliver it.

Markets differ, so products are configurable: four common products are built in, and you can define any number of your own.

"services": {
  "regulation_up":   { "capacity_price": 0.012, "deployment": 0.1 },
  "regulation_down": { "capacity_price": 0.010, "deployment": 0.1 },
  "products": [
    { "name": "frequency_response", "direction": "symmetric", "capacity_price": 0.012,
      "deployment": 0.05, "duration_h": 0.5, "max_kw": 100 }
  ],
  "demand_response": [
    { "name": "evening_event", "type": "payment", "start": "2026-11-17T17:00", "end": "2026-11-17T19:00",
      "price_per_kwh": 0.5 }
  ]
}

Products

A product is up (the site can reduce its draw or supply more when called: discharging, charging less, heating less), down (the site can increase its draw: charging, heating more) or symmetric (one offer that must be available both ways).

Built-in products

Key Direction duration_h default
regulation_up up 0.25
regulation_down down 0.25
spinning_reserve up 1
non_spinning_reserve up 1

A built-in product is used when its key is present. Set "symmetric_regulation": true to require equal regulation up and down offers.

Your own products

services.products is a list; each item takes name and direction ("up", "down" or "symmetric") plus the settings below. A symmetric product appears in the results as two halves, <name>_up and <name>_down, with equal offers; its capacity price is paid once.

Product settings

Setting Type Default Meaning
capacity_price series required Paid per kW offered, per hour
energy_price series 0 Paid per kWh actually delivered when called
price_unit per_kw_h, per_mw_h per_kw_h Unit of both prices: per kW-hour (kWh) or per MW-hour (MWh)
deployment fraction 0 Expected share of the offer that is called. It is paid at energy_price, and its energy flows through the batteries
duration_h number see above; 1 for your own How long the offer must be sustainable: energy is kept in reserve for this many hours at the full offer
min_kw, max_kw number 0, no limit Offer limits per step. With min_kw, each step offers zero or at least min_kw
window time rule or list all times When the product can be offered
providers list ["batteries"] Which devices may provide it: "batteries", "evs", "hvac"
enabled true/false true Switch the product off without deleting it

A capacity price series (for example "capacity_price": "reg_up_price" with a reg_up_price series in data) lets the price change every step.

What an offer requires

For each step, KERNEL makes sure the offer could really be delivered:

  • Batteries, up: the offer fits in the room between the current power and full discharge, and the battery holds enough energy to deliver it for duration_h without going below its minimum. Down: the same against full charge and the maximum.
  • EVs (while plugged in), up: no more than the current charging power, plus the V2G discharge limit. Down: no more than the room up to full charging power.
  • HVAC (with "services": true), up: no more than its current power. Down: no more than the room up to its maximum.

A device can take part in several products at once; the sum of its offers in one direction must fit. Each device's services setting can opt it out.

In stochastic mode the offers are the same in every scenario: the market needs one offer.

Demand response events

Events are periods when the site is asked to reduce its demand.

type Settings Meaning
"payment" price_per_kwh Paid for every kWh the site's net import is below its baseline during the event
"commitment" reduce_kw, penalty_per_kwh The site has committed to be reduce_kw below its baseline; each kWh short costs the penalty
"cap" limit_kw, penalty_per_kwh Import must stay under limit_kw; each kWh above costs the penalty
Setting Type Default Meaning
name text event_1, … Name in the results
start, end date-time required The event
baseline_kw number the site's net demand without optimisation The reference the reduction is measured against
penalty_per_kwh number 10 × the highest energy price For commitment and cap

Results

Where Name Meaning
series <product>_kw The offer in each step
series dr.<event>.reduction_kw / dr.<event>.shortfall_kw Reduction below the baseline (payment) or shortfall against the commitment or cap
summary service_revenue Capacity and expected energy payments
summary dr_revenue, dr_penalty Demand-response payments and penalties
summary <product>_kwh Offer summed over the horizon (kW × h)

In examples/sites/office_stochastic/ a 500 kWh battery earns 18.24 CAD a day from a symmetric frequency-response product and 155.49 CAD from a two-hour demand-response event, on top of its tariff savings.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

Optimisation

"optimization": {
  "mode": "stochastic",
  "solver": "highs",
  "time_limit_s": 120,
  "stochastic": { "scenarios": 7, "method": "quantiles", "commit_hours": 1, "risk_weight": 0.2 }
}

Deterministic or stochastic

mode Meaning
"deterministic" (default) The data are taken as exact. One schedule
"stochastic" Series with an uncertainty (see Uncertainty) are expanded into scenarios, and one plan is found that works across all of them

Use deterministic when forecasts are good or when you re-plan often with fresh data. Use stochastic when the forecast error matters: a demand charge that a surprise peak could set, an EV that must be charged whatever happens, PV that may or may not come.

Solver settings

Setting Type Default Meaning
solver text "highs" "highs", "scip", "gurobi" or "cplex", see Solvers
solver_library path searched Gurobi or CPLEX: the solver's shared library, if it is not found automatically
solver_params object Solver parameters by their own names, passed through
time_limit_s number 300 Stop after this many seconds and return the best schedule found
mip_gap fraction 0.0001 Stop when the schedule is proven within this share of the optimum (problems with integer variables)
threads integer 1 Solver threads; 0 lets the solver decide. One thread gives the same result on every run
tie_break "smooth", "none" "smooth" Among equally cheap schedules, return the smoothest (details)
exclusive_charge_discharge true, false, "auto" "auto" Forbid a battery from charging and discharging in the same step. auto: only when prices can be negative, where doing both would otherwise burn energy for money
exclusive_import_export true, false, "auto" "auto" Forbid importing and exporting in the same step. auto: only when export can be worth more than import

When the problem is mixed-integer

The model is a linear program (fast, solved to proven optimality) unless something needs on/off decisions:

Setting Adds integer variables
hvac[].on_off: true one per unit per step
evs[].charge_min_kw > 0 one per car per step while plugged in
a service product with min_kw one per product per step
exclusive_charge_discharge / exclusive_import_export in effect one per battery (or the grid) per step

Mixed-integer problems are solved by branch and bound and stop at mip_gap or time_limit_s. The result's status is "optimal" when the gap was reached and "time_limit" otherwise, with mip_gap in the summary and a warning.

Solvers

Solver Included Solves Licence
HiGHS always LP, MIP and the tie-break QP MIT, free
SCIP (with SoPlex) when built with KERNEL_WITH_SCIP=ON, the default LP and MIP Apache 2.0, free
Gurobi loaded at run time if installed LP and MIP commercial; needs a Gurobi licence
CPLEX loaded at run time if installed LP and MIP commercial; needs a CPLEX licence

HiGHS is the default and solves every problem KERNEL builds well. SCIP is a second open-source choice for hard mixed-integer cases. Gurobi and CPLEX are for users who already have them; they are never shipped with KERNEL. The smooth tie-break always uses HiGHS, whichever solver found the cost.

List what this installation can use:

$ cediskernel solvers
  highs    available (bundled, 1.15.1)
  scip     available (bundled, 10.1.0)
  gurobi   not found (set GUROBI_HOME or KERNEL_GUROBI_LIBRARY)
  cplex    not found (set CPLEX_STUDIO_DIR<version> or KERNEL_CPLEX_LIBRARY)

(cedis_kernel.solver_info(), Kernel.solverInfo() and kernel_solver_info() give the same list.)

How Gurobi and CPLEX are found

Solver Looked for in this order
Gurobi solver_library; the KERNEL_GUROBI_LIBRARY environment variable; $GUROBI_HOME/lib (Linux) or %GUROBI_HOME%\bin (Windows); the system library path. Versions 13.1 back to 9.5
CPLEX solver_library; KERNEL_CPLEX_LIBRARY; the CPLEX_STUDIO_DIR<version> folders the CPLEX installer sets (22.1.2 back to 12.10); the system library path

The licence is checked when solving. A missing or expired licence gives a solver error that says so; nothing else changes.

Solver parameters

solver_params passes parameters to the solver by the solver's own names. Numbers, text and true/false are accepted; unknown names are an error.

"solver_params": { "presolve": "off", "mip_rel_gap": 1e-6 }              // HiGHS
"solver_params": { "limits/nodes": 100000, "presolving/maxrounds": 5 }  // SCIP
"solver_params": { "MIPFocus": 1, "FeasibilityTol": 1e-7 }               // Gurobi
"solver_params": { "CPXPARAM_MIP_Strategy_Search": 1 }                   // CPLEX

Stochastic optimisation

With "mode": "stochastic", every series that has an uncertainty becomes a set of scenarios: possible versions of the future, each with a probability. KERNEL then finds one plan for all of them at once.

Scenario tree with a common first stage The decisions for the commitment period are shared by all scenarios; after it each scenario has its own decisions. committedsame in every scenario p₁p₂p₃p₄p₅ each scenario adapts after the commitment period
The first `commit_hours` of device decisions are shared by all scenarios: they are what you would actually do now. Later decisions may differ between scenarios, as they would once you learn which future is happening.

Settings

Setting (under stochastic) Type Default Meaning
scenarios integer, 1–500 5 Number of scenarios (for quantiles and sampled)
method text "quantiles" How scenarios are made, see below
probabilities list equal Scenario probabilities (normalised to 1)
correlation number, −1–1 0.9 sampled: step-to-step correlation of the forecast error
seed integer 42 sampled: random seed. The same seed gives the same scenarios on every platform
commit_hours number one step How long the shared first stage lasts
risk_weight fraction 0 Weight on the cost of the bad scenarios, see Risk
cvar_alpha fraction 0.95 Which tail counts as bad: the worst 1 − α of outcomes

How scenarios are made

method Scenarios
"quantiles" Scenario k of K is the (k − ½)/K quantile of every uncertain series, at every step: a low, middle and high version of the forecast. Deterministic, and good with few scenarios
"sampled" Random paths: the forecast plus a normal error that is correlated from step to step (an AR(1) process with correlation). More realistic shapes; needs more scenarios
"provided" Scenarios you give, as scenarios columns or lists in the data (every uncertain series with the same number)

Series without an uncertainty are the same in every scenario. PV scenarios are never negative.

A forecast series has quantiles rather than a standard deviation. Its scenarios are read from the quantiles directly: quantiles takes level (k − ½)/K, interpolated between the forecast levels (and held at the outer ones beyond them); sampled turns each correlated normal error into a level the same way. The forecast's own shape of uncertainty (for example, PV that can only fall short of clear sky) is kept.

What is shared and what is not

Shared by all scenarios: device decisions in the first commit_hours (battery, EV and HVAC power) and every service offer (the market needs one offer). Each scenario has its own later decisions, grid flows and peaks.

The summary gives expected values (probability-weighted means), and the series are expected values too. Also reported: cost_min, cost_max, cost_var and cost_cvar (the value-at-risk and conditional value-at-risk of the total cost at cvar_alpha), and a Scenarios table with each scenario's probability and main figures. Set "output": {"scenario_series": true} to write every scenario's schedule as well.

Risk

With risk_weight λ, KERNEL minimises

(1 − λ) × expected cost + λ × CVaR_α(cost)

CVaRα is the average cost over the worst 1 − α of outcomes. λ = 0 minimises the average; larger λ pays a little more on average to make bad outcomes less bad (for example, keeping more battery in reserve before a possible demand peak).

Re-planning

A stochastic plan is meant to be used for its first commit_hours, then recomputed with new data. That is the rolling-horizon pattern: solve, apply the committed decisions, move the horizon forward, solve again.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

Results

A solve returns a result: the schedule as time series, a summary of costs and energy, tables per device, EV session and scenario, and any warnings. You can read it in code or write it to CSV, Excel or JSON.

Output settings

"output": { "step": "1h", "format": "json", "path": "results", "timestamps": "local_offset" }
Setting Type Default Meaning
step duration the model step (15 minutes by default) Step of the written and returned series. Any step that divides the horizon
format csv, xlsx, json "csv" Format used when a path has no extension, or when no path is given
path path Where results go when the caller gives no path (cediskernel solve site.json without -o, result.write() without arguments). Relative to the configuration file
timestamps local_offset, local, utc local_offset when offsets are known, else local How times are written: 2026-11-16T18:00:00-05:00, 2026-11-16T18:00:00 or 2026-11-16T23:00:00Z
scenario_series true/false false Stochastic: also write every scenario's schedule

How series are converted to the output step is described in Concepts.

Status

status Meaning
optimal The cost is proven optimal (within mip_gap for mixed-integer problems)
ok A forecast or evaluation ("kind": "forecast" in JSON)
time_limit The solver stopped at time_limit_s with a feasible schedule that may not be optimal; mip_gap says how far it may be, and a warning is added

A problem that has no feasible schedule, or for which the solver found none in time, raises an error instead of returning a result.

Series

One value per output step. Names with a device id start with it.

Series Unit Meaning
load_kw kW Site load
pv_kw, pv_used_kw kW PV available; PV used (when curtailable)
grid_import_kw, grid_export_kw kW Grid flows, each ≥ 0
net_grid_kw kW Import − export
price, export_price per kWh Import price (including adders and critical peak); export price
<battery>.power_kw kW + charging, − discharging
<battery>.soc_pct % State of charge at the end of the step
<ev>.power_kw, <ev>.energy_kwh, <ev>.plugged kW, kWh, 0–1 See EV charging
<hvac>.power_kw, <hvac>.indoor_c, <hvac>.comfort_min_c, <hvac>.comfort_max_c kW, °C See HVAC
<product>_kw kW Ancillary-service offer
dr.<event>.reduction_kw, dr.<event>.shortfall_kw kW Demand-response events

Values that do not exist at a time (an EV's energy while it is away) are empty in CSV and Excel, null in JSON and NaN in code.

Summary

Metric Meaning
total_cost The cost KERNEL minimised: energy − export credit + demand + fixed + wear + penalties − revenues
baseline_total_cost The same for the site without optimisation (Concepts)
savings, savings_pct Baseline − total, and as a percentage of the baseline
energy_cost, export_credit, demand_cost, fixed_cost Tariff terms (each with a baseline_ version)
wear_cost, baseline_wear_cost Battery wear
service_revenue, dr_revenue, dr_penalty Ancillary services and demand response
ev_shortfall_penalty, comfort_penalty Penalties for unmet EV energy and comfort
peak_kw, baseline_peak_kw Highest import
import_kwh, export_kwh, load_kwh, pv_kwh, pv_curtailed_kwh Energy totals
battery_charged_kwh, battery_discharged_kwh, battery_losses_kwh All batteries
ev_energy_kwh, ev_shortfall_kwh, baseline_ev_shortfall_kwh All EVs
hvac_energy_kwh, comfort_violation_ch, baseline_comfort_violation_ch All HVAC units
<product>_kwh Service offers summed over the horizon
objective, mip_gap, solve_time_s, variables, constraints, integer_variables, scenarios, smoothed About the solve
cost_min, cost_max, cost_var, cost_cvar, cvar_alpha Stochastic only

Costs are in the tariff's currency, energies in kWh. units gives the unit of every metric.

Tables

Table Columns
Devices device, type, metric, value, unit: per-device figures such as charged_kwh, cycles, cycle_fade_pct, calendar_fade_pct, energy_kwh, shortfall_kwh, comfort_violation_ch
EV sessions ev, session, arrival, departure, need_kwh, delivered_kwh, shortfall_kwh, prorated
Scenarios scenario, probability, total_cost, energy_cost, demand_cost, peak_kw, battery_discharged_kwh, ev_shortfall_kwh (stochastic only)
Warnings One row per warning
Forecasts ev_sessions (expected sessions: arrival, departure, energy_kwh, energy_kwh_p90, probability, …), thermal_model (parameter, value, unit), and for evaluations metrics and by_lead; see Forecasting

Files

The format follows the path's extension, or format:

Path Written
results.xlsx One workbook with sheets Schedule, Summary, Devices, EV sessions, Scenarios, Scenario 1 … (with scenario_series), Warnings; only the sheets that have content. Times are real Excel date-times, with the UTC offset in a column next to them
results.json One JSON document, below
results.csv The schedule in results.csv, plus results_summary.csv, results_devices.csv, results_ev_sessions.csv, results_scenarios.csv, results_warnings.csv as present
results (a folder) with --format csv or "format": "csv" schedule.csv, summary.csv, devices.csv, … in that folder

JSON layout

{
  "status": "optimal",
  "solver": "highs",
  "currency": "CAD",
  "step_s": 3600,
  "timestamps": ["2026-11-17T00:00:00-05:00", "2026-11-17T01:00:00-05:00", …],
  "series": { "load_kw": [61.17, 59.9, …], "bess.power_kw": [28.28, 28.28, …], … },
  "summary": { "total_cost": 584.27, "baseline_total_cost": 872.3, "savings": 288.03, … },
  "units": { "total_cost": "CAD", "peak_kw": "kW", … },
  "devices": [ { "device": "bess", "type": "battery", "metric": "cycles", "value": 0.891, "unit": "" }, … ],
  "ev_sessions": [],
  "scenarios": [ { "scenario": 1, "probability": 0.2, "total_cost": 534.23, … }, … ],
  "warnings": []
}

(Shortened: … marks values left out. This is examples/sites/office_stochastic written with -o results.json.)

A result JSON file can be read back as a data file, for example to use one run's grid import as another run's load.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

Forecasting

KERNEL can learn from a site's past data and predict the next hours or days: the building's demand, PV generation, EV charging and the HVAC load. Every forecast comes with a range (for example, "between 3.1 and 3.6 kW, most likely 3.3 kW"), and each model reports how accurate it was on recent days it had not seen.

You describe what to forecast in a small JSON file, the same way you describe a site:

{
  "target": "demand",
  "history": { "file": "data/demand.csv", "value": "load_kw" },
  "features": { "temperature": { "file": "data/weather.csv", "value": "temperature_c" } },
  "holidays": "ontario",
  "horizon": "48h",
  "forecast": { "start": "2026-11-16T00:00-05:00" }
}
$ cediskernel forecast demand.json -o load.csv
method: gbm
  energy_kwh                           165.7665 kWh
  peak_kw                                4.9334 kW
  energy_kwh_p10                       156.1463 kWh
  energy_kwh_p90                       174.5189 kWh
  validation_mae                         0.1728 kW
  validation_wape                        6.4950 %
  validation_crps                        0.1165 kW
  validation_coverage_80                80.0881 %
  ...
written: load.csv
timestamp,load,load.p10,load.p25,load.p50,load.p75,load.p90
2026-11-16T00:00:00-05:00,3.368474,3.142941,3.232816,3.332747,3.447563,3.531974
2026-11-16T00:15:00-05:00,3.462308,3.21942,3.322204,3.426152,3.543189,3.627741

load is the forecast; load.p10 … load.p90 are its quantiles: the actual value should be below load.p10 one time in ten, and below load.p90 nine times in ten. The validation_ figures score the forecasts for the last 15 days of the history, made by a model trained only on the days before them (Metrics explains each one). The final model is then trained on all the history.

The examples in examples/forecasting forecast a house in Ottawa: demand, PV, EV and heat pump, then schedule the site with the forecasts.

Train once, forecast many times

Training takes seconds to a minute. For a forecast every day, train once, save the model file, and forecast from it with fresh data:

$ cediskernel train demand.json -m load.model.json
$ cediskernel forecast load.model.json --start 2026-11-17T00:00-05:00 --request today.json -o load.csv
import cedis_kernel as ck

model = ck.train("demand.json")
model.save("load.model.json")
print(model.validation["mae"], model.validation["coverage_80"])

model = ck.load_model("load.model.json")
r = model.forecast(start="2026-11-17T00:00-05:00", horizon="24h",
                   history="meter_last_week.csv",                    # recent values
                   features={"temperature": "weather_forecast.csv"})  # values for the forecast period
df = r.to_pandas()                     # load, load.p10, ..., load.p90

The model file is JSON and holds everything needed to forecast, including the last 21 days of history. Pass recent values (history) when you forecast more than a day or two after the end of the training data; KERNEL warns when the latest known value is more than two days before the start. Retrain every few weeks, or when the site changes.

Java, C++ and C have the same operations: Java, C++, C.

Settings

Setting Type Default Meaning
target demand, pv, ev, hvac demand What is forecast; see Targets
history series required (except EV) Past values, in kW; any series settings
features object none Other inputs by name, e.g. temperature or cloud cover; see Features
method gbm, kernel1, linear, seasonal_naive, auto gbm How the model is built; see Methods
step duration 15min Forecast step; must divide one hour
horizon duration 24h How far ahead, up to 14 days
issue_time time of day "00:00" When forecasts are usually made. Training and validation use forecasts made at this time each day
quantiles list [0.1, 0.25, 0.5, 0.75, 0.9] Quantile levels to forecast (0.5 is always added)
holidays preset, list or "none" "none" Holidays, as for tariffs: "ontario", or a list of dates
location {latitude, longitude} none Site location; PV uses it for the sun's position and night-time zeros
capacity_kw number none PV: system size, for errors as a share of capacity
nonnegative true/false from the history Clip forecasts at zero (automatic when the history has no negative values)
utc_offset "-05:00" from the data Offset of times written without one
validation duration 20 % of the history (7 to 56 days) Days held out at the end of the history to score and calibrate the model
refit true/false true After validation, train again on all the history
calibrate true/false true Adjust the quantiles so they cover what they should on the validation days
seed integer 42 Random seed; the same data and seed give the same model on every platform
name text load, pv, ev, hvac Name of the forecast series
ev, thermal object Target-specific settings, below
options object Method settings for specialists; see Options
forecast object The forecast request, for cediskernel forecast on a training file; see Forecast request
evaluation object {"test": "28d", "methods": [...]} for cediskernel evaluate; see Evaluation
output object CSV path, format (csv, xlsx, json), step, timestamps, as for results

Times, units and file formats are read exactly as for a site (Time and data). Missing intervals in the history are skipped in training, and short gaps (up to three steps) are filled by interpolation. KERNEL warns about missing data, and about a meter that repeats the same value for two days or more (usually an outage, which would teach the model the wrong thing).

Targets

Demand

The building's electricity use. Demand depends mostly on the time of day, the day of the week, holidays and the weather, so give the holidays and the outdoor temperature when you have them.

PV

Generation of a solar system. Give the location: the model then knows where the sun is at every step, how much a clear sky would give, and that there is nothing at night. Cloud cover, irradiance or temperature forecasts help most:

{
  "target": "pv",
  "history": { "file": "data/pv.csv", "value": "pv_kw" },
  "features": { "cloud": { "file": "data/weather.csv", "value": "cloud_pct" } },
  "location": { "latitude": 45.42, "longitude": -75.70 },
  "capacity_kw": 6
}

With a location, night-time steps (sun below the horizon) are forecast as zero and left out of the scores, since any model gets them right.

EV charging

From a list of past charging sessions, KERNEL learns when cars plug in, how long they stay and how much energy they take, separately for weekdays and for weekends and holidays. It forecasts both the sessions (for the scheduler) and the charging load the site would see if cars charged at full power as soon as they plug in (for the site's baseline).

{
  "target": "ev",
  "ev": { "sessions": "data/ev_sessions.csv", "charge_kw": 7.2, "efficiency": 0.9 },
  "holidays": "ontario"
}
arrival,departure,energy_kwh
2026-09-01T17:19-04:00,2026-09-02T07:50-04:00,9.39
2026-09-02T16:42-04:00,2026-09-03T07:31-04:00,10.58
Setting under ev Default Meaning
sessions required Past sessions: a file or list with arrival, departure and energy_kwh
charge_kw 7.2 Charger power, for the uncontrolled charging load
efficiency 0.9 Share of the power drawn that reaches the battery
threshold 0.5 Predict a session on a day when at least this share of similar days had one

A history of the charger's power can be given as well; without one, the load is built from the sessions. The forecast lists the expected sessions:

expected EV sessions:
  2026-11-16T17:34:00-05:00 -> 2026-11-17T07:49:00-05:00  12.22 kWh (p = 0.90)

Each session gets the typical arrival time, stay and energy of its day type, and p is the share of similar days on which a car plugged in. For several sessions a day (a workplace), the sessions spread over the typical arrival times.

HVAC

The electric load of a heat pump, furnace fan or air conditioner. Give the outdoor temperature as a feature (named outdoor_temperature or temperature). With the indoor temperature as well, KERNEL also fits the building's thermal model: the resistance R, the capacitance C and the internal heat gains.

{
  "target": "hvac",
  "history": { "file": "data/hvac.csv", "value": "hvac_kw" },
  "features": { "outdoor_temperature": { "file": "data/weather.csv", "value": "temperature_c" } },
  "thermal": { "indoor": { "file": "data/hvac.csv", "value": "indoor_c" }, "mode": "heating", "cop": 3.0 }
}
thermal model:
  resistance_c_per_kw                    3.9932 degC/kW
  capacitance_kwh_per_c                  3.0273 kWh/degC
  gains_kw                               0.4041 kW
  time_constant_h                       12.0888 h
  rmse_simulation_c                      0.0399 degC
  r2                                     0.9984

(The example house was simulated with R = 4, C = 3 and 0.4 kW of gains.)

Setting under thermal Default Meaning
indoor required Indoor temperature series
outdoor the first temperature feature Name of the feature that holds the outdoor temperature
mode heating heating or cooling: the sign of the heat the unit delivers
cop 1 Converts electric power to heat: a number, or {"a": 2.5, "b": 0.05, "min": 1} for a COP that follows the outdoor temperature (as for HVAC units)

The fit is a regression of each step's indoor temperature change on the indoor-outdoor difference and the heat delivered. rmse_simulation_c is the error when the fitted model runs on its own over the whole history; a few tenths of a degree is good. Periods with windows open, a fireplace or a thermostat schedule the data do not show will make it worse.

Methods

In short: leave method out. The default, gbm, was the most accurate on almost every dataset we tested (Benchmark). To check on your own data, run cediskernel evaluate, or set "method": "auto" to let KERNEL pick.

Method What it does
gbm (default) Gradient-boosted decision trees. Learns from the time of day, the day of the week, holidays, recent values (yesterday, last week, today's average so far) and the features. A separate set of trees forecasts each quantile
kernel1 The KERNEL 1.x (R9) forecast, ported: groups past days into typical daily shapes, picks the shape for the forecast day, corrects it with neural networks, blends the two by hour, and takes the range from past errors
linear Ridge regression on time-of-day by day-type terms, recent values and the features; the range from past errors at each time of day
seasonal_naive The same time last week (PV: yesterday). The reference every other method should beat
auto Trains all four, scores them on the validation days, keeps the best (lowest CRPS). The model reports all their scores

gbm

The trees see these inputs at each step: hour, hour_sin, hour_cos, weekday, weekend, holiday, near_holiday (the day before or after a holiday), doy_sin and doy_cos (time of year, when there are at least 180 days of history), lead_h (hours since the forecast was made, for horizons longer than a day), lag_day and lag_week (the same time yesterday and last week, when already known), mean_day (the average of the last 24 hours), last (the latest value), the features, and for PV with a location sun_elevation, clearsky (what a clear sky would give) and clearness_day (yesterday's share of the clear-sky energy).

For demand, EV and HVAC the trees learn the remainder of a ridge regression (linear_base), so trends outside the history (a colder week than any before) are followed instead of flattened. The point forecast is the mean; quantile trees are trained with the pinball loss, and on the validation days each quantile is shifted so that it covers its nominal share (conformal calibration). Training stops when the validation score stops improving, and the model is then retrained on all the data.

kernel1

A port of setDemand/setPV from KERNEL 1.x R9, so 1.x users can compare. Days are grouped by type (holiday, weekend, weekday; PV: one group); the daily profiles of each group are clustered with k-means (k chosen on a 70/30 split of the days); a naive Bayes classifier picks the cluster for the forecast day from its date, day type and weather; a neural network (layers 20-20-20-15) corrects the cluster profile. Three neural networks per day type forecast each step directly. The two forecasts are blended with weights for each hour, and recent errors correct the level. The range comes from the distribution of errors on held-out days at each time of day.

Three things in R9 were fixed in the port: the error sign was reversed, the correction ignored negative errors, and the blend weights and error distribution were fitted on the days used for training. "options": {"r9_compat": true} restores R9's behaviour for comparison. The port cannot reproduce R9's numbers exactly (MATLAB's random initialisation and training algorithms differ), but in R9 mode it tracks R9's forecast for the sample building (correlation 0.6 to 0.7).

Features

A feature is any series that helps explain the target: outdoor temperature, cloud cover, irradiance, humidity, occupancy, production schedules. Give it for the history period and for the forecast period. Weather forecasts are fine; the model learns from what it is given.

"features": {
  "temperature": { "file": "weather.csv", "value": "temperature_c" },
  "cloud": { "file": "weather.csv", "value": "cloud_pct" },
  "occupied": { "file": "schedule.csv", "value": "people" }
}

A name containing temp is read as a temperature (°C, or "unit": "F"); other features are used as they are. Features are resampled to the forecast step. A forecast fails with a clear message when a feature has no value for some step of the forecast period.

Calendar effects (time of day, day of week, holidays) and recent values are built in; do not add them as features.

Forecast request

What to forecast, given with --request, under "forecast" in a training file, or as arguments in Python and Java:

Setting Default Meaning
start right after the latest known value First step of the forecast
horizon the model's Length, up to 14 days
history the last 21 days kept in the model Recent values (any series), joined to those in the model
features the training files Values of each feature for the forecast period, by name. Without them the files used in training are read again
output CSV Output settings
{
  "start": "2026-11-17T00:00-05:00",
  "horizon": "24h",
  "history": { "file": "meter_last_week.csv" },
  "features": { "temperature": { "file": "weather_forecast.csv", "value": "temperature_c" } }
}

The forecast result

Part Content
Series <name> (the forecast) and <name>.pXX for each quantile, e.g. load.p10
Summary energy_kwh and peak_kw of the forecast, the energy at the lowest and highest quantile (energy_kwh_p10, energy_kwh_p90), and the model's validation scores (validation_mae, validation_crps, …)
ev_sessions EV: the expected sessions (arrival, departure, energy, probability)
thermal_model HVAC with thermal: R, C, gains, time constant and fit errors

The result is written like a site result (Results): CSV by default, Excel with a sheet per part, or JSON with "kind": "forecast".

Evaluation

evaluate answers "how good would this forecast have been?" It trains each method on the data before a test period, forecasts every day of the period as if it were live (issued at issue_time, with only the data known then) and scores the forecasts against what happened:

$ cediskernel evaluate demand.json --methods gbm,linear,seasonal_naive --test 14d -o eval.xlsx
  method                        MAE       RMSE   WAPE %       CRPS    skill % cover80 %
  gbm                         0.194     0.3423     7.29     0.1204      75.29      77.6
  linear                     0.1913     0.3453     7.19     0.1695      75.64      62.1
  seasonal_naive             0.7852      1.008    29.52     0.8499       0.00      43.9
best (lowest CRPS): gbm
Option Default Meaning
--methods / evaluation.methods all four Methods to compare
--test / evaluation.test 28d Length of the test period, at the end of the history

The result has a metrics table (every metric, one row per method), a by_lead table (errors by hours ahead), the actual values and each method's forecast as series, and for EV a table comparing the predicted and actual sessions. Use at least four weeks of test data when you can: a week or two depends a lot on the weather of those days.

r = ck.evaluate("demand.json", methods=["gbm", "kernel1"], test="28d")
for row in r.tables["metrics"]:
    print(row)

Forecasts in a site

A site can use forecasts directly: KERNEL trains (or loads) the model, forecasts the site's horizon and uses the quantiles as the uncertainty for stochastic optimisation.

"data": {
  "load": { "forecast": "demand.json" },
  "pv": { "forecast": "pv.model.json" }
},
"evs": [ { "id": "car", "battery_kwh": 60, "charge_max_kw": 7.2,
           "sessions": { "forecast": "ev.json" } } ],
"hvac": [ { "id": "heat_pump", "thermal": { "model": "hvac.json" }, ... } ]
Where Value Effect
data.<name> {"forecast": file} The series is the forecast, with its quantiles as uncertainty. The file is a model or a training configuration; add "history" and "features" to pass fresh data to a model
evs[].sessions {"forecast": file} The car's sessions are the expected sessions; the energy needed is the typical energy of a session
hvac[].thermal {"model": file} R, C and the internal gains come from the fitted thermal model (any of them can still be set)

The forecast covers the site's horizon, which must have a start. examples/forecasting/site.json forecasts and schedules a house in one call.

Options

For specialists; the defaults suit most sites.

Option Method Default Meaning
trees gbm 1000 Most trees per model (early stopping usually ends sooner)
learning_rate gbm 0.05 Shrinkage
leaves, max_depth gbm 31, 12 Tree size
min_leaf gbm 20 Fewest samples in a leaf (the outer quantiles use at least 100)
l2 gbm 1 L2 penalty on leaf values
feature_fraction, bagging_fraction gbm 0.9, 0.8 Share of inputs and rows used per tree
early_stopping gbm 50 Rounds without improvement before stopping
linear_base gbm true (PV: false) Trees learn the remainder of a ridge regression
relative gbm false Trees learn the ratio to the last week's average level
clusters kernel1 chosen Number of daily-profile clusters per day type
hidden kernel1 [20, 20, 20, 15] Neural network layers
networks kernel1 3 Networks averaged per day type
epochs kernel1 200 Most training epochs
r9_compat kernel1 false Reproduce R9's behaviour, see kernel1
ridge linear 0.0001 L2 penalty (on standardised inputs)

Good data, good forecasts

  • History: at least four weeks; three months or more for demand and HVAC so the model has seen different weather; a full year to learn seasons.
  • Weather: the temperature (demand, HVAC) and cloud cover or irradiance (PV) make the biggest difference, if you will have forecasts of them.
  • Holidays: give them; a holiday looks like a Sunday to a building.
  • Changes: a new tenant, a new heat pump or a battery behind the meter changes the pattern. Retrain on data from after the change.
  • Check: validation_coverage_80 should be near 80 %. Much lower means the ranges are too narrow for this site, usually because the last weeks differed from the history.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

Forecast metrics

Every forecasting model scores itself on days it did not train on, and evaluate scores whole methods on a test period. This page explains the scores. They can also be computed for any forecast, from KERNEL or not; see Computing metrics.

Which ones to look at

  • MAE, in kW: the typical size of the error. "On average the forecast is off by 0.17 kW."
  • WAPE, in %: the same as a share of the actual energy, to compare sites of different sizes.
  • Skill, in %: how much better than "the same time last week". 0 % is no better; 50 % halves the error. Negative means the reference was better.
  • Coverage 80, in %: how often the actual value fell inside the forecast's 80 % range (between p10 and p90). It should be close to 80.
  • CRPS, in kW: one number for the whole forecast, ranges included. Lower is better. KERNEL picks methods by CRPS.

Point forecast

a is the actual value, f the forecast, over the N steps scored.

Metric Unit Definition Notes
samples Steps scored Steps with a missing actual are skipped; so are PV night-time steps when the location is known
mae kW mean |f − a| Mean absolute error
rmse kW √ mean (f − a)² Weighs large errors more
bias kW mean (f − a) Positive: the forecast is too high on average
mape % 100 × mean |f − a| / |a| Only over steps whose actual is at least 5 % of the mean, so near-zero values (night PV, an idle charger) do not dominate
smape % 100 × mean 2|f − a| / (|a| + |f|) Symmetric; between 0 and 200
wape % 100 × Σ|f − a| / Σ|a| Error as a share of the energy; robust to zeros
nrmse % 100 × rmse / mean |a|
nmae_capacity, nrmse_capacity % 100 × mae / capacity When a capacity is given (PV capacity_kw)
r2 1 − Σ(f − a)² / Σ(a − ā)² Share of the variation explained; 1 is perfect
skill_mae, skill_rmse % 100 × (1 − mae / mae of the reference) The reference is seasonal_naive (same time last week; PV: yesterday)

Days

Scored per day, then averaged. Days whose actual peak is under 10 % of the typical daily peak (a PV system under snow, a closed building) are left out, since any relative error on them is meaningless.

Metric Unit Definition
daily_peak_error % |forecast peak − actual peak| / actual peak, per day
peak_time_error h Hours between the forecast's and the actual peak, per day
daily_energy_error % |forecast energy − actual energy| / actual energy, per day

For a demand charge, daily_peak_error matters more than MAE; for an energy bill, daily_energy_error does.

Ranges (quantiles)

q_τ is the forecast quantile at level τ (for example load.p10, τ = 0.1).

Metric Unit Definition Ideal
pinball kW Mean over levels of the pinball loss: τ(a − q_τ) if a ≥ q_τ, else (1 − τ)(q_τ − a) Lower
crps kW 2 × pinball: the continuous ranked probability score, approximated from the quantiles. For a forecast with no range it equals the MAE Lower
coverage_80, coverage_50 % Share of steps with q_0.1 ≤ a ≤ q_0.9 (q_0.25 ≤ a ≤ q_0.75) 80, 50
width_80, width_50 kW Mean q_0.9 − q_0.1 (q_0.75 − q_0.25) Narrow, if coverage is right
winkler_80, winkler_50 kW Width, plus 2/α times the distance by which the actual falls outside (α = 0.2, 0.5) Lower
reliability_p10, … % Share of steps with a ≤ q_τ τ × 100

A range that covers too little is overconfident: the optimiser will trust it too much. One that covers too much is wider than it needs to be, which makes stochastic plans more cautious (and costlier) than necessary. CRPS and the Winkler score reward ranges that are both right and narrow.

By lead time

evaluate also gives MAE, RMSE, CRPS and 80 % coverage for each hour ahead (the by_lead table), since a forecast for the next hour is usually better than one for tomorrow evening.

EV sessions

For EV charging, evaluate also compares the predicted sessions with the actual ones (the ev_session_metrics table):

Metric Unit Definition
plug_in_day_accuracy % Days on which the forecast was right about whether a car plugs in
arrival_mae, departure_mae h Mean error of the arrival and departure times (first session of the day), on days with both a predicted and an actual session
energy_mae kWh Mean error of the session energy, on the same days
days Test days

Computing metrics

The same metrics for any forecast, from KERNEL or not:

import cedis_kernel as ck

m = ck.metrics(actual, forecast,
               quantiles={0.1: p10, 0.9: p90},     # optional
               reference=last_week,                # optional, for skill
               steps_per_day=96, step_hours=0.25)  # optional, for the daily metrics
print(m["mae"], m["crps"], m["coverage_80"])
$ cediskernel metrics request.json
{
  "actual": [3.1, 3.3, null, 3.6],
  "forecast": [3.0, 3.4, 3.5, 3.5],
  "quantiles": { "0.1": [2.7, 3.0, 3.1, 3.2], "0.9": [3.3, 3.8, 3.9, 3.9] },
  "reference": [2.9, 3.1, 3.3, 3.9],
  "steps_per_day": 96, "step_hours": 0.25, "capacity": 6
}

null marks a missing value; that step is skipped. The C function is kernel_metrics, Java Kernel.metrics, C++ cedis::kernel::metrics_json.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

Benchmark

Which forecasting method should KERNEL use by default? We ported the KERNEL 1.x method (kernel1), added a modern one (gbm, gradient-boosted quantile trees) and two simple references (linear and seasonal_naive), and tested all of them on the same data: the KERNEL 1.x R9 sample, public building data, workplace EV charging, and the example house.

In short: gbm gave the best forecasts in 17 of 18 cases, by CRPS (one score for the forecast and its range together). It is the default. The ported 1.x method beat "same time last week" in most cases but trailed gbm by about half again in CRPS (median 1.5 times gbm's), and its ranges were too narrow.

How the test works

For each dataset and method:

  1. The method is trained on the data before a test period (the last 3 to 13 weeks of the data).
  2. It forecasts every day of the test period, 24 hours ahead, issued at midnight with only the data known at that time, as it would be used live.
  3. The forecasts are scored against what happened (Metrics).

Every method gets the same inputs: the history, the calendar and holidays, and the same weather series. For the test days that is the weather recorded in the data (for the R9 building, the daily maximum temperature and weather code in the R9 files), as if the weather forecast had been perfect. Live forecasts use weather forecasts, which are less accurate, so live errors will be somewhat larger for every method, most for PV.

kernel1 is run twice: as ported, with three R9 quirks fixed (see kernel1), and in R9 mode ("options": {"r9_compat": true}), which keeps them.

Data

Case Data Step History Test
R9 building, demand KERNEL 1.x R9 sample: commercial building, Korea; daily maximum temperature and weather code 15 min Jan 2017 – Jul 2018 last 91 days
R9 PV KERNEL 1.x R9 sample: PV system, Korea; temperature, cloud, humidity; location 15 min 2018 last 90 days
BDG2, demand (5 buildings) Building Data Genome 2: electricity of offices and schools (sites Fox, Hog, Moose, Robin, Wolf); outdoor temperature 1 h 2016 – 2017 Oct – Dec 2017
BDG2, cooling (3 buildings) Building Data Genome 2: chilled-water (cooling) load of schools; outdoor temperature 1 h Jan 2016 – Sep 2017 Jul – Sep 2017
BDG2, PV (3 systems) Building Data Genome 2: rooftop PV; temperature and cloud; no location in the data 1 h 2016 – 2017 Oct – Dec 2017
Workplace EV charging 520 charging sessions at the busiest of 25 workplace locations (Harvard Dataverse, CC0) 15 min Mar – Oct 2015 last 42 days
Synthetic house examples/forecasting: simulated Ottawa house (demand, 6 kW PV, EV, heat pump) 15 min Sep – Nov 2026 last 21 days

One BDG2 office (Lamb) was left out: its meter stopped for weeks during the test period, which no method can forecast. KERNEL now warns about such "stuck" meters.

Results

CRPS of each method relative to gbm (below 1 is better than gbm; the best method of each case in bold):

Case Best (CRPS) gbm kernel1 kernel1 (R9 mode) linear seasonal_naive
R9 building, demand gbm 1.00 1.84 3.28 1.73 1.87
R9 PV gbm 1.00 1.10 1.07 1.48 1.60
BDG2 Fox_education_Andre, demand gbm 1.00 1.19 1.09 1.05 1.39
BDG2 Hog_office_Gustavo, demand gbm 1.00 1.91 2.11 1.65 1.14
BDG2 Moose_education_Ricardo, demand gbm 1.00 1.48 1.45 1.23 1.82
BDG2 Robin_office_Sammie, demand gbm 1.00 1.25 2.03 1.14 1.48
BDG2 Wolf_office_Darleen, demand gbm 1.00 1.32 1.35 1.16 1.50
BDG2 Bull_education_Lyn, cooling gbm 1.00 1.25 1.21 1.34 1.95
BDG2 Eagle_education_Peter, cooling linear 1.00 1.42 2.49 0.97 2.34
BDG2 Fox_education_Andre, cooling gbm 1.00 1.50 1.60 1.16 1.87
BDG2 Bobcat_education_Coleman, pv gbm 1.00 1.72 1.52 1.45 1.48
BDG2 Bobcat_education_Dylan, pv gbm 1.00 2.01 2.03 1.44 1.35
BDG2 Bobcat_other_Timothy, pv gbm 1.00 1.99 1.95 1.40 1.61
Workplace EV charging gbm 1.00 1.21 1.70 1.15 1.41
Synthetic house, demand gbm 1.00 1.96 3.02 1.25 4.50
Synthetic house, PV gbm 1.00 5.05 7.43 3.51 7.18
Synthetic house, heat pump gbm 1.00 1.69 1.99 1.32 5.29
Synthetic house, EV gbm 1.00 1.30 1.51 1.23 1.64

Detail

MAE and CRPS are in kW (BDG2 cooling: the meter's own unit). Skill is the MAE improvement over seasonal_naive. Coverage 80 should be near 80 %.

R9 building, demand (KERNEL 1.x R9 sample, 15 min, Jan 2017 - Jul 2018; test 91d)

Method MAE WAPE % Skill % Daily peak error % CRPS Coverage 80 %
gbm 21.5 7.2 34.9 9.3 15.3 85.9
kernel1 37.4 12.6 -13.0 15.4 28.1 68.2
kernel1 (R9 mode) 56.8 19.1 -71.7 14.9 50.1 34.2
linear 35.7 12.0 -7.8 13.4 26.4 80.8
seasonal_naive 33.1 11.1 0.0 14.5 28.6 68.9

R9 PV (KERNEL 1.x R9 sample, 15 min, 2018; test 90d)

Method MAE WAPE % Skill % Daily peak error % CRPS Coverage 80 %
gbm 0.15 28.3 34.3 21.6 0.106 83.4
kernel1 0.168 31.8 26.1 27.8 0.117 87.0
kernel1 (R9 mode) 0.151 28.5 33.7 23.7 0.113 72.7
linear 0.188 35.5 17.6 28.9 0.157 63.2
seasonal_naive 0.228 43.0 0.0 57.0 0.169 81.1

BDG2 Fox_education_Andre, demand (Building Data Genome 2, hourly, 2016-2017; test 91d)

Method MAE WAPE % Skill % Daily peak error % CRPS Coverage 80 %
gbm 15.8 3.3 27.1 4.2 11.6 77.3
kernel1 18.2 3.8 16.0 4.5 13.7 68.6
kernel1 (R9 mode) 16.8 3.5 22.5 4.5 12.6 68.6
linear 16.5 3.5 23.9 4.7 12.1 76.7
seasonal_naive 21.7 4.6 0.0 4.3 16.1 74.9

BDG2 Hog_office_Gustavo, demand (Building Data Genome 2, hourly, 2016-2017; test 91d)

Method MAE WAPE % Skill % Daily peak error % CRPS Coverage 80 %
gbm 24.1 3.2 -7.8 3.8 16 67.8
kernel1 39.2 5.2 -75.6 6.6 30.6 63.9
kernel1 (R9 mode) 39.5 5.2 -76.9 5.9 33.8 38.6
linear 36.9 4.9 -65.1 5.7 26.4 73.2
seasonal_naive 22.3 3.0 0.0 4.1 18.1 87.7

BDG2 Moose_education_Ricardo, demand (Building Data Genome 2, hourly, 2016-2017; test 91d)

Method MAE WAPE % Skill % Daily peak error % CRPS Coverage 80 %
gbm 11.3 3.4 41.7 4.3 8.04 76.3
kernel1 15.7 4.7 19.2 4.6 11.9 62.6
kernel1 (R9 mode) 15.3 4.6 21.4 4.6 11.7 59.8
linear 13.7 4.1 29.7 4.8 9.89 68.7
seasonal_naive 19.5 5.8 0.0 6.6 14.6 69.4

BDG2 Robin_office_Sammie, demand (Building Data Genome 2, hourly, 2016-2017; test 91d)

Method MAE WAPE % Skill % Daily peak error % CRPS Coverage 80 %
gbm 5.87 7.7 32.5 7.1 4.35 84.7
kernel1 7.73 10.1 11.2 12.9 5.44 70.0
kernel1 (R9 mode) 11.5 15.1 -32.4 10.8 8.82 47.4
linear 6.5 8.5 25.3 8.2 4.95 75.4
seasonal_naive 8.7 11.4 0.0 10.4 6.43 78.0

BDG2 Wolf_office_Darleen, demand (Building Data Genome 2, hourly, 2016-2017; test 91d)

Method MAE WAPE % Skill % Daily peak error % CRPS Coverage 80 %
gbm 6.62 16.2 28.3 26.2 4.7 68.4
kernel1 8.06 19.7 12.7 28.7 6.18 61.6
kernel1 (R9 mode) 7.99 19.5 13.5 36.6 6.34 60.8
linear 7.42 18.1 19.7 30.8 5.45 70.9
seasonal_naive 9.23 22.5 0.0 38.2 7.02 79.1

BDG2 Bull_education_Lyn, cooling (Building Data Genome 2, hourly, 2016-2017; test 91d)

Method MAE WAPE % Skill % Daily peak error % CRPS Coverage 80 %
gbm 29.8 12.3 39.4 10.3 18.9 75.6
kernel1 33.7 13.9 31.4 13.4 23.7 77.1
kernel1 (R9 mode) 31.3 12.9 36.4 11.1 22.8 63.7
linear 37.2 15.4 24.2 15.9 25.2 68.3
seasonal_naive 49.2 20.3 0.0 18.2 36.9 72.5

BDG2 Eagle_education_Peter, cooling (Building Data Genome 2, hourly, 2016-2017; test 91d)

Method MAE WAPE % Skill % Daily peak error % CRPS Coverage 80 %
gbm 6.71e+05 16.0 57.3 11.8 4.71e+05 82.1
kernel1 9.81e+05 23.4 37.5 22.7 6.69e+05 72.3
kernel1 (R9 mode) 1.61e+06 38.5 -2.8 34.7 1.17e+06 47.7
linear 6.43e+05 15.4 59.0 10.7 4.56e+05 85.4
seasonal_naive 1.57e+06 37.5 0.0 33.4 1.1e+06 90.0

BDG2 Fox_education_Andre, cooling (Building Data Genome 2, hourly, 2016-2017; test 91d)

Method MAE WAPE % Skill % Daily peak error % CRPS Coverage 80 %
gbm 583 9.7 50.6 8.4 450 67.4
kernel1 832 13.9 29.5 9.4 676 47.9
kernel1 (R9 mode) 897 15.0 23.9 10.4 722 40.6
linear 651 10.9 44.8 9.4 524 57.9
seasonal_naive 1179 19.7 0.0 17.7 843 72.2

BDG2 Bobcat_education_Coleman, pv (Building Data Genome 2, hourly, 2016-2017; test 91d)

Method MAE WAPE % Skill % Daily peak error % CRPS Coverage 80 %
gbm 0.963 34.6 29.4 44.2 0.741 79.7
kernel1 1.7 61.1 -24.7 78.1 1.28 49.7
kernel1 (R9 mode) 1.59 57.2 -16.7 65.0 1.13 58.5
linear 1.45 52.2 -6.5 67.8 1.07 55.3
seasonal_naive 1.36 49.0 0.0 78.1 1.1 75.5

BDG2 Bobcat_education_Dylan, pv (Building Data Genome 2, hourly, 2016-2017; test 91d)

Method MAE WAPE % Skill % Daily peak error % CRPS Coverage 80 %
gbm 1.38 36.6 18.7 29.7 1.07 88.8
kernel1 2.59 68.7 -52.8 56.7 2.15 65.4
kernel1 (R9 mode) 2.98 78.9 -75.5 56.3 2.17 55.7
linear 2.09 55.4 -23.2 42.3 1.54 67.4
seasonal_naive 1.7 45.0 0.0 40.8 1.44 84.4

BDG2 Bobcat_other_Timothy, pv (Building Data Genome 2, hourly, 2016-2017; test 91d)

Method MAE WAPE % Skill % Daily peak error % CRPS Coverage 80 %
gbm 0.728 31.3 31.4 33.7 0.522 90.5
kernel1 1.36 58.3 -27.9 53.8 1.04 62.1
kernel1 (R9 mode) 1.42 61.1 -34.0 62.7 1.02 57.3
linear 1.04 44.6 2.2 57.0 0.733 52.7
seasonal_naive 1.06 45.6 0.0 69.3 0.839 81.2

Workplace EV charging (DOE workplace charging (moderndive), 2015; test 42d)

Method MAE WAPE % Skill % Daily peak error % CRPS Coverage 80 %
gbm 0.655 91.4 -4.4 37.7 0.38 94.4
kernel1 0.812 113.3 -29.4 25.2 0.458 47.4
kernel1 (R9 mode) 0.903 125.8 -43.8 31.5 0.645 32.4
linear 0.659 91.9 -5.0 37.6 0.436 76.5
seasonal_naive 0.628 87.5 0.0 38.6 0.536 93.3

Synthetic house, demand (examples/forecasting (simulated); test 21d)

Method MAE WAPE % Skill % Daily peak error % CRPS Coverage 80 %
gbm 0.193 6.8 77.7 24.4 0.132 77.1
kernel1 0.333 11.8 61.5 19.7 0.259 53.6
kernel1 (R9 mode) 0.462 16.4 46.4 22.9 0.399 29.5
linear 0.221 7.9 74.4 27.8 0.166 72.1
seasonal_naive 0.863 30.6 0.0 19.3 0.594 68.4

Synthetic house, PV (examples/forecasting (simulated); test 21d)

Method MAE WAPE % Skill % Daily peak error % CRPS Coverage 80 %
gbm 0.0486 5.9 86.3 5.1 0.0358 82.1
kernel1 0.228 27.8 35.7 8.7 0.181 46.5
kernel1 (R9 mode) 0.327 39.9 7.8 12.8 0.266 32.5
linear 0.175 21.4 50.6 11.3 0.126 52.9
seasonal_naive 0.355 43.3 0.0 37.4 0.257 60.8

Synthetic house, heat pump (examples/forecasting (simulated); test 21d)

Method MAE WAPE % Skill % Daily peak error % CRPS Coverage 80 %
gbm 0.08 7.7 75.8 2.6 0.0456 83.8
kernel1 0.0928 8.9 71.9 8.2 0.0772 52.3
kernel1 (R9 mode) 0.105 10.1 68.2 7.9 0.0907 48.5
linear 0.0952 9.1 71.2 8.5 0.0601 72.0
seasonal_naive 0.331 31.7 0.0 0.0 0.241 64.3

Synthetic house, EV (examples/forecasting (simulated); test 21d)

Method MAE WAPE % Skill % Daily peak error % CRPS Coverage 80 %
gbm 0.464 103.6 8.9 45.7 0.276 84.3
kernel1 0.511 113.9 -0.2 26.3 0.36 56.7
kernel1 (R9 mode) 0.544 121.3 -6.7 27.8 0.416 39.3
linear 0.464 103.4 9.0 45.7 0.34 92.2
seasonal_naive 0.509 113.7 0.0 18.1 0.452 94.0

What the results say

  • gbm is the best default. Best CRPS in 17 of 18 cases, best MAE in 14. Its median skill over "same time last week" is 33 %, against 22 % for linear and 14 % for kernel1.
  • Its ranges are about right. Its 80 % ranges covered between 67 % and 94 % of actual values (median 82 %). kernel1's covered a median of 62 %, and 48 % in R9 mode: R9's intervals were too narrow, so a stochastic plan built on them would be overconfident.
  • Where gbm did not win. On one school's cooling load (Eagle), linear was 3 % better: cooling follows the temperature almost linearly. On one office (Hog) and the workplace chargers, "same time last week" had a slightly lower MAE: their weekly pattern repeats closely. gbm still had the better CRPS in both.
  • Peaks of intermittent loads. gbm's point forecast is a mean, which smooths sharp, irregular peaks such as EV charging. Methods that copy the shape of past days (kernel1, and on the house also seasonal_naive) had smaller daily peak errors on the two EV cases and on the house's demand. For peak-sensitive uses, look at the upper quantile (.p90), or use the EV session forecast, which keeps the full charging power.
  • The R9 fixes help. The ported kernel1 beat R9 mode in 12 of 18 cases, and by far on the R9 building itself (CRPS 28 against 50). R9 mode was slightly better on some PV and school cases, where R9's blend weights happened to suit the data.
  • Without a location, PV is harder. The BDG2 PV systems have no location in their metadata, so no method knew where the sun was; errors are larger than for the R9 and synthetic PV, which had one.

The R9 port compared with R9

R9's sample output (Demand_Results.csv) forecasts the sample building for Sunday 29 July 2018, the day after its data end. There are no actual values for that day, so this compares the port with R9's forecast, not with reality:

Forecast Mean (kW) Correlation with R9's forecast Difference from R9's forecast (MAPE)
R9 (KERNEL 1.x, MATLAB) 216 1 0 %
gbm 243 0.65 12.9 %
kernel1 279 -0.28 30.5 %
kernel1, R9 mode, seed 1 249 0.57 15.6 %
kernel1, R9 mode, seed 2 252 0.69 17.2 %
kernel1, R9 mode, seed 3 251 0.63 16.4 %

R9's forecast averages 216 kW; the last four Sundays in the data averaged 255 kW. In R9 mode the port follows R9's shape (correlation 0.57 to 0.69 with R9's forecast). It cannot match R9 exactly: R9's neural networks and naive Bayes classifier came from MATLAB (fitnet trained by scaled conjugate gradient, fitcnb), whose random initialisation and training details cannot be reproduced outside MATLAB.

Reproducing

The scripts are in benchmarks/ (see its README). The public data are downloaded by benchmarks/prepare_public.py; the R9 data come from the KERNEL 1.x archive and are not distributed.

python benchmarks/run_benchmark.py data benchmarks/results.json
python benchmarks/summarize.py benchmarks/results.json

Every method is deterministic for a given seed, so the same data give the same figures on any computer.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

Command line

cediskernel solves a site configuration from a terminal or a script. It is built with the library (Install) and uses the same C interface as every other language.

cediskernel solve <site.json> [-o <out.xlsx|out.json|out.csv|out_dir>] [--format csv|xlsx|json] [--all] [--quiet]
cediskernel validate <site.json>
cediskernel train <forecast.json> [-m <model.json>] [--quiet]
cediskernel forecast <model.json|forecast.json> [--start <time>] [--horizon <duration>]
                    [--request <request.json>] [-o <out>] [--format csv|xlsx|json] [--quiet]
cediskernel evaluate <forecast.json> [--methods gbm,kernel1,linear,seasonal_naive] [--test <duration>]
                    [-o <out>] [--format csv|xlsx|json] [--quiet]
cediskernel model <model.json>
cediskernel metrics <request.json>
cediskernel presets [<name>]
cediskernel solvers
cediskernel version

solve

Reads the configuration and its data, solves, prints the summary and writes the results.

Option Meaning
-o, --output PATH Where to write. The format follows the extension (.xlsx, .json, .csv); a path without one is a folder. Without -o, results go to the configuration's output.path if it has one, otherwise nothing is written
--format csv\|xlsx\|json Force the format
--all Print every summary value, including zeros
-q, --quiet Print nothing (errors still go to stderr)
$ cediskernel solve examples/sites/office_stochastic/site.json -o results.json
status: optimal
  total_cost                               584.2686 CAD
  baseline_total_cost                      872.3007 CAD
  savings                                  288.0321 CAD
  savings_pct                               33.0335 %
  energy_cost                              369.4803 CAD
  demand_cost                              355.3800 CAD
  fixed_cost                                12.0000 CAD
  wear_cost                                 21.1405 CAD
  service_revenue                           18.2435 CAD
  dr_revenue                               155.4887 CAD
  ...
written: results.json

The summary leaves out values that are zero (cost terms the site does not have); the written results always hold everything.

validate

Checks the configuration and loads all data without solving:

$ cediskernel validate site.json
ok: 192 steps of 900 s

Forecasting

See Forecasting for the configuration.

Command Does
train <forecast.json> -m <model.json> Trains a model, prints its validation scores, writes the model file (default: <configuration>.model.json next to the configuration)
forecast <model.json> Forecasts with a saved model
forecast <forecast.json> Trains and forecasts in one go, using the configuration's forecast request
evaluate <forecast.json> Backtests the methods and prints a comparison; writes every metric with -o
model <model.json> Prints what a model forecasts, its data period and its validation scores
metrics <request.json> Metrics of any forecast (JSON in, JSON out)
Option Commands Meaning
-m, --model PATH train Where to write the model
--start TIME forecast First step, e.g. 2026-11-17T00:00-05:00
--horizon DURATION forecast e.g. 24h, 2d
--request FILE forecast A forecast request with recent history and feature values. With a model, its file paths are relative to the request's folder; with a training configuration, to the configuration's. --start and --horizon override the request
--methods LIST evaluate Methods to compare, comma-separated
--test DURATION evaluate Length of the test period (default 28d)
-o, --format, --quiet forecast, evaluate As for solve
$ cediskernel train examples/forecasting/hvac.json -m hvac.model.json
target: hvac   method: gbm   step: 15min   horizon: 2d
...
thermal model: R = 3.993 degC/kW, C = 3.027 kWh/degC, gains 0.404 kW, tau 12.1 h (simulation RMSE 0.04 degC)
model written: hvac.model.json

$ cediskernel forecast hvac.model.json --start 2026-11-16T00:00-05:00 --horizon 24h -o hvac.csv

presets

Lists the built-in tariffs, or prints one as JSON (a starting point for your own):

$ cediskernel presets
  ontario_tou                    Ontario RPP Time-of-Use (OEB, from 1 Nov 2026): 9.1 / 14.6 / 18.9 c/kWh
  ontario_ulo                    Ontario RPP Ultra-Low Overnight (OEB, from 1 Nov 2026): 3.7 / 9.1 / 14.6 / 37.7 c/kWh
  ontario_tiered                 Ontario RPP Tiered, residential (OEB, from 1 Nov 2026): 11.2 / 13.2 c/kWh, 1000 kWh (Nov-Apr) / 600 kWh
  ontario_tiered_nonresidential  Ontario RPP Tiered, non-residential (OEB, from 1 Nov 2026): 11.2 / 13.2 c/kWh, 750 kWh
  flat                           A single price per kWh (set energy.price)

$ cediskernel presets ontario_ulo > my_tariff.json

solvers

Shows each solver and whether it can be used; see Solvers.

Exit codes

Code Meaning
0 Success
1 An error; the message is on stderr, starting with error:
2 Wrong command-line usage

Errors always name the setting, file, line or column involved, so scripts can show them as they are.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

Python

import cedis_kernel as ck

r = ck.solve("site.json")
print(r.status, r.summary["total_cost"], r.currency)
soc = r["home_battery.soc_pct"]          # a list, one value per output step
r.write("results.xlsx")

The package is cedis_kernel (Python 3.11 or newer). Install builds it with pip install .. Solving releases the GIL, so several solves can run in parallel threads.

Solving a site

solve(config, base_dir=None) -> Result

config is any of:

Type Example Data files are relative to
a path (str or pathlib.Path) ck.solve("sites/home/site.json") the file's folder
a dict ck.solve({"horizon": {...}, "batteries": [...]}) base_dir, or the current folder
JSON text ck.solve('{"horizon": ...}') base_dir, or the current folder

A dict is the easy way to change a configuration in code:

import json, pathlib
cfg = json.loads(pathlib.Path("site.json").read_text())
results = {}
for size in (5, 10, 13.5, 20):
    cfg["batteries"][0]["capacity_kwh"] = size
    results[size] = ck.solve(cfg, base_dir="sites/home").summary["savings"]

validate(config, base_dir=None) -> dict

Checks the configuration and data without solving, and returns the model grid: {"steps": 192, "step_seconds": 900}. Raises the same errors as solve.

The Result

Attribute or method Type Meaning
status str "optimal" or "time_limit"; forecasts: "ok"
kind str "schedule" or "forecast"
solver str The solver used
currency str The tariff's currency
step_seconds int Output step
timestamps list[str] Start of each output step, ISO 8601
series dict[str, list[float]] Every series by name (NaN where undefined)
r[name], name in r list[float], bool One series; KeyError lists the names if it does not exist
summary dict[str, float] Every summary value
metric(name) float One summary value
units dict[str, str] Unit of each summary value that has one
devices, ev_sessions, scenarios list[dict] The tables, one dict per row
tables dict[str, list[dict]] Every table by name, including the forecasting ones
warnings list[str] Warnings
to_dict() dict Everything (the JSON layout)
to_pandas() DataFrame The series indexed by timestamp (needs pandas)
write(path=None, format=None) Write .xlsx, .json, .csv or a folder. Defaults: output.path and output.format
df = r.to_pandas()
df[["grid_import_kw", "home_battery.power_kw"]].resample("1h").mean().plot()

for row in r.ev_sessions:
    print(row["ev"], row["delivered_kwh"], row["shortfall_kwh"])

The series are expected values when the optimisation is stochastic; the scenarios table and cost_min / cost_max / cost_cvar give the spread.

Errors

Every error is a subclass of cedis_kernel.KernelError, with the message naming the setting or file:

Exception Also a When
InvalidArgumentError ValueError A setting is missing, unknown or out of range
KernelIOError OSError A file cannot be read or written
DataError ValueError Data are malformed or do not cover the horizon
InfeasibleError No schedule meets every hard limit
SolverError The solver failed (no licence, time limit with no schedule)
try:
    r = ck.solve(cfg)
except ck.InfeasibleError as e:
    print("cannot be done:", e)

TypeError is raised when config is not a dict, a string or a path.

Catalogues

Function Returns
__version__ "2.1.0-alpha.1"
solvers() Solvers usable now, e.g. ["highs", "scip"]
solver_info() [{"name": "gurobi", "status": "not found (…)"}, …]
tariff_presets() [{"name": "ontario_tou", "description": …}, …]
tariff_preset(name) The preset as a dict, ready to change and pass as "tariff"
tou = ck.tariff_preset("ontario_tou")
tou["energy"]["periods"]["on_peak"] = 0.21
cfg["tariff"] = tou

Forecasting

model = ck.train("demand.json")              # or a dict; see Forecasting
print(model)                                 # <cedis_kernel.Forecaster demand, method=gbm, validation MAE=0.1728>
model.save("load.model.json")

r = ck.load_model("load.model.json").forecast(
        start="2026-11-17T00:00-05:00", horizon="24h",
        history=recent,                                   # file, dict or pandas Series
        features={"temperature": "weather_forecast.csv"})
r["load"], r["load.p10"], r["load.p90"]
Function or member Returns Meaning
train(config, base_dir=None) Forecaster Train a model (Forecasting); releases the GIL
load_model(path) Forecaster Read a model file
forecast(config, base_dir=None) Result Train and forecast in one call (the configuration's forecast request)
evaluate(config, base_dir=None, methods=None, test=None) Result Backtest; r.tables["metrics"] has one row per method
metrics(actual, forecast, quantiles=None, reference=None, steps_per_day=None, step_hours=0.25, capacity=None) dict Metrics of any forecast
Forecaster.forecast(start=None, horizon=None, history=None, features=None, output=None, base_dir=None) Result Forecast. start: text or datetime; horizon: "24h" or seconds; history and each feature: a file name, a series dict, a number or a pandas Series with evenly spaced times
Forecaster.save(path), to_dict() The model file
Forecaster.target, method, name, quantiles What the model forecasts and how
Forecaster.validation dict Scores on the held-out days (mae, crps, coverage_80, …)
Forecaster.thermal dict or None HVAC: the fitted thermal model
Forecaster.info dict All of the above, plus the data period, inputs and notes

A forecast Result has kind == "forecast", status == "ok", method, the series name and name.pXX, and the tables in tables (ev_sessions, thermal_model; for an evaluation metrics and by_lead).

The storage scheduler

The package also has the simpler battery-only interface from earlier releases, schedule_ess() and schedule_ess_files(), which takes load and price lists directly. See Storage scheduler.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

Java

import org.cedislab.kernel.Kernel;
import org.cedislab.kernel.SiteResult;
import java.nio.file.Path;

try (SiteResult r = Kernel.solve(Path.of("site.json"))) {
    double cost = r.metric("total_cost");
    double[] soc = r.series("home_battery.soc_pct");
    r.write(Path.of("results.xlsx"), null);
}

The package org.cedislab.kernel needs Java 22 or newer (25 LTS recommended), which has the final Foreign Function & Memory API. Run with --enable-native-access=ALL-UNNAMED on the class path, or --enable-native-access=org.cedislab.kernel on the module path. How the native library is found is described in Install.

All methods are thread-safe; solves can run in parallel.

Kernel

Method Returns Meaning
solve(Path config) SiteResult Solve a configuration file; data paths are relative to its folder
solve(String json, Path baseDir) SiteResult Solve JSON text; data paths relative to baseDir (null: the current folder)
solve(String json) SiteResult The same with the current folder
validate(Path config), validate(String json, Path baseDir) Kernel.SiteInfo Check without solving: steps(), stepSeconds()
version() String "2.1.0-alpha.1"
solvers() List<String> Solvers usable now
solverInfo(), tariffPresets(), tariffPreset(name) String JSON text

Building configurations in code is easiest with a JSON library you already use (Jackson, Gson, jakarta.json), or a text block:

String site = """
    {"horizon": {"start": "2026-11-16T00:00-05:00", "duration": "24h"},
     "data": {"load": "load.csv"},
     "batteries": [{"id": "b1", "capacity_kwh": %s, "power_kw": 5}]}
    """.formatted(capacity);
try (SiteResult r = Kernel.solve(site, Path.of("data"))) { ... }

SiteResult

Series, metrics and warnings are copied into Java when the result is created, so they stay available after close(). json() and write() use the native result and need it open. Closing is optional (a Cleaner frees it otherwise) but frees memory sooner.

Method Returns Meaning
status() String "optimal" or "time_limit"
steps(), stepSeconds() int, long Output grid
timestamps() List<String> Start of each step, ISO 8601
seriesNames(), hasSeries(name) List<String>, boolean
series(name) double[] A copy of one series (NaN where undefined)
metric(name) double One summary value
metrics(), units() Map<String, Double>, Map<String, String> All summary values, in report order, and their units
warnings() List<String>
json() String Everything as JSON (layout)
write(Path path, String format) Write .xlsx, .json, .csv or a folder; null path: output.path; null format: from the extension
write() Write to output.path in output.format
close() Free the native result (safe to call twice)

Errors

Every failure throws the unchecked KernelException, whose status() is one of INVALID_ARGUMENT, IO, DATA, INFEASIBLE, SOLVER, INTERNAL:

try (SiteResult r = Kernel.solve(config)) {
    ...
} catch (KernelException e) {
    if (e.status() == KernelException.Status.INFEASIBLE) { ... }
    System.err.println(e.getMessage());   // names the setting, file, line or column
}

Forecasting

try (Forecaster model = Forecaster.train(Path.of("demand.json"))) {
    model.save(Path.of("load.model.json"));
    String request = """
        {"start": "2026-11-17T00:00-05:00", "horizon": "24h",
         "features": {"temperature": "weather_forecast.csv"}}
        """;
    try (SiteResult f = model.forecast(request, Path.of("data"))) {
        double[] load = f.series("load");
        double[] p90 = f.series("load.p90");
    }
}
Method Returns Meaning
Forecaster.train(Path config), train(String json, Path baseDir) Forecaster Train a model (Forecasting)
Forecaster.load(Path model), parse(String modelJson) Forecaster A saved model
forecast(String requestJson, Path baseDir), forecast() SiteResult Forecast; the request may be null
save(Path), json(), info() The model file, and a summary (JSON) with the validation scores
Kernel.forecast(Path config), forecast(String json, Path baseDir) SiteResult Train and forecast in one call
Kernel.evaluate(Path config), evaluate(String json, Path baseDir) SiteResult Backtest; the metrics table is in json()
Kernel.metrics(String requestJson) String Metrics of any forecast, JSON in and out

A Forecaster is AutoCloseable and thread-safe. Forecasts and evaluations come back as a SiteResult whose status() is "ok".

The storage scheduler

Kernel.scheduleEss(...) and Kernel.scheduleEssFiles(...) are the simpler battery-only interface; see Storage scheduler.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

C++

#include <cedis/kernel.hpp>
namespace k = cedis::kernel;

const k::Result r = k::Site::load("site.json").solve();   // throws k::Error
double cost = r.metric("total_cost");
std::span<const double> soc = r.series("home_battery.soc_pct");
r.write("results.xlsx");

cedis/kernel.hpp is a header-only C++20 layer over the C interface: RAII handles, exceptions, std::string and std::span. Link against the cediskernel library (target_link_libraries(app PRIVATE cedis::cediskernel) after find_package(CedisKernel), see Install). A complete program is examples/cpp/site.cpp.

Site

Member Meaning
static Site load(const std::string& path) Read a configuration file; data paths relative to its folder
static Site parse(const std::string& json, const std::string& base_dir = {}) Parse JSON text; data paths relative to base_dir
size_t steps(), int64_t step_seconds() The model grid
Result solve() const Optimise. A Site can be solved several times and from several threads

k::solve_json(json, base_dir) parses and solves in one call.

Result

Member Meaning
std::string status() "optimal" or "time_limit"
size_t steps(), int64_t step_seconds() Output grid
std::string timestamp(size_t i), timestamps() ISO 8601 start of each step
std::vector<std::string> series_names(), bool has_series(name)
std::span<const double> series(name) A view of one series, valid while the Result lives (NaN where undefined); throws if unknown
double metric(name) One summary value; throws if unknown
std::vector<MetricValue> metrics() {name, value, unit} for every summary value
std::vector<std::string> warnings()
std::string json() Everything as JSON
void write(path = {}, format = {}) Write .xlsx, .json, .csv or a folder; empty path means output.path
std::string output_path() The configuration's output.path, resolved

Result and Site are move-only.

Errors

Every failure throws k::Error (derived from std::runtime_error), with status() returning k::Status::InvalidArgument, Io, Data, Infeasible, Solver or Internal, and what() naming the setting, file, line or column.

try {
    auto r = k::Site::load(argv[1]).solve();
} catch (const k::Error& e) {
    if (e.status() == k::Status::Infeasible) { /* relax a limit */ }
    std::cerr << e.what() << '\n';
}

Catalogues

k::version(), k::solvers() (a vector of names), k::solver_info(), k::tariff_presets() and k::tariff_preset(name) (JSON text).

Forecasting

const k::Forecaster model = k::Forecaster::train_file("demand.json");
model.save("load.model.json");
const k::Result f = model.forecast(R"({"start": "2026-11-17T00:00-05:00", "horizon": "24h"})");
std::span<const double> load = f.series("load"), p90 = f.series("load.p90");
Member Meaning
static Forecaster train_file(path), train(json, base_dir = {}) Train a model (Forecasting)
static Forecaster load(path), parse(json) A saved model
Result forecast(request_json = "{}", base_dir = {}) const Forecast (request)
void save(path) const, std::string json() const, std::string info() const The model file, and a summary with the validation scores
k::forecast_file(path), k::forecast_json(json, base_dir) Train and forecast in one call
k::evaluate_file(path), k::evaluate_json(json, base_dir) Backtest
k::metrics_json(request_json) Metrics of any forecast

A complete program is examples/cpp/forecast.cpp.

The storage scheduler

k::schedule_ess(load, price, units, options) and k::schedule_ess_files(...) are the battery-only interface; see Storage scheduler.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

C

#include <cedis/kernel.h>

kernel_site* site = NULL;
kernel_result* r = NULL;
if (kernel_site_load("site.json", &site) != KERNEL_OK || kernel_solve(site, &r) != KERNEL_OK) {
    fprintf(stderr, "%s\n", kernel_last_error());
} else {
    double cost;
    kernel_result_metric(r, "total_cost", &cost);
    const double* soc = kernel_result_series(r, "home_battery.soc_pct");
    kernel_result_write(r, "results.xlsx", NULL);
}
kernel_result_free(r);
kernel_site_free(site);

cedis/kernel.h is the library's stable interface. Every other language uses it, so a C program sees exactly what Python or Java see. It is plain C11 and the ABI is the same on Windows and Linux, x86-64 and arm64. A complete program is examples/c/site.c.

Conventions

  • Every function that can fail returns a kernel_status; on failure, kernel_last_error() gives the message for the calling thread.
  • Objects returned by the library are freed with the matching *_free function. Freeing NULL is allowed.
  • Strings are UTF-8, including file paths on Windows.
  • Returned const char* and const double* pointers stay valid until the object they came from is freed.
  • All functions are thread-safe; different threads may solve at once.

Sites

Function Meaning
kernel_status kernel_site_load(const char* path, kernel_site** out) Read a configuration file
kernel_status kernel_site_parse(const char* json, const char* base_dir, kernel_site** out) Parse JSON text; base_dir may be NULL
size_t kernel_site_steps(const kernel_site*), int64_t kernel_site_step_seconds(const kernel_site*) Model grid
kernel_status kernel_solve(const kernel_site*, kernel_result** out) Optimise
kernel_status kernel_solve_json(const char* json, const char* base_dir, kernel_result** out) Parse and optimise
void kernel_site_free(kernel_site*)

Results

Function Meaning
const char* kernel_result_status(r) "optimal" or "time_limit"
size_t kernel_result_steps(r), int64_t kernel_result_step_seconds(r) Output grid
const char* kernel_result_timestamp(r, i) ISO 8601
size_t kernel_result_series_count(r), const char* kernel_result_series_name(r, i) Series names
const double* kernel_result_series(r, name) steps values, or NULL if there is no such series
size_t kernel_result_metric_count(r), kernel_result_metric_name(r, i), kernel_result_metric_unit(r, i) Summary names and units
kernel_status kernel_result_metric(r, name, double* value) One summary value
size_t kernel_result_warning_count(r), const char* kernel_result_warning(r, i) Warnings
const char* kernel_result_json(r) Everything as JSON
kernel_status kernel_result_write(r, path, format) Write a file or folder. path NULL or "": output.path. format NULL: from the extension, else output.format
const char* kernel_result_output_path(r) The configuration's output.path, resolved ("" if none)
void kernel_result_free(kernel_result*)

Forecasting

kernel_forecaster* m = NULL;
kernel_result* f = NULL;
if (kernel_forecaster_train_file("demand.json", &m) == KERNEL_OK &&
    kernel_forecast(m, "{\"start\": \"2026-11-17T00:00-05:00\"}", NULL, &f) == KERNEL_OK) {
    const double* load = kernel_result_series(f, "load");
    const double* p90 = kernel_result_series(f, "load.p90");
    kernel_forecaster_save(m, "load.model.json");
}
kernel_result_free(f);
kernel_forecaster_free(m);
Function Meaning
kernel_forecaster_train(json, base_dir, &m), kernel_forecaster_train_file(path, &m) Train a model (Forecasting)
kernel_forecaster_load(path, &m), kernel_forecaster_parse(json, &m) A saved model
kernel_forecaster_save(m, path), kernel_forecaster_json(m) The model file
kernel_forecaster_info(m) Summary as JSON: target, method, data period, validation scores
kernel_forecast(m, request_json, base_dir, &r) Forecast; request_json may be NULL (request)
kernel_forecast_json(json, base_dir, &r), kernel_forecast_file(path, &r) Train and forecast in one call
kernel_evaluate_json(json, base_dir, &r), kernel_evaluate_file(path, &r) Backtest; the metrics table is in kernel_result_json(r)
kernel_metrics(request_json) Metrics of any forecast as JSON; valid until the next call on the thread
kernel_forecaster_free(m)

Forecasts are kernel_result objects with status "ok": the same accessors and writers as schedules. A complete program is examples/c/forecast.c.

Status codes

Code Value Meaning
KERNEL_OK 0 Success
KERNEL_ERR_INVALID_ARGUMENT 1 A setting or argument is missing or out of range
KERNEL_ERR_IO 2 A file could not be read or written
KERNEL_ERR_DATA 3 Input data failed a check
KERNEL_ERR_INFEASIBLE 4 No schedule satisfies the constraints
KERNEL_ERR_SOLVER 5 The solver did not reach a solution
KERNEL_ERR_INTERNAL 99 A bug; please report it

Catalogues

Function Returns
kernel_version() "2.1.0-alpha.1"
kernel_solvers() Solvers usable now, comma-separated: "highs,scip"
kernel_solver_info() JSON: [{"name": "highs", "status": "available (bundled, 1.15.1)"}, …]
kernel_tariff_presets() JSON: [{"name": …, "description": …}, …]
kernel_tariff_preset(name) The preset as JSON, or NULL (see kernel_last_error())

Linking

System Library Notes
Linux libcediskernel.so (soname libcediskernel.so.2) Exports only kernel_* symbols. With GCC the C++ runtime is linked statically (KERNEL_STATIC_CXX_RUNTIME, on by default)
Windows cediskernel.dll + import library cediskernel.lib Build with -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded for a DLL that needs no Visual C++ redistributable

The storage scheduler

kernel_schedule_ess() and kernel_schedule_ess_files() are the battery-only interface; see Storage scheduler.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

Storage scheduler

Besides the site model, KERNEL keeps the simpler interface of its first 2.0 release: batteries only, against a load and a price per step given as arrays. It is the quickest way to schedule storage when you already have the numbers in memory, and the way to run KERNEL 1.x input files.

For anything more (EVs, HVAC, tariffs with periods, services, stochastic optimisation, file formats) use the site model.

import cedis_kernel as ck

battery = ck.EssUnit(id=1, capacity_kwh=200, charge_max_kw=60, discharge_max_kw=60)
r = ck.schedule_ess(load_kw, price, [battery], demand_charge_rate=8320)   # 15-minute steps by default

r.power_kw[0]                 # kW per step: + charging, − discharging
r.soc_pct[0]                  # state of charge at the end of each step
r.summary.reduced_peak_kw     # and costs, energy, losses …

Inputs

load_kw is the site's demand per step net of on-site generation (it may be negative), and price the energy price per kWh for each step. Both have one value per step.

Each battery (EssUnit):

Field Default Meaning
id 1 Identifier
capacity_kwh required Usable capacity
soc_init_pct, soc_min_pct, soc_max_pct 50, 10, 90 State of charge
charge_max_kw, discharge_max_kw required Power limits
charge_eff, discharge_eff 0.95 One-way efficiencies (fractions)

Options

Option Default Meaning
dt_hours 0.25 Step length in hours
demand_charge_rate 0 Currency per kW of billing peak
billing_peak_kw 0 Peak already set this billing period
degradation_cost 0 Currency per kWh of battery throughput
terminal_soc AT_LEAST_INITIAL End-of-horizon requirement: AT_LEAST_INITIAL, FREE, AT_LEAST_TARGET (with terminal_soc_pct)
allow_export, export_price off Net export to the grid
model STANDARD LEGACY_R9 reproduces the 2021 MATLAB scheduler
tie_break SMOOTH Which of several equally cheap schedules to return

Results

Per battery: power_kw and soc_pct per step; for the site: net_load_kw. The summary:

Field Meaning
forecast_peak_kw, reduced_peak_kw, peak_reduction_pct Peak without and with storage
baseline_energy_cost, optimal_energy_cost Energy cost without and with storage
baseline_demand_cost, optimal_demand_cost Demand charge
baseline_total_cost, optimal_total_cost, cost_savings_pct Totals
energy_charged_kwh, energy_discharged_kwh, energy_losses_kwh Battery energy
degradation_cost, objective_value, solve_time_s

The mathematics is in The model.

KERNEL 1.x files

All languages can read the 1.x inputs, write ESS_Results.csv and append to AOS.csv:

ck.schedule_ess_files("essConfig.csv", "tou.csv", "peakprice.csv", "Demand_Results.csv",
                      "out/ESS_Results.csv", pv="PV_Results.csv")
File Columns used
essConfig.csv ESSID, BATT_CAP[KWH], BATT_CURR_SOC[%], MIN_SOC, MAX_SOC, MAX_CH[KW], MAX_DCH[KW] (negative or positive), CH_EFF[%], DCH_EFF[%], FLAG (only units with FLAG = 1 are scheduled)
tou.csv price, column 7, one row per step
peakprice.csv HighestDemand (month-to-date peak, kW), DemandCharge (per kW)
demand / PV forecast results timestamp (columns 1–6), mean (column 7)

ESS_Results.csv has the 1.x columns (BuildingIndex, Year, Month, Day, Hour, Quarter, ESS_<id>[KW], SOC_<id>[%], …). AOS.csv has R9's nine columns with LEGACY_R9, and seventeen with STANDARD (R9's nine, then energy and cost components). Rows are appended; a file in the other format is refused rather than mixed.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

The model

This page states the optimisation problem KERNEL solves, term by term. It is a linear program, or a mixed-integer linear program when some decisions are on/off (which settings).

Notation

Symbol Meaning
t = 1…T Model steps; Δt the step length in hours
s = 1…S Scenarios with probabilities πs (S = 1 when deterministic)
Lt, Gt Load and PV, kW (per scenario)
pt, pxt Import and export price per kWh
it, xt Grid import and export, kW (variables, ≥ 0)

Every scenario has its own copy of the variables below; the scenario index is left out where it does not matter.

Objective

minimise   (1 − λ) Σ_s π_s C_s  +  λ CVaR_α(C)              (λ = 0 when deterministic)

C_s = Σ_t Δt p_t i_t − Σ_t Δt p^x_t x_t              energy, export credit
    + Σ_k r_k P_k + fixed                             demand charges, fixed charges
    + wear + Σ penalties − Σ revenues                 batteries, EVs, HVAC, services, events

with CVaR written in its linear form (Rockafellar–Uryasev): CVaRα = η + 1/(1 − α) Σs πs ζs, ζs ≥ Cs − η, ζs ≥ 0.

Power balance and grid

For every step:

i_t − x_t = L_t − g_t + Σ_b (c_bt − d_bt) + Σ_e (p_et − q_et) + Σ_h (P^heat_ht + P^cool_ht)
            + Σ_products expected deployment
0 ≤ i_t ≤ import_limit,   0 ≤ x_t ≤ export_limit  (0 when export is not allowed)

gt = Gt when PV is not curtailable, otherwise 0 ≤ gt ≤ Gt is a variable.

When export can be worth more than import (or exclusive_import_export is true), a binary zt forbids both at once: it ≤ M zt, xt ≤ M (1 − zt).

Tariff

  • Flat, TOU, series: pt is the time-weighted price of the step, plus adder_per_kwh, with critical-peak events applied.
  • Tiered: import is split into block variables, it = Σj qjt, each priced at its tier, with Σt in month m Δt qjt ≤ capacity of tier j in month m (less consumed_kwh for the first month). Prices rise with the tier, so the cheap blocks fill first without integer variables.
  • Demand charge k, month m: Pkm ≥ it for every step t of month m inside the window, Pkm ≥ peak_so_far_kw (first month), cost rk Pkm.

Batteries

For battery b with capacity E, limits C (charge) and D (discharge), efficiencies ηc, ηd and self-discharge σ per hour:

e_t = (1 − σΔt) e_{t−1} + η_c Δt c_t − Δt d_t / η_d          (e_0 = initial energy)
E·soc_min ≤ e_t ≤ E·soc_max,   0 ≤ c_t ≤ C,   0 ≤ d_t ≤ D
e_T ≥ e_0  (at_least_initial)  ·  e_T ≥ E·target  ·  nothing (free)

With negative prices (or exclusive_charge_discharge), a binary yt gives ct ≤ C yt, dt ≤ D (1 − yt).

Wear

  • Throughput: cost κ Δt dt, κ = cost_per_kwh.
  • Cycle depth (Xu et al. 2018): the energy range is split into J equal segments ejt ∈ [0, ΔE], et = E·soc_min + Σj ejt, each with its own balance and flows cjt, djt. Discharging segment j (depth band [δj−1, δj] from the top) costs R (Φ(δj) − Φ(δj−1)) / ΔE per kWh, with Φ(δ) = δk / N100 and R the replacement cost. Deeper segments cost more, so the battery uses its top segments first; the cost of a cycle is then the piecewise-linear approximation of Φ(depth) R.
  • Calendar: fade rate a + b·SOC (% per year) through the two given points; cost R / (100 − EOL) × (a + b·SOCt) × Δt / 8760 per step, linear in et.

Reported fade uses rainflow counting (ASTM E1049) of the state-of-charge path: Σ cycles × depthk / N100 × (100 − EOL) %.

EVs

During a session (steps where the car is plugged in for a fraction ft of the step):

e_t = e_{t−1} + η_c Δt p_t − Δt q_t / η_d                    (e = arrival energy before the first step)
0 ≤ p_t ≤ f_t P_max,   0 ≤ q_t ≤ f_t Q_max  (q = 0 without V2G)
e_min ≤ e_t ≤ e_max
e_last + u ≥ arrival energy + need,   0 ≤ u ≤ need  (u = 0 when must_meet)

with shortfall u penalised at shortfall_penalty_per_kwh. With charge_min_kw, a binary wt gives ft Pmin wt ≤ pt ≤ ft Pmax wt.

HVAC

The 1R1C zone model, integrated exactly over each step with a = exp(−Δt / (R C)):

T_t = a T_{t−1} + (1 − a) [ T^out_t + R (gains_t + COP^h_t P^h_t − COP^c_t P^c_t) ]
T_t + s^lo_t ≥ T^min_t,   T_t − s^hi_t ≤ T^max_t,   s ≥ 0

The slacks cost penalty_per_c_h × Δt per °C. On/off units add binaries with Pt = Pmax ut, and, for single-mode units with a hard band, the cut Σt ut ≥ k, where k is the least number of full-power steps that can hold the band (from a small LP with continuous power, rounded up).

Ancillary services

For product k, the offer Rkt ≥ 0 is common to all scenarios (0 outside the product's window, at most max_kw), split among providers: Rkt = Σv akvt. Revenue: Δt (capacity price × Rkt + deployment × energy price × Rkt).

For each battery, with Ut and Nt its up and down allocations summed over products and τ each product's duration_h:

U_t ≤ D − d_t + c_t                    e_t − Σ τ_k a_kt / η_d ≥ E·soc_min
N_t ≤ C − c_t + d_t                    e_t + Σ τ_k a_kt η_c ≤ E·soc_max

EVs: Ut ≤ pt − qt + ftQmax, Nt ≤ ftPmax − pt + qt. HVAC: Ut ≤ Pt, Nt ≤ Pmax − Pt. Expected deployment (deployment × allocation) flows through the battery balance and the site balance. Symmetric products add Rupkt = Rdownkt; min_kw adds a binary per step.

Demand response

With baseline Bt (default: the site's net demand without optimisation) and the share ft of the step inside the event:

Type Constraint Cost
payment rt ≤ Bt − (it − xt), 0 ≤ rt ≤ Bt − price × ft Δt rt
commitment it − xt − ut ≤ Bt − reduce penalty × ft Δt ut
cap it − ut ≤ limit penalty × ft Δt ut

Stochastic structure

Each scenario has its own variables and constraints. Non-anticipativity ties the device decisions of the first K steps (K = commit_hours / Δt, at least one) across scenarios: c, d (batteries), p, q (EVs), Ph, Pc (HVAC). Service offers are first-stage for the whole horizon.

Baseline

The baseline is simulated, not optimised: batteries idle; EVs charge at full power on arrival until their need is met; HVAC adds just enough heat or cooling to stay in the band (full power for on/off units); PV is used, and surplus exported if allowed. It is priced with the same tariff.

Tie-break

A schedule's cost usually has many minimisers. KERNEL returns a defined one (tie_break: "smooth"):

  1. Cost. Solve the problem. For a mixed-integer problem, fix the integer variables at their values and re-solve the LP to get duals.
  2. Smoothest on the optimal face. Using the duals, fix every variable and constraint that complementary slackness pins in all optimal solutions; this leaves exactly the set of optimal schedules. On it, minimise Σ wj xj2 over device powers, with w = 1 / rating (HiGHS QP). The minimiser is unique: no pointless cycling, charging spread evenly over equal-price periods, work shared in proportion to ratings.
  3. Exact. The QP solver leaves about 1e-4 infeasibility, so the point is moved to an exactly feasible, equally cheap schedule within 1e-5 of each rating.
  4. Level. Runs of consecutive values that agree to within 1e-4 of the rating (solver noise) are made exactly equal where that stays feasible and as cheap, so a block of equal prices gives one constant power.

The cost never changes (checked to 1e-9 relative). The tie-break runs when the problem has at most 2,000 weighted variables (for example, one day of 15-minute steps with ten batteries); beyond that, or if a stage does not finish cleanly, the stage-1 schedule is returned and smoothed is 0.

The storage scheduler

The storage scheduler solves the battery part of this model with a price series, one optional demand charge and optional export:

minimise   Σ_t Δt (p_t i_t − p^x x_t)  +  r P  +  κ Δt Σ_b,t (c_bt + d_bt)
subject to the battery equations above,  i_t − x_t = L_t + Σ_b (c_bt − d_bt),
           i_t ≤ P,  P ≥ billing_peak_kw,  x_t = 0 unless allow_export

Lt is the load net of generation and may be negative.

Legacy R9 model

model = LEGACY_R9 transcribes getESS.m (KERNEL/TEMS R9, May 2021). With η̄ = (ηc + ηd)/2 and battery power xbt ∈ [−D, C]:

minimise   Σ_t p_t g_t + r P
subject to E_min − E_0 ≤ η̄ Σ_{k≤t} x_bk ≤ E_max − E_0
           g_t = L_t + Σ_b x_bt,  g_t ≥ 0,   Σ_b x_bt − P ≤ −L_t

On the R9 sample it reproduces R9's forecast peak and total cost exactly, and its reduced peak (237.977667 kW) and optimal cost (9,479,774.86) to the printed precision.

Simplifications in R9

  1. No time step: kW were added to kWh, so with 15-minute steps a battery moved four times its real energy and energy costs were four times too high.
  2. Lossless round trip: charging x added η̄x and discharging x removed only η̄x, so cycling was free.
  3. Demand charge against today only, ignoring the month's peak so far.
  4. No end-of-day requirement: batteries drained to their minimum, and the savings included selling that energy.
  5. PV divided by 1000, and demand and PV files were not checked against each other.
  6. The AOS.csv writer corrupted earlier rows.

These are why the standard model is the default.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

Migrating from 1.x

KERNEL 2 is a re-implementation, not an update. KERNEL 1.x was a Windows-only C++ application (MFC/ATL, a particle-swarm optimiser) plus MATLAB code (R9, May 2021) exposed to Java through MATLAB Compiler wrappers. KERNEL 2 is one portable library with a C interface and C++, Python and Java bindings, for Windows and Linux on x86-64 and arm64. It needs no MATLAB Runtime.

What maps to what

1.x KERNEL 2
getESS.m (R9) / getSchedule.java The site model with batteries, or schedule_ess_files() for the 1.x files (Storage scheduler)
C++ objESS + PSO (particle swarm) A linear program solved by HiGHS (or SCIP, Gurobi, CPLEX)
objV2X (EV / vehicle-to-grid) EV charging, with sessions, V2G and minimum power
objSGS (controllable loads, HVAC) HVAC, with a thermal model and comfort bands
Demand and PV forecast results (Demand_Results.csv, PV_Results.csv) Read directly as data, including their distributions for stochastic optimisation (1.x files)
setDemand / getDemand, setPV / getPV (forecasting) Forecasting: "method": "kernel1" is the R9 ensemble ported ("options": {"r9_compat": true} for R9's exact behaviour); the default method is more accurate (Benchmark)
Demand_LTD.csv, PV_LTD.csv (forecast history) Read directly as forecasting history and features
TEMS REST API A separate project, built on this library
iniReader, Log, MFC UI Not carried over: a library has no UI or global log

Why the particle swarm was replaced. Scheduling a site is a linear (or mixed-integer) program. A solver returns the proven optimum, deterministically and without tuning. The swarm returned approximate answers that varied from run to run, and it needed a 9e8 penalty term to respect the peak limit.

Behaviour changes from R9

Each of these changes the numbers, and each fixes a problem in R9 (see The model):

  1. Energy uses the time step. At 15 minutes, a kW for one step is 0.25 kWh, so costs and state-of-charge changes are a quarter of R9's.
  2. Round-trip losses are real. Charge efficiency applies to charging and discharge efficiency to discharging. Reported power is the power at the site.
  3. The demand charge counts against the month's peak so far, so the optimiser no longer spends energy shaving a peak that does not set the bill.
  4. Batteries end the horizon with at least their starting energy by default (R9 behaviour: terminal: "free").
  5. PV is in kW, like demand. R9 divided it by 1000.
  6. Demand and PV must cover the same intervals. The R9 sample pairs building 1 on 2018-07-29 with building 3 on 2018-12-31; KERNEL 2 rejects that with a data error.
  7. Input checks with messages that name the file, line and column.
  8. One defined schedule among equals (tie-break).

To compare with an existing 1.x run, use the storage scheduler with model = LEGACY_R9. It reproduces R9's summary figures.

Error handling

1.x returned a flag or wrote to a log. KERNEL 2 returns a status from every C function, and the other languages raise exceptions; see Error messages.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

FAQ and troubleshooting

Results

Why does the battery end where it started? By default every battery must end with at least its starting charge (terminal: "at_least_initial"), so savings are not borrowed from after the horizon. Use "terminal": "free" to let it end anywhere, or {"soc_min_pct": …} for a target.

The battery does nothing. Why? Usually the price spread is not worth the losses (with 90 % round trip, buying at 0.10 must be repaid at more than 0.111), or a wear model makes cycling cost more than it saves. Check wear_cost and the prices in the price series. Also check soc_init_pct against soc_min_pct: a battery that starts at its minimum cannot discharge first.

Why is savings negative? It should not be, except with stochastic optimisation (the plan must work for every scenario, so in a given scenario it can cost more than the baseline), or with a soft comfort band that the baseline violates and the optimised schedule respects. Compare the cost terms in the summary.

Why are two batteries given the same power? That is the tie-break: when several schedules cost the same, KERNEL returns the one that shares the work in proportion to power ratings. Set "tie_break": "none" to get whichever schedule the solver finds first.

Why do numbers end in …999? Results are exact solutions of the model, printed with full precision. Round them for display.

Errors

"no schedule satisfies all the constraints" A hard limit cannot be met. The usual causes: the import limit is below the load; a battery's end-of-horizon target cannot be reached; an EV session with "must_meet": true cannot be charged in time; a service min_kw is too high; PV is above the load on a zero-export site without pv.curtailable. Remove limits one at a time to find it.

"'load' (…) covers … but the horizon runs from … to …" Every series must cover the whole horizon. Shorten the horizon, or give more data. With no horizon.end, duration or steps, the horizon follows the load data automatically.

"timestamps must increase" Two rows have the same time or go backwards. At the autumn daylight-saving change, local times repeat; give the timestamps with their UTC offset (2026-11-01T01:30-04:00, 2026-11-01T01:30-05:00).

"must be a fraction in (0, 1], e.g. 0.95 (not 95)" Efficiencies are fractions. Percentages are only for state of charge (…_pct settings).

Gurobi or CPLEX "not found" Set GUROBI_HOME (or KERNEL_GUROBI_LIBRARY to the library file), or the CPLEX_STUDIO_DIR<version> variable the CPLEX installer sets (or KERNEL_CPLEX_LIBRARY), or give solver_library in the configuration. Check with cediskernel solvers.

Performance

How big can a problem be? Up to 200,000 steps. As a guide, on one core: a house for two days at 15 minutes (battery, EV, heat pump) solves in about 0.1 s; an office for one day with five stochastic scenarios and services in about 0.3 s. Linear problems grow roughly linearly with steps × devices × scenarios.

It is slow. What can I do? - Find the integer variables (integer_variables in the summary). On/off HVAC, EV minimum power, service min_kw and exclusivity binaries make the problem mixed-integer; drop the ones you do not need. - Use a longer step or a shorter horizon. - Use fewer scenarios. - Set time_limit_s: the best schedule found so far is returned. - Try "solver": "scip", or Gurobi or CPLEX if you have them.

An on/off heat pump on a flat price hits the time limit. With a flat price nearly every on/off pattern that keeps the room warm costs the same, and proving which is optimal is slow. KERNEL adds a bound that helps, but the solver may still stop at time_limit_s with a small gap. The schedule is feasible and the result says status: time_limit. Use time-of-use prices (the common case), a modulating model ("on_off": false), or a shorter time_limit_s if a near-optimal answer is enough.

Are results the same on every machine? They are designed to be. With the default single thread and the smooth tie-break, the schedule is uniquely defined, so it agrees across Windows and Linux and across languages to the solver's tolerance (about 1e-6). With threads above 1, a mixed-integer solve can find a different schedule of the same cost.

Data

My data are hourly but I want 15-minute steps. That is fine. Powers keep their hourly average in every quarter hour; temperatures are interpolated. See Time and data.

My PV data are in W / my prices in ¢/kWh / my temperatures in °F. Add "unit": "W", "unit": "cents_per_kwh" or "unit": "F" to the series.

Can I use the results of one run as data for another? Yes: a results.json (or a results workbook) can be read as a data file.

Forecasting

How much history do I need? At least four weeks for a forecast; three months or more for demand and HVAC, so the model has seen different weather; a full year to learn seasons. With less than five weeks, KERNEL holds out a third of the days to score the model.

The forecast is flat or misses the peaks. Check the features: without the temperature, a model cannot know that tomorrow is colder. Check the holidays. Look at validation_skill_mae: below zero means the model is worse than "the same time last week", usually because the history is short or the site changed recently.

validation_coverage_80 is far below 80 %. The ranges are too narrow, usually because the last weeks of the history differ from the rest (new equipment, a holiday period). Retrain on data from after the change, or lengthen validation so the calibration sees more days.

Why is my forecast different from KERNEL 1.x? The default method is not the 1.x one. Set "method": "kernel1" for the ported 1.x ensemble, and add "options": {"r9_compat": true} for R9's exact behaviour. Even then the numbers differ somewhat, since MATLAB's neural network training and random numbers cannot be reproduced.

Training is slow. gbm takes seconds to a minute; kernel1 trains many neural networks and can take a few minutes on a year of 15-minute data. Train once and save the model file (Train once, forecast many times).

Will the same data give the same forecast on another computer? Yes. Training is deterministic for a given seed, on every platform and from every language.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

Roadmap and changes

2.1.0-alpha.1

Forecasting.

  • Models built from history for demand, PV, EV charging and HVAC, with quantile forecasts (p10 to p90 by default) at any step up to one hour and horizons up to 14 days; holidays, weather and other features; daylight saving handled (Forecasting).
  • Methods: gradient-boosted quantile trees with conformal calibration (gbm, the default), the KERNEL 1.x R9 ensemble ported (kernel1, with an R9-compatible mode), ridge regression (linear), the same time last week (seasonal_naive), and auto.
  • Benchmarked on the R9 sample data, Building Data Genome 2 and workplace EV charging; gbm was the most accurate in almost every case and is the default (Benchmark).
  • EV: expected sessions (arrival, departure, energy) from past sessions, and the uncontrolled charging load. HVAC: the building's thermal model (R, C, gains) fitted from indoor temperature.
  • Performance metrics: MAE, RMSE, bias, MAPE, sMAPE, WAPE, nRMSE, R², skill, daily peak, peak time and energy errors, pinball loss, CRPS, coverage, width, Winkler score, reliability (Metrics); every model scores itself on held-out days, and evaluate backtests methods.
  • Forecast and schedule in one call: {"forecast": ...} for data series, EV sessions and HVAC thermal models; forecast quantiles drive the stochastic scenarios.
  • Model files (JSON) to train once and forecast many times; the same results from C, C++, Python, Java and the command line (train, forecast, evaluate, model, metrics).
  • Data: "stamp": "end" for meter exports stamped at the end of each interval (detected automatically for KERNEL 1.x files).

2.0.0-alpha.1

First release of KERNEL 2, a re-implementation of KERNEL 1.x (R9, 2021).

Library - C++20 core behind a stable C interface, with a header-only C++ interface, a Python package (3.11+) and a Java package (22+, FFM), for Windows and Linux on x86-64 and arm64; a command-line tool.

Site model - Batteries with separate efficiencies, self-discharge, end-of-horizon targets, and an optional wear model per battery: throughput, cycle depth, calendar ageing. - EV charging: sessions with energy or state-of-charge targets, sessions from files, minimum charging power, vehicle-to-grid, shortfall reporting. - HVAC: 1R1C building model integrated exactly, heating and cooling, COP that follows the outdoor temperature, comfort schedules, soft or hard comfort, on/off units. - PV with optional curtailment; import and export limits; zero export. - Tariffs: time-of-use (the default), flat, tiered, series, critical peak, demand charges with windows, export, adders, fixed charges, holiday calendars; Ontario RPP presets effective 1 November 2026. - Ancillary services: regulation, reserves and user-defined products (up, down or symmetric) from batteries, EVs and HVAC; demand-response events. - Deterministic or stochastic optimisation (quantile, sampled or provided scenarios; non-anticipativity; CVaR). - Solvers: HiGHS (default) and SCIP built in; Gurobi and CPLEX loaded at run time; solver parameters passed through. - Data in CSV (default), Excel and JSON at any sample step, resampled to the model step (default 15 minutes); results in CSV (default), Excel or JSON at any output step (default: the model step); UTC offsets and daylight-saving changes handled. - Smooth tie-break: a defined, reproducible schedule among equally cheap ones. - Baseline simulation and savings in every result.

Storage scheduler - The battery-only interface with the standard and legacy R9 models, and the KERNEL 1.x CSV files.

Later

  • A rolling-horizon helper (re-plan every interval with fresh data, retrain forecasts on a schedule).
  • Probabilistic EV sessions (several session scenarios) for the stochastic optimisation.
  • A faster tie-break for long horizons, lifting the 2,000-variable limit.
  • More presets (other utilities and markets) as they are needed.
  • macOS builds, if needed.

The REST/API service is a separate project and builds on this library.

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab

Author

Kofi Agyeman, Ph.D, P. Eng

Research Specialization
Intelligent Cyber-Physical Energy Systems
Research Laboratory
Cyber-Physical Energy and Distributed Intelligent Systems Laboratory (CEDIS Lab)
Laboratory website
cedislab.org
Contact
kofi@cedislab.org

KERNEL 2.1.0-alpha.1 · Apache License 2.0 · CEDIS Lab