Carving¶
The carving module implements the three geometric strategies used to remove voxels from the maximum buildable volume:
- Sun-ray carving (
carve_with_sun_rays): traces rays along actual sun vectors at specific dates/times. Used by thetime-basedmode. - Sky-patch carving (
carve_with_sky_patch_rays): traces rays toward Tregenza sky patches weighted by irradiance, heating benefit, daylight luminance, or radiative cooling potential. Used by theirradiance,benefit,daylight, andradiative_coolingmodes. - Plane carving (
carve_with_planes): removes voxels above a tilted cut plane at a fixed angle from each test surface. Used by thetilted_planemode.
All three take a voxel grid and surface sample points with normals. Sky-patch carving returns per-voxel weighted scores; sun-ray and plane carving return a carved grid and, on request, per-voxel hit counts. The preprocessing stage stores these as scores.npy (for time-based, the counts are converted to m²·h), and the thresholding stage turns them into a binary carving mask.
sun_ray_set and sky_patch_ray_set build the rays (and, for the sky patches, the patch and edge_taper weights) that the carvers trace, so the access evaluation below traces the same ones.
urbansolarcarver.carving
¶
UrbanSolarCarver: carving utilities¶
Purpose
Convert point/normal samples on analysis surfaces into ray sets, trace those through a voxelized envelope, and count or score the voxels they visit. Supports:
• Time-based solar carving (sun vectors from the EPW for specific datetimes): every visited voxel is removed. • Sky-patch-weighted carving (Tregenza patches + mode-specific weights): returns per-voxel scores; the threshold is applied later, in api_core/thresholding.py. • Tilted-plane daylight carving (single or per-octant plane angle): every voxel at or above a visited voxel in its column is removed; extra rays rotate the plane around convex turns of the test-surface outline.
Raytracing contract
Rays are traced by the fused DDA kernels of warp_kernels.py (launched from
ray_tracing.py), which visit every voxel a ray crosses exactly once and
accumulate counts or scores in place; without Warp the carvers raise
WarpBackendUnavailableError. The kernels count voxels that lie entirely
in front of the surface a ray starts from, plus the surface's skin voxels
(crossed by its plane) that are occupied and have nothing of the max
volume behind them. Occupied skin voxels with max volume behind them are
the surface's own skin: not counted, but raised to the value of the voxel
behind them once tracing is done (_follow_mass_behind_skin), so they
never outlast the mass behind them.
Context and terrain
With a blocking_mesh (context_geometry.build_blocking_mesh), the two ray
carvers drop every ray that hits the context or terrain right after the ray
set is built, before scoring and before the skin rule: that sun or sky is
lost whatever is built, so no voxel is blamed for it. With a
skin_occupancy (the max volume plus the cells inside the context and
below the ground), every carver's skin rule counts context and ground as
solid mass behind a skin voxel, as the max volume is.
Coordinate/scale conventions
grid_origin is the world-space min corner for grid index [0,0,0].
grid_extent is the physical cube size (meters). grid_resolution is D, the
number of voxels per side, so one voxel is grid_extent / D meters wide.
The tracers receive scale = grid_extent.
Determinism and batching
Given a fixed config, hit counts are deterministic. Float scores are summed
with atomic adds on the GPU, so the order of additions, and therefore the last
bits of a score, can differ between runs. Rays are processed in batches of
the ray_batch_size run option (0 = sized from free GPU memory) on the device of the
input voxel grid.
SkyPatchCarvingResult
¶
Bases: NamedTuple
Return type for :func:carve_with_sky_patch_rays.
ray_origins / ray_directions are None unless the carver was
called with return_rays=True: copying the full ray set to host
memory costs hundreds of MB at typical ray counts.
SunRaySet
¶
Bases: NamedTuple
Rays from the sample points toward the sun (:func:sun_ray_set).
SkyPatchRaySet
¶
Bases: NamedTuple
Rays and weights of the sky-patch modes (:func:sky_patch_ray_set).
sun_ray_set(device, sample_points, sample_normals, settings, datetimes)
¶
The rays of time-based carving: from each sample point toward the sun at each of datetimes that it faces, on device.
Uses epw_path, min_altitude, north_deg and time_basis
of settings. Returns None when no sun position is above
min_altitude.
sky_patch_ray_set(device, sample_points, sample_normals, settings, hoys, point_weights=None)
¶
The rays and weights of the sky-patch modes, on device.
One ray from each sample point toward every Tregenza patch on the
outward side of its normal; rays of points whose point_weights
(edge_taper) entry is 0 are dropped. The patch weights are those of
settings.mode over the hours hoys; in the modes whose incidence
is set (irradiance, benefit) each traced ray counts its patch weight times
cos θ to its surface's normal, which the kernels apply per ray or sub-ray.
With settings.rays_per_patch above 1, the kernels trace each ray as
that many jittered sub-rays (sub_rays), and a ray is kept for every
patch the surface faces in part, not only those whose centre it faces.
Raises:
| Type | Description |
|---|---|
ValueError
|
If point_weights does not have one entry per sample point. |
carve_with_sun_rays(voxel_grid, grid_origin, grid_extent, grid_resolution, sample_points, sample_normals, settings, datetimes, return_counts=False, return_rays=False, *, ray_batch_size, blocking_mesh=None, return_ray_drop=False, skin_occupancy=None)
¶
Time-based carving of a voxel grid with sun vectors for explicit datetimes.
This builds a classical solar envelope by tracing rays toward the sun positions computed from the EPW location for the given datetimes. No scoring, normalization, or thresholding is applied here: any voxel visited by any ray is removed from the returned grid.
Core procedure
1. Compute sun vectors for the provided datetimes from the EPW file and
drop those below settings.min_altitude.
2. For each surface sample point, build rays toward the sun directions
on the outward side of its normal (dot product > 0).
3. Trace each ray through the grid (exact Warp DDA when available),
counting hits per voxel and skipping voxels behind the source surface.
4. Remove every voxel visited by at least one ray.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
voxel_grid
|
(Tensor, shape(X, Y, Z))
|
Input occupancy grid on CPU or GPU. |
required |
grid_origin
|
(array_like, shape(3))
|
Minimum corner of the voxel volume in world coordinates. |
required |
grid_extent
|
float
|
Physical span of the cubic grid (meters). |
required |
grid_resolution
|
int or (3,)
|
Number of voxels along each axis (must represent a cube). |
required |
sample_points
|
(Tensor or ndarray, shape(R, 3))
|
Coordinates of R surface evaluation points. |
required |
sample_normals
|
(Tensor or ndarray, shape(R, 3))
|
Outward unit normals at each sample point. |
required |
settings
|
PreprocessingSettings
|
Settings used: - epw_path: path to EPW file used for sun positions. - min_altitude: degrees above horizon for filtering sun vectors. - north_deg: model north, degrees clockwise from +Y. - time_basis: "standard", "daylight_saving" or "solar", the clock datetimes are in. - ray_length: maximum traced distance along each ray. |
required |
datetimes
|
Sequence[datetime]
|
Timestamps for which sun vectors are generated, in local standard
time, daylight saving time or true solar time ( |
required |
return_counts
|
bool
|
If True, return a 4th element: per-voxel hit counts (int32 array). |
False
|
return_rays
|
bool
|
If True, return the full ray set as host numpy arrays. Off by default: at millions of rays this is hundreds of MB of device-to-host transfer that the pipeline never uses. |
False
|
ray_batch_size
|
int
|
Rays processed per batch (0 = automatic); keyword only. |
required |
blocking_mesh
|
BlockingMesh
|
Context and terrain: rays that hit it are dropped before counting. |
None
|
return_ray_drop
|
bool
|
If True, return a last element: the RayDrop (None without blocking_mesh); keyword only. |
False
|
skin_occupancy
|
Tensor
|
The solid mass the skin rule reads (whether a skin voxel has mass behind it): the max volume plus the context and the ground; default voxel_grid; keyword only. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
carved_grid |
(Tensor, shape(X, Y, Z))
|
Voxel grid after removing all cells intersected by any traced ray. |
ray_origins |
np.ndarray, shape (N, 3), or None
|
World-space ray start points (None unless return_rays is True). |
ray_directions |
np.ndarray, shape (N, 3), or None
|
Unit ray directions (None unless return_rays is True). |
counts |
(ndarray, shape(X * Y * Z), int32, optional)
|
Per-voxel hit counts (flat). Only returned when return_counts is True. |
carve_with_sky_patch_rays(voxel_grid, grid_origin, grid_extent, grid_resolution, sample_points, sample_normals, settings, hoys, return_rays=False, point_weights=None, *, ray_batch_size, blocking_mesh=None, skin_occupancy=None)
¶
Score each voxel by the sky-patch weight of the rays that cross it.
Each Tregenza sky patch gets a weight according to settings.mode:
• irradiance: cumulative direct + diffuse irradiance per patch (kWh/m²)
from the EPW over the analysis hours (Ladybug sky matrix).
• benefit: the same, counted only in hours cold enough for solar gains
to offset heating (kWh/m²), optionally minus hot-hour irradiance
(include_harm).
• daylight: relative luminance of the CIE standard overcast sky times
the patch solid angle.
• radiative_cooling: long-wave cooling potential from the dew point and
the Bliss angular law, normalized to sum to 1.
Procedure:
1. Take the 145 Tregenza patch directions.
2. Cast a ray from each sample point toward every patch on the outward
side of its normal: toward the patch centre with
settings.rays_per_patch 1, else rays_per_patch jittered
sub-rays spread over the patch (one per cell of equal solid angle),
each with that share of the patch weight.
3. Trace the rays through the voxel volume and add each ray's patch
weight (times its point weight, if given) to every voxel it visits
in front of its source surface.
No voxel is removed here: thresholding the scores into a keep/carve mask
happens in api_core.thresholding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
voxel_grid
|
(Tensor, shape(X, Y, Z))
|
Occupancy grid; only its shape and device are used. |
required |
grid_origin
|
(array_like, shape(3))
|
Minimum corner of the voxel volume in world coordinates. |
required |
grid_extent
|
float
|
Physical span of the cubic grid (meters). |
required |
grid_resolution
|
int or (3,)
|
Number of voxels along each axis (must represent a cube). |
required |
sample_points
|
(ndarray, shape(R, 3))
|
Coordinates of R surface evaluation points. |
required |
sample_normals
|
(ndarray, shape(R, 3))
|
Outward-facing unit normals at each sample point. |
required |
settings
|
PreprocessingSettings
|
Settings used: - mode: weight mode selector. - epw_path: EPW file (irradiance and benefit). - dew_point_celsius, bliss_k, min_sky_elevation_deg: radiative_cooling. - balance_temperature, balance_offset, include_harm, simulated_weights_path: benefit. - north_deg: model north, degrees clockwise from +Y. - ray_length: maximum ray length. - rays_per_patch: rays traced per sky patch (1, 4, 9 or 16). |
required |
hoys
|
Sequence[int]
|
Hour-of-year indices (0..8759) of the analysis period, used by the EPW-based modes. |
required |
return_rays
|
bool
|
If True, include the full ray set (host numpy arrays) in the result. Off by default: at millions of rays this is hundreds of MB of device-to-host transfer that the pipeline never uses. |
False
|
point_weights
|
ndarray(R)
|
Per-sample-point design weights in [0, 1] (edge_taper): each ray's contribution is patch_weight × point_weight, and zero-weight rays are dropped before tracing. None (default) = all points count fully. |
None
|
ray_batch_size
|
int
|
Rays processed per batch (0 = automatic); keyword only. |
required |
blocking_mesh
|
BlockingMesh
|
Context and terrain: rays that hit it are dropped before scoring; keyword only. |
None
|
skin_occupancy
|
Tensor
|
The solid mass the skin rule reads, as in :func: |
None
|
Returns:
| Type | Description |
|---|---|
SkyPatchCarvingResult
|
NamedTuple with fields: - ray_origins (N, 3): ray start points, or None unless return_rays. - ray_directions (N, 3): unit ray vectors, or None unless return_rays. - raw_voxel_scores (XYZ,): accumulated weights per voxel (float32). - patch_weights (P,): weight per Tregenza sky patch. - ray_drop: the RayDrop of blocking_mesh, or None without it. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If point_weights does not have one entry per sample point. |
carve_with_planes(voxel_grid, grid_origin, grid_extent, grid_resolution, sample_points, sample_normals, settings, return_counts=False, *, ray_batch_size, skin_occupancy=None)
¶
Tilted-plane daylight carving.
One ray per sample point: 1) Project the surface normal onto the XY plane to get n_xy. 2) Select the tilt angle α (single value or per-octant table). 3) Form d = cos(α)·n_xy + sin(α)·ẑ and trace a ray along it. Every voxel at or above a visited cell in its (x, y) column is deleted: the ray traces the plane's section through that column, and everything above the plane is forbidden, not only the cells the ray crosses.
Where the test-surface outline turns convexly (two panels meeting at an
outside corner or a kink), the rays of the two panels diverge. Extra
rays from the corner sweep the headings between the two normals, so the
plane rotates around the corner instead of leaving the columns between
the diverging rays standing (see :func:_corner_fan_rays).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
voxel_grid
|
|
required | |
grid_origin
|
|
required | |
grid_extent
|
|
required | |
grid_resolution
|
|
required | |
sample_points
|
See :func: |
required | |
sample_normals
|
See :func: |
required | |
settings
|
PreprocessingSettings
|
Must contain |
required |
return_counts
|
bool
|
If True, return a 4th element: per-voxel counts, propagated up each column (a voxel's count is the largest ray count at or below it). |
False
|
ray_batch_size
|
int
|
Rays processed per batch (0 = automatic); keyword only. |
required |
skin_occupancy
|
Tensor
|
The solid mass the skin rule reads, as in :func: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
carved_grid |
(Tensor, shape(D, D, D))
|
|
ray_origins |
(ndarray, shape(R, 3))
|
The sample points (one ray each; the corner rays are not included). |
ray_directions |
(ndarray, shape(R, 3))
|
|
counts |
(ndarray, shape(D * D * D), int32, optional)
|
Only returned when return_counts is True. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Test point access evaluation¶
test_point_access_evaluation (in access_evaluation.py) tells how much sun or sky each test point still receives through an occupancy grid: the uncarved max volume or a carved envelope on the same grid. It traces the mode's preprocessing rays until the first occupied voxel, under the same front-face and skin rules as scoring, and returns per test point test_point_accessible_weight (rays that reach no occupied voxel) and test_point_blocked_weight (the others). The weights are in the mode's patch weight unit (kWh/m² for irradiance and benefit, a share of the sky for daylight and radiative_cooling, so a horizontal point in the open has about 1), or hours of sun for time-based. tilted_plane has no rays toward the sky and is refused. For a carved envelope, pass the max volume as max_volume: the skin rule reads it, as in scoring, so a facade voxel left standing in front of carved mass still counts as the test point's own wall. It is a Python function only for now, with no CLI command or stage.
urbansolarcarver.access_evaluation
¶
UrbanSolarCarver: test point access evaluation¶
How much sun or sky each test point still receives through an occupancy
grid, uncarved or carved: :func:test_point_access_evaluation traces the
rays of the mode's preprocessing (sky-patch rays with their patch weights
and edge_taper point weights, or sun rays for time-based) until the first
occupied voxel, and sums per test point the weight of the rays that reach
none (accessible) and of the others (blocked). Voxels count under the
same front-face and skin rules as in scoring, so a point's own surface
does not block it; on a carved grid, pass the max volume too, which the
skin rule reads as it does in scoring.
PointAccessResult
¶
Bases: NamedTuple
Return type of :func:test_point_access_evaluation.
test_point_access_evaluation(occupancy, grid_origin, grid_extent, grid_resolution, sample_points, sample_normals, settings, point_weights=None, *, max_volume=None, device=None, ray_batch_size=0)
¶
Accessible and blocked weight of every test point through occupancy.
The rays are those of preprocessing for settings.mode:
- the weighted modes: one ray per sample point and Tregenza patch it
faces (or
rays_per_patchjittered sub-rays, each with that share), weighted by the mode's patch weight times the point's point_weights entry (edge_taper); the weights are in the mode'sweight_unit(kWh/m² for irradiance and benefit, a share of the sky that sums to 1 over the sphere for daylight and radiative_cooling); - time-based: one ray per sample point and sun position it faces over
the analysis period, each worth 1 /
sun_steps_per_hourh, so the weights are hours of sun; point_weights is ignored, as in preprocessing.
A ray is blocked at the first occupied voxel it visits under the front-face and skin rules of scoring. For every point, accessible + blocked is the total weight of its rays, and an empty grid leaves all of it accessible.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
occupancy
|
(Tensor or ndarray, shape(X, Y, Z))
|
The grid to evaluate (nonzero = occupied): the max volume, or a carved envelope on the same grid. |
required |
grid_origin
|
The grid's minimum corner, cubic extent (m) and voxels per side, in the frame of sample_points. |
required | |
grid_extent
|
The grid's minimum corner, cubic extent (m) and voxels per side, in the frame of sample_points. |
required | |
grid_resolution
|
The grid's minimum corner, cubic extent (m) and voxels per side, in the frame of sample_points. |
required | |
sample_points
|
(ndarray, shape(P, 3))
|
Test points and their outward unit normals. |
required |
sample_normals
|
(ndarray, shape(P, 3))
|
Test points and their outward unit normals. |
required |
settings
|
PreprocessingSettings
|
Settings of the preprocessing run (mode, weather, period, north, ray length, mode parameters). |
required |
point_weights
|
(ndarray, shape(P))
|
edge_taper weight per point (weighted modes). |
None
|
max_volume
|
(Tensor or ndarray, shape(X, Y, Z))
|
The uncarved max volume, which the skin rule reads as in scoring: a test point's own facade voxel, kept in front of carved mass, then still does not block it. Default occupancy; pass it whenever occupancy is a carved envelope. |
None
|
device
|
device or str
|
Device to trace on; default the device of a occupancy tensor, or
|
None
|
ray_batch_size
|
int
|
Rays per batch (0 = automatic). |
0
|
Returns:
| Type | Description |
|---|---|
PointAccessResult
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
For |
Column post-processing¶
column_postprocessing.py holds the column rules thresholding applies after the score threshold: carve_above_columns (the carve_above setting), carve_above_scores (for each voxel, the score cutoff below which carve_above removes it; thresholding uses it so that carve_fraction counts what carve_above removes) and limit_column_slope (the slope limit, max_slope_deg).
urbansolarcarver.column_postprocessing
¶
UrbanSolarCarver: column post-processing of the carved grid
Column rules applied by thresholding after the score threshold, so the kept volume is a buildable height field:
- carve_above_columns / carve_above_scores: carve every occupied voxel
above the lowest sufficiently-carved region of each (x, y) column
(
carve_above,carve_above_min_consecutive), on a boolean carve mask or directly on the scores. - limit_column_slope: cut columns that rise more steeply than
max_slope_degabove a median-filtered height map, which turns one-voxel spires and tall cliffs into ramps. It only removes voxels.
The column loops are numba kernels.
carve_above_columns(mask, voxel_grid, min_consecutive=1)
¶
Carve occupied voxels above the lowest sufficiently-carved run per column.
For each (x, y) column, scans bottom-to-top (z=0 upward) for runs of consecutive carved voxels (occupied in voxel_grid, False in mask; empty cells break a run and never count as carved):
- Runs with length >= min_consecutive trigger carve-above: all occupied voxels above the run are carved. The first (lowest) qualifying run triggers; scanning stops for that column.
- Shorter runs do not trigger, but stay carved: the result only ever removes voxels, so it never re-violates the carving constraint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask
|
ndarray (D, D, D) bool
|
Thresholding mask. True = keep, False = carved. Not mutated. |
required |
voxel_grid
|
ndarray (D, D, D) bool
|
Original envelope occupancy. True = occupied. |
required |
min_consecutive
|
int
|
Minimum consecutive carved voxels to trigger carve-above. |
1
|
Returns:
| Type | Description |
|---|---|
ndarray (D, D, D) bool
|
A copy of mask with the occupied voxels above qualifying runs set to False. |
carve_above_scores(scores, occupancy, min_consecutive=1)
¶
For each voxel, the score cutoff below which carve_above removes it.
Carving the occupied voxels that score above a cutoff t and then running
:func:carve_above_columns removes exactly the occupied voxels whose
value here is above t: a voxel goes when it scores above t itself, or
when some run of min_consecutive consecutive occupied voxels below it
in its column all score above t. So the value is the larger of the
voxel's own score and, over those runs below it, the smallest score in
the run. Empty cells break runs.
With these values a score-mass cutoff can count everything carve_above removes, not only the voxels the cutoff picks itself. NaN scores count as +inf (always carved).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
ndarray (X, Y, Z) float
|
|
required |
occupancy
|
ndarray (X, Y, Z) bool
|
|
required |
min_consecutive
|
int
|
|
1
|
Returns:
| Type | Description |
|---|---|
ndarray (X, Y, Z) float64
|
Values on empty cells are their own score and carry no meaning. |
limit_column_slope(mask, occupancy, max_slope_deg, median_size=5)
¶
Lower columns that rise too steeply above their neighbours.
Each building column's kept height (one above its highest kept voxel,
0 if nothing is kept) is capped so that it rises at most
tan(max_slope_deg) voxels per voxel of horizontal distance above a
reference height map, counting the reference at the column itself as
one voxel away; every kept voxel above the cap is removed. The result
only ever removes voxels.
The reference is the kept height map after a median_size x
median_size median filter over the building's columns, so features
one or two columns wide are ignored: a single tall column (a spire) is
measured against its surroundings and ends at most one slope step above
them, and a single low column (a stub left at a curved edge) or a
narrow slot does not pull its neighbours down. Wider differences in
height, including next to areas carved to the ground, become ramps of
the given slope, cut from the taller side. Columns outside the
building (no occupied voxel) take no part.
The cap never rises when the input loses voxels, so carving more before this step never keeps more after it (a carve_fraction slider stays nested).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask
|
ndarray (X, Y, Z) bool
|
Kept voxels (True), normally after carve_above. Not mutated. |
required |
occupancy
|
ndarray (X, Y, Z) bool
|
The building's voxels before carving; decides which columns count. |
required |
max_slope_deg
|
float
|
Steepest allowed rise between neighbouring columns, in degrees above horizontal (0 < angle < 90; voxels are cubes, so the slope is the same in metres). |
required |
median_size
|
int
|
Width in voxels of the median filter that builds the reference. |
5
|
Returns:
| Type | Description |
|---|---|
ndarray (X, Y, Z) bool
|
A copy of mask with the voxels above each column's cap removed. |