-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathoptimization.py
More file actions
1757 lines (1560 loc) · 73.5 KB
/
Copy pathoptimization.py
File metadata and controls
1757 lines (1560 loc) · 73.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Optimization module for PV system sizing and configuration.
This module provides:
- Tilt angle optimization
- Battery sizing optimization
- ZEB (Zero Energy Building) sizing
"""
from dataclasses import dataclass
from typing import Any, Callable, Dict, Optional, Sequence, Tuple, Union
import numpy as np
import pandas as pd
from breos.battery import BatteryConfig, simulate_energy_balance
from breos.economics import (
calculate_costs,
calculate_lcoe_from_projection,
cost_analysis_projection,
cost_params_from_config,
system_ac_production_power,
)
from breos.emissions import EmissionsParams
from breos.execution import DEFAULT_EXECUTION_BACKEND, require_backend, validate_execution_backend
from breos.pv.model_options import configured_pv_model_kwargs
from breos.solar import (
PVModuleParams,
calculate_pv_production_dc,
default_azimuth,
)
from breos.utils import get_hours_per_step
@dataclass
class OptimizationResult:
"""Result from an optimization run."""
optimal_value: float
objective_value: float
iterations: int
details: Dict[str, Any]
@dataclass
class ProjectedDesignResult:
"""Detailed result for one fixed design evaluated over a project horizon.
``metrics`` contains the projected headline values used by the optimizer.
``yearly`` is the simulated annual energy and degradation-state ledger, and
``financial`` is the corresponding discounted cost ledger.
"""
metrics: Dict[str, Any]
yearly: pd.DataFrame
financial: pd.DataFrame
def _serial_elementwise_runner(func: Callable[[Any], Any], args: list[Any]) -> list[Any]:
"""Fallback pymoo elementwise runner for single-process evaluation."""
return [func(arg) for arg in args]
def _resolve_max_tilt_deg(constraints: Dict[str, Any], latitude: float) -> float:
"""Resolve the optimization tilt upper bound from constraints."""
value = constraints.get("max_tilt_deg", 90.0)
if isinstance(value, str):
lowered = value.strip().lower()
if lowered == "adjust":
margin = float(constraints.get("tilt_margin_deg", 15.0))
adjusted = 5.0 * round((abs(float(latitude)) + margin) / 5.0)
return float(np.clip(adjusted, 60.0, 90.0))
try:
return float(value)
except ValueError as exc:
raise ValueError(
f"Unsupported constraints.max_tilt_deg value: {value!r}. Use a number or 'adjust'."
) from exc
return float(value)
def optimize_tilt(
weather_data: pd.DataFrame,
location,
n_modules: int,
model_options: Optional[Dict[str, Any]] = None,
pv_params: Optional[PVModuleParams] = None,
surface_azimuth: Optional[float] = None,
tilt_range: Tuple[float, float] = (0.0, 60.0),
objective: str = "max_production",
freq: str = "h",
n_points: int = 13,
verbose: bool = True,
) -> OptimizationResult:
"""
Optimize panel tilt angle for maximum production.
Args:
weather_data: Weather DataFrame with solar irradiance
location: pvlib Location object
n_modules: Number of PV modules
pv_params: PV module parameters
surface_azimuth: Panel azimuth (180=South, 0=North). If None, auto-detected from hemisphere.
tilt_range: (min_tilt, max_tilt) in degrees
objective: Must be ``"max_production"``. The historical
``"max_self_consumption"`` label was never implemented because
this function has no load input; it now raises instead of silently
optimizing production.
freq: Time frequency
n_points: Number of tilt values to evaluate
verbose: Print progress
Returns:
OptimizationResult with optimal tilt
"""
if objective != "max_production":
raise ValueError("optimize_tilt supports objective='max_production' only")
if surface_azimuth is None:
surface_azimuth = default_azimuth(location.latitude)
tilts = np.linspace(tilt_range[0], tilt_range[1], n_points)
results = []
successful_evaluations = 0
for tilt in tilts:
try:
dc_power = calculate_pv_production_dc(
weather_data=weather_data,
location=location,
tilt=tilt,
surface_azimuth=surface_azimuth,
n_modules=n_modules,
pv_params=pv_params,
freq=freq,
verbose=False,
**(model_options or {}),
)
total_production = dc_power.sum() * get_hours_per_step(freq) / 1000 # kWh (DC)
results.append({"tilt": tilt, "production_kwh": total_production})
successful_evaluations += 1
if verbose:
print(f" Tilt {tilt:.1f}°: {total_production:.1f} kWh")
except Exception as e:
if verbose:
print(f" Tilt {tilt:.1f}°: Error - {e}")
results.append({"tilt": tilt, "production_kwh": 0})
if successful_evaluations == 0:
raise RuntimeError("Tilt optimization failed for every evaluated angle")
results_df = pd.DataFrame(results)
optimal_idx = results_df["production_kwh"].idxmax()
optimal_tilt = results_df.loc[optimal_idx, "tilt"]
optimal_production = results_df.loc[optimal_idx, "production_kwh"]
if verbose:
print(f"\nOptimal tilt: {optimal_tilt:.1f}° ({optimal_production:.1f} kWh)")
return OptimizationResult(
optimal_value=optimal_tilt,
objective_value=optimal_production,
iterations=len(tilts),
details={"all_results": results_df},
)
def optimize_battery_size(
pv_dc: pd.Series,
houseload: pd.DataFrame,
battery_sizes_wh: list,
start_time: Optional[pd.Timestamp] = None,
end_time: Optional[pd.Timestamp] = None,
freq: str = "h",
objective: str = "max_self_consumption",
verbose: bool = True,
execution_backend: str = DEFAULT_EXECUTION_BACKEND,
) -> OptimizationResult:
"""
Optimize battery size for self-consumption or grid independence.
Args:
pv_dc: PV DC production series
houseload: Load DataFrame
battery_sizes_wh: List of battery sizes to evaluate
start_time: Simulation start
end_time: Simulation end
freq: Time frequency
objective: 'max_self_consumption' or 'min_import'
verbose: Print progress
Returns:
OptimizationResult with optimal battery size
"""
# Before the first candidate, not inside the loop over battery sizes.
require_backend(execution_backend)
results = []
for size_wh in battery_sizes_wh:
config = BatteryConfig(nominal_energy_wh=size_wh)
try:
df, total_pv, summary, _, _, _ = simulate_energy_balance(
pv_dc=pv_dc,
houseload=houseload,
battery_config=config,
start_time=start_time,
end_time=end_time,
freq=freq,
debug=False,
execution_backend=execution_backend,
)
grid_independence = summary["Grid Independence [%]"].iloc[0]
import_pct = summary["Import [%]"].iloc[0]
total_pv_kwh = summary["Total PV [kWh]"].iloc[0]
export_kwh = summary["Sell [kWh]"].iloc[0]
self_consumption_pct = ((total_pv_kwh - export_kwh) / total_pv_kwh) * 100 if total_pv_kwh > 0 else 0.0
results.append(
{
"battery_size_wh": size_wh,
"battery_size_kwh": size_wh / 1000,
"grid_independence": grid_independence,
"import_percent": import_pct,
"self_consumption": self_consumption_pct,
}
)
if verbose:
print(f" {size_wh / 1000:.1f} kWh: {grid_independence:.1f}% grid independence")
except Exception as e:
if verbose:
print(f" {size_wh / 1000:.1f} kWh: Error - {e}")
results_df = pd.DataFrame(results)
if results_df.empty:
raise RuntimeError("No battery sizes could be evaluated.")
if objective == "max_self_consumption":
optimal_idx = results_df["self_consumption"].idxmax()
optimal_value = results_df.loc[optimal_idx, "self_consumption"]
elif objective == "max_grid_independence":
optimal_idx = results_df["grid_independence"].idxmax()
optimal_value = results_df.loc[optimal_idx, "grid_independence"]
elif objective == "min_import":
optimal_idx = results_df["import_percent"].idxmin()
optimal_value = results_df.loc[optimal_idx, "import_percent"]
else:
raise ValueError("objective must be 'max_self_consumption', 'max_grid_independence', or 'min_import'")
optimal_size = results_df.loc[optimal_idx, "battery_size_wh"]
return OptimizationResult(
optimal_value=optimal_size,
objective_value=optimal_value,
iterations=len(battery_sizes_wh),
details={"all_results": results_df},
)
# ==========================================
# 2. HELPER FUNCTIONS
# ==========================================
# Constants for defaults (can be overridden by config)
DEFAULT_PANEL_WP = 550
DEFAULT_MODULE_AREA = 1.134 * 2.278
DEFAULT_INFLATION_ELEC = 0.02
DEFAULT_DISCOUNT_RATE = 0.0
DEFAULT_PROJECT_LIFESPAN = 20
# Candidate scoring spans the project lifetime by default. A design is chosen
# for how it performs over 20 years of PV degradation, battery fade, and
# replacement, not for its first year, so the cheaper annual basis is the
# opt-in screening mode rather than the default.
DEFAULT_OBJECTIVE_BASIS = "projected"
def _estimate_battery_replacement_treatment(
battery_kwh: float,
annual_soh_loss_pct: float,
initial_soh_pct: float,
eol_percentage: float,
project_lifespan: int,
replacement_cost_eur: float,
) -> Dict[str, Any]:
"""Approximate replacement years by repeating the simulated year-1 SOH loss.
The first interval starts at the candidate's configured initial SOH. Each
replacement resets SOH to 100%, matching :class:`BatteryConfig`; later
intervals therefore use the full 100%-to-EOL window. This is deliberately
a steady-state approximation. The App's multiyear projection remains the
higher-fidelity path because it propagates SOH and records actual events.
"""
annual_loss = max(0.0, float(annual_soh_loss_pct))
eol_pct = float(eol_percentage) * 100.0
treatment: Dict[str, Any] = {
"method": "repeat_simulated_year_1_soh_loss_to_eol",
"annual_soh_loss_pct": annual_loss,
"initial_soh_pct": float(initial_soh_pct),
"eol_soh_pct": eol_pct,
"replacement_cost_eur_each": float(replacement_cost_eur),
"replacement_years": [],
}
if battery_kwh <= 0.0 or annual_loss <= 0.0 or replacement_cost_eur <= 0.0:
return treatment
first_interval = max(1, int(np.ceil((float(initial_soh_pct) - eol_pct) / annual_loss)))
repeat_interval = max(1, int(np.ceil((100.0 - eol_pct) / annual_loss)))
replacement_year = first_interval
while replacement_year <= project_lifespan:
treatment["replacement_years"].append(replacement_year)
replacement_year += repeat_interval
return treatment
def _year_one_soh_loss_pct(
results_df: pd.DataFrame,
summary_df: pd.DataFrame,
initial_soh_pct: float,
has_battery: bool,
) -> float:
"""Read the candidate's year-one SOH loss from the simulator outputs."""
if not has_battery:
return 0.0
if "Final SOH [%]" in summary_df.columns and not summary_df.empty:
final_soh = float(summary_df["Final SOH [%]"].iloc[0])
elif "Battery_SOH" in results_df.columns and not results_df.empty:
valid_soh = pd.to_numeric(results_df["Battery_SOH"], errors="coerce").dropna()
if valid_soh.empty:
return 0.0
final_soh = float(valid_soh.iloc[-1])
else:
return 0.0
return max(0.0, float(initial_soh_pct) - final_soh)
def _pv_params_from_config(params: Dict[str, Any]) -> PVModuleParams:
"""Build PVModuleParams from an inline config mapping."""
return PVModuleParams(
Mpp=params.get("Mpp", 550),
Vmp=params.get("Vmp", 42.05),
Imp=params.get("Imp", 13.08),
Voc=params.get("Voc", 49.88),
Isc=params.get("Isc", 14.01),
T_Pmax_pct=params.get("T_Pmax_pct", params.get("T_Pmax", -0.34)),
T_Voc_pct=params.get("T_Voc_pct", params.get("T_Voc", -0.26)),
T_Isc_pct=params.get("T_Isc_pct", params.get("T_Isc", 0.05)),
N_Cells=params.get("N_Cells", 144),
celltype=params.get("celltype", "monoSi"),
)
def _dimensions_from_section(section: Dict[str, Any]) -> Optional[Dict[str, Any]]:
if section.get("dimensions"):
return section["dimensions"]
if "module_width_m" in section or "module_length_m" in section:
return {
"width": section.get("module_width_m"),
"length": section.get("module_length_m"),
}
return None
def _module_area_from_dimensions(dimensions: Optional[Dict[str, Any]]) -> float:
"""Resolve module footprint from config dimensions, falling back only when absent."""
if not dimensions:
return DEFAULT_MODULE_AREA
missing = {key for key in ("width", "length") if key not in dimensions or dimensions[key] is None}
if missing:
missing_list = ", ".join(sorted(missing))
raise ValueError(f"PV module dimensions missing required key(s): {missing_list}")
width = float(dimensions["width"])
length = float(dimensions["length"])
area = width * length
if area <= 0.0:
raise ValueError(f"PV module dimensions must define a positive area, got width={width}, length={length}")
return area
def _resolve_pv_module_and_area(config: Dict[str, Any]) -> Tuple[PVModuleParams, float]:
"""Resolve electrical module parameters and physical module area from config."""
pv_spec = config.get("pv_specs", {}) or {}
pv_cfg = config.get("pv", {}) or {}
pv_spec_params = pv_spec.get("params") or {}
pv_cfg_params = pv_cfg.get("params") or {}
pv_spec_dimensions = _dimensions_from_section(pv_spec)
pv_cfg_dimensions = _dimensions_from_section(pv_cfg)
if pv_spec_params:
pv_params = _pv_params_from_config(pv_spec_params)
dimensions = pv_spec_dimensions or pv_cfg_dimensions
elif pv_cfg_params:
pv_params = _pv_params_from_config(pv_cfg_params)
dimensions = pv_cfg_dimensions or pv_spec_dimensions
else:
from breos.pv_modules import get_module
module_name = pv_cfg.get("module") or config.get("pv_module") or "Suntech_STP550S_STC"
pv_params = get_module(module_name)
dimensions = pv_cfg_dimensions or pv_spec_dimensions
module_area = _module_area_from_dimensions(dimensions)
return pv_params, module_area
def _temperature_series_from_config(
temp_config: Any,
index: pd.DatetimeIndex,
weather_df: Optional[pd.DataFrame] = None,
indoor_model: Optional[Dict[str, Any]] = None,
default_temp: float = 25.0,
) -> pd.Series:
"""Build a battery temperature series from config, weather, or a fixed value."""
from breos.weather import build_battery_temperature_series
return build_battery_temperature_series(
temp_config=temp_config,
index=index,
weather_df=weather_df,
indoor_model=indoor_model,
default_temp=default_temp,
)
def _validated_dc_output_scale(config: Dict[str, Any]) -> float:
"""Read and check the DC-side yield correction from a study config.
A DC-side factor is applied to the raw array output before dispatch, so
clipping, charging and the part-load ratio all respond to it. That makes
it the correct knob for a model that under-predicts measured yield, and
it is deliberately not bounded above.
"""
scale = float(config.get("dc_output_scale", 1.0))
if not np.isfinite(scale) or scale <= 0.0:
raise ValueError("dc_output_scale must be finite and greater than 0")
return scale
def _validated_ac_output_scale(config: Dict[str, Any]) -> float:
"""Read and check the AC-side derate from a study config.
The factor derates AC delivery from inside dispatch, so discharge
decisions respond to it. Unlike the DC-side factor it lands after the
inverter nameplate limit, so it is bounded to ``(0, 1]``: above 1 the
inverter would deliver more than its nameplate and more AC than the DC
entering it, and the reported inverter loss would pin at zero. Correct an
under-predicting model with ``dc_output_scale`` instead.
Rejecting here means an out-of-range study config fails before any
evaluation starts, rather than being clamped inside the inverter helpers.
"""
scale = float(config.get("ac_output_scale", 1.0))
if not np.isfinite(scale) or not 0.0 < scale <= 1.0:
raise ValueError(
"ac_output_scale must be finite, greater than 0 and at most 1; it is applied after "
"the inverter nameplate limit. Use dc_output_scale to correct an under-predicting "
"model on the DC side"
)
return scale
def _build_battery_config_from_spec(
batt_spec: Dict[str, Any],
nominal_energy_wh: float,
inverter_efficiency: float = 0.96,
initial_soh: float = 100.0,
enable_replacement: bool = False,
inverter_ac_capacity_w: Optional[float] = None,
replacement_cost: Optional[float] = None,
ac_output_scale: float = 1.0,
) -> BatteryConfig:
"""Build a BatteryConfig for optimization paths without dropping supported settings."""
return BatteryConfig(
nominal_energy_wh=nominal_energy_wh,
battery_type=batt_spec.get("battery_type", "lfp"),
min_soc=batt_spec.get("min_soc", 0.2),
max_soc=batt_spec.get("max_soc", 0.8),
charge_efficiency=batt_spec.get("charge_efficiency", 0.9795),
discharge_efficiency=batt_spec.get("discharge_efficiency", 0.9795),
standby_loss_wh=batt_spec.get("standby_loss_wh", 5.0),
initial_soh=initial_soh,
eol_percentage=batt_spec.get("eol_percentage", 0.7),
inverter_efficiency=inverter_efficiency,
inverter_ac_capacity_w=inverter_ac_capacity_w,
max_charge_power_w=batt_spec.get("max_charge_power_w"),
max_discharge_power_w=batt_spec.get("max_discharge_power_w"),
power_limit_c_rate=batt_spec.get("power_limit_c_rate"),
dc_coupled=batt_spec.get("dc_coupled", True),
calendar_model=batt_spec.get("calendar_model", "naumann_lam_field_calibrated"),
enable_replacement=enable_replacement,
replacement_cost=replacement_cost,
enable_resistance_fade=batt_spec.get("enable_resistance_fade", False),
ac_output_scale=ac_output_scale,
)
def _safe_ratio(numerator: float, denominator: float) -> float:
"""Return a finite scalar ratio, or zero when the denominator is zero."""
denominator = float(denominator)
if abs(denominator) < 1e-12:
return 0.0
return float(numerator) / denominator
def _projected_replacement_cost(batt_spec: Dict[str, Any], battery_kwh: float, storage_cost: float) -> float:
"""Resolve a projected replacement event cost from explicit or calculated input."""
configured = batt_spec.get("replacement_cost")
if configured is None or (isinstance(configured, str) and configured.strip().lower() in {"auto", "calculate"}):
return float(battery_kwh) * float(storage_cost)
if isinstance(configured, bool):
raise ValueError("battery.replacement_cost must be a non-negative number or 'calculate'")
replacement_cost = float(configured)
if not np.isfinite(replacement_cost) or replacement_cost < 0.0:
raise ValueError("battery.replacement_cost must be a non-negative number or 'calculate'")
return replacement_cost
def _interpolate_payback_year(cost_projection: pd.DataFrame) -> Optional[float]:
"""Interpolate discounted payback from cumulative NPV savings."""
if "Savings_Cumulative_NPV" not in cost_projection.columns or cost_projection.empty:
return None
savings = cost_projection["Savings_Cumulative_NPV"].to_numpy(dtype=float)
years = cost_projection["Year"].to_numpy(dtype=float)
if savings[0] >= 0.0:
return float(years[0])
for idx in range(1, len(savings)):
if savings[idx] >= 0.0 and savings[idx - 1] < 0.0:
delta = savings[idx] - savings[idx - 1]
if abs(delta) < 1e-12:
return float(years[idx])
return float(years[idx - 1] - savings[idx - 1] / delta)
return None
def _projected_year_summary(
*,
year: int,
results_df: pd.DataFrame,
freq: str,
pv_degradation_factor: float,
battery_soh: float,
annual_fec: float,
cumulative_fec: float,
cumulative_calendar_seconds: float,
cumulative_cycle_degradation: float,
cumulative_calendar_degradation: float,
resistance_growth: float,
replacements: int,
replacement_cost: float,
) -> Dict[str, Any]:
"""Aggregate one simulated project year from the canonical energy ledger."""
hours_per_step = get_hours_per_step(freq)
def energy_kwh(column: str) -> float:
return float(pd.to_numeric(results_df[column], errors="coerce").fillna(0.0).sum() * hours_per_step / 1000.0)
def optional_energy_kwh(column: str) -> float:
return energy_kwh(column) if column in results_df.columns else 0.0
def optional_mean_pct(column: str) -> float:
"""Mean of a fractional state column as a percentage, 0.0 when absent.
State columns, unlike the ledger flow columns, are already levels
rather than average power, so they are averaged and not integrated.
"""
if column not in results_df.columns:
return 0.0
return float(pd.to_numeric(results_df[column], errors="coerce").fillna(0.0).mean() * 100.0)
load_kwh = energy_kwh("Houseload")
import_kwh = energy_kwh("Import_From_Grid")
export_kwh = energy_kwh("Sell_To_Grid")
pv_kwh = float(system_ac_production_power(results_df).sum() * hours_per_step / 1000.0)
grid_independence = 100.0 * (1.0 - _safe_ratio(import_kwh, load_kwh)) if load_kwh > 0.0 else 0.0
return {
"Year": int(year),
"PV_Production_kWh": pv_kwh,
"PV_DC_kWh": optional_energy_kwh("PV_DC"),
"PV_DC_Curtailed_kWh": optional_energy_kwh("PV_DC_Curtailed"),
"Inverter_Loss_kWh": optional_energy_kwh("Inverter_Loss"),
"Load_kWh": load_kwh,
"Import_kWh": import_kwh,
"Export_kWh": export_kwh,
"Grid_Independence_%": grid_independence,
"Battery_SOH_%": float(battery_soh),
# Cell-side energy in and out, so the pair reflects round-trip loss and
# feeds cycle ageing directly. Charge is measured after charging losses
# and discharge before inverter losses.
"Battery_Charge_Throughput_kWh": optional_energy_kwh("Battery_Charge_Stored"),
"Battery_Discharge_Throughput_kWh": optional_energy_kwh("Battery_Discharge_DC"),
# Normalized SOC is the position in the usable window; absolute SOC is
# the fraction of the SOH-derated pack, so it rises as the pack fades.
"Battery_SOC_Normalized_Mean_%": optional_mean_pct("Battery_SOC_Normalized"),
"Battery_SOC_Absolute_Mean_%": optional_mean_pct("Battery_SOC_Absolute"),
# Annual FEC is the rainflow count every pack used in this year
# accumulated, a retired pack's part-year included. Cumulative FEC
# belongs to the installed pack alone and restarts at zero on
# replacement, so differencing it across a replacement year loses the
# retired pack's final cycles.
"Battery_Annual_FEC": float(annual_fec),
"Battery_Cumulative_FEC": float(cumulative_fec),
"Battery_Cumulative_Calendar_Seconds": float(cumulative_calendar_seconds),
"Battery_Cumulative_Cycle_Degradation": float(cumulative_cycle_degradation),
"Battery_Cumulative_Calendar_Degradation": float(cumulative_calendar_degradation),
"Battery_Resistance_Growth": float(resistance_growth),
"Replacements": int(replacements),
"Replacement_Cost": float(replacement_cost),
"PV_Degradation_Factor": float(pv_degradation_factor),
}
def _summarize_projected_lifetime_metrics(yearly_summary_df: pd.DataFrame) -> Dict[str, float]:
"""Summarize lifetime metrics from actual simulated yearly values."""
if yearly_summary_df.empty:
raise ValueError("yearly_summary_df must contain at least one year")
load = yearly_summary_df["Load_kWh"].astype(float)
production = yearly_summary_df["PV_Production_kWh"].astype(float)
imports = yearly_summary_df["Import_kWh"].astype(float)
annual_gi = yearly_summary_df["Grid_Independence_%"].astype(float)
annual_zeb = np.divide(
production.to_numpy(dtype=float),
load.to_numpy(dtype=float),
out=np.zeros(len(yearly_summary_df), dtype=float),
where=load.to_numpy(dtype=float) > 0.0,
)
return {
"Projected_Grid_Independence_%": 100.0 * (1.0 - _safe_ratio(imports.sum(), load.sum())),
"Projected_Grid_Independence_Year1_%": float(annual_gi.iloc[0]),
"Projected_Grid_Independence_FinalYear_%": float(annual_gi.iloc[-1]),
"Projected_Grid_Independence_Mean_%": float(annual_gi.mean()),
"Projected_Grid_Independence_Min_%": float(annual_gi.min()),
"Projected_ZEB_Ratio": _safe_ratio(production.sum(), load.sum()),
"Projected_ZEB_Ratio_Year1": float(annual_zeb[0]),
"Projected_ZEB_Ratio_FinalYear": float(annual_zeb[-1]),
"Projected_ZEB_Ratio_Mean": float(np.mean(annual_zeb)),
"Projected_ZEB_Ratio_Min": float(np.min(annual_zeb)),
}
def _evaluate_projected_design_metrics(
*,
base_dc_power: Union[pd.Series, Sequence[pd.Series]],
tmy_data: pd.DataFrame,
houseload: pd.DataFrame,
temperature_series: pd.Series,
pv_params: PVModuleParams,
batt_spec: Dict[str, Any],
costs_cfg: Dict[str, Any],
fin_cfg: Dict[str, Any],
freq: str,
years_projection: int,
degradation_rate: float,
n_modules: int,
battery_kwh: float,
inverter_efficiency: float,
inverter_ac_capacity_w: Optional[float],
emissions_params: Optional[EmissionsParams] = None,
return_tables: bool = False,
execution_backend: str = DEFAULT_EXECUTION_BACKEND,
ac_output_scale: float = 1.0,
) -> Dict[str, Any]:
"""Evaluate one design over the projected horizon using production engines.
``base_dc_power`` is normally one weather year, repeated for every
projected year and scaled by PV degradation. Passing a sequence of series
instead runs a real weather sequence, one entry per projected year, so a
study can keep observed inter-annual variability rather than repeating a
single year. The sequence must have exactly ``years_projection`` entries.
A one-year sequence is equivalent to passing that series directly.
"""
if years_projection < 1:
raise ValueError("projected optimization requires at least one project year")
if isinstance(base_dc_power, pd.Series):
dc_by_year: Sequence[pd.Series] = [base_dc_power] * years_projection
else:
dc_by_year = list(base_dc_power)
if len(dc_by_year) != years_projection:
raise ValueError(f"projected weather sequence has {len(dc_by_year)} years, expected {years_projection}")
if not all(isinstance(series, pd.Series) for series in dc_by_year):
raise ValueError("every projected weather-sequence entry must be a pandas Series")
if not 0.0 <= float(degradation_rate) < 1.0:
raise ValueError("projected PV degradation rate must be between 0 and 1")
cost_params = cost_params_from_config(costs_cfg, fin_cfg)
costs = calculate_costs(
n_modules=n_modules,
module_power_w=pv_params.Mpp,
battery_capacity_wh=battery_kwh * 1000.0,
cost_params=cost_params,
)
replacement_cost = _projected_replacement_cost(
batt_spec,
battery_kwh,
cost_params.battery_cost_per_kwh,
)
has_battery = battery_kwh > 0.0
current_soh = float(batt_spec.get("initial_soh", 100.0)) if has_battery else 100.0
cumulative_fec = 0.0
cumulative_cal_seconds = 0.0
cumulative_resistance_growth = 0.0
cumulative_cycle_deg = 0.0
cumulative_cal_deg = 0.0
carried_energy_wh: Optional[float] = None
carried_pv_origin_energy_wh: Optional[float] = None
degradation_engine = str(batt_spec.get("degradation_engine", "native")).strip().lower()
blast_model = batt_spec.get("blast_model")
degradation_state: Optional[Dict[str, Any]] = None
total_replacements = 0
total_replacement_cost = 0.0
yearly_summaries: list[Dict[str, Any]] = []
first_year_results_df: Optional[pd.DataFrame] = None
for year_idx in range(years_projection):
degradation_factor = (1.0 - float(degradation_rate)) ** year_idx
dc_power = dc_by_year[year_idx] * degradation_factor
battery_config = _build_battery_config_from_spec(
batt_spec,
nominal_energy_wh=battery_kwh * 1000.0,
inverter_efficiency=inverter_efficiency,
initial_soh=current_soh,
enable_replacement=bool(batt_spec.get("enable_replacement", True)) and has_battery,
inverter_ac_capacity_w=inverter_ac_capacity_w,
replacement_cost=replacement_cost,
ac_output_scale=ac_output_scale,
)
state_kwargs: Dict[str, float] = {}
if carried_energy_wh is not None:
state_kwargs = {
"initial_energy_wh": carried_energy_wh,
"initial_pv_origin_energy_wh": carried_pv_origin_energy_wh or 0.0,
}
simulation = simulate_energy_balance(
pv_dc=dc_power,
houseload=houseload,
battery_config=battery_config,
start_time=dc_power.index[0],
end_time=dc_power.index[-1],
freq=freq,
temperature_series=temperature_series if has_battery else None,
initial_fec=cumulative_fec,
initial_calendar_seconds=cumulative_cal_seconds,
initial_resistance_growth=cumulative_resistance_growth,
initial_cumulative_cycle_deg=cumulative_cycle_deg,
initial_cumulative_cal_deg=cumulative_cal_deg,
degradation_engine=degradation_engine,
blast_model=blast_model,
initial_degradation_state=degradation_state if degradation_engine == "blast" else None,
return_degradation_state=True,
debug=False,
execution_backend=execution_backend,
**state_kwargs,
)
(
results_df,
_total_pv_wh,
_summary_df,
year_replacement_cost,
year_replacements,
degradation_df,
degradation_state,
) = simulation
if first_year_results_df is None:
first_year_results_df = results_df
annual_fec = 0.0
if has_battery:
carried_energy_wh = float(results_df["Battery_Energy_End"].iloc[-1])
carried_pv_origin_energy_wh = float(results_df["Battery_PV_Origin_Energy_End"].iloc[-1])
if not degradation_df.empty:
# Each project year is its own simulation span, so the span's
# all-pack total is exactly this year's FEC.
annual_fec = float(degradation_df["Cumulative_FEC_All_Packs"].iloc[-1])
cumulative_fec = float(degradation_df["Cumulative_FEC"].iloc[-1])
cumulative_cal_seconds = float(degradation_df["Cumulative_Calendar_Seconds"].iloc[-1])
cumulative_cycle_deg = float(degradation_df["Cumulative_Cycle_Degradation"].iloc[-1])
cumulative_cal_deg = float(degradation_df["Cumulative_Calendar_Degradation"].iloc[-1])
current_soh = float(degradation_df["SOH"].iloc[-1])
if "Resistance_Growth" in degradation_df.columns:
cumulative_resistance_growth = float(degradation_df["Resistance_Growth"].iloc[-1])
total_replacements += int(year_replacements)
total_replacement_cost += float(year_replacement_cost)
yearly_summaries.append(
_projected_year_summary(
year=year_idx + 1,
results_df=results_df,
freq=freq,
pv_degradation_factor=degradation_factor,
battery_soh=current_soh,
annual_fec=annual_fec,
cumulative_fec=cumulative_fec,
cumulative_calendar_seconds=cumulative_cal_seconds,
cumulative_cycle_degradation=cumulative_cycle_deg,
cumulative_calendar_degradation=cumulative_cal_deg,
resistance_growth=cumulative_resistance_growth,
replacements=int(year_replacements),
replacement_cost=float(year_replacement_cost),
)
)
yearly_summary_df = pd.DataFrame(yearly_summaries)
if first_year_results_df is None:
raise RuntimeError("projected design evaluation produced no simulation years")
cost_projection = cost_analysis_projection(
results_df=first_year_results_df,
costs=costs,
num_years=years_projection,
inflation_rate=float(fin_cfg.get("inflation_rate", DEFAULT_INFLATION_ELEC)),
sell_price_inflation=float(fin_cfg.get("sell_price_inflation", 0.0)),
discount_rate=float(fin_cfg.get("discount_rate", DEFAULT_DISCOUNT_RATE)),
freq=freq,
yearly_summary_df=yearly_summary_df,
total_replacement_cost=total_replacement_cost,
emissions_params=emissions_params,
)
payback_year = cost_projection.attrs.get("payback_year")
payback_exact = _interpolate_payback_year(cost_projection)
metrics: Dict[str, Any] = {
**_summarize_projected_lifetime_metrics(yearly_summary_df),
"Projected_NPV_Eur": float(cost_projection["Savings_Cumulative_NPV"].iloc[-1]),
"Projected_Breakeven_Year": float(payback_year) if payback_year is not None else np.nan,
"Projected_Breakeven_Year_Exact": payback_exact if payback_exact is not None else np.nan,
"Projected_Initial_Cost_Eur": float(costs["total_initial_cost"]),
"Projected_Replacement_Cost_Eur": float(total_replacement_cost),
"Projected_Total_Replacements": int(total_replacements),
"Projected_Final_SOH_%": float(current_soh),
"Projected_PV_Production_Year1_kWh": float(yearly_summary_df["PV_Production_kWh"].iloc[0]),
"Projected_PV_Production_FinalYear_kWh": float(yearly_summary_df["PV_Production_kWh"].iloc[-1]),
"Projected_PV_DC_Year1_kWh": float(yearly_summary_df["PV_DC_kWh"].iloc[0]),
"Projected_PV_DC_FinalYear_kWh": float(yearly_summary_df["PV_DC_kWh"].iloc[-1]),
"Projected_PV_DC_Curtailed_Year1_kWh": float(yearly_summary_df["PV_DC_Curtailed_kWh"].iloc[0]),
"Projected_Inverter_Loss_Year1_kWh": float(yearly_summary_df["Inverter_Loss_kWh"].iloc[0]),
"Projected_LCOE_Eur_kWh": float(
calculate_lcoe_from_projection(
cost_projection,
total_investment=float(costs["total_initial_cost"]),
discount_rate=float(fin_cfg.get("discount_rate", DEFAULT_DISCOUNT_RATE)),
)
),
}
if "CO2_Avoided_Total_Cumulative_kg" in cost_projection:
metrics.update(
{
"Projected_CO2_Avoided_Total_kg": float(cost_projection["CO2_Avoided_Total_Cumulative_kg"].iloc[-1]),
"Projected_CO2_Avoided_SelfConsumed_kg": float(
cost_projection["CO2_Avoided_SelfConsumed_Cumulative_kg"].iloc[-1]
),
}
)
if return_tables:
metrics["_yearly_summary_df"] = yearly_summary_df
metrics["_cost_projection_df"] = cost_projection
return metrics
def evaluate_projected_design(
tmy_data: pd.DataFrame,
houseload: pd.DataFrame,
config: Dict[str, Any],
*,
n_modules: int,
battery_kwh: float,
tilt: float,
azimuth: float,
execution_backend: str = DEFAULT_EXECUTION_BACKEND,
weather_by_year: Optional[Sequence[pd.DataFrame]] = None,
) -> ProjectedDesignResult:
"""Evaluate one fixed PV-battery design over the projected horizon.
This is the detailed fixed-design counterpart to projected NSGA-II
scoring. It uses the same PV, battery, replacement, degradation, and
economics components as :func:`optimize_system_multi_objective` and
returns the annual source tables needed for analysis or plotting.
Args:
tmy_data: One-year weather DataFrame.
houseload: One-year load profile.
config: Nested projected-optimization configuration.
n_modules: Installed PV module count.
battery_kwh: Installed nominal battery capacity in kWh.
tilt: PV surface tilt in degrees.
azimuth: PV surface azimuth in degrees.
weather_by_year: Optional real weather sequence, one frame per
projected year, replacing the repeated ``tmy_data`` year. Each
frame is run through the same PV model, and PV degradation still
applies by project year. ``tmy_data`` is still used for the
battery temperature series and must remain a representative year.
The sequence length must equal the projected horizon.
Returns:
Projected metrics, yearly simulation ledger, and financial ledger.
"""
# Zero modules is a valid grid corner, not an error: the exhaustive
# lattice enumerates it so the battery-only slice is measured rather than
# assumed dominated. It produces no PV, so its inverter rating is zero and
# its LCOE is undefined.
if int(n_modules) < 0:
raise ValueError("n_modules must be non-negative")
if float(battery_kwh) < 0.0:
raise ValueError("battery_kwh must be non-negative")
# Before the PV production model runs, not after it. Computing a year of
# irradiance and then failing on a missing import wastes the expensive part
# and reports the cheap problem late.
require_backend(execution_backend)
from pvlib.location import Location
location = config["location"]
loc_obj = Location(
float(location["latitude"]),
float(location["longitude"]),
tz=location.get("timezone", "UTC"),
altitude=float(location.get("altitude", 0.0)),
name=str(location.get("name", "")),
)
simulation = config.get("simulation", {}) or {}
financials = config.get("financials", {}) or {}
emissions_config = config.get("emissions")
pv_config = config.get("pv", {}) or {}
battery = config.get("battery", {}) or {}
freq = str(simulation.get("resolution", "h"))
years_projection = int(
simulation.get("years_projection", financials.get("project_lifespan", DEFAULT_PROJECT_LIFESPAN))
)
degradation_rate = float(pv_config.get("degradation_rate", financials.get("pv_degradation_rate", 0.005)))
pv_params, _module_area = _resolve_pv_module_and_area(config)
# A DC-side yield correction: the array itself produces this much less,
# or more. Unlike ac_output_scale it is applied before dispatch, so
# charging, clipping and the part-load ratio all respond to it, which is
# why it is the correction to reach for when the model under-predicts.
dc_output_scale = _validated_dc_output_scale(config)
def _dc_for(weather_frame: pd.DataFrame) -> pd.Series:
series = calculate_pv_production_dc(
weather_data=weather_frame,
location=loc_obj,
tilt=float(tilt),
surface_azimuth=float(azimuth),
n_modules=int(n_modules),
pv_params=pv_params,
freq=freq,
verbose=False,
**configured_pv_model_kwargs(config),
)
return series if dc_output_scale == 1.0 else series * dc_output_scale
if weather_by_year is None:
base_dc_power: Union[pd.Series, Sequence[pd.Series]] = _dc_for(tmy_data)
dc_index = base_dc_power.index
else:
frames = list(weather_by_year)
if len(frames) != years_projection:
raise ValueError(f"weather_by_year has {len(frames)} years, expected {years_projection}")
# Every year must land on the same intra-year index, because the load
# profile and the battery temperature series are aligned to it once.
reference = _dc_for(frames[0])
series = [reference]
for frame in frames[1:]:
year_dc = _dc_for(frame)
if len(year_dc) != len(reference):
raise ValueError(
"every weather_by_year frame must produce the same number of "
f"timesteps; got {len(year_dc)} against {len(reference)}"
)
year_dc.index = reference.index
series.append(year_dc)
base_dc_power = series
dc_index = reference.index
temperature_series = _temperature_series_from_config(
battery.get("temperature", "weather"),
dc_index,
weather_df=tmy_data,
indoor_model=battery.get("indoor_model"),
)
dc_ac_ratio = cost_params_from_config(config.get("costs"), financials).dc_ac_ratio
inverter_ac_capacity_w = int(n_modules) * pv_params.Mpp / dc_ac_ratio if dc_ac_ratio > 0.0 else None
raw_metrics = _evaluate_projected_design_metrics(
execution_backend=execution_backend,
base_dc_power=base_dc_power,
tmy_data=tmy_data,
houseload=houseload,
temperature_series=temperature_series,
pv_params=pv_params,
batt_spec=battery,
costs_cfg=config.get("costs", {}) or {},