fix BA cutoff
Some checks failed
CI and deploy / migration-check (push) Failing after 13s
CI and deploy / deploy (push) Has been skipped

This commit is contained in:
Dusan Vojacek
2026-05-24 16:58:45 +02:00
parent 9d31b19ec6
commit 747a5bed08
5 changed files with 129 additions and 12 deletions

View File

@@ -59,7 +59,7 @@ NEG_SELL_CURTAIL_PENALTY_CZK_KWH = 1.0
NEG_SELL_PV_CHARGE_REWARD_CZK_KWH = 0.8
# Měkký tlak: v okně sell<0 dobít na soc_max (ne zastavit na ~94 % kvůli curtail).
NEG_SELL_SOC_UNDERFILL_PENALTY_CZK_PER_WH = 0.35
PLANNER_BUILD_TAG = "2026-05-25-neg-sell-no-export-fixed-v8"
PLANNER_BUILD_TAG = "2026-05-25-purchase-fixed-neg-sell-v9"
CORRECTION_WINDOW_H = 1 # hodina zpět pro výpočet korekčního faktoru
CORRECTION_MIN_CLAMP = 0.5 # spodní limit korekčního faktoru
CORRECTION_MAX_CLAMP = 1.5 # horní limit korekčního faktoru
@@ -665,11 +665,20 @@ def _slot_profitable_battery_export(
return sell_t > acq + min_spread
def _purchase_pricing_fixed(grid: Any) -> bool:
"""Režim nákupu z DB (`site_market_config.purchase_pricing_mode`), ne odhad z rozptylu buy."""
return (
str(getattr(grid, "purchase_pricing_mode", "spot") or "spot").strip().lower()
== "fixed"
)
def _horizon_fixed_tariff_like(slots: list[PlanningSlot]) -> bool:
"""
Fixní nákup (KV1): buy v horizontu je prakticky konstantní.
Heuristika pro drahý import / charge_acquisition: buy v horizontu je prakticky konstantní.
U spotu (home-01) nesmí expensive_import používat charge_acquisition — jinak
buy > ~1 Kč označí téměř všechny sloty jako drahé (gi=0 pro dům) → Infeasible.
BA81 má fixní nákup v DB, ale NT/VT → buy skáče; proto neg-sell export řídí _purchase_pricing_fixed.
"""
buys = [float(s.buy_price) for s in slots if float(s.buy_price) >= 0.0]
if not buys:
@@ -1184,7 +1193,8 @@ def solve_dispatch(
else min(float(s.buy_price) for s in slots)
)
min_spread_pre = float(degradation_cost_effective)
fixed_tariff_like_pre = _horizon_fixed_tariff_like(slots)
purchase_fixed_pre = _purchase_pricing_fixed(grid)
fixed_tariff_like_pre = purchase_fixed_pre or _horizon_fixed_tariff_like(slots)
profitable_export_ts_pre: set[int] = set()
if om == "AUTO":
for _t in range(T):
@@ -1641,8 +1651,9 @@ def solve_dispatch(
prob += ge[t] == 0
prob += ge_pv[t] == 0
prob += ge_bat[t] == 0
elif fixed_tariff_like_pre:
# BA81: při sell<0 neexportovat (záporná cena výkupu = platíš za export).
elif purchase_fixed_pre:
# Fixní nákup + spot výkup (BA81, KV1 bez block_export): sell<0 = platíš za vývoz.
# Nesouvisí s NT/VT skokem buy — řídí se výkupní cenou, ne rozptylem buy v horizontu.
# Přebytek FVE → baterie / curtail A; B přes z_gen_cutoff nebo bc_pv.
prob += ge[t] == 0
prob += ge_pv[t] == 0
@@ -1833,7 +1844,7 @@ def solve_dispatch(
float(s.pv_b_forecast_w) > 0
and not getattr(grid, "block_export_on_negative_sell", False)
and sell_t < 0
and not fixed_tariff_like_pre
and not purchase_fixed_pre
) or (
# KV1: plná baterie + kladný sell — neblokovat ge_pv==0 (jinak masivní curtail).
getattr(grid, "block_export_on_negative_sell", False)
@@ -1842,7 +1853,7 @@ def solve_dispatch(
)
# BA81: export pole B jen při kladném sell (po sell<0 jinak ge==0 výše).
fixed_pv_b_export_cap = (
fixed_tariff_like_pre
purchase_fixed_pre
and float(s.pv_b_forecast_w) > 0
and not getattr(grid, "block_export_on_negative_sell", False)
and sell_t >= 0
@@ -1870,7 +1881,7 @@ def solve_dispatch(
# Spot (home-01): buy > min ne-záporného buy v horizontu.
# Fixní tarif (KV1): navíc buy > charge_acquisition (konstantní buy ≈ ref).
expensive_import_slot = buy_t > ref_buy_horizon + min_spread
if _horizon_fixed_tariff_like(slots):
if fixed_tariff_like_pre:
expensive_import_slot = expensive_import_slot or (
buy_t > charge_acquisition_czk_kwh + min_spread
)
@@ -2600,11 +2611,14 @@ async def _load_site_context(site_id: int, db):
)
g = ctx["grid"]
m = ctx.get("market") or {}
grid = SimpleNamespace(
max_import_power_w=int(g["max_import_power_w"]),
max_export_power_w=int(g["max_export_power_w"]),
block_export_on_negative_sell=bool(g.get("block_export_on_negative_sell") or False),
deye_gen_microinverter_cutoff_enabled=bool(g.get("deye_gen_microinverter_cutoff_enabled") or False),
purchase_pricing_mode=str(m.get("purchase_pricing_mode") or "spot").strip().lower(),
sale_pricing_mode=str(m.get("sale_pricing_mode") or "spot").strip().lower(),
)
vehicles: list[SimpleNamespace] = []

View File

@@ -1222,7 +1222,7 @@ class NegativeSellPvChargeTests(unittest.TestCase):
50.0,
operating_mode="AUTO",
)
self.assertEqual(snap.get("planner_build_tag"), "2026-05-25-neg-sell-no-export-fixed-v8")
self.assertEqual(snap.get("planner_build_tag"), "2026-05-25-purchase-fixed-neg-sell-v9")
self.assertGreater(
results[0].battery_setpoint_w,
5_500,
@@ -1366,7 +1366,7 @@ class NegativeSellPvChargeTests(unittest.TestCase):
50.0,
operating_mode="AUTO",
)
self.assertEqual(snap.get("planner_build_tag"), "2026-05-25-neg-sell-no-export-fixed-v8")
self.assertEqual(snap.get("planner_build_tag"), "2026-05-25-purchase-fixed-neg-sell-v9")
self.assertEqual(len(results), len(slots))
def test_gen_cutoff_full_soc_neg_sell_with_pv_b_feasible(self) -> None:
@@ -1430,7 +1430,7 @@ class NegativeSellPvChargeTests(unittest.TestCase):
55.0,
operating_mode="AUTO",
)
self.assertEqual(snap.get("planner_build_tag"), "2026-05-25-neg-sell-no-export-fixed-v8")
self.assertEqual(snap.get("planner_build_tag"), "2026-05-25-purchase-fixed-neg-sell-v9")
self.assertEqual(len(results), len(slots))
def test_fixed_tariff_neg_sell_no_grid_export(self) -> None:
@@ -1460,6 +1460,8 @@ class NegativeSellPvChargeTests(unittest.TestCase):
max_export_power_w=16_000,
block_export_on_negative_sell=False,
deye_gen_microinverter_cutoff_enabled=True,
purchase_pricing_mode="fixed",
sale_pricing_mode="spot",
)
hp = SimpleNamespace(
rated_heating_power_w=0,
@@ -1493,6 +1495,71 @@ class NegativeSellPvChargeTests(unittest.TestCase):
self.assertGreaterEqual(r.battery_setpoint_w, 0, "neg sell má nabíjet")
self.assertGreaterEqual(r.grid_setpoint_w, 0, "neg sell bez exportu do sítě")
def test_ba81_fixed_purchase_nt_vt_buy_spread_neg_sell_no_export(self) -> None:
"""BA81: NT/VT buy v horizontu (rozptyl >0,25) — záporný sell stále bez exportu."""
slots = [
PlanningSlot(
interval_start=datetime(2026, 5, 25, 7, 0, tzinfo=timezone.utc)
+ timedelta(minutes=15 * i),
buy_price=3.088 if i % 2 == 0 else 4.086,
sell_price=-0.5,
pv_a_forecast_w=10_000,
pv_b_forecast_w=2_500,
load_baseline_w=300,
ev1_connected=False,
ev2_connected=False,
allow_charge=True,
allow_discharge_export=False,
charge_acquisition_buy_czk_kwh=3.61,
)
for i in range(4)
]
self.assertGreater(
max(s.buy_price for s in slots) - min(s.buy_price for s in slots),
0.25,
)
battery = _battery(uc_wh=12_500.0, terminal_soc_value_factor=0.0)
battery.soc_max_wh = 12_500.0
battery.max_charge_power_w = 6_250
grid = SimpleNamespace(
max_import_power_w=17_000,
max_export_power_w=16_000,
block_export_on_negative_sell=False,
deye_gen_microinverter_cutoff_enabled=True,
purchase_pricing_mode="fixed",
sale_pricing_mode="spot",
)
hp = SimpleNamespace(
rated_heating_power_w=0,
tuv_min_temp_c=45.0,
tuv_target_temp_c=55.0,
)
vehicles = [
SimpleNamespace(
max_charge_power_w=0,
battery_capacity_kwh=1.0,
default_target_soc_pct=80.0,
),
SimpleNamespace(
max_charge_power_w=0,
battery_capacity_kwh=1.0,
default_target_soc_pct=80.0,
),
]
results, _ms, _ = solve_dispatch(
slots,
battery,
hp,
grid,
[None, None],
vehicles,
8_000.0,
50.0,
operating_mode="AUTO",
)
for r in results:
self.assertGreaterEqual(r.grid_setpoint_w, 0)
class AutoPvSurplusExportTests(unittest.TestCase):
"""Plná baterie + vysoká FVE: export přebytku (ge_pv), ne curtailment, bez SELL."""

View File

@@ -10,6 +10,7 @@ declare
v_b jsonb;
v_hp jsonb;
v_grid jsonb;
v_market jsonb;
v_veh jsonb;
v_ev jsonb;
v_soc_pct numeric;
@@ -136,6 +137,25 @@ begin
raise exception 'No site_grid_connection for site_id=%', p_site_id;
end if;
select jsonb_build_object(
'purchase_pricing_mode', lower(trim(coalesce(smc.purchase_pricing_mode, 'spot'))),
'sale_pricing_mode', lower(trim(coalesce(smc.sale_pricing_mode, 'spot')))
)
into v_market
from ems.site_market_config smc
where smc.site_id = p_site_id
and smc.valid_to is null
order by smc.valid_from desc
limit 1;
v_market := coalesce(
v_market,
jsonb_build_object(
'purchase_pricing_mode', 'spot',
'sale_pricing_mode', 'spot'
)
);
select coalesce(
jsonb_agg(
jsonb_build_object(
@@ -263,6 +283,7 @@ begin
'battery', v_b,
'heat_pump', v_hp,
'grid', v_grid,
'market', v_market,
'vehicles', v_veh,
'ev_sessions', v_ev,
'soc_wh', v_soc_wh,

View File

@@ -18,7 +18,8 @@
- **Load-first (Deye, AUTO):** proměnné `pv_ld` (PV → load+EV+TČ), `pv_sp` (přebytek), `bc_pv` / `bc_gi`. Plná bilance `pv_a + pv_b + gi + bd = load + ev + hp + bc + ge`; `bc_pv + ge_pv ≤ pv_sp`; `gi ≤ load + bc_gi`; mimo `allow_discharge_export`: `bd ≤ load pv_ld` a **`pv_ld ≥ load gi bd`**. Snapshot: `load_first_enabled=true`. Test `LoadFirstDispatchTests`.
- **Tvrdé výkonové limity site/baterie:** `gi ≤ site_grid_connection.max_import_power_w` (breaker); **`bc_pv + bc_gi ≤ asset_battery.max_charge_power_w`**; **`ge ≤ max_export_power_w`** (proměnná `ge`, platí `ge = ge_pv + ge_bat`); **`bd + ge_bat ≤ asset_battery.max_discharge_power_w`** (vybíjení do domu + export z baterie nesmí současně překročit BMS). Dříve LP dovoloval import+nabíjení a dvojnásobné nabíjení; u prodeje hrozilo současné `bd` a `ge_bat` až 2× max discharge — viz `SitePowerCapTests`.
- **Hodnota FVE (PV store value):** `ge_pv = 0`, pokud `sell < future_sell_opportunity degradation` (ne `charge_acquisition` — u fixního KV1 by jinak blokoval export při sell 2 Kč). **Před prvním `sell < 0` v horizontu:** při `sell ≥ 0` smí `ge_pv` až do `pv_sp` (strategie BA81: vyvézt přes poledne, pak nabít z FVE v záporném okně). Výjimka **nucený vent** jen plná baterie. Testy `Home01PvStoreValueTests`, `PreNegativeSellExportTests`.
- **Drahý nákup → vlastní spotřeba z baterie:** mimo `allow_charge` platí `bd + pv_ld ≥ load_baseline + hp[t]` a `gi ≤ EV + hp[t]` (ne `hp_rated`). **Spot:** drahý slot = `buy > min(buy≥0) + degradace`. **Fixní tarif (KV1):** navíc `buy > charge_acquisition + degradace` (`_horizon_fixed_tariff_like` — rozptyl buy &lt; 0,25 Kč/kWh). Na spotu **nesmí** `charge_acquisition` (~0,9 Kč) označit všechny sloty jako drahé → Infeasible (home-01). Při **Infeasible** solver jednou opakuje s `relaxed_expensive_import` (síť smí krmit baseload v drahých slotech; v `solver_params.inputs.relaxed_expensive_import=true`). Testy `AutoPassiveSelfConsumptionTests`, `test_spot_low_acquisition_does_not_mark_all_slots_expensive`, `test_negative_buy_in_horizon_does_not_block_all_grid_import`.
- **Drahý nákup → vlastní spotřeba z baterie:** mimo `allow_charge` platí `bd + pv_ld ≥ load_baseline + hp[t]` a `gi ≤ EV + hp[t]` (ne `hp_rated`). **Spot:** drahý slot = `buy > min(buy≥0) + degradace`. **Fixní nákup (DB `purchase_pricing_mode=fixed` nebo heuristika rozptylu buy &lt; 0,25):** navíc `buy > charge_acquisition + degradace`. Na spotu **nesmí** `charge_acquisition` (~0,9 Kč) označit všechny sloty jako drahé → Infeasible (home-01). Při **Infeasible** solver jednou opakuje s `relaxed_expensive_import` (síť smí krmit baseload v drahých slotech; v `solver_params.inputs.relaxed_expensive_import=true`). Testy `AutoPassiveSelfConsumptionTests`, `test_spot_low_acquisition_does_not_mark_all_slots_expensive`, `test_negative_buy_in_horizon_does_not_block_all_grid_import`.
- **Záporný výkup (`sell < 0`) bez exportu:** `block_export_on_negative_sell` (KV1) **nebo** `purchase_pricing_mode=fixed` z `fn_planning_site_context` (BA81) — **ne** podle rozptylu buy v horizontu (v8 chyba). Spot nákup (home-01) může při plné baterii ventovat PV B. Tag `2026-05-25-purchase-fixed-neg-sell-v9`, test `test_ba81_fixed_purchase_nt_vt_buy_spread_neg_sell_no_export`.
- **Pole B při sell&lt;0 (home-01):** pokud `block_export_on_negative_sell = false`, LP nesmí vynutit `ge_pv = 0` (přebytek neriťitelného PV B). KV1 s `block_export = true` jen curtail A / nabíjení.
- **`ref_buy_min` (brána exportu):** `min(buy_price)` horizontu — jen „existuje levný nákup?“, **ne** průměrná cena nabití přes hodiny. Export sloty: `sell > ref_buy_min + degradation` (spot). Viz [`planning-arbitrage-accounting.md`](planning-arbitrage-accounting.md).
- Pokud `energy_to_fill <= 0` nebo `charge_slot_buffer = 0`: všechny sloty povoleny.

View File

@@ -5,6 +5,20 @@ Formát: **datum (ISO)** · stručný důvod · soubory · chování / ověřen
---
## 2026-05-25 (m) — BA81: záporný výkup bez exportu podle DB `purchase_pricing_mode`
**Problém (tag v8 v produkci):** KV1 OK; **BA81** pořád export při `sell < 0` (dnes i zítra). v8 používalo `_horizon_fixed_tariff_like` (rozptyl **buy** &lt; 0,25 Kč/kWh). U BA81 buy skáče **NT/VT** (3,09 ↔ 4,09) → heuristika **false** → zákaz exportu se neaplikoval.
**Oprava (tag `2026-05-25-purchase-fixed-neg-sell-v9`):**
- `ems.fn_planning_site_context` vrací **`market.purchase_pricing_mode`** / **`sale_pricing_mode`** z `site_market_config`.
- Při **`sell < 0`** a **`purchase_pricing_mode = fixed`**: `ge = 0` (nezávisle na rozptylu buy). **home-01** (spot nákup) výjimku nemá — může ventovat PV B.
- `_horizon_fixed_tariff_like` zůstává jen pro **drahý import** / `charge_acquisition` (heuristika + DB `fixed`).
**Ověření:** `pytest …::NegativeSellPvChargeTests::test_ba81_fixed_purchase_nt_vt_buy_spread_neg_sell_no_export`; po deploy + replan BA81: žádný `grid < 0` při `sell < 0` v MCP.
---
## 2026-05-25 (l) — Plán 25. 5.: BA81 neg. výkup bez exportu, KV1 ranní curtail
**Problém (MCP plán run 1634616350, tag v7):** KV1 0608 h masivní **curtail** FVE (plná baterie, `ge_pv=0` z pv_store). BA81 při `sell<0` **export ~10 kW** místo nabíjení. Večer slabý export u KV1/home-01 (spot: `sell < buy`).