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
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,24 @@ 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.
- `PVPlant` and `Racks` issue one `RackOrientationWarning` listing any racks whose front face points
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

- 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.
- `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__`
Expand Down
2 changes: 2 additions & 0 deletions solarfarmer/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
PVSystem,
QuadDouble,
Rack,
RackOrientationWarning,
Racks,
ShadingObjects,
SimpleTerrain,
Expand Down Expand Up @@ -169,6 +170,7 @@
"PVSystem",
"QuadDouble",
"Rack",
"RackOrientationWarning",
"Racks",
"run_energy_calculation",
"service",
Expand Down
3 changes: 2 additions & 1 deletion solarfarmer/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -84,6 +84,7 @@
"PVSystem",
"QuadDouble",
"Rack",
"RackOrientationWarning",
"Racks",
"ShadingObjects",
"SimpleTerrain",
Expand Down
9 changes: 6 additions & 3 deletions solarfarmer/models/module_index_range.py
Original file line number Diff line number Diff line change
Expand Up @@ -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``; 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``
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)
Expand Down
12 changes: 10 additions & 2 deletions solarfarmer/models/pv_plant.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
114 changes: 108 additions & 6 deletions solarfarmer/models/quad_double.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,128 @@
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.PVPlant` and
: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
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
"""
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")
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

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)
63 changes: 62 additions & 1 deletion solarfarmer/models/rack.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
import math
import warnings

from pydantic import Field

from ._base import SolarFarmerBaseModel
from .quad_double import QuadDouble

_MAX_LISTED_RACK_IDS = 10


class RackOrientationWarning(UserWarning):
"""Warn when racks' corner order puts their front face below the horizon."""


class Rack(SolarFarmerBaseModel):
"""A fixed-tilt rack in a 3D plant layout.
Expand All @@ -11,6 +20,14 @@ 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, 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
means the corners are in the reverse order.

Attributes
----------
id : int
Expand All @@ -25,11 +42,55 @@ 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
mounting_type_id: str = Field(..., alias="mountingTypeID", min_length=1)
pitch_to_back: float | None = None
pitch_to_front: float | None = None
quad: QuadDouble


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})"

problems = []
if facing_down:
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."
)
if no_area:
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)
13 changes: 11 additions & 2 deletions solarfarmer/models/racks.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,25 @@
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]
The individual rack objects making up this collection
"""

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
Loading
Loading