Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 25 additions & 1 deletion solarfarmer/models/pvsystem/pvsystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)")
Expand Down Expand Up @@ -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,
)
Expand Down
22 changes: 22 additions & 0 deletions tests/test_construct_plant.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
24 changes: 24 additions & 0 deletions tests/test_pvsystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)."""
Expand Down
Loading