From b7abdcd2de7b96544a7d495b0f0daaca3641b8a5 Mon Sep 17 00:00:00 2001 From: Javier Lopez Lorente Date: Wed, 25 Nov 2026 11:06:30 +0100 Subject: [PATCH] Add PVsystem.power_binning override for PAN file supplements --- CHANGELOG.md | 4 ++++ solarfarmer/models/pvsystem/pvsystem.py | 26 ++++++++++++++++++++++++- tests/test_construct_plant.py | 22 +++++++++++++++++++++ tests/test_pvsystem.py | 24 +++++++++++++++++++++++ 4 files changed, 75 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c0b719..22c3cd2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- `PVSystem.power_binning` overrides the `power_binning_effect` of the module's `PanFileSupplements` + (per unit, range [-0.1, 0.1], validated on construction and assignment). When `None` (default), no + override is written and the value is inferred from the PAN file. It is listed by `PVSystem.describe(verbose=True)`. + - `QuadDouble.width`, `depth`, `front_normal`, `tilt` and `azimuth` report how a rack's corners will be interpreted. - `PVPlant` and `Racks` issue one `RackOrientationWarning` listing any racks whose front face points diff --git a/solarfarmer/models/pvsystem/pvsystem.py b/solarfarmer/models/pvsystem/pvsystem.py index 87c8fcd..a1af18d 100644 --- a/solarfarmer/models/pvsystem/pvsystem.py +++ b/solarfarmer/models/pvsystem/pvsystem.py @@ -6,7 +6,9 @@ from dataclasses import asdict, dataclass, field, replace from enum import Enum from pathlib import Path -from typing import Any +from typing import Annotated, Any + +from pydantic import TypeAdapter, ValidationError from ... import rcl from ...logging import get_logger @@ -72,6 +74,11 @@ "inverter_type": InverterType, } +# Reuses the PanFileSupplements field constraints so the accepted range has a single source of truth. +_POWER_BINNING_ADAPTER: TypeAdapter[float | None] = TypeAdapter( + Annotated[float | None, *PanFileSupplements.model_fields["power_binning_effect"].metadata] +) + # CustomRotations is excluded: PVSystem has no way to supply a rotation table. _PVSYSTEM_TRACKING_ALGORITHMS: tuple[TrackerAlgorithm, ...] = ( TrackerAlgorithm.SLOPE_AWARE_BACKTRACKING, @@ -240,6 +247,12 @@ class PVSystem: Loss due to light-induced degradation (LID) (per unit). When set, overrides the LIDLoss value in the PAN file. When ``None`` (default), the value from the PAN file is used. If the PAN file also has no LIDLoss key, the SF API defaults to 0.0. + power_binning: Optional[float] = None + Power binning effect of the module (per unit), range [-0.1, 0.1]. When set, it is + written to the ``power_binning_effect`` field of the module's ``PanFileSupplements``, + overriding the module default. When ``None`` (default), no override is written and + the value is inferred from the PAN file by the calculation. The range is validated on + construction and assignment, using the ``PanFileSupplements`` constraints. module_iam_model_override: Optional[IAMModelTypeForOverride] = None Override for the module IAM model used in the calculation (default is None, which will use the values from the module's PAN file). @@ -360,6 +373,7 @@ class PVSystem: recalculate_modeling_correction_factor: bool = True module_quality_factor: float | None = 0.0 lid_loss: float | None = None + power_binning: float | None = None module_iam_model_override: str | None = None constant_heat_coefficient: float | None = CONSTANT_HEAT_COEFFICIENT convective_heat_coefficient: float | None = CONVECTIVE_HEAT_COEFFICIENT @@ -683,6 +697,14 @@ def ond_file_map(self) -> dict[str, Path]: return dict(self._ond_files) def __setattr__(self, name: str, value: Any) -> None: + if name == "power_binning": + try: + value = _POWER_BINNING_ADAPTER.validate_python(value) + except ValidationError as err: + raise ValueError( + f"Invalid power_binning {value!r}: {err.errors()[0]['msg']} " + "(per unit, range [-0.1, 0.1])." + ) from err if name == "tracking_algorithm": value = _coerce_tracking_algorithm(value) enum_cls = _ENUM_FIELDS.get(name) @@ -911,6 +933,7 @@ def describe(self, verbose=False) -> None: print(f"Module Mismatch Loss: {self.module_mismatch} (per unit)") print(f"Module Quality Factor: {self.module_quality_factor} (per unit)") print(f"LID Loss: {self.lid_loss} (per unit)") + print(f"Power Binning Effect: {self.power_binning} (per unit)") print(f"Transformer Fixed Loss: {plant.transformer_fixed_loss} (per unit)") print(f"Transformer Variable Loss: {plant.transformer_variable_loss} (per unit)") print(f"Auxiliary Loss (Fixed Factor): {self.aux_loss_fixed_factor} (per unit)") @@ -1935,6 +1958,7 @@ def generate_pan_file_supplements( recalculate_modeling_correction_factor=plant.recalculate_modeling_correction_factor, module_quality_factor=plant.module_quality_factor, lid_loss=lid_loss, + power_binning_effect=plant.power_binning, bifaciality_factor=bifaciality_factor, iam_model_type_override=plant.module_iam_model_override, ) diff --git a/tests/test_construct_plant.py b/tests/test_construct_plant.py index 8a710b7..c0556ce 100644 --- a/tests/test_construct_plant.py +++ b/tests/test_construct_plant.py @@ -351,6 +351,28 @@ def test_lid_loss_is_none_when_neither_plant_nor_pan_provides_value( pan_key = module_info_without_lid["pan_filename"] assert supplements[pan_key].lid_loss is None + def test_power_binning_is_none_by_default(self, module_info_with_lid): + """No override is written when plant.power_binning is unset.""" + supplements = generate_pan_file_supplements( + PVSystem(latitude=0, longitude=0), module_info_with_lid, bifaciality_factor=0.0 + ) + pan_key = module_info_with_lid["pan_filename"] + assert supplements[pan_key].power_binning_effect is None + + def test_plant_power_binning_overrides_module_default(self, module_info_with_lid): + plant = PVSystem(latitude=0, longitude=0, power_binning=-0.02) + supplements = generate_pan_file_supplements( + plant, module_info_with_lid, bifaciality_factor=0.0 + ) + pan_key = module_info_with_lid["pan_filename"] + assert supplements[pan_key].power_binning_effect == pytest.approx(-0.02) + + def test_power_binning_reaches_payload(self, plant): + plant.power_binning = 0.01 + payload = json.loads(plant.produce_payload()) + supplements = next(iter(payload["panFileSupplements"].values())) + assert supplements["powerBinningEffect"] == pytest.approx(0.01) + class TestListPathInput: """Verify pan_files and ond_files accept list[Path] in addition to dict.""" diff --git a/tests/test_pvsystem.py b/tests/test_pvsystem.py index b330ad9..f553fb6 100644 --- a/tests/test_pvsystem.py +++ b/tests/test_pvsystem.py @@ -936,6 +936,30 @@ def test_describe_prints_effective_defaults(self, capsys): assert "Mounting Height: 1.5" in capsys.readouterr().out + def test_describe_shows_power_binning(self, capsys): + PVSystem(latitude=45.0, longitude=10.0, power_binning=0.01).describe(verbose=True) + + assert "Power Binning Effect: 0.01" in capsys.readouterr().out + + @pytest.mark.parametrize("value", [-0.1, 0.0, 0.1, None]) + def test_power_binning_accepts_values_within_range(self, value): + assert PVSystem(power_binning=value).power_binning == value + + @pytest.mark.parametrize("value", [-0.11, 0.11]) + def test_power_binning_out_of_range_raises(self, value): + with pytest.raises(ValueError, match="power_binning"): + PVSystem(power_binning=value) + plant = PVSystem() + with pytest.raises(ValueError, match="power_binning"): + plant.power_binning = value + assert plant.power_binning is None + + def test_power_binning_round_trips_through_file(self, tmp_path): + path = tmp_path / "plant.json" + PVSystem(power_binning=0.02).to_file(path) + + assert PVSystem.from_file(path).power_binning == 0.02 + class TestPVSystemPersistence: """Tests for to_file() / from_file() round-trip (Phase 3 bug fix)."""