Skip to content

feat(plan): metric_battery_grid_charge_cost - extra cost per kWh of grid energy into the battery - #6209

Open
brdsutte wants to merge 3 commits into
springfall2008:mainfrom
brdsutte:feature/battery-grid-charge-cost
Open

brdsutte wants to merge 3 commits into
springfall2008:mainfrom
brdsutte:feature/battery-grid-charge-cost

Conversation

@brdsutte

@brdsutte brdsutte commented Nov 15, 2026 •

Copy link
Copy Markdown

Fixes #6207

Adds an expert-mode setting metric_battery_grid_charge_cost (p/kWh, default 0): an extra cost on grid energy that ends up in the battery, for installations where grid charging costs more than the import rate - e.g. a generation subsidy (green certificates in Flanders) paid on a generation meter between the inverter and the house, which counts grid energy going into the inverter as negative generation, so every kWh charged from the grid loses the subsidy on the round-trip losses. As discussed in the issue, it is a direct p/kWh setting (not auto-derived), and it only applies to grid energy charged into the battery - not to energy consumed directly by the house.

What changes

  • Simulation (prediction.py, mirrored in prediction_kernel.cpp): per step, only the grid import that covers the battery's AC charge demand is charged:
    grid_to_battery = min(diff - car_gone_kwh, -(battery_draw + pv_dc) / inverter_loss), if positive. PV serves the house first, house load imported during a charge window is not charged, and neither are solar charging or discharging.
  • Planner (plan.py): battery_value_rate includes the cost in the refill cost (not in the cap, see review), and the charge-window price sort (sort_window_by_price_combined) adds it to charge (c) entries the same way as the losses and metric_battery_cycle. That keeps the order among charge windows, but moves them relative to the freeze-charge (cf) entries and changes the price bands.
  • Output (output.py): the plan's adjusted import rate includes it, and the settings line in the log shows it when non-zero.
  • Config: new CONFIG_ITEMS entry (expert mode, min 0, default 0), read in fetch_config_options(), default in PredBat.reset(), copied into Prediction with a getattr fallback for older debug dumps.
  • Docs: new paragraph in docs/customisation.md next to metric_battery_cycle.

With the default of 0 every calculation is bit-identical to before ((rate + 0) / losses is unchanged and the new simulation term is skipped).

Deliberately not changed / design choices

  • Not added in compute_metric() (as the triage comment suggested, like metric_battery_cycle): import_kwh_battery counts all import during a charge window, including house load, so it would over-attribute (the triage comment flags this too). Counting only grid energy into the battery needs the per-step battery draw and PV, which only the simulation has. Adding a separate result for it would mean changing the 11-value prediction result tuple at ~18 call sites, so the cost is added to the simulated metric instead, the way the car rate premium is. A side effect is that it shows in cost predictions, which I think is right as it is a real cost, but I'm happy to rework it if you prefer.
  • battery_value_rate includes the cost because refilling the battery from the grid pays it too.
  • Export pricing is unchanged: the generation subsidy doesn't depend on whether energy is exported.

Kernel

  • PkContext gains battery_grid_charge_cost after iboost_rate_threshold_export: PK_ABI_VERSION / KERNEL_ABI_VERSION 11 -> 12, PK_PARITY_REVISION / KERNEL_PARITY_REVISION 20 -> 21.
  • Binaries rebuilt with build_kernel_cross.sh using zig 0.16.0 (as in CI), since the kernel-binaries job doesn't run on fork PRs. The x86_64 binary passes verify_kernel_binary.py.

Testing

  • New tests/test_battery_grid_charge_cost.py (registered as battery_grid_charge_cost):
    • simulation: hybrid and AC-coupled grid-only charging, charging with house load, full and partial solar charging, discharge only; each case asserts the metric rises by exactly cost x grid energy into the battery and that energy flows and SoC are unchanged; every case runs on the Python engine and on the C++ kernel;
    • battery_value_rate rises by cost / losses;
    • config wiring (expert-mode item, fetch_config_options());
    • optimiser: a 6p window with 10% inverter loss and 10p house import is charged with cost 0 and dropped with 4p ((6+4)/0.9 > 10).
  • kernel_parity random scenarios now also randomise the new cost (drawn last, so the existing seeded scenarios are unchanged).
  • pre-commit run --all-files passes (check-json5 could not run locally; it only covers files this PR doesn't touch).
  • unit_test.py --quick passes with PREDBAT_KERNEL_REQUIRED=1, as do optimise_windows_kernel and debug_cases (Python 3.13 locally).
  • GitNexus impact analysis (detect-changes --scope compare against main): 19 files, 38 symbols, 14 flows, risk high - battery_value_rate is CRITICAL (it feeds compute_metric and the whole optimiser) and Prediction.run_prediction is central. That is expected for a cost term in the core model; with the default of 0 every calculation is bit-identical.
  • Running on my own system (FoxESS H1 G2 via Fox cloud, Belgian day-ahead prices, read-only) since 15 Nov: with metric_battery_grid_charge_cost 4.05 the plan's adjusted import rate is e.g. (29.09 + 4.05) / (0.98 x 0.975) + 1 = 35.68p as expected.

Nothing that I'm aware of is failing on main.

Developed with the help of Claude (Anthropic); I reviewed the change.

@springfall2008 springfall2008 left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated comment from the triage bot.

Reviewed head commit e1d97ef1 (metric_battery_grid_charge_cost). The new simulation term in prediction.py is arithmetically right on every path I traced — it matches get_diff's AC conversion for a charging step, fires only when net DC flow is charging, and handles the gone-car allocation, PV-covered charging and discharge/export steps correctly — and the C++ kernel mirrors it exactly with ABI/parity bumped. 3 findings, all inline: one correctness issue in battery_value_rate (the cap drops the new cost, so the setting can be a no-op on flat tariffs) and two maintainer-rule findings (a getattr with a false justification, and no test for any of the three output.py changes).

Comment thread apps/predbat/plan.py Resolved
Comment thread apps/predbat/prediction.py Resolved
Comment thread apps/predbat/output.py Resolved
@springfall2008 springfall2008 removed the BOT_REVIEW Trigger an autotriage label Nov 15, 2026
@brdsutte

Copy link
Copy Markdown
Author

Thanks for the review - pushed a follow-up commit:

  1. getattr in Prediction - agreed, PredBat.reset() always sets it. It's now a direct copy.
  2. output.py untested - added run_grid_charge_output_tests: with cost 0 and 4p it checks import_rate_adjusted in the JSON plan, the plan_debug HTML figure and the log_option_best line (named only when non-zero). Reverting the output.py changes makes it fail on all three.
  3. battery_value_rate cap - I've kept the cap as it is, deliberately. The cap is what a stored kWh can realise by avoiding an import at the highest rate after losses. The grid charge cost is paid on the way into the battery, not on the way out, so it raises the replacement cost but not what discharging the energy can save. Lifting the cap by the cost would value stored energy above what it can realise, which the docstring says leads to freeze charging every window. So on a flat tariff the cost correctly has no effect on the battery value: grid charging never pays there, and the stored kWh is worth what it displaces. I've added run_grid_charge_battery_value_cap_tests to pin this, and clarified the docstring and customisation.md. Happy to change it if you see it differently.

Quick suite (with PREDBAT_KERNEL_REQUIRED=1) and pre-commit run --all-files pass. No kernel changes in this commit.

@springfall2008 springfall2008 added the BOT_REVIEW Trigger an autotriage label Nov 15, 2026

@springfall2008 springfall2008 left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated comment from the triage bot.

Reviewed head f2d87b21; this supersedes the review of e1d97ef1. 2 findings inline, 0 in the body.

I re-read the whole diff, not only the follow-up commit. The earlier findings are settled: the getattr in Prediction.__init__ is now a direct copy, and run_grid_charge_output_tests does fail when the three output.py sites are reverted. On the third, I accept your reasoning for leaving the battery_value_rate cap alone - the cost is paid on the way into the battery while the cap is what a stored kWh can realise by avoiding an import, so on a flat tariff the setting correctly has no effect there. My earlier framing of that as a defect was wrong, and run_grid_charge_battery_value_cap_tests now pins the intended behaviour.

Verified this pass:

  • the simulation term min(diff - car_gone_kwh, -(battery_draw + pv_dc) * inverter_loss_recp) charges exactly the AC import that covers the battery's charge demand, for both hybrid (DC PV offsets the charge) and AC-coupled (surplus PV lowers diff first), and is zero when PV covers the charge, when the gone car's share is netted off, and on discharge - the recp matches the branch get_diff takes for a negative balance;
  • the C++ mirror is line-for-line, the new PkContext field sits after iboost_rate_threshold_export on both sides, and ABI 12 / parity 21 are bumped in prediction_kernel.cpp and prediction_kernel.py together;
  • the four adjusted-charge-rate sites (battery_value_rate, the charge sort, the plan_debug string and import_rate_adjusted) all use the same (rate + cost) / battery_loss / inverter_loss convention, so the planner, the simulation and the display agree;
  • the new module is registered in TEST_REGISTRY, its kernel pass is skipped only via kernel_available(), and it restores the state it mutates (reset_inverter, fetch_config_options, plan_debug, log).

Comment thread apps/predbat/plan.py Resolved
Comment thread apps/predbat/plan.py
# Account for losses in average rate as it makes import higher
average = window["average"] / self.inverter_loss / self.battery_loss + self.metric_battery_cycle
# Account for losses in average rate as it makes import higher, and for any grid charge cost on top of it
average = (window["average"] + self.metric_battery_grid_charge_cost) / self.inverter_loss / self.battery_loss + self.metric_battery_cycle

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated comment from the triage bot.

Adding the same metric_battery_grid_charge_cost to every window's average and dividing by the same losses cannot reorder the windows - only the 0.2p banding from dp1(average / 2) * 2 changes which windows tie and fall back to the time/id tie-break. The resulting level is read only for price_set ordering; charge_window_best[...]["set"] is written here and nowhere else. In the optimiser test's own numbers the two windows get adjusted averages of 6.67 and 11.11 without the cost and 11.11 and 15.56 with it, so they sort the same way either way, and no test asserts a level value - reverting this line would not fail the suite. If the intent is the reported charge level, a one-line assertion on price_set (or window_links[...]["average"]) would pin it; if the intent is the shortlist ordering, the PR description overstates it. Not a blocker either way, but the description's "so the window shortlist agrees with the simulation" reads as if the ordering depended on it.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed for the order among charge windows - corrected the description. It does move charge entries relative to the freeze-charge entries in the same sort (they carry no losses, cycle cost or grid charge cost), now pinned by run_grid_charge_window_sort_tests in fd54007. Details in the comment below.

@springfall2008 springfall2008 removed the BOT_REVIEW Trigger an autotriage label Nov 15, 2026
@brdsutte

Copy link
Copy Markdown
Author

Thanks - pushed a follow-up:

  1. Cap docstring - reworded: the cap is what a stored kWh can save by avoiding an import at the highest rate after losses and the cycle cost, and metric_battery_grid_charge_cost doesn't lift it because it is paid on the way into the battery, not on the way out.
  2. Window average - agreed it can't reorder charge windows among themselves, and that the description overstated it. It does change the order relative to the freeze-charge (cf) entries in the same sort, which carry neither losses, cycle cost nor the grid charge cost. With windows at 10p and 12p and a 4p cost, the sort goes from c12, cf12, c10, cf10 to c16, c14, cf12, cf10, so the 10p charge entry moves ahead of the 12p freeze entry (and the levels stop sharing bands). That matches how losses and metric_battery_cycle are already applied to c but not cf. Added run_grid_charge_window_sort_tests to pin this; it fails without the plan.py change.

Quick suite (with PREDBAT_KERNEL_REQUIRED=1) and pre-commit run --all-files pass.

brdsutte and others added 3 commits November 16, 2026 00:11
…rid energy into the battery

Some installations pay more for grid charging than the import rate - for example where a generation
subsidy (green energy certificates in Flanders) is paid on a generation meter between the inverter and
the house, which counts grid energy going into the inverter as negative generation, so every kWh
charged from the grid loses the subsidy on the round-trip losses.

Add an expert-mode setting, metric_battery_grid_charge_cost (p/kWh, default 0), that the simulation
adds to the metric for the grid import covering the battery's AC charge demand only: solar charging,
discharging and import that serves the house are unaffected. The charge-window price sort, the battery
value (refill cost) and the plan's adjusted import rate include it too.

The C++ kernel mirrors the change (ABI 12, parity 21) and the binaries are rebuilt with zig 0.16.0.
With the default of 0 every calculation is bit-identical to before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GwWwnCWzPxCS83RgVj4GXH
- Prediction copies metric_battery_grid_charge_cost directly: PredBat.reset() always sets it, so the
  getattr fallback was not needed.
- Test the output.py changes: import_rate_adjusted in the JSON plan and the plan_debug HTML figure include
  the cost, and log_option_best names the setting only when it is non-zero.
- Keep the battery_value_rate cap unchanged and pin it with a flat-tariff test: the grid charge cost is paid
  when charging, not when discharging, so it raises the replacement cost but not what a stored kWh can
  realise, which is what the cap bounds. Docstring and docs say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GwWwnCWzPxCS83RgVj4GXH
… sort

- battery_value_rate docstring: the cap is what a stored kWh can save by avoiding an import at the
  highest rate after losses and the cycle cost; the grid charge cost does not lift it because it is
  paid on the way into the battery, not on the way out.
- New run_grid_charge_window_sort_tests: the cost shifts charge ("c") entries but not freeze charge
  ("cf") entries, so with windows at 10p and 12p and a 4p cost the 10p window's charge entry moves
  ahead of the 12p window's freeze entry and the levels stop sharing bands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GwWwnCWzPxCS83RgVj4GXH
@brdsutte
brdsutte force-pushed the feature/battery-grid-charge-cost branch from fd54007 to bf51e3f Compare November 15, 2026 23:11
@brdsutte

Copy link
Copy Markdown
Author

Rebased onto current main. #6212 took kernel ABI 12 and parity revision 23, so this change now uses ABI 13 / parity 24. Kernel binaries rebuilt for all platforms with build_kernel_cross.sh (zig 0.16.0); verify_kernel_binary.py passes parity and ./run_all --quick passes.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

extra cost per kWh charged into the battery from the grid due to lost green certificates / generation subsidy

2 participants