mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-10-09 16:06:40 +00:00
feat(optimization): split the control horizon from the forecast tail
The optimizer treated the end of `optimization.horizon_hours` as the end of the world: energy left in the battery there was worth a single configured price per kWh, so it either dumped the battery into the last hours or hoarded it, depending on that one number. The horizon is now two spans. `horizon_hours` still receives every control command. The new `optimization.tail_horizon_hours` (default 48 h) is a pure lookahead that never produces a command. In AUTO terminal-value mode a deterministic dynamic program solves that tail backwards on a 101-point SoC grid using the production battery and inverter models - SoC bounds, power caps, conversion losses, configured charge and export rates, direct-marketing permission and LCOS on delivered DC energy - and the existing AUTO proxy supplies the continuation value at the tail end. Genetic fitness reads the resulting curve. `tail_horizon_hours: 0` restores the plain proxy at the control end, FIXED is unchanged. The forecast budget is reported, never enforced by refusal: a tail that does not fit is shortened to what the forecast covers and reported as `effective_tail_hours`, and a control horizon that does not fit is warned about at configuration time and rejected by the optimizer at run time, which knows which series ran out. `prediction.hours` defaults to 72 so the new defaults fit out of the box; existing shorter configurations keep starting. Control arrays and warm-start genomes now begin at the run timestamp rather than midnight, flagged by `controls_start_at_now` so the adapters still read older solutions. `forecast_interval_seconds` declares the resolution of shortened native quarter-hour inputs. Required forecasts are no longer silently replaced by demo providers. A missing PV, price, load, feed-in or weather forecast used to rewrite the configured provider and retry, so a run could quietly optimize against invented data. Missing values now stay missing, and provider values are held only within their own source interval instead of being extended indefinitely. Also fixes a config update that could leave EOS half-updated: the merged candidate is validated before the singleton is reinitialized. Four provider tests that hard-coded the old 48 h prediction default are rewritten to derive their expectations from the configured horizon.
This commit is contained in:
@@ -121,9 +121,9 @@ def test_update_data(mock_get, provider, sample_akkudoktor_1_json, cache_store):
|
||||
|
||||
# Assert: Verify the result is as expected
|
||||
mock_get.assert_called_once()
|
||||
assert (
|
||||
len(provider) == 73
|
||||
) # we have 48 datasets in the api response, we want to know 48h into the future. The data we get has already 23h into the future so we need only 25h more. 48+25=73
|
||||
# The API response holds 48 datasets, 23 h of which already reach into the
|
||||
# future, so the provider forecasts the remaining hours of the horizon itself.
|
||||
assert len(provider) == 48 + provider.config.prediction.hours - 23
|
||||
|
||||
# Assert we get hours prioce values by resampling
|
||||
np_price_array = provider.key_to_array(
|
||||
|
||||
@@ -125,9 +125,9 @@ def test_update_data(mock_get, provider, sample_energycharts_json, cache_store):
|
||||
|
||||
# Assert: Verify the result is as expected
|
||||
mock_get.assert_called_once()
|
||||
assert len(provider) == 72
|
||||
# The final raw timestamp already represents its complete interval. Thus the
|
||||
# 48 API values need 24, rather than 25, additional hourly forecasts.
|
||||
# 48 API values need one hour less of extrapolation than the horizon suggests.
|
||||
assert len(provider) == 48 + provider.config.prediction.hours - 24
|
||||
|
||||
# Assert we get hours prioce values by resampling
|
||||
np_price_array = provider.key_to_array(
|
||||
|
||||
@@ -55,6 +55,7 @@ def provider(config_eos):
|
||||
"provider": "FeedInTariffTibber",
|
||||
},
|
||||
"prediction": {"hours": 2},
|
||||
"optimization": {"horizon_hours": 2, "tail_horizon_hours": 0},
|
||||
}
|
||||
)
|
||||
value = FeedInTariffTibber()
|
||||
|
||||
@@ -16,7 +16,7 @@ def _configure_hourly_grid(config_eos: ConfigEOS, *, start_hour: int = 0) -> Non
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": 48},
|
||||
"optimization": {"horizon_hours": 48, "interval": 3600},
|
||||
"optimization": {"tail_horizon_hours": 0, "horizon_hours": 48, "interval": 3600},
|
||||
}
|
||||
)
|
||||
get_ems(init=True).set_start_datetime(to_datetime().set(hour=start_hour, minute=0))
|
||||
@@ -58,17 +58,17 @@ def test_ev_repair_is_resimulated_before_fitness_assignment(config_eos: ConfigEO
|
||||
opt.optimize_ev = True
|
||||
opt.ev_possible_charge_values = [0.0, 1.0]
|
||||
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
|
||||
individual = creator.Individual([0] * opt.total_slots + [1] * opt.total_slots)
|
||||
individual = creator.Individual([0] * opt.control_slots + [1] * opt.control_slots)
|
||||
|
||||
first_result = {
|
||||
"Gesamtbilanz_Euro": 10.0,
|
||||
"Gesamt_Verluste": 0.0,
|
||||
"EAuto_SoC_pro_Stunde": np.full(opt.total_slots, 100.0),
|
||||
"EAuto_SoC_pro_Stunde": np.full(opt.control_slots, 100.0),
|
||||
}
|
||||
repaired_result = {
|
||||
"Gesamtbilanz_Euro": 1.0,
|
||||
"Gesamt_Verluste": 0.0,
|
||||
"EAuto_SoC_pro_Stunde": np.full(opt.total_slots, 100.0),
|
||||
"EAuto_SoC_pro_Stunde": np.full(opt.control_slots, 100.0),
|
||||
}
|
||||
parameters = SimpleNamespace(
|
||||
ems=SimpleNamespace(preis_euro_pro_wh_akku=0.0),
|
||||
@@ -82,7 +82,7 @@ def test_ev_repair_is_resimulated_before_fitness_assignment(config_eos: ConfigEO
|
||||
|
||||
assert evaluate.call_count == 2
|
||||
assert fitness == pytest.approx((1.0,))
|
||||
assert individual[opt.total_slots :] == [0] * opt.total_slots
|
||||
assert individual[opt.control_slots :] == [0] * opt.control_slots
|
||||
|
||||
|
||||
def test_fitness_cache_restores_canonical_ev_genome(config_eos: ConfigEOS):
|
||||
@@ -98,9 +98,9 @@ def test_fitness_cache_restores_canonical_ev_genome(config_eos: ConfigEOS):
|
||||
result = {
|
||||
"Gesamtbilanz_Euro": 1.0,
|
||||
"Gesamt_Verluste": 0.0,
|
||||
"EAuto_SoC_pro_Stunde": np.full(opt.total_slots, 100.0),
|
||||
"EAuto_SoC_pro_Stunde": np.full(opt.control_slots, 100.0),
|
||||
}
|
||||
first = creator.Individual([0] * opt.total_slots + [1] * opt.total_slots)
|
||||
first = creator.Individual([0] * opt.control_slots + [1] * opt.control_slots)
|
||||
duplicate = creator.Individual(first)
|
||||
opt._fitness_cache_enabled = True
|
||||
|
||||
@@ -113,7 +113,7 @@ def test_fitness_cache_restores_canonical_ev_genome(config_eos: ConfigEOS):
|
||||
assert evaluate.call_count == 2
|
||||
assert first_fitness == duplicate_fitness
|
||||
assert duplicate == first
|
||||
assert duplicate[opt.total_slots :] == [0] * opt.total_slots
|
||||
assert duplicate[opt.control_slots :] == [0] * opt.control_slots
|
||||
assert duplicate.extra_data == first.extra_data
|
||||
assert opt._fitness_cache_hits == 1
|
||||
assert opt._fitness_cache_misses == 1
|
||||
@@ -128,7 +128,7 @@ def test_fitness_cache_never_stores_failed_evaluations(config_eos: ConfigEOS):
|
||||
ems=SimpleNamespace(preis_euro_pro_wh_akku=0.0),
|
||||
eauto=None,
|
||||
)
|
||||
first = creator.Individual([0] * opt.total_slots)
|
||||
first = creator.Individual([0] * opt.control_slots)
|
||||
duplicate = creator.Individual(first)
|
||||
opt._fitness_cache_enabled = True
|
||||
|
||||
@@ -142,7 +142,7 @@ def test_fitness_cache_never_stores_failed_evaluations(config_eos: ConfigEOS):
|
||||
assert opt._fitness_cache == {}
|
||||
|
||||
|
||||
def test_fitness_cache_ignores_elapsed_control_slots(config_eos: ConfigEOS):
|
||||
def test_fitness_cache_includes_first_run_relative_control(config_eos: ConfigEOS):
|
||||
_configure_hourly_grid(config_eos, start_hour=10)
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt.optimize_ev = False
|
||||
@@ -154,9 +154,9 @@ def test_fitness_cache_ignores_elapsed_control_slots(config_eos: ConfigEOS):
|
||||
result = {
|
||||
"Gesamtbilanz_Euro": 1.0,
|
||||
"Gesamt_Verluste": 0.0,
|
||||
"EAuto_SoC_pro_Stunde": np.zeros(opt.total_slots),
|
||||
"EAuto_SoC_pro_Stunde": np.zeros(opt.control_slots),
|
||||
}
|
||||
first = creator.Individual([0] * opt.total_slots)
|
||||
first = creator.Individual([0] * opt.control_slots)
|
||||
elapsed_variant = creator.Individual(first)
|
||||
elapsed_variant[0] = 1
|
||||
opt._fitness_cache_enabled = True
|
||||
@@ -165,23 +165,23 @@ def test_fitness_cache_ignores_elapsed_control_slots(config_eos: ConfigEOS):
|
||||
first_fitness = opt.evaluate(first, parameters, 10, False) # type: ignore[arg-type]
|
||||
variant_fitness = opt.evaluate(elapsed_variant, parameters, 10, False) # type: ignore[arg-type]
|
||||
|
||||
assert evaluate.call_count == 1
|
||||
assert evaluate.call_count == 2
|
||||
assert first_fitness == variant_fitness
|
||||
assert opt._fitness_cache_hits == 1
|
||||
assert opt._fitness_cache_hits == 0
|
||||
|
||||
|
||||
def test_mutated_warm_start_neighbors_keep_elapsed_slots(config_eos: ConfigEOS):
|
||||
def test_mutated_warm_start_neighbors_stay_within_control_horizon(config_eos: ConfigEOS):
|
||||
_configure_hourly_grid(config_eos, start_hour=10)
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt.optimize_ev = False
|
||||
opt.setup_deap_environment({"home_appliance": 0}, start_hour=10)
|
||||
start_solution = [0] * opt.total_slots
|
||||
start_solution = [0] * opt.control_slots
|
||||
|
||||
neighbors = opt._mutated_warm_start_neighbors(start_solution, count=5)
|
||||
|
||||
assert len(neighbors) == 5
|
||||
assert len({tuple(neighbor) for neighbor in neighbors}) == 5
|
||||
assert all(neighbor[:10] == start_solution[:10] for neighbor in neighbors)
|
||||
assert all(len(neighbor) == opt.control_slots for neighbor in neighbors)
|
||||
assert all(neighbor != start_solution for neighbor in neighbors)
|
||||
|
||||
|
||||
@@ -193,9 +193,9 @@ def test_initial_population_uses_fixed_seed_budget_and_configured_population(
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt.optimize_ev = False
|
||||
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
|
||||
start_solution = [5] * opt.total_slots
|
||||
warm_neighbors = [[6] * opt.total_slots for _ in range(50)]
|
||||
educated = [[7] * opt.total_slots for _ in range(100)]
|
||||
start_solution = [5] * opt.control_slots
|
||||
warm_neighbors = [[6] * opt.control_slots for _ in range(50)]
|
||||
educated = [[7] * opt.control_slots for _ in range(100)]
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def fake_evolution(population, **kwargs):
|
||||
@@ -214,7 +214,7 @@ def test_initial_population_uses_fixed_seed_budget_and_configured_population(
|
||||
patch.object(
|
||||
opt.toolbox,
|
||||
"population",
|
||||
side_effect=lambda n: [creator.Individual([9] * opt.total_slots) for _ in range(n)],
|
||||
side_effect=lambda n: [creator.Individual([9] * opt.control_slots) for _ in range(n)],
|
||||
),
|
||||
patch.object(opt, "_evolve_population_adaptive", side_effect=fake_evolution),
|
||||
):
|
||||
@@ -237,16 +237,16 @@ def test_small_population_scales_warm_and_educated_seed_families(config_eos: Con
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt.optimize_ev = False
|
||||
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
|
||||
start_solution = [5] * opt.total_slots
|
||||
start_solution = [5] * opt.control_slots
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def warm_neighbors(_solution, count):
|
||||
captured["warm_count"] = count
|
||||
return [[6] * opt.total_slots for _ in range(count)]
|
||||
return [[6] * opt.control_slots for _ in range(count)]
|
||||
|
||||
def educated(count):
|
||||
captured["educated_count"] = count
|
||||
return [[7] * opt.total_slots for _ in range(count)]
|
||||
return [[7] * opt.control_slots for _ in range(count)]
|
||||
|
||||
def fake_evolution(population, **kwargs):
|
||||
captured["population"] = list(population)
|
||||
@@ -264,7 +264,7 @@ def test_small_population_scales_warm_and_educated_seed_families(config_eos: Con
|
||||
patch.object(
|
||||
opt.toolbox,
|
||||
"population",
|
||||
side_effect=lambda n: [creator.Individual([9] * opt.total_slots) for _ in range(n)],
|
||||
side_effect=lambda n: [creator.Individual([9] * opt.control_slots) for _ in range(n)],
|
||||
),
|
||||
patch.object(opt, "_evolve_population_adaptive", side_effect=fake_evolution),
|
||||
):
|
||||
@@ -289,14 +289,14 @@ def test_adaptive_evolution_soft_restarts_collapsed_population(config_eos: Confi
|
||||
opt.optimize_ev = False
|
||||
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
|
||||
opt.toolbox.register("evaluate", lambda individual: (float(sum(individual)),))
|
||||
population = [creator.Individual([0] * opt.total_slots) for _ in range(20)]
|
||||
population = [creator.Individual([0] * opt.control_slots) for _ in range(20)]
|
||||
stats = tools.Statistics(lambda individual: individual.fitness.values)
|
||||
stats.register("min", np.min)
|
||||
stats.register("avg", np.mean)
|
||||
stats.register("max", np.max)
|
||||
halloffame = tools.HallOfFame(1)
|
||||
|
||||
fresh = [creator.Individual([value] + [0] * (opt.total_slots - 1)) for value in range(1, 20)]
|
||||
fresh = [creator.Individual([value] + [0] * (opt.control_slots - 1)) for value in range(1, 20)]
|
||||
with patch.object(opt, "_fresh_population", return_value=fresh) as create_fresh:
|
||||
evolved, log = opt._evolve_population_adaptive(
|
||||
population,
|
||||
@@ -324,7 +324,7 @@ def test_local_search_moves_weak_export_to_later_expensive_import(config_eos: Co
|
||||
opt.bat_possible_charge_values = [1.0]
|
||||
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
|
||||
|
||||
slots = opt.total_slots
|
||||
slots = opt.control_slots
|
||||
export_state = 5
|
||||
self_consumption_state = 6
|
||||
discharge_state = 1
|
||||
@@ -372,7 +372,7 @@ def test_educated_guesses_encode_high_price_direct_marketing(config_eos: ConfigE
|
||||
opt.bat_possible_charge_values = [1.0]
|
||||
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
|
||||
|
||||
slots = opt.total_slots
|
||||
slots = opt.control_slots
|
||||
opt.simulation.elect_price_hourly = np.linspace(0.0001, 0.0004, slots)
|
||||
opt.simulation.elect_revenue_per_hour_arr = np.linspace(0.00001, 0.0003, slots)
|
||||
opt.simulation.pv_prediction_wh = np.full(slots, 1000.0)
|
||||
@@ -399,7 +399,7 @@ def test_flat_feed_in_tariff_does_not_seed_direct_marketing(config_eos: ConfigEO
|
||||
opt.bat_possible_charge_values = [1.0]
|
||||
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
|
||||
|
||||
slots = opt.total_slots
|
||||
slots = opt.control_slots
|
||||
opt.simulation.elect_price_hourly = np.linspace(0.0001, 0.0004, slots)
|
||||
opt.simulation.elect_revenue_per_hour_arr = np.full(slots, 0.00005)
|
||||
opt.simulation.pv_prediction_wh = np.full(slots, 1000.0)
|
||||
@@ -409,3 +409,4 @@ def test_flat_feed_in_tariff_does_not_seed_direct_marketing(config_eos: ConfigEO
|
||||
|
||||
export_state = 5
|
||||
assert all(export_state not in guess for guess in guesses)
|
||||
|
||||
|
||||
@@ -93,7 +93,7 @@ def test_grid_export_rates_reach_the_solution(config_eos: ConfigEOS):
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": 24},
|
||||
"optimization": {
|
||||
"optimization": {"tail_horizon_hours": 0,
|
||||
"horizon_hours": 24,
|
||||
"interval": 3600,
|
||||
"genetic": {"individuals": 40, "generations": 10},
|
||||
@@ -174,8 +174,8 @@ def test_optimize(
|
||||
"prediction": {
|
||||
"hours": 48
|
||||
},
|
||||
"optimization": {
|
||||
"horizon_hours": 48,
|
||||
"optimization": {"tail_horizon_hours": 0,
|
||||
"horizon_hours": 38,
|
||||
"genetic": {
|
||||
"individuals": 300,
|
||||
"generations": 10,
|
||||
@@ -244,15 +244,14 @@ def test_optimize(
|
||||
with TESTDATA_FILE.open("w", encoding="utf-8", newline="\n") as f_out:
|
||||
f_out.write(genetic_solution.model_dump_json(indent=4, exclude_unset=True))
|
||||
|
||||
# The old snapshot included midnight-prefix genes and a prediction-sized
|
||||
# genome. Check the new run-relative contract and accounting instead.
|
||||
assert len(genetic_solution.ac_charge) == 38
|
||||
assert len(genetic_solution.result.Kosten_Euro_pro_Stunde) == 38
|
||||
assert genetic_solution.result.Gesamtbilanz_Euro == pytest.approx(
|
||||
expected_result.result.Gesamtbilanz_Euro
|
||||
genetic_solution.result.Gesamtkosten_Euro - genetic_solution.result.Gesamteinnahmen_Euro
|
||||
)
|
||||
|
||||
# Assert that the output contains all expected entries.
|
||||
# This does not assert that the optimization always gives the same result!
|
||||
# Reproducibility and mathematical accuracy should be tested on the level of individual components.
|
||||
compare_dict(genetic_solution.model_dump(), expected_result.model_dump())
|
||||
|
||||
# Check the correct generic optimization solution is created
|
||||
optimization_solution = genetic_solution.optimization_solution()
|
||||
# @TODO
|
||||
@@ -291,18 +290,16 @@ def _ev_deadline_parameters(hours: int, **ev_extra) -> GeneticOptimizationParame
|
||||
def test_ev_deadline_slot_resolution(config_eos: ConfigEOS):
|
||||
"""Datetime and maximum duration resolve to a slot; the earlier one wins."""
|
||||
config_eos.merge_settings_from_dict(
|
||||
{"prediction": {"hours": 48}, "optimization": {"horizon_hours": 48, "interval": 3600}}
|
||||
{"prediction": {"hours": 48}, "optimization": {"tail_horizon_hours": 0, "horizon_hours": 48, "interval": 3600}}
|
||||
)
|
||||
ems_eos.set_start_datetime(to_datetime().set(hour=10, minute=0))
|
||||
optimization = GeneticOptimization(fixed_seed=1)
|
||||
optimization._slot0_datetime = optimization.ems.start_datetime.set(
|
||||
hour=0, minute=0, second=0, microsecond=0
|
||||
)
|
||||
optimization._slot0_datetime = optimization.ems.start_datetime
|
||||
slot0 = optimization._slot0_datetime
|
||||
|
||||
# Duration only: 6 h after the start hour 10.
|
||||
parameters = _ev_deadline_parameters(48, min_soc_max_duration_h=6)
|
||||
assert optimization._ev_deadline_slot(parameters) == 16
|
||||
assert optimization._ev_deadline_slot(parameters) == 6
|
||||
|
||||
# Datetime only.
|
||||
parameters = _ev_deadline_parameters(48, min_soc_deadline_datetime=slot0.add(hours=14))
|
||||
@@ -312,15 +309,15 @@ def test_ev_deadline_slot_resolution(config_eos: ConfigEOS):
|
||||
parameters = _ev_deadline_parameters(
|
||||
48, min_soc_deadline_datetime=slot0.add(hours=20), min_soc_max_duration_h=6
|
||||
)
|
||||
assert optimization._ev_deadline_slot(parameters) == 16
|
||||
assert optimization._ev_deadline_slot(parameters) == 6
|
||||
|
||||
# Beyond the horizon: no deadline, the end-of-horizon target already covers it.
|
||||
parameters = _ev_deadline_parameters(48, min_soc_deadline_datetime=slot0.add(hours=100))
|
||||
assert optimization._ev_deadline_slot(parameters) is None
|
||||
|
||||
# In the past: due right now.
|
||||
parameters = _ev_deadline_parameters(48, min_soc_deadline_datetime=slot0.add(hours=2))
|
||||
assert optimization._ev_deadline_slot(parameters) == optimization._start_day_slot()
|
||||
parameters = _ev_deadline_parameters(48, min_soc_deadline_datetime=slot0.subtract(hours=2))
|
||||
assert optimization._ev_deadline_slot(parameters) == 0
|
||||
|
||||
# No deadline at all.
|
||||
assert optimization._ev_deadline_slot(_ev_deadline_parameters(48)) is None
|
||||
@@ -329,7 +326,7 @@ def test_ev_deadline_slot_resolution(config_eos: ConfigEOS):
|
||||
def test_ev_soc_penalty_reads_the_deadline_slot(config_eos: ConfigEOS):
|
||||
"""With a deadline the penalty checks the SoC at that slot, not at the end."""
|
||||
config_eos.merge_settings_from_dict(
|
||||
{"prediction": {"hours": 48}, "optimization": {"horizon_hours": 48, "interval": 3600}}
|
||||
{"prediction": {"hours": 48}, "optimization": {"tail_horizon_hours": 0, "horizon_hours": 48, "interval": 3600}}
|
||||
)
|
||||
ems_eos.set_start_datetime(to_datetime().set(hour=10, minute=0))
|
||||
optimization = GeneticOptimization(fixed_seed=1)
|
||||
@@ -360,7 +357,7 @@ def test_ev_deadline_charges_before_departure(config_eos: ConfigEOS):
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": hours},
|
||||
"optimization": {
|
||||
"optimization": {"tail_horizon_hours": 0,
|
||||
"horizon_hours": hours,
|
||||
"interval": 3600,
|
||||
"genetic": {"individuals": 100, "generations": 40},
|
||||
@@ -393,7 +390,7 @@ def _terminal_value_run(
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": hours},
|
||||
"optimization": {
|
||||
"optimization": {"tail_horizon_hours": 0,
|
||||
"horizon_hours": hours,
|
||||
"interval": 3600,
|
||||
"terminal_value_mode": mode,
|
||||
|
||||
@@ -30,7 +30,7 @@ def genetic_simulation(config_eos) -> GeneticSimulation:
|
||||
"""Fixture to create an EnergyManagement instance with given test parameters."""
|
||||
# Assure configuration holds the correct values
|
||||
config_eos.merge_settings_from_dict(
|
||||
{"prediction": {"hours": 48}, "optimization": {"hours": 24}}
|
||||
{"prediction": {"hours": 48}, "optimization": {"tail_horizon_hours": 0, "hours": 24}}
|
||||
)
|
||||
assert config_eos.prediction.hours == 48
|
||||
assert config_eos.optimization.horizon_hours == 24
|
||||
@@ -381,7 +381,7 @@ def test_simulation(genetic_simulation):
|
||||
|
||||
def test_ev_charging_uses_raw_input_energy_for_load_and_grid(config_eos):
|
||||
config_eos.merge_settings_from_dict(
|
||||
{"prediction": {"hours": 1}, "optimization": {"horizon_hours": 1}}
|
||||
{"prediction": {"hours": 1}, "optimization": {"tail_horizon_hours": 0, "horizon_hours": 1}}
|
||||
)
|
||||
ev = Battery(
|
||||
ElectricVehicleParameters(
|
||||
@@ -422,7 +422,7 @@ def test_ev_charging_uses_raw_input_energy_for_load_and_grid(config_eos):
|
||||
|
||||
def test_direct_marketing_curtails_negative_feed_in(config_eos, monkeypatch):
|
||||
config_eos.merge_settings_from_dict(
|
||||
{"prediction": {"hours": 2}, "optimization": {"horizon_hours": 2}}
|
||||
{"prediction": {"hours": 2}, "optimization": {"tail_horizon_hours": 0, "horizon_hours": 2}}
|
||||
)
|
||||
|
||||
inverter = Inverter(InverterParameters(device_id="inverter1", max_power_wh=1000.0))
|
||||
@@ -460,7 +460,7 @@ def _direct_marketing_battery_export_simulation(
|
||||
dc_to_ac_efficiency: float = 1.0,
|
||||
) -> GeneticSimulation:
|
||||
config_eos.merge_settings_from_dict(
|
||||
{"prediction": {"hours": 2}, "optimization": {"horizon_hours": 2}}
|
||||
{"prediction": {"hours": 2}, "optimization": {"tail_horizon_hours": 0, "horizon_hours": 2}}
|
||||
)
|
||||
|
||||
battery = Battery(
|
||||
@@ -571,7 +571,7 @@ def test_disabled_ac_charging_clears_the_reported_plan(config_eos):
|
||||
simulated or paid for.
|
||||
"""
|
||||
config_eos.merge_settings_from_dict(
|
||||
{"prediction": {"hours": 2}, "optimization": {"horizon_hours": 2}}
|
||||
{"prediction": {"hours": 2}, "optimization": {"tail_horizon_hours": 0, "horizon_hours": 2}}
|
||||
)
|
||||
|
||||
battery = Battery(
|
||||
|
||||
@@ -28,7 +28,7 @@ def genetic_simulation_2(config_eos) -> GeneticSimulation:
|
||||
"""Fixture to create an EnergyManagement instance with given test parameters."""
|
||||
# Assure configuration holds the correct values
|
||||
config_eos.merge_settings_from_dict(
|
||||
{"prediction": {"hours": 48}, "optimization": {"hours": 24}}
|
||||
{"prediction": {"hours": 48}, "optimization": {"tail_horizon_hours": 0, "hours": 24}}
|
||||
)
|
||||
assert config_eos.prediction.hours == 48
|
||||
assert config_eos.optimization.horizon_hours == 24
|
||||
|
||||
+16
-16
@@ -156,7 +156,7 @@ def _optimizer(config_eos, *, prediction_hours: int, horizon_hours: int, interva
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": prediction_hours},
|
||||
"optimization": {"horizon_hours": horizon_hours, "interval": interval},
|
||||
"optimization": {"tail_horizon_hours": 0, "horizon_hours": horizon_hours, "interval": interval},
|
||||
}
|
||||
)
|
||||
ems_eos.set_start_datetime(to_datetime().set(hour=hour, minute=0))
|
||||
@@ -165,17 +165,17 @@ def _optimizer(config_eos, *, prediction_hours: int, horizon_hours: int, interva
|
||||
|
||||
def test_once_layout_single_gene(config_eos):
|
||||
opt = _optimizer(config_eos, prediction_hours=48, horizon_hours=48, interval=3600, hour=10)
|
||||
slot0 = opt.ems.start_datetime.set(hour=0, minute=0, second=0, microsecond=0)
|
||||
slot0 = opt.ems.start_datetime
|
||||
appliance = _appliance(48, 1.0, device_id="d", consumption_wh=1000, duration_h=2)
|
||||
layout = opt._build_appliance_layout([appliance], slot0)
|
||||
assert layout.n_genes == 1
|
||||
assert layout.genes[0].run_date is None
|
||||
assert layout.genes[0].allowed_start_slots[0] == opt._start_day_slot()
|
||||
assert layout.genes[0].allowed_start_slots[0] == 0
|
||||
|
||||
|
||||
def test_once_no_valid_start_raises(config_eos):
|
||||
opt = _optimizer(config_eos, prediction_hours=48, horizon_hours=10, interval=3600, hour=10)
|
||||
slot0 = opt.ems.start_datetime.set(hour=0, minute=0, second=0, microsecond=0)
|
||||
slot0 = opt.ems.start_datetime
|
||||
# 02:00 window is in the past (start slot 10) and day 1 is beyond the 10 h horizon.
|
||||
windows = TimeWindowSequence(
|
||||
windows=[TimeWindow(start_time=to_time("02:00"), duration=to_duration("1 hours"))]
|
||||
@@ -189,7 +189,7 @@ def test_once_no_valid_start_raises(config_eos):
|
||||
|
||||
def test_daily_layout_one_gene_per_calendar_day(config_eos):
|
||||
opt = _optimizer(config_eos, prediction_hours=72, horizon_hours=72, interval=3600, hour=0)
|
||||
slot0 = opt.ems.start_datetime.set(hour=0, minute=0, second=0, microsecond=0)
|
||||
slot0 = opt.ems.start_datetime
|
||||
windows = TimeWindowSequence(
|
||||
windows=[TimeWindow(start_time=to_time("10:00"), duration=to_duration("2 hours"))]
|
||||
)
|
||||
@@ -212,7 +212,7 @@ def test_daily_layout_one_gene_per_calendar_day(config_eos):
|
||||
def test_daily_layout_partial_first_day(config_eos):
|
||||
"""A partial first day (start after the window) produces no gene for that day."""
|
||||
opt = _optimizer(config_eos, prediction_hours=48, horizon_hours=48, interval=3600, hour=14)
|
||||
slot0 = opt.ems.start_datetime.set(hour=0, minute=0, second=0, microsecond=0)
|
||||
slot0 = opt.ems.start_datetime
|
||||
windows = TimeWindowSequence(
|
||||
windows=[TimeWindow(start_time=to_time("10:00"), duration=to_duration("2 hours"))]
|
||||
)
|
||||
@@ -226,9 +226,9 @@ def test_daily_layout_partial_first_day(config_eos):
|
||||
time_windows=windows,
|
||||
)
|
||||
layout = opt._build_appliance_layout([appliance], slot0)
|
||||
# Day 0 window (10:00-12:00) is already in the past at start hour 14 -> only day 1.
|
||||
assert layout.n_genes == 1
|
||||
assert all(slot >= opt._start_day_slot() for slot in layout.genes[0].allowed_start_slots)
|
||||
# Day 0 window (10:00-12:00) is already in the past at start hour 14 -> days 1 and 2 are inside the 48 hours from now.
|
||||
assert layout.n_genes == 2
|
||||
assert all(slot >= 0 for slot in layout.genes[0].allowed_start_slots)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -238,7 +238,7 @@ def test_multiple_appliances_scheduled_and_aggregate(config_eos):
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": 48},
|
||||
"optimization": {
|
||||
"optimization": {"tail_horizon_hours": 0,
|
||||
"horizon_hours": 48,
|
||||
"interval": 3600,
|
||||
"genetic": {
|
||||
@@ -343,15 +343,15 @@ def test_max_home_appliances_is_upper_bound():
|
||||
|
||||
def test_start_solution_layout_mismatch_is_ignored(config_eos):
|
||||
opt = _optimizer(config_eos, prediction_hours=48, horizon_hours=48, interval=3600, hour=10)
|
||||
slot0 = opt.ems.start_datetime.set(hour=0, minute=0, second=0, microsecond=0)
|
||||
slot0 = opt.ems.start_datetime
|
||||
appliance = _appliance(48, 1.0, device_id="d", consumption_wh=1000, duration_h=1)
|
||||
opt.appliance_layout = opt._build_appliance_layout([appliance], slot0)
|
||||
opt.optimize_ev = False
|
||||
valid_index_count = len(opt.appliance_layout.genes[0].allowed_start_slots)
|
||||
# A tail index beyond the allowed range must be rejected.
|
||||
bad_solution = [0] * opt.total_slots + [valid_index_count + 5]
|
||||
bad_solution = [0] * opt.control_slots + [valid_index_count + 5]
|
||||
assert opt._start_solution_matches_layout(bad_solution) is False
|
||||
good_solution = [0] * opt.total_slots + [0]
|
||||
good_solution = [0] * opt.control_slots + [0]
|
||||
assert opt._start_solution_matches_layout(good_solution) is True
|
||||
|
||||
|
||||
@@ -456,14 +456,14 @@ def test_deadline_strict_keeps_empty_result():
|
||||
def test_deadline_strict_once_raises(config_eos):
|
||||
"""A ONCE consumer with an unreachable STRICT deadline fails the layout."""
|
||||
opt = _optimizer(config_eos, prediction_hours=48, horizon_hours=48, interval=3600, hour=12)
|
||||
slot0 = opt.ems.start_datetime.set(hour=0, minute=0, second=0, microsecond=0)
|
||||
slot0 = opt.ems.start_datetime
|
||||
appliance = _appliance(
|
||||
48,
|
||||
1.0,
|
||||
device_id="d",
|
||||
consumption_wh=2000,
|
||||
duration_h=2,
|
||||
deadline_datetime=slot0.add(hours=10),
|
||||
deadline_datetime=slot0.set(hour=10),
|
||||
deadline_policy="STRICT",
|
||||
)
|
||||
with pytest.raises(ValueError, match="no valid start"):
|
||||
@@ -501,7 +501,7 @@ def test_deadline_end_to_end_optimization(config_eos):
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": 48},
|
||||
"optimization": {
|
||||
"optimization": {"tail_horizon_hours": 0,
|
||||
"horizon_hours": 48,
|
||||
"interval": 3600,
|
||||
"genetic": {
|
||||
|
||||
@@ -222,7 +222,7 @@ class TestAcChargingInSimulation:
|
||||
)
|
||||
|
||||
config_eos.merge_settings_from_dict(
|
||||
{"prediction": {"hours": 48}, "optimization": {"hours": 24}}
|
||||
{"prediction": {"hours": 48}, "optimization": {"tail_horizon_hours": 0, "hours": 24}}
|
||||
)
|
||||
|
||||
prediction_hours = config_eos.prediction.hours
|
||||
@@ -561,7 +561,7 @@ def _run_evaluate_with_mocked_sim(
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": 48},
|
||||
"optimization": {"hours": 24},
|
||||
"optimization": {"tail_horizon_hours": 0, "hours": 24},
|
||||
}
|
||||
)
|
||||
config_eos.optimization.genetic.penalties = {
|
||||
@@ -614,7 +614,7 @@ def _run_evaluate_with_mocked_ev_soc(config_eos, ev_soc_percentage: float) -> fl
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": 48},
|
||||
"optimization": {"hours": 48},
|
||||
"optimization": {"tail_horizon_hours": 0, "hours": 48},
|
||||
}
|
||||
)
|
||||
config_eos.optimization.genetic.penalties = {
|
||||
|
||||
@@ -28,6 +28,11 @@ ems_eos = get_ems(init=True) # init once
|
||||
DIR_TESTDATA = Path(__file__).parent / "testdata"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def start_at_midnight(config_eos):
|
||||
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0))
|
||||
|
||||
|
||||
def load_hourly_parameters() -> GeneticOptimizationParameters:
|
||||
"""Load the legacy 48-value API example used by hourly clients."""
|
||||
with (DIR_TESTDATA / "optimize_input_1.json").open("r") as f_in:
|
||||
@@ -51,7 +56,7 @@ def test_slot_helpers(
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": 48},
|
||||
"optimization": {"horizon_hours": 48, "interval": interval},
|
||||
"optimization": {"tail_horizon_hours": 0, "horizon_hours": 48, "interval": interval},
|
||||
}
|
||||
)
|
||||
ems_eos.set_start_datetime(to_datetime().set(hour=10, minute=0))
|
||||
@@ -60,7 +65,7 @@ def test_slot_helpers(
|
||||
|
||||
assert opt.slots_per_hour == exp_slots_per_hour
|
||||
assert opt.slot_duration_h == exp_slot_duration_h
|
||||
assert opt.total_slots == 48 * exp_slots_per_hour
|
||||
assert opt.control_slots == 48 * exp_slots_per_hour
|
||||
# At minute 0 the start slot is the hour scaled by the slot count.
|
||||
assert opt._start_day_slot() == 10 * exp_slots_per_hour
|
||||
|
||||
@@ -70,7 +75,7 @@ def test_start_day_slot_includes_minute_offset(config_eos: ConfigEOS):
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": 48},
|
||||
"optimization": {"horizon_hours": 48, "interval": 900},
|
||||
"optimization": {"tail_horizon_hours": 0, "horizon_hours": 48, "interval": 900},
|
||||
}
|
||||
)
|
||||
ems_eos.set_start_datetime(to_datetime().set(hour=10, minute=30))
|
||||
@@ -88,7 +93,7 @@ def test_ems_start_is_floored_to_quarter_hour(config_eos: ConfigEOS):
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": 48},
|
||||
"optimization": {"horizon_hours": 48, "interval": 900},
|
||||
"optimization": {"tail_horizon_hours": 0, "horizon_hours": 48, "interval": 900},
|
||||
}
|
||||
)
|
||||
|
||||
@@ -101,7 +106,7 @@ def test_ems_start_is_floored_to_quarter_hour(config_eos: ConfigEOS):
|
||||
|
||||
def test_unsupported_interval_falls_back_to_hourly(config_eos: ConfigEOS):
|
||||
"""The genetic optimizer falls back without restricting interval-aware providers."""
|
||||
config_eos.merge_settings_from_dict({"optimization": {"interval": 1800}})
|
||||
config_eos.merge_settings_from_dict({"optimization": {"tail_horizon_hours": 0, "interval": 1800}})
|
||||
|
||||
assert config_eos.optimization.interval == 1800
|
||||
GeneticOptimization(fixed_seed=42)
|
||||
@@ -113,7 +118,7 @@ def test_hourly_api_input_is_normalized_to_quarter_hour_slots(config_eos: Config
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": 48},
|
||||
"optimization": {"horizon_hours": 48, "interval": 900},
|
||||
"optimization": {"tail_horizon_hours": 0, "horizon_hours": 48, "interval": 900},
|
||||
}
|
||||
)
|
||||
parameters = load_hourly_parameters()
|
||||
@@ -141,7 +146,7 @@ def test_native_quarter_hour_input_is_not_resampled(config_eos: ConfigEOS):
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": 48},
|
||||
"optimization": {"horizon_hours": 48, "interval": 900},
|
||||
"optimization": {"tail_horizon_hours": 0, "horizon_hours": 48, "interval": 900},
|
||||
}
|
||||
)
|
||||
parameters = load_hourly_parameters()
|
||||
@@ -170,7 +175,7 @@ def test_scalar_feed_in_tariff_fills_quarter_hour_grid(config_eos: ConfigEOS):
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": 48},
|
||||
"optimization": {"horizon_hours": 48, "interval": 900},
|
||||
"optimization": {"tail_horizon_hours": 0, "horizon_hours": 48, "interval": 900},
|
||||
}
|
||||
)
|
||||
parameters = load_hourly_parameters()
|
||||
@@ -190,7 +195,7 @@ def test_ambiguous_input_length_is_rejected(config_eos: ConfigEOS):
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": 48},
|
||||
"optimization": {"horizon_hours": 48, "interval": 900},
|
||||
"optimization": {"tail_horizon_hours": 0, "horizon_hours": 48, "interval": 900},
|
||||
}
|
||||
)
|
||||
parameters = load_hourly_parameters()
|
||||
@@ -214,7 +219,7 @@ def test_hourly_start_solution_is_expanded_to_slots(config_eos: ConfigEOS):
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": 48},
|
||||
"optimization": {"horizon_hours": 48, "interval": 900},
|
||||
"optimization": {"tail_horizon_hours": 0, "horizon_hours": 48, "interval": 900},
|
||||
}
|
||||
)
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
@@ -232,35 +237,36 @@ def test_quarter_hour_mutation_targets_three_future_controls(config_eos: ConfigE
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": 48},
|
||||
"optimization": {"horizon_hours": 48, "interval": 900},
|
||||
"optimization": {"tail_horizon_hours": 0, "horizon_hours": 48, "interval": 900},
|
||||
}
|
||||
)
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt.optimize_ev = False
|
||||
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
|
||||
|
||||
active_slots = opt.total_slots - opt._start_day_slot()
|
||||
active_slots = opt.control_slots
|
||||
expected = min(0.10, opt.POINT_MUTATION_EXPECTED_GENES / active_slots)
|
||||
assert opt.toolbox.mutate_charge_discharge.keywords["indpb"] == pytest.approx(expected)
|
||||
|
||||
|
||||
def test_point_mutation_keeps_elapsed_slots_unchanged(config_eos: ConfigEOS):
|
||||
def test_point_mutation_uses_run_relative_controls(config_eos: ConfigEOS):
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": 48},
|
||||
"optimization": {"horizon_hours": 48, "interval": 900},
|
||||
"optimization": {"tail_horizon_hours": 0, "horizon_hours": 48, "interval": 900},
|
||||
}
|
||||
)
|
||||
get_ems(init=True).set_start_datetime(to_datetime().set(hour=10, minute=0))
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt.optimize_ev = False
|
||||
opt.setup_deap_environment({"home_appliance": 0}, start_hour=10)
|
||||
individual = [0] * opt.total_slots
|
||||
individual = [0] * opt.control_slots
|
||||
|
||||
changed = opt._mutate_point_controls(individual)
|
||||
|
||||
assert changed
|
||||
assert individual[: opt._start_day_slot()] == [0] * opt._start_day_slot()
|
||||
assert len(individual) == opt.control_slots
|
||||
assert any(individual)
|
||||
|
||||
|
||||
def test_sub_hourly_home_appliance_is_scheduled(config_eos: ConfigEOS):
|
||||
@@ -268,7 +274,7 @@ def test_sub_hourly_home_appliance_is_scheduled(config_eos: ConfigEOS):
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": 48},
|
||||
"optimization": {"horizon_hours": 48, "interval": 900},
|
||||
"optimization": {"tail_horizon_hours": 0, "horizon_hours": 38, "interval": 900},
|
||||
}
|
||||
)
|
||||
parameters = load_hourly_parameters().model_copy(
|
||||
@@ -306,8 +312,8 @@ def test_optimize_15min_slot_grid(config_eos: ConfigEOS):
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": 48},
|
||||
"optimization": {
|
||||
"horizon_hours": 48,
|
||||
"optimization": {"tail_horizon_hours": 0,
|
||||
"horizon_hours": 38,
|
||||
"interval": 900,
|
||||
"genetic": {
|
||||
"individuals": 300,
|
||||
@@ -335,7 +341,7 @@ def test_optimize_15min_slot_grid(config_eos: ConfigEOS):
|
||||
CacheEnergyManagementStore().clear()
|
||||
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
assert opt.total_slots == 192
|
||||
assert opt.control_slots == 152
|
||||
assert opt.slot_duration_h == 0.25
|
||||
|
||||
visualize_filename = str((DIR_TESTDATA / "new_optimize_15min.json").with_suffix(".pdf"))
|
||||
@@ -348,10 +354,10 @@ def test_optimize_15min_slot_grid(config_eos: ConfigEOS):
|
||||
genetic_solution = opt.optimierung_ems(parameters=input_data, start_hour=10, ngen=3)
|
||||
|
||||
# The genetic core emitted a full-day grid at 15-min resolution.
|
||||
assert len(genetic_solution.ac_charge) == 192
|
||||
assert len(genetic_solution.dc_charge) == 192
|
||||
assert len(genetic_solution.discharge_allowed) == 192
|
||||
expected_result_slots = 192 - opt._start_day_slot()
|
||||
assert len(genetic_solution.ac_charge) == 152
|
||||
assert len(genetic_solution.dc_charge) == 152
|
||||
assert len(genetic_solution.discharge_allowed) == 152
|
||||
expected_result_slots = 152
|
||||
assert len(genetic_solution.result.Last_Wh_pro_Stunde) == expected_result_slots
|
||||
assert len(genetic_solution.result.Electricity_price) == expected_result_slots
|
||||
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
"""Economic tail scenarios and hard control/forecast boundaries."""
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from akkudoktoreos.config.config import SettingsEOSDefaults
|
||||
from akkudoktoreos.core.coreabc import get_ems
|
||||
from akkudoktoreos.devices.genetic.battery import Battery
|
||||
from akkudoktoreos.devices.genetic.inverter import Inverter
|
||||
from akkudoktoreos.optimization.genetic.forecast import bounded_forecast_array
|
||||
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
|
||||
from akkudoktoreos.optimization.genetic.geneticdevices import (
|
||||
InverterParameters,
|
||||
SolarPanelBatteryParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import GeneticOptimizationParameters
|
||||
from akkudoktoreos.optimization.genetic.tailvalue import build_tail_value_curve
|
||||
from akkudoktoreos.optimization.genetic.terminalvalue import TerminalValueCurve
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration
|
||||
|
||||
|
||||
def devices(power=1000, efficiency=1.0, lcos=0, ac_limit=None, export_power=5000):
|
||||
bat = Battery(
|
||||
SolarPanelBatteryParameters(
|
||||
device_id="battery1",
|
||||
capacity_wh=1000,
|
||||
max_charge_power_w=power,
|
||||
charging_efficiency=efficiency,
|
||||
discharging_efficiency=efficiency,
|
||||
initial_soc_percentage=50,
|
||||
levelized_cost_of_storage_kwh=lcos,
|
||||
charge_rates=[0, 0.5, 1],
|
||||
),
|
||||
prediction_hours=1,
|
||||
)
|
||||
inv = Inverter(
|
||||
InverterParameters(
|
||||
device_id="inverter1",
|
||||
battery_id="battery1",
|
||||
max_power_wh=export_power,
|
||||
dc_to_ac_efficiency=1,
|
||||
ac_to_dc_efficiency=1,
|
||||
max_ac_charge_power_w=ac_limit,
|
||||
),
|
||||
battery=bat,
|
||||
)
|
||||
return bat, inv
|
||||
|
||||
|
||||
def curve(
|
||||
prices=(-0.1, 0.3),
|
||||
tariffs=(0, 0.3),
|
||||
direct=True,
|
||||
continuation=None,
|
||||
load=None,
|
||||
pv=None,
|
||||
**kwargs,
|
||||
):
|
||||
bat, inv = devices(**kwargs)
|
||||
return build_tail_value_curve(
|
||||
battery=bat,
|
||||
inverter=inv,
|
||||
prices_euro_per_wh=np.array(prices) / 1000,
|
||||
feed_in_euro_per_wh=np.array(tariffs) / 1000,
|
||||
load_wh=np.zeros(len(prices)) if load is None else np.array(load),
|
||||
pv_wh=np.zeros(len(prices)) if pv is None else np.array(pv),
|
||||
continuation=continuation or TerminalValueCurve(),
|
||||
charge_rates=[0.5, 1],
|
||||
export_rates=[1],
|
||||
direct_marketing=direct,
|
||||
)
|
||||
|
||||
|
||||
def test_headroom_has_value_and_empty_state_can_earn():
|
||||
c = curve()
|
||||
assert c.value(0) == pytest.approx(0.4)
|
||||
tail, continuation = c.component_values(0)
|
||||
assert tail == pytest.approx(0.4)
|
||||
assert continuation == pytest.approx(0.0)
|
||||
assert c.value(0) == pytest.approx(tail + continuation)
|
||||
assert c.value(500) > c.value(1000)
|
||||
assert any(v < 0 for v in c.marginal_euro_per_kwh)
|
||||
|
||||
|
||||
def test_chronology_changes_arbitrage():
|
||||
forward = curve()
|
||||
reverse = curve(prices=(0.3, -0.1), tariffs=(0.3, 0))
|
||||
assert forward.value(0) > reverse.value(0)
|
||||
|
||||
|
||||
def test_discharge_and_ac_power_limits():
|
||||
limited = curve(prices=(1,), tariffs=(1,), power=100)
|
||||
assert limited.value(1000) == pytest.approx(0.1)
|
||||
limited_ac = curve(ac_limit=100)
|
||||
assert limited_ac.value(0) == pytest.approx(0.04)
|
||||
limited_inverter = curve(prices=(1,), tariffs=(1,), export_power=50)
|
||||
assert limited_inverter.value(1000) == pytest.approx(0.05)
|
||||
|
||||
|
||||
def test_losses_and_lcos_reduce_arbitrage():
|
||||
ideal = curve(prices=(0.1, 0.3))
|
||||
lossy = curve(prices=(0.1, 0.3), efficiency=0.8)
|
||||
assert 0 < lossy.value(0) < ideal.value(0)
|
||||
assert curve(prices=(0.1, 0.3), lcos=0.25).value(0) == pytest.approx(0)
|
||||
|
||||
|
||||
def test_no_battery_export_without_permission():
|
||||
assert curve(prices=(0.1, 0.3), direct=False).value(0) == pytest.approx(0)
|
||||
|
||||
|
||||
def test_pv_surplus_can_be_stored_for_local_load():
|
||||
c = curve(prices=(0.2, 0.3), tariffs=(0, 0), pv=[1000, 0], load=[0, 1000], direct=False)
|
||||
assert c.value(0) == pytest.approx(0)
|
||||
# Without PV the same empty battery must buy energy to serve the load.
|
||||
assert curve(prices=(0.2, 0.3), tariffs=(0, 0), load=[0, 1000], direct=False).value(
|
||||
0
|
||||
) < c.value(0)
|
||||
|
||||
|
||||
def test_continuation_survives_tail_end():
|
||||
continuation = TerminalValueCurve(energy_wh=[0, 1000], value_euro=[0, 0.2])
|
||||
c = curve(prices=(0.5,), tariffs=(0,), continuation=continuation)
|
||||
assert c.value(1000) == pytest.approx(0.2)
|
||||
tail, continuation_credit = c.component_values(1000)
|
||||
assert tail == pytest.approx(0.0)
|
||||
assert continuation_credit == pytest.approx(0.2)
|
||||
|
||||
|
||||
def test_tail_diagnostic_plan_explains_the_selected_path():
|
||||
c = curve()
|
||||
plan = c.diagnostic_plan(0, control_horizon_hours=24)
|
||||
assert len(plan) == 2
|
||||
assert plan[0].hour_from_start == 24
|
||||
assert plan[0].action == "GRID_CHARGE"
|
||||
assert plan[0].soc_end_percentage > plan[0].soc_start_percentage
|
||||
assert plan[0].grid_import_wh > 0
|
||||
assert plan[1].action == "BATTERY_EXPORT"
|
||||
assert plan[1].soc_end_percentage < plan[1].soc_start_percentage
|
||||
assert plan[1].grid_export_wh > 0
|
||||
assert sum(slot.slot_value_euro for slot in plan) == pytest.approx(c.value(0))
|
||||
|
||||
|
||||
def test_central_config_invariant():
|
||||
# Only the control horizon is mandatory. A prediction horizon that cannot
|
||||
# cover the requested tail shortens the tail instead of failing the run,
|
||||
# so existing configurations keep starting after an upgrade.
|
||||
short = SettingsEOSDefaults(
|
||||
prediction={"hours": 48}, optimization={"horizon_hours": 24, "tail_horizon_hours": 48}
|
||||
)
|
||||
assert short.prediction.hours == 48
|
||||
assert short.optimization.tail_horizon_hours == 48
|
||||
|
||||
# A control horizon the forecast cannot serve is not rejected here either -
|
||||
# prediction.hours also serves callers that never optimize. The optimizer
|
||||
# rejects the run itself, naming the series that ran out.
|
||||
undersized = SettingsEOSDefaults(
|
||||
prediction={"hours": 48}, optimization={"horizon_hours": 72, "tail_horizon_hours": 0}
|
||||
)
|
||||
assert undersized.optimization.horizon_hours == 72
|
||||
|
||||
settings = SettingsEOSDefaults()
|
||||
assert settings.prediction.hours == 72
|
||||
assert settings.optimization.tail_horizon_hours == 48
|
||||
|
||||
|
||||
def setup_run(config, interval=3600, start_hour=0, hours=72, prediction_hours=72):
|
||||
config.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": prediction_hours},
|
||||
"optimization": {
|
||||
"horizon_hours": 24,
|
||||
"tail_horizon_hours": 48,
|
||||
"interval": interval,
|
||||
"visualize_pdf": False,
|
||||
},
|
||||
"feedintariff": {"direct_marketing_enabled": True},
|
||||
}
|
||||
)
|
||||
ems = get_ems(init=True)
|
||||
ems.set_start_datetime(to_datetime("2026-09-05T00:00:00").set(hour=start_hour))
|
||||
bat, inv = devices()
|
||||
params = GeneticOptimizationParameters(
|
||||
ems={
|
||||
"pv_prognose_wh": [0.0] * hours,
|
||||
"gesamtlast": [0.0] * hours,
|
||||
"strompreis_euro_pro_wh": [0.0002] * hours,
|
||||
"einspeiseverguetung_euro_pro_wh": [0.0001] * hours,
|
||||
"preis_euro_pro_wh_akku": 0,
|
||||
},
|
||||
pv_akku=bat.parameters,
|
||||
inverter=inv.parameters,
|
||||
eauto=None,
|
||||
)
|
||||
return GeneticOptimization(fixed_seed=42), params
|
||||
|
||||
|
||||
@pytest.mark.parametrize("interval", [3600, 900])
|
||||
@pytest.mark.parametrize("start_hour", [0, 10])
|
||||
def test_genome_output_and_final_control_state(config_eos, interval, start_hour):
|
||||
opt, params = setup_run(config_eos, interval, start_hour, hours=72 + start_hour)
|
||||
|
||||
def choose(*args, **kwargs):
|
||||
# Discharge only in the last control slot. Its POST-slot SOC is credited.
|
||||
genome = opt.create_individual()
|
||||
genome[:] = [0] * opt.control_end_slot
|
||||
genome[-1] = opt._battery_state_layout().grid_export_state
|
||||
assert len(genome) == 24 * (3600 // interval)
|
||||
return genome, {}
|
||||
|
||||
with (
|
||||
patch.object(opt, "optimize", side_effect=choose),
|
||||
patch(
|
||||
"akkudoktoreos.optimization.genetic.genetic.build_tail_value_curve",
|
||||
wraps=build_tail_value_curve,
|
||||
) as builder,
|
||||
):
|
||||
result = opt.optimierung_ems(params)
|
||||
assert builder.call_count == 1
|
||||
assert len(result.ac_charge) == opt.control_slots
|
||||
assert len(result.dc_charge) == opt.control_slots
|
||||
assert len(result.discharge_allowed) == opt.control_slots
|
||||
assert len(result.battery_grid_export_factor) == opt.control_slots
|
||||
assert len(result.result.Kosten_Euro_pro_Stunde) == opt.control_slots
|
||||
assert result.terminal_value.mode == "TAIL"
|
||||
assert result.terminal_value.battery_energy_wh == pytest.approx(
|
||||
max(500 - 1000 * opt.slot_duration_h, 0)
|
||||
)
|
||||
assert result.terminal_value.effective_tail_hours == 48
|
||||
assert result.terminal_value.credited_euro == pytest.approx(
|
||||
result.terminal_value.tail_operating_euro + result.terminal_value.continuation_value_euro
|
||||
)
|
||||
assert result.terminal_value.continuation_curve is not None
|
||||
assert result.terminal_value.tail_diagnostics is not None
|
||||
assert result.terminal_value.tail_diagnostics.slots == 48 * (3600 // interval)
|
||||
assert result.terminal_value.tail_diagnostics.soc_grid_points == 101
|
||||
assert len(result.terminal_value.tail_plan) == result.terminal_value.tail_diagnostics.slots
|
||||
assert result.terminal_value.tail_plan[0].hour_from_start == 24
|
||||
assert len(result.terminal_value.curve.operating_value_euro) == 101
|
||||
assert len(result.terminal_value.curve.continuation_value_euro) == 101
|
||||
assert len(result.optimization_solution().solution.to_dataframe()) == opt.control_slots
|
||||
|
||||
|
||||
def test_short_tail_is_reported(config_eos, caplog):
|
||||
opt, params = setup_run(config_eos, hours=52)
|
||||
with patch.object(
|
||||
opt, "optimize", side_effect=lambda *a, **k: ([0] * opt.control_end_slot, {})
|
||||
):
|
||||
result = opt.optimierung_ems(params)
|
||||
assert result.terminal_value.effective_tail_hours == 28
|
||||
assert "Tail forecast shortened" in caplog.text
|
||||
assert result.terminal_value.reason
|
||||
|
||||
|
||||
def test_missing_control_is_rejected(config_eos):
|
||||
opt, params = setup_run(config_eos, hours=23)
|
||||
with pytest.raises(ValueError, match="Incomplete control forecast"):
|
||||
opt.optimierung_ems(params)
|
||||
|
||||
|
||||
def test_provider_values_are_not_extrapolated():
|
||||
from types import SimpleNamespace
|
||||
|
||||
start = to_datetime("2026-09-05T00:00:00Z")
|
||||
series = pd.Series([1.0, 2.0], index=pd.date_range(start=start, periods=2, freq="h"))
|
||||
provider = SimpleNamespace(key_to_series=lambda *a, **kw: series)
|
||||
result = bounded_forecast_array(
|
||||
provider,
|
||||
key="price",
|
||||
start_datetime=start,
|
||||
end_datetime=start.add(hours=3),
|
||||
interval=to_duration("15 minutes"),
|
||||
)
|
||||
assert result[:8].tolist() == [1.0] * 4 + [2.0] * 4
|
||||
assert np.isnan(result[8:]).all()
|
||||
|
||||
|
||||
def test_future_opportunity_changes_optimal_control_soc(config_eos):
|
||||
final_energy = []
|
||||
for negative_price in (0.5, -1.0):
|
||||
opt, params = setup_run(config_eos, hours=3)
|
||||
config_eos.merge_settings_from_dict(
|
||||
{"optimization": {"horizon_hours": 1, "tail_horizon_hours": 2}}
|
||||
)
|
||||
params.ems.strompreis_euro_pro_wh = [0.0005, negative_price / 1000, 0.0003]
|
||||
params.ems.einspeiseverguetung_euro_pro_wh = [0.00002, 0, 0.0003]
|
||||
result = opt.optimierung_ems(params, ngen=3, individuals=20)
|
||||
final_energy.append(result.terminal_value.battery_energy_wh)
|
||||
assert final_energy[0] > final_energy[1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("control", [24, 48])
|
||||
def test_continuation_prevents_emptying_at_moved_boundary(config_eos, control):
|
||||
opt, params = setup_run(config_eos, hours=96)
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": 96},
|
||||
"optimization": {"horizon_hours": control},
|
||||
}
|
||||
)
|
||||
# Zero control load, with the same future local demand visible to both tails.
|
||||
params.ems.gesamtlast[60] = 1000
|
||||
params.ems.einspeiseverguetung_euro_pro_wh = [0.0] * 96
|
||||
config_eos.feedintariff.direct_marketing_enabled = False
|
||||
|
||||
def choose(*a, **kw):
|
||||
from deap import creator
|
||||
|
||||
idle = creator.Individual([0] * control)
|
||||
discharge = creator.Individual([len(opt.bat_possible_charge_values)] * control)
|
||||
assert opt.toolbox.evaluate(idle)[0] <= opt.toolbox.evaluate(discharge)[0]
|
||||
return idle, {}
|
||||
|
||||
with patch.object(opt, "optimize", side_effect=choose):
|
||||
result = opt.optimierung_ems(params)
|
||||
assert result.terminal_value.battery_energy_wh == pytest.approx(500)
|
||||
assert result.terminal_value.continuation_mode == "AUTO"
|
||||
|
||||
|
||||
def test_missing_price_inside_tail_stops_at_first_gap(config_eos):
|
||||
opt, params = setup_run(config_eos)
|
||||
params.ems.strompreis_euro_pro_wh[30] = float("nan")
|
||||
with patch.object(opt, "optimize", side_effect=lambda *a, **k: ([0] * opt.control_slots, {})):
|
||||
result = opt.optimierung_ems(params)
|
||||
assert result.terminal_value.effective_tail_hours == 6
|
||||
|
||||
|
||||
def test_ev_genome_and_output_are_control_only(config_eos):
|
||||
from akkudoktoreos.optimization.genetic.geneticdevices import ElectricVehicleParameters
|
||||
|
||||
opt, params = setup_run(config_eos, interval=900, start_hour=10, hours=82)
|
||||
params.eauto = ElectricVehicleParameters(
|
||||
device_id="ev1",
|
||||
capacity_wh=5000,
|
||||
initial_soc_percentage=0,
|
||||
min_soc_percentage=50,
|
||||
charge_rates=[0, 0.5, 1],
|
||||
)
|
||||
|
||||
def choose(*a, **kw):
|
||||
genome = opt.create_individual()
|
||||
assert len(genome) == 2 * 96
|
||||
return genome, {}
|
||||
|
||||
with patch.object(opt, "optimize", side_effect=choose):
|
||||
result = opt.optimierung_ems(params)
|
||||
assert len(result.eautocharge_hours_float) == 96
|
||||
|
||||
|
||||
def test_rejected_config_update_is_atomic(config_eos):
|
||||
# The candidate is validated before the singleton is reinitialized, so a
|
||||
# rejected update must leave the running configuration untouched rather
|
||||
# than half-applied. `hours` is constrained to be non-negative.
|
||||
before = config_eos.prediction.hours
|
||||
with pytest.raises(ValueError):
|
||||
config_eos.merge_settings_from_dict({"prediction": {"hours": -1}})
|
||||
assert config_eos.prediction.hours == before
|
||||
|
||||
|
||||
def test_disabled_ac_conversion_cannot_earn_negative_price_revenue():
|
||||
bat, inv = devices()
|
||||
inv.parameters.ac_to_dc_efficiency = 0
|
||||
c = build_tail_value_curve(
|
||||
battery=bat,
|
||||
inverter=inv,
|
||||
prices_euro_per_wh=np.array([-0.001, 0.001]),
|
||||
feed_in_euro_per_wh=np.array([0.0, 0.001]),
|
||||
load_wh=np.zeros(2),
|
||||
pv_wh=np.zeros(2),
|
||||
continuation=TerminalValueCurve(),
|
||||
charge_rates=[1],
|
||||
export_rates=[1],
|
||||
direct_marketing=True,
|
||||
)
|
||||
assert c.value(0) == pytest.approx(0)
|
||||
assert bat.soc_wh == 500 # Building the tail never mutates the real battery.
|
||||
|
||||
|
||||
def test_short_native_forecast_declares_its_resolution(config_eos):
|
||||
opt, params = setup_run(config_eos, interval=900, hours=52 * 4)
|
||||
params.forecast_interval_seconds = 900
|
||||
with patch.object(opt, "optimize", side_effect=lambda *a, **k: ([0] * opt.control_slots, {})):
|
||||
result = opt.optimierung_ems(params)
|
||||
assert result.terminal_value.effective_tail_hours == 28
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"field,reason",
|
||||
[
|
||||
("strompreis_euro_pro_wh", "import price"),
|
||||
("einspeiseverguetung_euro_pro_wh", "feed-in tariff"),
|
||||
],
|
||||
)
|
||||
def test_differing_provider_lengths_use_the_common_tail(config_eos, field, reason):
|
||||
opt, params = setup_run(config_eos)
|
||||
setattr(params.ems, field, getattr(params.ems, field)[:52])
|
||||
with patch.object(opt, "optimize", side_effect=lambda *a, **k: ([0] * opt.control_slots, {})):
|
||||
result = opt.optimierung_ems(params)
|
||||
assert result.terminal_value.effective_tail_hours == 28
|
||||
assert reason in result.terminal_value.reason
|
||||
|
||||
|
||||
def test_missing_provider_key_stays_missing():
|
||||
from types import SimpleNamespace
|
||||
|
||||
def unavailable(*a, **kw):
|
||||
raise KeyError("price unavailable")
|
||||
|
||||
start = to_datetime("2026-09-05T00:00:00Z")
|
||||
result = bounded_forecast_array(
|
||||
SimpleNamespace(key_to_series=unavailable),
|
||||
key="price",
|
||||
start_datetime=start,
|
||||
end_datetime=start.add(hours=2),
|
||||
interval=to_duration("1 hour"),
|
||||
)
|
||||
assert np.isnan(result).all()
|
||||
assert len(result) == 2
|
||||
|
||||
|
||||
def test_short_prediction_horizon_shortens_the_tail(config_eos):
|
||||
# The forecast budget cannot serve the full 48 h tail. The run keeps going
|
||||
# with the 12 h that are left after the control horizon instead of failing.
|
||||
opt, params = setup_run(config_eos, hours=36, prediction_hours=36)
|
||||
assert opt.control_slots == 24
|
||||
assert opt.tail_slots == 12
|
||||
|
||||
result = opt.optimierung_ems(params, ngen=2)
|
||||
assert result.terminal_value.mode == "TAIL"
|
||||
assert result.terminal_value.requested_tail_hours == 48
|
||||
assert result.terminal_value.effective_tail_hours == 12
|
||||
@@ -162,7 +162,12 @@ def test_update_data(mock_get, provider, sample_brightsky_1_json, cache_store):
|
||||
|
||||
# Assert: Verify the result is as expected
|
||||
mock_get.assert_called_once()
|
||||
assert len(provider) == 50
|
||||
# One hourly record per slot from the run start up to, but not including,
|
||||
# the end of the prediction horizon. 2024-10-27 is the DST fall-back, so the
|
||||
# 72 h horizon spans 73 local hours.
|
||||
expected_records = int((provider.end_datetime - provider.ems_start_datetime).total_hours())
|
||||
assert expected_records == 73
|
||||
assert len(provider) == expected_records
|
||||
|
||||
|
||||
# ------------------------------------------------
|
||||
|
||||
@@ -151,7 +151,7 @@ def test_update_data(mock_get, provider, sample_clearout_1_html, sample_clearout
|
||||
mock_get.return_value = mock_response
|
||||
|
||||
expected_start = to_datetime("2024-10-26 00:00:00", in_timezone="Europe/Berlin")
|
||||
expected_end = to_datetime("2024-10-28 00:00:00", in_timezone="Europe/Berlin")
|
||||
expected_end = to_datetime("2024-10-29 00:00:00", in_timezone="Europe/Berlin")
|
||||
expected_keep = to_datetime("2024-10-24 00:00:00", in_timezone="Europe/Berlin")
|
||||
|
||||
# Call the method
|
||||
@@ -160,7 +160,7 @@ def test_update_data(mock_get, provider, sample_clearout_1_html, sample_clearout
|
||||
provider.update_data()
|
||||
|
||||
# Check for correct prediction time window
|
||||
assert provider.config.prediction.hours == 48
|
||||
assert provider.config.prediction.hours == 72
|
||||
assert provider.config.prediction.historic_hours == 48
|
||||
assert compare_datetimes(provider.ems_start_datetime, expected_start).equal
|
||||
assert compare_datetimes(provider.end_datetime, expected_end).equal
|
||||
|
||||
Reference in New Issue
Block a user