From fa21c521f70efee9dda63431903847eba1850f7a Mon Sep 17 00:00:00 2001 From: Will Holmgren Date: Thu, 19 Nov 2026 14:54:55 -0700 Subject: [PATCH 1/5] Document rack corner order and warn when a rack faces below the horizon The order of a rack's quad corners decides which face the calculation treats as the front of the modules, but QuadDouble and Rack did not document it, and every rack fixture in test_composition.py used the reverse order. That order passes validation and completes, but in an unshaded 3D control it returned about 15% of the equivalent 2D energy. - Document the order on QuadDouble and Rack: P1 at the low corner, P1->P2 up the slope, P1->P4 along the row (SW-low, NW-high, NE-high, SE-low for a south-facing rack), with x east, y north and z up, matching the ModelChainAsync documentation example - Add QuadDouble.width, depth, front_normal, tilt and azimuth - Issue RackOrientationWarning when a rack's front face points below the horizon, or its quad has no area - Correct the four rack fixtures in test_composition.py Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 +++ solarfarmer/__init__.py | 2 + solarfarmer/models/__init__.py | 3 +- solarfarmer/models/quad_double.py | 84 +++++++++++++++++++-- solarfarmer/models/rack.py | 37 ++++++++- tests/test_models/test_composition.py | 16 ++-- tests/test_models/test_validation.py | 104 ++++++++++++++++++++++++++ 7 files changed, 241 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c980bc0..ee24e14 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,8 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- `QuadDouble.width`, `depth`, `front_normal`, `tilt` and `azimuth` report how a rack's corners will be + interpreted. +- Constructing a `Rack` whose front face points below the horizon issues a `RackOrientationWarning`. + This almost always means the corners are in the reverse order, which passes validation but gives + badly wrong energy. + ### Fixed +- The `QuadDouble` and `Rack` docstrings now document the corner order: P1 at the low corner, P1→P2 up + the slope and P1→P4 along the row (SW-low, NW-high, NE-high, SE-low for a south-facing rack), with x + east, y north and z up. The rack fixtures in `tests/test_models/test_composition.py` used the reverse + order and have been corrected. - `__released__` now reports the release date of installed wheels instead of `"unreleased"` or the tag date of whichever git repository the user's working directory belonged to. It is also exposed at the package top level, like `solarfarmer.__version__`; previously `import solarfarmer as sf; sf.__released__` diff --git a/solarfarmer/__init__.py b/solarfarmer/__init__.py index 13c525c..8a8c6bb 100644 --- a/solarfarmer/__init__.py +++ b/solarfarmer/__init__.py @@ -71,6 +71,7 @@ PVSystem, QuadDouble, Rack, + RackOrientationWarning, Racks, ShadingObjects, SimpleTerrain, @@ -169,6 +170,7 @@ "PVSystem", "QuadDouble", "Rack", + "RackOrientationWarning", "Racks", "run_energy_calculation", "service", diff --git a/solarfarmer/models/__init__.py b/solarfarmer/models/__init__.py index b8f5cc2..a29ca14 100644 --- a/solarfarmer/models/__init__.py +++ b/solarfarmer/models/__init__.py @@ -36,7 +36,7 @@ from .pvsystem.pvsystem import PVSystem from .pvsystem.validation import ValidationMessage from .quad_double import QuadDouble -from .rack import Rack +from .rack import Rack, RackOrientationWarning from .racks import Racks from .shading_objects import ShadingObjects from .simple_terrain import SimpleTerrain @@ -84,6 +84,7 @@ "PVSystem", "QuadDouble", "Rack", + "RackOrientationWarning", "Racks", "ShadingObjects", "SimpleTerrain", diff --git a/solarfarmer/models/quad_double.py b/solarfarmer/models/quad_double.py index b5f8721..36bab2a 100644 --- a/solarfarmer/models/quad_double.py +++ b/solarfarmer/models/quad_double.py @@ -1,26 +1,98 @@ +import math + from ._base import SolarFarmerBaseModel from .vector3double import Vector3Double +def _difference(a: Vector3Double, b: Vector3Double) -> tuple[float, float, float]: + return (a.x - b.x, a.y - b.y, a.z - b.z) + + class QuadDouble(SolarFarmerBaseModel): """A quadrilateral in 3D space defined by four corner vertices. - Represents the footprint or boundary of a rack or similar planar object, - where the four points define the corners of a quadrilateral face. + Represents the surface of a fixed-tilt rack. Coordinates are in metres with + x pointing east, y pointing north and z up, as in the projected coordinates + of the ModelChainAsync API examples. + + The corner order determines which face is the front of the modules. Seen + from in front of the modules, start at the low corner on the left and go up + the slope first:: + + P2 ---------------- P3 high edge + | | + P1 ---------------- P4 low edge + + ``P1 -> P2`` runs up the slope (the rack depth) and ``P1 -> P4`` runs along + the row (the rack width). For a south-facing rack the order is SW-low, + NW-high, NE-high, SE-low, which is clockwise when seen from above. With this + order, ``(P4 - P1) x (P2 - P1)`` points out of the front face + (:attr:`front_normal`). + + The reverse order also passes schema validation, but gives badly wrong + energy, consistent with the calculation treating the back of the modules as + the front. :class:`~solarfarmer.models.Rack` warns when a quad's front face + points below the horizon. Attributes ---------- p1 : Vector3Double - First corner vertex of the quadrilateral + Low corner at the start of the row (lower left, seen from the front) p2 : Vector3Double - Second corner vertex of the quadrilateral + High corner directly up the slope from ``p1`` p3 : Vector3Double - Third corner vertex of the quadrilateral + High corner at the end of the row p4 : Vector3Double - Fourth corner vertex of the quadrilateral + Low corner at the end of the row, directly down the slope from ``p3`` """ p1: Vector3Double p2: Vector3Double p3: Vector3Double p4: Vector3Double + + @property + def width(self) -> float: + """Length of the ``P1 -> P4`` edge, along the row, in metres.""" + return math.hypot(*_difference(self.p4, self.p1)) + + @property + def depth(self) -> float: + """Length of the ``P1 -> P2`` edge, up the slope, in metres.""" + return math.hypot(*_difference(self.p2, self.p1)) + + @property + def front_normal(self) -> tuple[float, float, float]: + """Unit vector pointing out of the front face, ``(P4 - P1) x (P2 - P1)`` normalized. + + Raises + ------ + ValueError + If ``P1``, ``P2`` and ``P4`` are collinear, so the quad has no area + """ + ax, ay, az = _difference(self.p4, self.p1) + bx, by, bz = _difference(self.p2, self.p1) + normal = (ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx) + length = math.hypot(*normal) + if length < 1e-12: + raise ValueError("Quad corners P1, P2 and P4 are collinear, so the quad has no area") + return (normal[0] / length, normal[1] / length, normal[2] / length) + + @property + def tilt(self) -> float: + """Angle of the front face from horizontal, in degrees. + + 0 means facing straight up, 90 means vertical, and more than 90 means + the front face points below the horizon. + """ + return math.degrees(math.acos(max(-1.0, min(1.0, self.front_normal[2])))) + + @property + def azimuth(self) -> float: + """Direction the front face points, in degrees clockwise from north (the y axis). + + North is 0, east 90, south 180 and west 270. Not meaningful for a + horizontal quad. + """ + nx, ny, _ = self.front_normal + return math.degrees(math.atan2(nx, ny)) % 360.0 diff --git a/solarfarmer/models/rack.py b/solarfarmer/models/rack.py index 8951729..b0864ba 100644 --- a/solarfarmer/models/rack.py +++ b/solarfarmer/models/rack.py @@ -1,9 +1,15 @@ -from pydantic import Field +import warnings + +from pydantic import Field, model_validator from ._base import SolarFarmerBaseModel from .quad_double import QuadDouble +class RackOrientationWarning(UserWarning): + """Warn when a rack's corner order puts its front face below the horizon.""" + + class Rack(SolarFarmerBaseModel): """A fixed-tilt rack in a 3D plant layout. @@ -11,6 +17,11 @@ class Rack(SolarFarmerBaseModel): identified by an integer ID and referencing a mounting type. The rack geometry is described by a quadrilateral (``quad``) in world coordinates. + The order of the ``quad`` corners determines which face is the front of + the modules; see :class:`~solarfarmer.models.QuadDouble`. A rack whose front + face points below the horizon almost always has its corners in the reverse + order, so constructing one issues a :class:`RackOrientationWarning`. + Attributes ---------- id : int @@ -25,7 +36,8 @@ class Rack(SolarFarmerBaseModel): Row-to-row pitch to the adjacent rack in front of this one, in metres. ``None`` if this rack has no neighbour in front of it (e.g. first row) quad : QuadDouble - 3D quadrilateral defining the four corner vertices of the rack surface + 3D quadrilateral defining the four corner vertices of the rack surface, + in the order described in :class:`~solarfarmer.models.QuadDouble` """ id: int @@ -33,3 +45,24 @@ class Rack(SolarFarmerBaseModel): pitch_to_back: float | None = None pitch_to_front: float | None = None quad: QuadDouble + + @model_validator(mode="after") + def _warn_on_reversed_corners(self) -> "Rack": + """Warn if the quad has no area or its front face points below the horizon.""" + # Warn rather than reorder: reordering corners would also change module indexing + try: + normal_z = self.quad.front_normal[2] + except ValueError as e: + warnings.warn(f"Rack {self.id}: {e}.", RackOrientationWarning, stacklevel=3) + return self + if normal_z < -1e-9: + warnings.warn( + f"Rack {self.id}: the front face of the quad points below the horizon " + f"(tilt {self.quad.tilt:.1f} degrees), so the calculation would treat the " + "back of the modules as the front. The corners are probably in the reverse " + "order; for a south-facing rack use P1 SW-low, P2 NW-high, P3 NE-high, " + "P4 SE-low.", + RackOrientationWarning, + stacklevel=3, + ) + return self diff --git a/tests/test_models/test_composition.py b/tests/test_models/test_composition.py index ee3b621..be1d684 100644 --- a/tests/test_models/test_composition.py +++ b/tests/test_models/test_composition.py @@ -310,9 +310,9 @@ def test_rack_objects_serialized(self) -> None: """PVPlant.racks serializes Rack objects with correct camelCase keys.""" quad = QuadDouble( p1=Vector3Double(x=0.0, y=0.0, z=0.0), - p2=Vector3Double(x=4.0, y=0.0, z=0.0), + p2=Vector3Double(x=0.0, y=2.0, z=1.0), p3=Vector3Double(x=4.0, y=2.0, z=1.0), - p4=Vector3Double(x=0.0, y=2.0, z=1.0), + p4=Vector3Double(x=4.0, y=0.0, z=0.0), ) rack = Rack(id=0, mounting_type_id="mount_r", pitch_to_front=5.0, quad=quad) @@ -425,9 +425,9 @@ def test_racks_collection_roundtrip(self) -> None: mounting_type_id="m1", quad=QuadDouble( p1=Vector3Double(x=0.0, y=0.0, z=0.0), - p2=Vector3Double(x=4.0, y=0.0, z=0.0), + p2=Vector3Double(x=0.0, y=2.0, z=1.0), p3=Vector3Double(x=4.0, y=2.0, z=1.0), - p4=Vector3Double(x=0.0, y=2.0, z=1.0), + p4=Vector3Double(x=4.0, y=0.0, z=0.0), ), ), Rack( @@ -435,9 +435,9 @@ def test_racks_collection_roundtrip(self) -> None: mounting_type_id="m1", quad=QuadDouble( p1=Vector3Double(x=0.0, y=6.0, z=0.0), - p2=Vector3Double(x=4.0, y=6.0, z=0.0), + p2=Vector3Double(x=0.0, y=8.0, z=1.0), p3=Vector3Double(x=4.0, y=8.0, z=1.0), - p4=Vector3Double(x=0.0, y=8.0, z=1.0), + p4=Vector3Double(x=4.0, y=6.0, z=0.0), ), ), ] @@ -539,9 +539,9 @@ def _build_3d_plant(self) -> PVPlant: quad = QuadDouble( p1=Vector3Double(x=0.0, y=0.0, z=10.0), - p2=Vector3Double(x=30.0, y=0.0, z=10.0), + p2=Vector3Double(x=0.0, y=2.0, z=10.2), p3=Vector3Double(x=30.0, y=2.0, z=10.2), - p4=Vector3Double(x=0.0, y=2.0, z=10.2), + p4=Vector3Double(x=30.0, y=0.0, z=10.0), ) rack_a = Rack(id=100, mounting_type_id="FT_Rack_14", pitch_to_front=1.55, quad=quad) rack_b = Rack( diff --git a/tests/test_models/test_validation.py b/tests/test_models/test_validation.py index 325331b..2551da8 100644 --- a/tests/test_models/test_validation.py +++ b/tests/test_models/test_validation.py @@ -1,3 +1,6 @@ +import json +import math +import warnings from datetime import UTC import pytest @@ -12,10 +15,14 @@ MountingTypeSpecification, OndFileSupplements, PanFileSupplements, + QuadDouble, + Rack, + RackOrientationWarning, TrackerCondition, TrackerSystem, TransformerLossModelTypes, TransformerSpecification, + Vector3Double, ) # --------------------------------------------------------------------------- @@ -479,3 +486,100 @@ def test_boundary_values_are_valid(self) -> None: tracker_rotations_array_values=[-8990, 0, 8990], ) assert cond.tracker_rotations_array_values == [-8990, 0, 8990] + + +# --------------------------------------------------------------------------- +# QuadDouble / Rack orientation +# --------------------------------------------------------------------------- + + +def _quad(*corners: tuple[float, float, float]) -> QuadDouble: + p1, p2, p3, p4 = (Vector3Double(x=x, y=y, z=z) for x, y, z in corners) + return QuadDouble(p1=p1, p2=p2, p3=p3, p4=p4) + + +# South-facing rack in the documented order (P1 SW-low, P2 NW-high, P3 NE-high, +# P4 SE-low): 10 m wide, 5 m deep, rising 3 m over 4 m +SOUTH_FACING = ((0.0, 0.0, 0.0), (0.0, 4.0, 3.0), (10.0, 4.0, 3.0), (10.0, 0.0, 0.0)) +# The same corners in the reverse order (P1 SW-low, P2 SE-low, P3 NE-high, P4 NW-high) +SOUTH_FACING_REVERSED = tuple(SOUTH_FACING[i] for i in (0, 3, 2, 1)) + + +class TestQuadDoubleGeometry: + def test_south_facing_rack(self) -> None: + quad = _quad(*SOUTH_FACING) + assert quad.width == pytest.approx(10.0) + assert quad.depth == pytest.approx(5.0) + assert quad.front_normal == pytest.approx((0.0, -0.6, 0.8)) + assert quad.tilt == pytest.approx(math.degrees(math.atan2(3.0, 4.0))) + assert quad.azimuth == pytest.approx(180.0) + + def test_modelchainasync_documentation_example(self) -> None: + """The rack in the web API's ModelChainAsync example faces south at about 34 degrees.""" + quad = _quad( + (633616.55525403516, 4502376.1064225091, 308.44455607951465), + (633616.60684414359, 4502378.5736383246, 310.10791430261804), + (633640.11553953763, 4502378.5736383246, 309.37877723037911), + (633640.0639494292, 4502376.1064225091, 307.71541900727573), + ) + assert quad.tilt == pytest.approx(34.0, abs=0.1) + assert quad.azimuth == pytest.approx(177.4, abs=0.1) + assert quad.depth == pytest.approx(2.976, abs=0.001) + + def test_east_facing_rack(self) -> None: + # Low edge on the east side; seen from the front, P1 is the south end of it + quad = _quad((4.0, 0.0, 0.0), (0.0, 0.0, 3.0), (0.0, 10.0, 3.0), (4.0, 10.0, 0.0)) + assert quad.azimuth == pytest.approx(90.0) + assert quad.tilt == pytest.approx(math.degrees(math.atan2(3.0, 4.0))) + + def test_horizontal_quad_faces_up(self) -> None: + quad = _quad((0.0, 0.0, 0.0), (0.0, 5.0, 0.0), (10.0, 5.0, 0.0), (10.0, 0.0, 0.0)) + assert quad.front_normal == pytest.approx((0.0, 0.0, 1.0)) + assert quad.tilt == pytest.approx(0.0) + + def test_reversed_order_faces_down(self) -> None: + quad = _quad(*SOUTH_FACING_REVERSED) + assert quad.front_normal[2] < 0 + assert quad.tilt > 90.0 + + def test_collinear_corners_have_no_normal(self) -> None: + quad = _quad((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (2.0, 0.0, 0.0), (3.0, 0.0, 0.0)) + with pytest.raises(ValueError, match="no area"): + _ = quad.front_normal + + +class TestRackOrientation: + def test_documented_order_does_not_warn(self) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("error", RackOrientationWarning) + Rack(id=0, mounting_type_id="m1", quad=_quad(*SOUTH_FACING)) + + def test_reversed_order_warns(self) -> None: + with pytest.warns(RackOrientationWarning, match="reverse order") as record: + Rack(id=7, mounting_type_id="m1", quad=_quad(*SOUTH_FACING_REVERSED)) + assert "Rack 7" in str(record[0].message) + assert record[0].filename == __file__ # points at the caller, not pydantic + + def test_reversed_order_warns_when_loaded_from_json(self) -> None: + corners = { + f"p{i}": dict(zip("xyz", c, strict=True)) + for i, c in enumerate(SOUTH_FACING_REVERSED, 1) + } + payload = json.dumps({"id": 0, "mountingTypeID": "m1", "quad": corners}) + + with pytest.warns(RackOrientationWarning): + Rack.model_validate_json(payload) + + def test_vertical_rack_does_not_warn(self) -> None: + """A vertical (e.g. bifacial fence) rack faces the horizon, not below it.""" + quad = _quad((0.0, 0.0, 0.0), (0.0, 0.0, 2.0), (10.0, 0.0, 2.0), (10.0, 0.0, 0.0)) + with warnings.catch_warnings(): + warnings.simplefilter("error", RackOrientationWarning) + rack = Rack(id=0, mounting_type_id="m1", quad=quad) + assert rack.quad.tilt == pytest.approx(90.0) + assert rack.quad.azimuth == pytest.approx(180.0) + + def test_zero_area_quad_warns(self) -> None: + quad = _quad((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (2.0, 0.0, 0.0), (3.0, 0.0, 0.0)) + with pytest.warns(RackOrientationWarning, match="no area"): + Rack(id=0, mounting_type_id="m1", quad=quad) From efdff00ecadd64453fb8aff5076125d4b746fad4 Mon Sep 17 00:00:00 2001 From: Will Holmgren Date: Thu, 19 Nov 2026 21:21:54 -0700 Subject: [PATCH 2/5] Check rack orientation once per collection instead of per rack A validator on every Rack added about 7 us per rack and printed one warning per reversed rack: 130,000 warnings for a 500 MW layout of 7-module racks generated in the wrong order. PVPlant and Racks now check all of their racks in one pass and issue a single RackOrientationWarning with the count and the first ten rack IDs. Validating 130,000 racks takes the same time as without the check (0.74 s here). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 +-- solarfarmer/models/pv_plant.py | 12 ++++- solarfarmer/models/quad_double.py | 15 ++++-- solarfarmer/models/rack.py | 78 +++++++++++++++++++--------- solarfarmer/models/racks.py | 13 ++++- tests/test_models/test_validation.py | 47 +++++++++++++---- 6 files changed, 124 insertions(+), 48 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ee24e14..4e4b05d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,9 +11,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `QuadDouble.width`, `depth`, `front_normal`, `tilt` and `azimuth` report how a rack's corners will be interpreted. -- Constructing a `Rack` whose front face points below the horizon issues a `RackOrientationWarning`. - This almost always means the corners are in the reverse order, which passes validation but gives - badly wrong energy. +- `PVPlant` and `Racks` issue one `RackOrientationWarning` listing any racks whose front face points + below the horizon. This almost always means the corners are in the reverse order, which passes + validation but gives badly wrong energy. The check is one pass over all racks, so large layouts + stay fast and get a single warning rather than one per rack. ### Fixed diff --git a/solarfarmer/models/pv_plant.py b/solarfarmer/models/pv_plant.py index cee9d6d..d6ff554 100644 --- a/solarfarmer/models/pv_plant.py +++ b/solarfarmer/models/pv_plant.py @@ -8,7 +8,7 @@ from .auxiliary_losses import AuxiliaryLosses from .indexed_object3d import IndexedObject3D from .mounting_type_specification import MountingTypeSpecification -from .rack import Rack +from .rack import Rack, _warn_on_reversed_racks from .simple_terrain import SimpleTerrain from .tracker import Tracker from .tracker_system import TrackerSystem @@ -40,7 +40,9 @@ class PVPlant(SolarFarmerBaseModel): auxiliary_losses : AuxiliaryLosses or None Plant-level auxiliary losses racks : list[Rack] or None - Fixed-tilt rack objects for 3D calculations. Not required for 2D + Fixed-tilt rack objects for 3D calculations. Not required for 2D. One + :class:`~solarfarmer.models.RackOrientationWarning` lists any racks + whose front face points below the horizon shading_objects : list[IndexedObject3D] or None 3D shading obstacles (buildings, terrain features, etc.). Used for 3D calculations; ignored for 2D @@ -90,3 +92,9 @@ def _check_transformer_spec_references(self) -> PVPlant: f"not in transformer_specifications. Available: {available}" ) return self + + @model_validator(mode="after") + def _check_rack_orientation(self) -> PVPlant: + """Warn once about racks whose front face points below the horizon.""" + _warn_on_reversed_racks(self.racks) + return self diff --git a/solarfarmer/models/quad_double.py b/solarfarmer/models/quad_double.py index 36bab2a..8a1e163 100644 --- a/solarfarmer/models/quad_double.py +++ b/solarfarmer/models/quad_double.py @@ -31,8 +31,9 @@ class QuadDouble(SolarFarmerBaseModel): The reverse order also passes schema validation, but gives badly wrong energy, consistent with the calculation treating the back of the modules as - the front. :class:`~solarfarmer.models.Rack` warns when a quad's front face - points below the horizon. + the front. :class:`~solarfarmer.models.PVPlant` and + :class:`~solarfarmer.models.Racks` warn about racks whose front face points + below the horizon. Attributes ---------- @@ -70,9 +71,7 @@ def front_normal(self) -> tuple[float, float, float]: ValueError If ``P1``, ``P2`` and ``P4`` are collinear, so the quad has no area """ - ax, ay, az = _difference(self.p4, self.p1) - bx, by, bz = _difference(self.p2, self.p1) - normal = (ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx) + normal = self._unscaled_normal() length = math.hypot(*normal) if length < 1e-12: raise ValueError("Quad corners P1, P2 and P4 are collinear, so the quad has no area") @@ -96,3 +95,9 @@ def azimuth(self) -> float: """ nx, ny, _ = self.front_normal return math.degrees(math.atan2(nx, ny)) % 360.0 + + def _unscaled_normal(self) -> tuple[float, float, float]: + """``(P4 - P1) x (P2 - P1)``; its length is twice the area of triangle P1, P2, P4.""" + ax, ay, az = _difference(self.p4, self.p1) + bx, by, bz = _difference(self.p2, self.p1) + return (ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx) diff --git a/solarfarmer/models/rack.py b/solarfarmer/models/rack.py index b0864ba..c548c3a 100644 --- a/solarfarmer/models/rack.py +++ b/solarfarmer/models/rack.py @@ -1,13 +1,16 @@ +import math import warnings -from pydantic import Field, model_validator +from pydantic import Field from ._base import SolarFarmerBaseModel from .quad_double import QuadDouble +_MAX_LISTED_RACK_IDS = 10 + class RackOrientationWarning(UserWarning): - """Warn when a rack's corner order puts its front face below the horizon.""" + """Warn when racks' corner order puts their front face below the horizon.""" class Rack(SolarFarmerBaseModel): @@ -18,9 +21,11 @@ class Rack(SolarFarmerBaseModel): geometry is described by a quadrilateral (``quad``) in world coordinates. The order of the ``quad`` corners determines which face is the front of - the modules; see :class:`~solarfarmer.models.QuadDouble`. A rack whose front - face points below the horizon almost always has its corners in the reverse - order, so constructing one issues a :class:`RackOrientationWarning`. + the modules; see :class:`~solarfarmer.models.QuadDouble`. + :class:`~solarfarmer.models.PVPlant` and :class:`~solarfarmer.models.Racks` + check all of their racks and issue one :class:`RackOrientationWarning` + listing any whose front face points below the horizon, which almost always + means the corners are in the reverse order. Attributes ---------- @@ -46,23 +51,46 @@ class Rack(SolarFarmerBaseModel): pitch_to_front: float | None = None quad: QuadDouble - @model_validator(mode="after") - def _warn_on_reversed_corners(self) -> "Rack": - """Warn if the quad has no area or its front face points below the horizon.""" - # Warn rather than reorder: reordering corners would also change module indexing - try: - normal_z = self.quad.front_normal[2] - except ValueError as e: - warnings.warn(f"Rack {self.id}: {e}.", RackOrientationWarning, stacklevel=3) - return self - if normal_z < -1e-9: - warnings.warn( - f"Rack {self.id}: the front face of the quad points below the horizon " - f"(tilt {self.quad.tilt:.1f} degrees), so the calculation would treat the " - "back of the modules as the front. The corners are probably in the reverse " - "order; for a south-facing rack use P1 SW-low, P2 NW-high, P3 NE-high, " - "P4 SE-low.", - RackOrientationWarning, - stacklevel=3, - ) - return self + +def _warn_on_reversed_racks(racks: list[Rack] | None) -> None: + """Issue one warning for racks whose front face points below the horizon or that have no area. + + Called from the model validators of collections of racks. Checking the whole + collection in one pass, with one warning, keeps large layouts fast and their + output readable; a per-rack warning would print once for every rack. + """ + if not racks: + return + + facing_down: list[int] = [] + no_area: list[int] = [] + for rack in racks: + nx, ny, nz = rack.quad._unscaled_normal() + length_squared = nx * nx + ny * ny + nz * nz + if length_squared < 1e-24: + no_area.append(rack.id) + elif nz < -1e-9 * math.sqrt(length_squared): + facing_down.append(rack.id) + + def describe(rack_ids: list[int]) -> str: + listed = ", ".join(str(i) for i in rack_ids[:_MAX_LISTED_RACK_IDS]) + more = len(rack_ids) - _MAX_LISTED_RACK_IDS + listed += f" and {more} more" if more > 0 else "" + return f"{len(rack_ids)} of {len(racks)} racks (IDs {listed})" + + # warn -> this function -> model validator -> pydantic entry point -> caller + if facing_down: + warnings.warn( + f"{describe(facing_down)} have a front face pointing below the horizon, so the " + "calculation would treat the back of their modules as the front. Their corners " + "are probably in the reverse order; for a south-facing rack use P1 SW-low, " + "P2 NW-high, P3 NE-high, P4 SE-low. QuadDouble.tilt shows how a rack is read.", + RackOrientationWarning, + stacklevel=4, + ) + if no_area: + warnings.warn( + f"{describe(no_area)} have a quad with no area: corners P1, P2 and P4 are collinear.", + RackOrientationWarning, + stacklevel=4, + ) diff --git a/solarfarmer/models/racks.py b/solarfarmer/models/racks.py index 7241f74..8010cab 100644 --- a/solarfarmer/models/racks.py +++ b/solarfarmer/models/racks.py @@ -1,12 +1,15 @@ -from pydantic import Field +from pydantic import Field, model_validator from ._base import SolarFarmerBaseModel -from .rack import Rack +from .rack import Rack, _warn_on_reversed_racks class Racks(SolarFarmerBaseModel): """A collection of fixed-tilt racks in a 3D plant layout. + Issues one :class:`~solarfarmer.models.RackOrientationWarning` listing any + racks whose front face points below the horizon. + Attributes ---------- racks : list[Rack] @@ -14,3 +17,9 @@ class Racks(SolarFarmerBaseModel): """ racks: list[Rack] = Field(default_factory=list) + + @model_validator(mode="after") + def _check_rack_orientation(self) -> "Racks": + """Warn once about racks whose front face points below the horizon.""" + _warn_on_reversed_racks(self.racks) + return self diff --git a/tests/test_models/test_validation.py b/tests/test_models/test_validation.py index 2551da8..5dbc807 100644 --- a/tests/test_models/test_validation.py +++ b/tests/test_models/test_validation.py @@ -15,9 +15,11 @@ MountingTypeSpecification, OndFileSupplements, PanFileSupplements, + PVPlant, QuadDouble, Rack, RackOrientationWarning, + Racks, TrackerCondition, TrackerSystem, TransformerLossModelTypes, @@ -548,38 +550,61 @@ def test_collinear_corners_have_no_normal(self) -> None: _ = quad.front_normal +def _rack(rack_id: int, corners) -> Rack: + return Rack(id=rack_id, mounting_type_id="m1", quad=_quad(*corners)) + + class TestRackOrientation: def test_documented_order_does_not_warn(self) -> None: with warnings.catch_warnings(): warnings.simplefilter("error", RackOrientationWarning) - Rack(id=0, mounting_type_id="m1", quad=_quad(*SOUTH_FACING)) + Racks(racks=[_rack(0, SOUTH_FACING)]) - def test_reversed_order_warns(self) -> None: + def test_single_rack_is_checked_by_its_collection(self) -> None: + """Racks are checked per collection, so a large layout gives one warning, not one per rack.""" + with warnings.catch_warnings(): + warnings.simplefilter("error", RackOrientationWarning) + rack = _rack(0, SOUTH_FACING_REVERSED) + with pytest.warns(RackOrientationWarning): + Racks(racks=[rack]) + + def test_many_reversed_racks_give_one_warning(self) -> None: + racks = [_rack(i, SOUTH_FACING_REVERSED) for i in range(25)] with pytest.warns(RackOrientationWarning, match="reverse order") as record: - Rack(id=7, mounting_type_id="m1", quad=_quad(*SOUTH_FACING_REVERSED)) - assert "Rack 7" in str(record[0].message) + Racks(racks=racks) + assert len(record) == 1 + message = str(record[0].message) + assert "25 of 25 racks (IDs 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and 15 more)" in message assert record[0].filename == __file__ # points at the caller, not pydantic + def test_plant_lists_only_reversed_racks(self) -> None: + racks = [_rack(0, SOUTH_FACING), _rack(7, SOUTH_FACING_REVERSED)] + with pytest.warns(RackOrientationWarning) as record: + PVPlant(transformers=[], mounting_type_specifications={}, racks=racks) + assert len(record) == 1 + assert "1 of 2 racks (IDs 7)" in str(record[0].message) + assert record[0].filename == __file__ + def test_reversed_order_warns_when_loaded_from_json(self) -> None: corners = { f"p{i}": dict(zip("xyz", c, strict=True)) for i, c in enumerate(SOUTH_FACING_REVERSED, 1) } - payload = json.dumps({"id": 0, "mountingTypeID": "m1", "quad": corners}) + payload = json.dumps({"racks": [{"id": 0, "mountingTypeID": "m1", "quad": corners}]}) with pytest.warns(RackOrientationWarning): - Rack.model_validate_json(payload) + Racks.model_validate_json(payload) def test_vertical_rack_does_not_warn(self) -> None: """A vertical (e.g. bifacial fence) rack faces the horizon, not below it.""" quad = _quad((0.0, 0.0, 0.0), (0.0, 0.0, 2.0), (10.0, 0.0, 2.0), (10.0, 0.0, 0.0)) with warnings.catch_warnings(): warnings.simplefilter("error", RackOrientationWarning) - rack = Rack(id=0, mounting_type_id="m1", quad=quad) - assert rack.quad.tilt == pytest.approx(90.0) - assert rack.quad.azimuth == pytest.approx(180.0) + Racks(racks=[Rack(id=0, mounting_type_id="m1", quad=quad)]) + assert quad.tilt == pytest.approx(90.0) + assert quad.azimuth == pytest.approx(180.0) def test_zero_area_quad_warns(self) -> None: - quad = _quad((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (2.0, 0.0, 0.0), (3.0, 0.0, 0.0)) + corners = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (2.0, 0.0, 0.0), (3.0, 0.0, 0.0)) with pytest.warns(RackOrientationWarning, match="no area"): - Rack(id=0, mounting_type_id="m1", quad=quad) + Racks(racks=[_rack(3, corners)]) From ea3a6cead8ae1070a15ec64ace2170eab883a879 Mon Sep 17 00:00:00 2001 From: Will Holmgren Date: Fri, 20 Nov 2026 06:40:17 -0700 Subject: [PATCH 3/5] Document module positions on a rack and add live 2D/3D parity tests Review on #59 asked for the 2D/3D parity check from #58's acceptance criteria and for the multi-module documentation the PR left out. - QuadDouble and ModuleIndexRange document where modules sit on a rack: index x counts along the row from the P1 end, y counts rows up the slope from the P1-P4 edge, and frame widths and spacing set each module's position. A descending range covers the same modules. The docs note that the SDK does not check the quad's size against the mounting type. - tests/test_rack_3d_parity.py (integration, skipped without SF_API_KEY) builds small plants from the Bern sample's weather, PAN and OND files: two-row south-facing racks and mixed-orientation racks must match the equivalent 2D layout within 0.1% with no near shading, and a wall in front of one end must show that index 0 is the module at P1. Results on API 7.0.15: the largest 2D/3D difference was 0.00076%, and the string at the P1 end behind the wall produced 1/9 of the same string at the other end. Every single-rack 3D plant we tried ended with status Failed and no reason, so each test plant has two racks. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 + solarfarmer/models/module_index_range.py | 9 +- solarfarmer/models/quad_double.py | 25 ++ solarfarmer/models/rack.py | 3 +- tests/test_rack_3d_parity.py | 364 +++++++++++++++++++++++ 5 files changed, 400 insertions(+), 4 deletions(-) create mode 100644 tests/test_rack_3d_parity.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e4b05d..d0be688 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 the slope and P1→P4 along the row (SW-low, NW-high, NE-high, SE-low for a south-facing rack), with x east, y north and z up. The rack fixtures in `tests/test_models/test_composition.py` used the reverse order and have been corrected. +- `QuadDouble` and `ModuleIndexRange` now document where modules sit on a rack: index `x` counts along + the row from the P1 end, `y` counts rows up the slope, and the frame widths and module spacing set + each module's position. A range with `start_x > end_x` covers the same modules as the ascending one. - `__released__` now reports the release date of installed wheels instead of `"unreleased"` or the tag date of whichever git repository the user's working directory belonged to. It is also exposed at the package top level, like `solarfarmer.__version__`; previously `import solarfarmer as sf; sf.__released__` diff --git a/solarfarmer/models/module_index_range.py b/solarfarmer/models/module_index_range.py index 42de6ee..129efa5 100644 --- a/solarfarmer/models/module_index_range.py +++ b/solarfarmer/models/module_index_range.py @@ -17,13 +17,16 @@ class ModuleIndexRange(SolarFarmerBaseModel): an ``id`` in ``PVPlant.racks`` or ``PVPlant.trackers`` start_x : int First index (inclusive) of this range of modules along the length of - a row on the mount. May be larger than ``end_x`` when the string runs - in the reverse direction along the rack + a row on the mount. On a rack, index 0 is the module at the ``P1`` + end; see :class:`~solarfarmer.models.QuadDouble`. May be larger than + ``end_x``: the range then covers the same modules, wired in the + opposite direction along the row end_x : int Last index (inclusive) of this range of modules along the length of a row on the mount. May be smaller than ``start_x`` y : int - Row index on the mount where the range is located (0 = bottom edge) + Row index on the mount where the range is located, counting up the + slope from 0 at the bottom edge (on a rack, the ``P1``-``P4`` edge) """ mounting_id: int = Field(..., alias="mountingID", ge=0) diff --git a/solarfarmer/models/quad_double.py b/solarfarmer/models/quad_double.py index 8a1e163..c88eba8 100644 --- a/solarfarmer/models/quad_double.py +++ b/solarfarmer/models/quad_double.py @@ -35,6 +35,31 @@ class QuadDouble(SolarFarmerBaseModel): :class:`~solarfarmer.models.Racks` warn about racks whose front face points below the horizon. + Modules sit on the quad in the grid set by the rack's + :class:`~solarfarmer.models.MountingTypeSpecification`: + ``number_of_modules_long`` positions along the row and + ``number_of_modules_high`` rows up the slope. + :class:`~solarfarmer.models.ModuleIndexRange` addresses them by ``x``, + counting along the row from the ``P1`` end, and ``y``, counting rows up the + slope from the ``P1``-``P4`` edge. For a rack 3 modules long and 2 high:: + + P2 +----------+----------+----------+ P3 + | (0, 1) | (1, 1) | (2, 1) | + +----------+----------+----------+ + | (0, 0) | (1, 0) | (2, 0) | + P1 +----------+----------+----------+ P4 + + Module ``(0, 0)`` is at the ``P1`` corner, inset by ``frame_end_width`` + along the row and ``frame_bottom_width`` up the slope. Each step in ``x`` + moves ``x_spacing_between_modules`` along the row, and each step in ``y`` + moves ``y_spacing_between_modules`` up the slope. ``modules_are_landscape`` + decides which side of the module lies along the row. + + The corner order says nothing about the quad's size, and the SDK does not + check it. To hold its modules, the quad should be ``2 * frame_end_width + + (number_of_modules_long - 1) * x_spacing_between_modules`` plus one module + side wide, and ``rack_height`` deep. + Attributes ---------- p1 : Vector3Double diff --git a/solarfarmer/models/rack.py b/solarfarmer/models/rack.py index c548c3a..8a27726 100644 --- a/solarfarmer/models/rack.py +++ b/solarfarmer/models/rack.py @@ -21,7 +21,8 @@ class Rack(SolarFarmerBaseModel): geometry is described by a quadrilateral (``quad``) in world coordinates. The order of the ``quad`` corners determines which face is the front of - the modules; see :class:`~solarfarmer.models.QuadDouble`. + the modules, and which end holds module index 0; see + :class:`~solarfarmer.models.QuadDouble`. :class:`~solarfarmer.models.PVPlant` and :class:`~solarfarmer.models.Racks` check all of their racks and issue one :class:`RackOrientationWarning` listing any whose front face points below the horizon, which almost always diff --git a/tests/test_rack_3d_parity.py b/tests/test_rack_3d_parity.py new file mode 100644 index 0000000..372e1fe --- /dev/null +++ b/tests/test_rack_3d_parity.py @@ -0,0 +1,364 @@ +"""Live checks that 3D racks are read the way QuadDouble and ModuleIndexRange document. + +Each test runs small, unshaded or deliberately shaded plants on the SolarFarmer API. They reuse +the Bern sample's weather, PAN and OND files but build their own payloads, so the 2D and 3D runs +differ only in how the geometry is described: same equipment, electrical layout and losses. + +A rack whose corners are in the reverse order passes validation and completes normally, but the +engine then treats the back of the modules as the front (about 15% of the expected energy in an +unshaded control). A serialization test cannot catch that; only a calculation can. + +Every plant here has at least two racks. In our runs (API 7.0.15), each of the four single-rack 3D +plants we tried (different wiring, with and without a shading object) ended with runtime status +"Failed" and no reason given, while the same racks in two-rack plants completed. +""" + +import functools +import math +from pathlib import Path + +import pytest + +import solarfarmer as sf +from solarfarmer.models import ( + IndexedObject3D, + InverterInput, + MiniSimpleTerrainDto, + ModuleIndexRange, + ModuleString, + QuadDouble, + Rack, + SimpleTerrain, + TerrainRowDto, + TerrainRowStartEndColumnsDto, + Vector3Double, +) + +pytestmark = pytest.mark.integration + +BERN = Path(__file__).parent.parent / "docs" / "notebooks" / "sample_data" / "Inputs_Bern_2D_racks" +MODULE = "CanadianSolar_CS6U-330M_APP" # 0.992 m x 1.960 m, Vmp 37.5 V, monofacial +INVERTER = "Sungrow_SG125HV_APP" # MPPT window 860-1450 V +STRING_LENGTH = 30 # 30 x 37.5 V = 1125 V +DEAD_STRING_LENGTH = 18 # Voc 18 x 45.9 V = 826 V, below the MPPT window: produces almost nothing +MODULE_WIDTH = 0.992 +MODULE_LENGTH = 1.960 +LOW_EDGE_HEIGHT = 1.0 + +# Tolerances for unshaded racks, 3D against the equivalent 2D layout. In our runs (API 7.0.15) +# the largest difference was 0.00076% (annual AC energy, mixed orientations) and near shading +# was at most 0.000003. A reversed rack is off by about 85%, so 0.1% leaves room for numerical +# changes in the engine while still catching that. +ENERGY_TOLERANCE = 0.001 # relative, for both effective irradiation and annual AC energy +MAX_NEAR_SHADING = 0.001 # absolute annual near-shading irradiance effect + + +def _vec(p): + return Vector3Double(x=p[0], y=p[1], z=p[2]) + + +def _rack_quad(p1, azimuth, tilt, width, depth): + """Corners for a rack facing ``azimuth`` (clockwise from north) at ``tilt``. + + P1 is the low corner, P1->P4 runs along the row and P1->P2 runs up the slope, so the front + face points toward ``azimuth``. + """ + a, t = math.radians(azimuth), math.radians(tilt) + along = (-math.cos(a), math.sin(a), 0.0) + up = (-math.sin(a) * math.cos(t), -math.cos(a) * math.cos(t), math.sin(t)) + p2 = [c + depth * u for c, u in zip(p1, up, strict=True)] + p4 = [c + width * v for c, v in zip(p1, along, strict=True)] + p3 = [c + depth * u for c, u in zip(p4, up, strict=True)] + # Round away floating-point noise such as sin(180°) = 1.2e-16, for readable payloads. + p1, p2, p3, p4 = ([round(c, 9) + 0.0 for c in p] for p in (p1, p2, p3, p4)) + quad = QuadDouble(p1=_vec(p1), p2=_vec(p2), p3=_vec(p3), p4=_vec(p4)) + assert quad.tilt == pytest.approx(tilt) + assert quad.azimuth == pytest.approx(azimuth % 360) + return quad + + +def _mounting(tilt, modules_long, modules_high=1): + """Portrait modules with no frame or gaps, so the quad is exactly modules_long x modules_high.""" + return sf.MountingTypeSpecification( + is_tracker=False, + number_of_modules_high=modules_high, + number_of_modules_long=modules_long, + modules_are_landscape=False, + rack_height=modules_high * MODULE_LENGTH, + y_spacing_between_modules=MODULE_LENGTH, + x_spacing_between_modules=MODULE_WIDTH, + frame_bottom_width=0.0, + frame_top_width=0.0, + frame_end_width=0.0, + tilt=tilt, + height_of_lowest_edge_from_ground=LOW_EDGE_HEIGHT, + constant_heat_transfer_coefficient=29.0, + convective_heat_transfer_coefficient=0.0, + monthly_soiling_loss=[0.0] * 12, + ) + + +def _flat_terrain(points, margin=100.0): + """A flat ground plane at z = 0: a 2 x 2 vertex grid, which is one terrain cell.""" + xs, ys = [p[0] for p in points], [p[1] for p in points] + x0, x1 = min(xs) - margin, max(xs) + margin + y0, y1 = min(ys) - margin, max(ys) + margin + return SimpleTerrain( + mini_simple_terrains=[ + MiniSimpleTerrainDto( + num_vertices_across=2, + num_vertices_down=2, + vertices=[_vec((x, y, 0.0)) for y in (y0, y1) for x in (x0, x1)], + terrain_rows=[ + TerrainRowDto( + start_end_columns=[ + TerrainRowStartEndColumnsDto(start_column_index=0, end_column_index=0) + ] + ) + ], + ) + ] + ) + + +def _box(name, x0, x1, y0, y1, height): + """A closed box standing on the ground, as a shading object.""" + footprint = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)] # anticlockwise from above + n = len(footprint) + vertices = [_vec((x, y, z)) for z in (0.0, height) for x, y in footprint] + sides = [[i, (i + 1) % n, (i + 1) % n + n, i + n] for i in range(n)] + caps = [[0, 2, 1], [0, 3, 2], [n, n + 1, n + 2], [n, n + 2, n + 3]] + return IndexedObject3D(name=name, vertices=vertices, quad_indices=sides, triangle_indices=caps) + + +@functools.cache +def _bern(): + return sf.EnergyCalculationInputs.model_validate_json( + (BERN / "EnergyCalcInputs.json").read_text() + ) + + +def _inputs(pv_plant): + """Bern's location, albedo, options and PAN supplements around ``pv_plant``.""" + base = _bern() + options = base.energy_calculation_options.model_copy( + update={ + "return_pv_syst_format_time_series_results": False, + "return_detailed_time_series_results": False, + "return_loss_tree_time_series_results": False, + } + ) + return base.model_copy(update={"pv_plant": pv_plant, "energy_calculation_options": options}) + + +def _plant(inverters, mounting_types, **geometry): + """Bern's transformer around ``inverters``, plus any 3D geometry.""" + base = _bern() + transformer = base.pv_plant.transformers[0].model_copy(update={"inverters": inverters}) + return sf.PVPlant( + transformers=[transformer], + transformer_specifications=base.pv_plant.transformer_specifications, + mounting_type_specifications=mounting_types, + **geometry, + ) + + +def _inverter_2d(name, mounting_id, azimuth, strings=1): + return sf.Inverter( + name=name, + inverter_spec_id=INVERTER, + inverter_count=1, + ac_wiring_ohmic_loss=0.0, + layouts=[ + sf.Layout( + layout_count=1, + module_specification_id=MODULE, + mounting_type_id=mounting_id, + is_trackers=False, + azimuth=azimuth, + pitch=10.0, + total_number_of_strings=strings, + string_length=STRING_LENGTH, + inverter_input=[0], + number_of_strings_in_isolated_row=strings, + dc_ohmic_connector_loss=0.0, + module_mismatch_loss=0.0, + ) + ], + ) + + +def _inverter_3d(name, strings): + """One inverter input; ``strings`` is a list of strings, each a list of ModuleIndexRange.""" + return sf.Inverter( + name=name, + inverter_spec_id=INVERTER, + inverter_count=1, + ac_wiring_ohmic_loss=0.0, + inverter_inputs=[ + InverterInput( + module_specification_id=MODULE, + module_strings=[ModuleString(module_index_ranges=r) for r in strings], + dc_ohmic_connector_loss=0.0, + module_mismatch_loss=0.0, + ) + ], + ) + + +def _annual(inputs, api_key, label): + result = sf.run_energy_calculation( + plant_builder=inputs, + meteorological_data_file_path=str(BERN / "Bern-hour.dat"), + pan_file_paths=[str(BERN / f"{MODULE}.PAN")], + ond_file_paths=[str(BERN / f"{INVERTER}.OND")], + project_id=f"test_sdk_rack_parity_{label}", + print_summary=False, + save_outputs=False, + api_key=api_key, + ) + assert result is not None + annual = result.AnnualData[0] + energy = annual["energyYieldResults"] + effects = annual["annualEffects"] + summary = { + "effective_irradiation": energy["globalEffectiveIrradiance"], + "net_energy": energy["netEnergy"], + "near_shading": effects["nearShadingIrradiance"], + } + print(f"{label}: {summary}") + return summary + + +def _assert_parity(result_3d, result_2d): + assert result_3d["effective_irradiation"] == pytest.approx( + result_2d["effective_irradiation"], rel=ENERGY_TOLERANCE + ) + assert result_3d["net_energy"] == pytest.approx(result_2d["net_energy"], rel=ENERGY_TOLERANCE) + assert abs(result_3d["near_shading"]) <= MAX_NEAR_SHADING + + +def test_two_row_racks_match_2d(api_key): + """Two identical south-facing racks of two portrait rows, one string per row. + + The wiring follows the ModelChainAsync documentation example: each string is one row, and + the first runs from the last index back to 0. The racks are 200 m apart, each on its own + inverter. + """ + tilt, azimuth, long, high = 30.0, 180.0, STRING_LENGTH, 2 + mounting = {"rack": _mounting(tilt, long, high)} + + plant_2d = _plant( + [_inverter_2d(f"2D {i}", "rack", azimuth, strings=high) for i in range(2)], mounting + ) + + racks, inverters, corners = [], [], [] + for rack_id, x in enumerate((0.0, 200.0)): + quad = _rack_quad( + (x, 0.0, LOW_EDGE_HEIGHT), azimuth, tilt, long * MODULE_WIDTH, high * MODULE_LENGTH + ) + racks.append(Rack(id=rack_id, mounting_type_id="rack", quad=quad)) + corners += [(p.x, p.y) for p in (quad.p1, quad.p2, quad.p3, quad.p4)] + strings = [ + [ModuleIndexRange(mounting_id=rack_id, start_x=long - 1, end_x=0, y=0)], + [ModuleIndexRange(mounting_id=rack_id, start_x=0, end_x=long - 1, y=1)], + ] + inverters.append(_inverter_3d(f"3D {rack_id}", strings)) + plant_3d = _plant(inverters, mounting, racks=racks, simple_terrain=_flat_terrain(corners)) + + _assert_parity( + _annual(_inputs(plant_3d), api_key, "two_row_3d"), + _annual(_inputs(plant_2d), api_key, "two_row_2d"), + ) + + +def test_mixed_orientation_racks_match_2d(api_key): + """Two racks with different azimuth and tilt, one inverter each, far enough apart not to shade.""" + orientations = {"east": (90.0, 20.0, (0.0, 0.0)), "west_southwest": (250.0, 35.0, (200.0, 0.0))} + mounting = {name: _mounting(tilt, STRING_LENGTH) for name, (_, tilt, _) in orientations.items()} + + plant_2d = _plant( + [_inverter_2d(name, name, azimuth) for name, (azimuth, _, _) in orientations.items()], + mounting, + ) + + racks, inverters, corners = [], [], [] + for rack_id, (name, (azimuth, tilt, (x, y))) in enumerate(orientations.items()): + quad = _rack_quad( + (x, y, LOW_EDGE_HEIGHT), azimuth, tilt, STRING_LENGTH * MODULE_WIDTH, MODULE_LENGTH + ) + racks.append(Rack(id=rack_id, mounting_type_id=name, quad=quad)) + corners += [(p.x, p.y) for p in (quad.p1, quad.p2, quad.p3, quad.p4)] + inverters.append( + _inverter_3d( + name, + [[ModuleIndexRange(mounting_id=rack_id, start_x=0, end_x=STRING_LENGTH - 1, y=0)]], + ) + ) + plant_3d = _plant(inverters, mounting, racks=racks, simple_terrain=_flat_terrain(corners)) + + _assert_parity( + _annual(_inputs(plant_3d), api_key, "mixed_3d"), + _annual(_inputs(plant_2d), api_key, "mixed_2d"), + ) + + +def test_module_index_x_starts_at_p1(api_key): + """Index x = 0 is the module at the P1 end of the rack. + + Energy parity cannot catch an indexing error, because every module on an unshaded rack sees + the same irradiance. Here a wall shades the P1 (west) end of a south-facing rack of 48 + modules. The rack is fully wired: a 30-module string feeds one inverter, and the other 18 + modules feed a second inverter whose voltage stays below the MPPT window, so they produce + almost nothing. A second, unshaded rack far away holds one more such string. The plant's + energy is therefore the 30-module string's energy. With x = 0 at P1, that string is behind + the wall when it starts at index 0, and in the open when it starts at index 18. + """ + tilt, azimuth = 30.0, 180.0 + long = STRING_LENGTH + DEAD_STRING_LENGTH + mounting = {"rack": _mounting(tilt, long), "spare": _mounting(tilt, DEAD_STRING_LENGTH)} + quad = _rack_quad( + (0.0, 0.0, LOW_EDGE_HEIGHT), azimuth, tilt, long * MODULE_WIDTH, MODULE_LENGTH + ) + assert quad.p4.x > quad.p1.x # P1 is the west end + spare = _rack_quad( + (200.0, 0.0, LOW_EDGE_HEIGHT), + azimuth, + tilt, + DEAD_STRING_LENGTH * MODULE_WIDTH, + MODULE_LENGTH, + ) + racks = [ + Rack(id=0, mounting_type_id="rack", quad=quad), + Rack(id=1, mounting_type_id="spare", quad=spare), + ] + # In front of module positions 1-16 from the P1 end, 2 m south of the rack and 8 m tall. + wall = _box("wall", MODULE_WIDTH, (DEAD_STRING_LENGTH - 1) * MODULE_WIDTH, -2.5, -2.0, 8.0) + terrain = _flat_terrain([(p.x, p.y) for q in (quad, spare) for p in (q.p1, q.p2, q.p3, q.p4)]) + + def run(live_start, dead_start, label): + live = [ + ModuleIndexRange( + mounting_id=0, start_x=live_start, end_x=live_start + STRING_LENGTH - 1, y=0 + ) + ] + dead = [ + ModuleIndexRange( + mounting_id=0, start_x=dead_start, end_x=dead_start + DEAD_STRING_LENGTH - 1, y=0 + ) + ] + dead_spare = [ModuleIndexRange(mounting_id=1, start_x=0, end_x=DEAD_STRING_LENGTH - 1, y=0)] + plant = _plant( + [_inverter_3d("live", [live]), _inverter_3d("dead", [dead, dead_spare])], + mounting, + racks=racks, + shading_objects=[wall], + simple_terrain=terrain, + ) + return _annual(_inputs(plant), api_key, label) + + live_at_p1_end = run(0, STRING_LENGTH, "index_live_at_p1_end") + live_at_p4_end = run(DEAD_STRING_LENGTH, 0, "index_live_at_p4_end") + + # In our runs (API 7.0.15) the string in the open produced 9.1 times as much. + assert live_at_p4_end["net_energy"] > 3 * live_at_p1_end["net_energy"] From 1b74cb84b1b1ccbe3f5c9e95dc804fbe2b74b5c9 Mon Sep 17 00:00:00 2001 From: Will Holmgren Date: Fri, 20 Nov 2026 08:04:44 -0700 Subject: [PATCH 4/5] Address review: one orientation warning, stricter live checks, docs link - Reversed and zero-area racks now share a single RackOrientationWarning instead of one each, matching the documented "one warning". - ModuleIndexRange no longer claims that a descending range is wired in the opposite direction; either endpoint order covers the same inclusive module positions. - The live tests' _annual helper rejects non-finite or non-positive effective irradiation and net energy, so two zero-production results can no longer pass the relative comparisons. - The documentation-example geometry test links the ModelChainAsync "Racks and Trackers" section and notes that its "anti-clockwise" wording holds only when seen from below. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 +++--- solarfarmer/models/module_index_range.py | 4 ++-- solarfarmer/models/rack.py | 17 ++++++++--------- tests/test_models/test_validation.py | 20 +++++++++++++++++++- tests/test_rack_3d_parity.py | 6 ++++++ 5 files changed, 38 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d0be688..7c0b719 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,9 +12,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `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 - below the horizon. This almost always means the corners are in the reverse order, which passes - validation but gives badly wrong energy. The check is one pass over all racks, so large layouts - stay fast and get a single warning rather than one per rack. + below the horizon, or whose quad has no area. A rack facing below the horizon almost always has its + corners in the reverse order, which passes validation but gives badly wrong energy. The check is one + pass over all racks, so large layouts stay fast and get a single warning rather than one per rack. ### Fixed diff --git a/solarfarmer/models/module_index_range.py b/solarfarmer/models/module_index_range.py index 129efa5..649f10c 100644 --- a/solarfarmer/models/module_index_range.py +++ b/solarfarmer/models/module_index_range.py @@ -19,8 +19,8 @@ class ModuleIndexRange(SolarFarmerBaseModel): First index (inclusive) of this range of modules along the length of a row on the mount. On a rack, index 0 is the module at the ``P1`` end; see :class:`~solarfarmer.models.QuadDouble`. May be larger than - ``end_x``: the range then covers the same modules, wired in the - opposite direction along the row + ``end_x``; either endpoint order covers the same inclusive module + positions end_x : int Last index (inclusive) of this range of modules along the length of a row on the mount. May be smaller than ``start_x`` diff --git a/solarfarmer/models/rack.py b/solarfarmer/models/rack.py index 8a27726..fe0de93 100644 --- a/solarfarmer/models/rack.py +++ b/solarfarmer/models/rack.py @@ -79,19 +79,18 @@ def describe(rack_ids: list[int]) -> str: listed += f" and {more} more" if more > 0 else "" return f"{len(rack_ids)} of {len(racks)} racks (IDs {listed})" - # warn -> this function -> model validator -> pydantic entry point -> caller + problems = [] if facing_down: - warnings.warn( + problems.append( f"{describe(facing_down)} have a front face pointing below the horizon, so the " "calculation would treat the back of their modules as the front. Their corners " "are probably in the reverse order; for a south-facing rack use P1 SW-low, " - "P2 NW-high, P3 NE-high, P4 SE-low. QuadDouble.tilt shows how a rack is read.", - RackOrientationWarning, - stacklevel=4, + "P2 NW-high, P3 NE-high, P4 SE-low. QuadDouble.tilt shows how a rack is read." ) if no_area: - warnings.warn( - f"{describe(no_area)} have a quad with no area: corners P1, P2 and P4 are collinear.", - RackOrientationWarning, - stacklevel=4, + problems.append( + f"{describe(no_area)} have a quad with no area: corners P1, P2 and P4 are collinear." ) + if problems: + # warn -> this function -> model validator -> pydantic entry point -> caller + warnings.warn(" ".join(problems), RackOrientationWarning, stacklevel=4) diff --git a/tests/test_models/test_validation.py b/tests/test_models/test_validation.py index 5dbc807..963b1ee 100644 --- a/tests/test_models/test_validation.py +++ b/tests/test_models/test_validation.py @@ -517,7 +517,15 @@ def test_south_facing_rack(self) -> None: assert quad.azimuth == pytest.approx(180.0) def test_modelchainasync_documentation_example(self) -> None: - """The rack in the web API's ModelChainAsync example faces south at about 34 degrees.""" + """The rack in the web API's ModelChainAsync example faces south at about 34 degrees. + + The example is in the "Racks and Trackers" section of the ModelChainAsync documentation: + https://mysoftware.dnv.com/download/public/renewables/solarfarmer/manuals/latest/WebApi/Endpoints/ModelChainAsyncEndpoint.html#racksxrefsolarfarmerapiclientpvplantsolarfarmerapiclientpvplantracks-and-trackersxrefsolarfarmerapiclientpvplantsolarfarmerapiclientpvplanttrackers + + Its corners are in the order documented on QuadDouble (SW-low, NW-high, NE-high, + SE-low). That page calls the order "anti-clockwise around the rack", which holds only + when seen from below; seen from above or from the front of the modules it is clockwise. + """ quad = _quad( (633616.55525403516, 4502376.1064225091, 308.44455607951465), (633616.60684414359, 4502378.5736383246, 310.10791430261804), @@ -608,3 +616,13 @@ def test_zero_area_quad_warns(self) -> None: corners = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (2.0, 0.0, 0.0), (3.0, 0.0, 0.0)) with pytest.warns(RackOrientationWarning, match="no area"): Racks(racks=[_rack(3, corners)]) + + def test_reversed_and_zero_area_racks_give_one_warning(self) -> None: + collinear = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (2.0, 0.0, 0.0), (3.0, 0.0, 0.0)) + racks = [_rack(0, SOUTH_FACING_REVERSED), _rack(1, collinear), _rack(2, SOUTH_FACING)] + with pytest.warns(RackOrientationWarning) as record: + Racks(racks=racks) + assert len(record) == 1 + message = str(record[0].message) + assert "1 of 3 racks (IDs 0) have a front face pointing below the horizon" in message + assert "1 of 3 racks (IDs 1) have a quad with no area" in message diff --git a/tests/test_rack_3d_parity.py b/tests/test_rack_3d_parity.py index 372e1fe..d109b5f 100644 --- a/tests/test_rack_3d_parity.py +++ b/tests/test_rack_3d_parity.py @@ -227,6 +227,12 @@ def _annual(inputs, api_key, label): "near_shading": effects["nearShadingIrradiance"], } print(f"{label}: {summary}") + # Reject non-producing or invalid results, which the relative comparisons would accept. + for key in ("effective_irradiation", "net_energy"): + assert math.isfinite(summary[key]) and summary[key] > 0, f"{label}: {key} = {summary[key]}" + assert math.isfinite(summary["near_shading"]), ( + f"{label}: near_shading = {summary['near_shading']}" + ) return summary From f63ff5adf938ce12ae3b1111c9ef00a4c9be41c1 Mon Sep 17 00:00:00 2001 From: Will Holmgren Date: Fri, 20 Nov 2026 08:57:30 -0700 Subject: [PATCH 5/5] Place the live tests' racks closer together The racks were 200 m apart, which made the scenes mostly empty ground. Two-row racks and the indexing test's spare rack now stand in one row 20 m apart (RACK_GAP), and the mixed-orientation racks' nearest corners are 40 m apart. A neighbour can then shade a rack only with the sun within about 6 degrees of the horizon in the east or west. Rerun on API 7.0.15: the two-row and indexing results are unchanged to the printed precision; the mixed-orientation 3D/2D energy difference went from 0.00076% to 0.0034%, and its near shading from 0.000003 to 0.00003, well inside the 0.1% and 0.001 tolerances. Co-Authored-By: Claude Opus 5.5 --- tests/test_rack_3d_parity.py | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/tests/test_rack_3d_parity.py b/tests/test_rack_3d_parity.py index d109b5f..1067071 100644 --- a/tests/test_rack_3d_parity.py +++ b/tests/test_rack_3d_parity.py @@ -44,10 +44,14 @@ MODULE_WIDTH = 0.992 MODULE_LENGTH = 1.960 LOW_EDGE_HEIGHT = 1.0 +# Racks in one row are this far apart, end to end. A neighbour can then shade a rack only with +# the sun within about 6 degrees of the horizon in the east or west, mostly behind these +# south-facing modules. +RACK_GAP = 20.0 # Tolerances for unshaded racks, 3D against the equivalent 2D layout. In our runs (API 7.0.15) -# the largest difference was 0.00076% (annual AC energy, mixed orientations) and near shading -# was at most 0.000003. A reversed rack is off by about 85%, so 0.1% leaves room for numerical +# the largest difference was 0.0034% (annual AC energy, mixed orientations) and near shading +# was at most 0.00003. A reversed rack is off by about 85%, so 0.1% leaves room for numerical # changes in the engine while still catching that. ENERGY_TOLERANCE = 0.001 # relative, for both effective irradiation and annual AC energy MAX_NEAR_SHADING = 0.001 # absolute annual near-shading irradiance effect @@ -248,8 +252,8 @@ def test_two_row_racks_match_2d(api_key): """Two identical south-facing racks of two portrait rows, one string per row. The wiring follows the ModelChainAsync documentation example: each string is one row, and - the first runs from the last index back to 0. The racks are 200 m apart, each on its own - inverter. + the first runs from the last index back to 0. The racks stand in one row, RACK_GAP apart, + each on its own inverter. """ tilt, azimuth, long, high = 30.0, 180.0, STRING_LENGTH, 2 mounting = {"rack": _mounting(tilt, long, high)} @@ -259,7 +263,7 @@ def test_two_row_racks_match_2d(api_key): ) racks, inverters, corners = [], [], [] - for rack_id, x in enumerate((0.0, 200.0)): + for rack_id, x in enumerate((0.0, long * MODULE_WIDTH + RACK_GAP)): quad = _rack_quad( (x, 0.0, LOW_EDGE_HEIGHT), azimuth, tilt, long * MODULE_WIDTH, high * MODULE_LENGTH ) @@ -279,8 +283,12 @@ def test_two_row_racks_match_2d(api_key): def test_mixed_orientation_racks_match_2d(api_key): - """Two racks with different azimuth and tilt, one inverter each, far enough apart not to shade.""" - orientations = {"east": (90.0, 20.0, (0.0, 0.0)), "west_southwest": (250.0, 35.0, (200.0, 0.0))} + """Two racks with different azimuth and tilt, one inverter each. + + Their nearest corners are 40 m apart, so either can shade the other only with the sun within + about 2 degrees of the horizon. + """ + orientations = {"east": (90.0, 20.0, (0.0, 0.0)), "west_southwest": (250.0, 35.0, (40.0, 0.0))} mounting = {name: _mounting(tilt, STRING_LENGTH) for name, (_, tilt, _) in orientations.items()} plant_2d = _plant( @@ -316,7 +324,7 @@ def test_module_index_x_starts_at_p1(api_key): the same irradiance. Here a wall shades the P1 (west) end of a south-facing rack of 48 modules. The rack is fully wired: a 30-module string feeds one inverter, and the other 18 modules feed a second inverter whose voltage stays below the MPPT window, so they produce - almost nothing. A second, unshaded rack far away holds one more such string. The plant's + almost nothing. A second rack, RACK_GAP east along the row, holds one more such string. The plant's energy is therefore the 30-module string's energy. With x = 0 at P1, that string is behind the wall when it starts at index 0, and in the open when it starts at index 18. """ @@ -328,7 +336,7 @@ def test_module_index_x_starts_at_p1(api_key): ) assert quad.p4.x > quad.p1.x # P1 is the west end spare = _rack_quad( - (200.0, 0.0, LOW_EDGE_HEIGHT), + (long * MODULE_WIDTH + RACK_GAP, 0.0, LOW_EDGE_HEIGHT), azimuth, tilt, DEAD_STRING_LENGTH * MODULE_WIDTH,