Pipeline¶
USC runs in three stages: preprocessing, thresholding, exporting, with massing as an optional fourth that reads the thresholding output like exporting. Each stage writes a manifest, last, after all its other outputs; the next stage reads it, so you can re-run thresholding with different parameters without recomputing scores. Every manifest has a random run_id, new on every run of its stage, and every manifest after preprocessing records the run_id of the manifest it was built from (upstream_run_id); a stage refuses an upstream that was re-run since (StageChainError). Manifests store paths relative to their own folder, so a run folder can be moved or copied. A stage first deletes the manifest and the outputs of its previous run in its folder, so a failed run leaves no manifest.
run_pipeline() runs the stages needed for what you ask it to produce, in one call. For finer control, call each stage individually.
from urbansolarcarver import load_config, run_pipeline
# One-shot: preprocessing, thresholding, exporting
result = run_pipeline(load_config("config.yaml"), out_dir="outputs")
print(result.exporting.export_path)
# Decomposed
from urbansolarcarver import preprocessing, thresholding, exporting
from pathlib import Path
cfg = load_config("config.yaml")
pre = preprocessing(cfg, Path("outputs/preprocessing"))
thr = thresholding(pre, cfg, Path("outputs/thresholding"))
exp = exporting(thr, cfg, Path("outputs/exporting"))
run_pipeline¶
run_pipeline(config, out_dir, produce=("exporting",), start_from="preprocessing", context=None, after=None) runs start_from and every later stage on the path to the stages in produce. Each stage writes into <out_dir>/<stage>; a stage before start_from is not run, and the next stage reads its output from its folder in out_dir.
# Floor plates as well as the mesh: preprocessing and thresholding run once
result = run_pipeline(cfg, "outputs", produce=["exporting", "massing"])
print(result.exporting.export_path, result.massing.plates_path)
# Change a threshold setting and reuse the scores already in outputs/preprocessing
cfg = load_config("config.yaml", ["carve_fraction=0.5"])
result = run_pipeline(cfg, "outputs", start_from="thresholding")
assert result.preprocessing is None # it did not run in this call
The PipelineResult has one attribute per stage (preprocessing, thresholding, exporting, massing): the Result of a stage that ran in this call, None for the others. Its issues are the conditions noticed during the call (see Issues and run context). A start_from stage that is not on the path to a produced stage raises ValueError; a missing or stale upstream output raises StageChainError. after is given to the thresholding stage as its after (see Thresholding).
urbansolarcarver.api
¶
Public API: the pipeline stages, the run_pipeline and run_chain sequencers, and config helpers.
Importing this module imports torch, and Warp if it is installed, through
api_core.
run_pipeline(config, out_dir, produce=('exporting',), start_from='preprocessing', context=None, after=None)
¶
Run the stages needed to produce produce, one after the other.
Each stage writes into out_dir/<stage>. The sequencer runs
start_from and every later stage on the path to a produced stage:
preprocessing and thresholding come before exporting and massing, and
producing both exporting and massing thresholds once. A stage before
start_from is not run; the stage after it reads the existing output
in out_dir/<stage>.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
user_config | str | Path
|
A validated config, or the path of a YAML config file. |
required |
out_dir
|
str | Path
|
The run folder that holds one subfolder per stage. |
required |
produce
|
iterable of str
|
Stages wanted: any of |
('exporting',)
|
start_from
|
str
|
The first stage to run; it must be on the path to a produced stage. |
'preprocessing'
|
context
|
RunContext | None
|
Progress callback and cancel flag for the run. Without one, a context
that also forwards issues to |
None
|
after
|
ThresholdingResult | str | Path | None
|
The previous criterion's thresholding result, folder or manifest,
given to the thresholding stage as its |
None
|
Returns:
| Type | Description |
|---|---|
PipelineResult
|
The Result of each stage that ran (None for the others) and the issues of the call. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If produce is empty or names an unknown stage, or start_from is not on the path to a produced stage. |
StageChainError
|
If the stage before |
RunCancelled
|
If the context is cancelled; stages that finished keep their output. |
urbansolarcarver.api_core.pipeline_result
¶
PipelineResult: what one run_pipeline call produced, and what run_chain holds per criterion.
It lives here, below api, because both api.run_pipeline and api_core.chain.run_chain build it.
PipelineResult(preprocessing, thresholding, exporting, massing, issues)
dataclass
¶
What one :func:~urbansolarcarver.run_pipeline call produced.
Each stage attribute holds the Result of a stage that ran in this call and
is None for a stage that did not. issues are the conditions reported
during the call, from all stages, in the order they were noticed.
run_chain¶
run_chain(chain, out_dir=None, produce=("exporting",), start_from="preprocessing", context=None, trace=None, threshold_from=None) runs the criteria of a chain file in order on one voxel grid, then exporting and massing from the last (see Criteria). chain is a path or a ChainConfig from load_chain. Each criterion's stages write to <out_dir>/criteria/<id>/<stage>, and a criterion's thresholding takes the previous criterion's as after. It returns a ChainResult: one PipelineResult per criterion in criteria, then exporting, massing and the issues of the call. With trace (ids of criteria), only those criteria run preprocessing again and the others read their existing preprocessing folder; every criterion from the first traced one on is thresholded again. With threshold_from (an id of the chain), thresholding starts at the earlier of that criterion and the first traced one; the earlier criterion's preprocessing is read as it is. With start_from="thresholding", every criterion is thresholded again unless threshold_from is given: thresholding then starts at that criterion, and the criteria before it keep their thresholding folders, which the criterion decides after (StageChainError naming the folder when one is missing).
urbansolarcarver.api_core.chain
¶
run_chain: criteria carved in sequence on one voxel grid, then exporting and massing from the last.
ChainResult(criteria, exporting, massing, issues)
dataclass
¶
What one :func:run_chain call produced.
criteria has one :class:~urbansolarcarver.PipelineResult per criterion, in order, holding the
preprocessing and thresholding Results of the stages that ran in this call (None for a stage that did not) and the
issues reported while that criterion ran. exporting and massing are built from the last criterion and are
None when they were not produced. issues are all the issues of the call, in the order they were noticed.
run_chain(chain, out_dir=None, produce=('exporting',), start_from='preprocessing', context=None, trace=None, threshold_from=None)
¶
Carve the criteria of chain one after the other on one voxel grid, then build from the last.
Criterion <id> runs preprocessing into out_dir/criteria/<id>/preprocessing and thresholding into
out_dir/criteria/<id>/thresholding, deciding only among the voxels the previous criterion kept. Exporting and
massing read the last criterion's thresholding and write out_dir/exporting and out_dir/massing, with the
settings the criteria share. out_dir/criteria/chain.json lists the criteria and the thresholding run of each,
and the run report has a "Criteria" section.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chain
|
ChainConfig | str | Path
|
A loaded chain, or the path of a YAML file with a |
required |
out_dir
|
str | Path | None
|
The run folder. Default: the |
None
|
produce
|
iterable of str
|
Stages wanted, as for :func: |
('exporting',)
|
start_from
|
str
|
|
'preprocessing'
|
context
|
RunContext | None
|
Progress callback and cancel flag for the run. Progress is reported under |
None
|
trace
|
collection of str | None
|
With |
None
|
threshold_from
|
str | None
|
With |
None
|
Returns:
| Type | Description |
|---|---|
ChainResult
|
The Results of each stage that ran (None for the others) and the issues of the call. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If produce is empty or names an unknown stage, start_from is not on the path to a produced stage, or trace names no criterion of the chain, or threshold_from names none. |
StageChainError
|
If a folder to read before |
RunCancelled
|
If the context is cancelled; stages that finished keep their output. |
Deciding what to re-run¶
stages_to_rerun(previous_config, new_config, produce) lists, in pipeline order, the stages that have to run to bring produce up to date after a config change. It compares the settings each stage reads (preprocessing, then thresholding, then each produced leaf stage) and does not look at input files or at which stages exist on disk; that is for the caller to decide. With no previous config it lists every stage produce needs.
urbansolarcarver.stage_settings
¶
Per-stage settings projected from the flat configuration.
Each stage reads only its own settings model; RunOptions holds what
does not affect results. effective_values gives the values a stage will
apply (defaults resolved, fields its mode does not read left out), so two
configs that mean the same compare equal, and :func:stages_to_rerun turns
those comparisons into the list of stages to run.
This module must not import api_core (it pulls in torch).
stages_to_rerun(previous_config, new_config, produce)
¶
The stages to run, in pipeline order, to bring produce up to date.
Compares settings only; whether an input file changed, or whether a stage was ever run, is for the caller to decide.
- Preprocessing effective values differ: preprocessing, thresholding and the produced leaves (exporting, massing).
- Else thresholding differs: thresholding and the produced leaves.
- Else each produced leaf whose own effective values differ.
Only stages that produce needs are listed, so producing "preprocessing"
alone stops the list there. With no previous_config, every stage
needed for produce is listed. Raises ValueError for a name that is not
in :data:PIPELINE_STAGES.
stage_folder(run_folder, stage)
¶
The folder of stage in a run folder: <run_folder>/<stage>.
Issues and run context¶
Conditions that are not errors (settings the mode ignores, nothing carved, a footprint that could not be read, ...) are reported as issues: an Issue has the stage it was noticed in, a short code and a message. Each stage Result has issues, and PipelineResult.issues holds those of the whole call. Without a run context the engine also emits each issue as a warning.
A RunContext passed to run_pipeline collects the issues, calls on_progress(stage, done, total) as a stage advances, and stops the run when cancel() is called (RunCancelled; stages that finished keep their output). report_issue(code, message) records an issue on the active context.
from urbansolarcarver.run_context import RunContext
context = RunContext(on_progress=lambda stage, done, total: print(stage, done, total))
result = run_pipeline(cfg, "outputs", context=context)
for issue in result.issues:
print(issue.stage, issue.code, issue.message)
urbansolarcarver.run_context
¶
Run context: collects issues, reports progress and carries cancellation.
Standard library only. A :class:RunContext is activated for a block with
:func:run_context; engine code then calls :func:report_issue and
:func:report_progress without passing the context around. Without an
active context an issue is emitted as a warning, so direct calls to engine
functions behave as before.
RunContext(on_progress=None, forward_issues_to_warnings=False)
¶
Issue(stage, code, message)
dataclass
¶
A user-facing condition noticed during a run (not an error).
report_issue(code, message)
¶
Record an issue on the active context, or warn when there is none.
report_progress(done, total)
¶
Tell the active context's progress callback how far the stage is.
run_context(context)
¶
Make context the active run context for the block.
Errors¶
Errors raised on purpose derive from UrbanSolarCarverError. ConfigError, InputError and StageChainError are also ValueError.
| Error | Raised when |
|---|---|
ConfigError |
A config is invalid. errors lists a ConfigFieldError(field, message) per problem (field is None for checks that involve several fields). |
InputError |
An input file or input data is missing or unusable: a mesh or EPW file, an empty voxel grid, no sample points. |
StageChainError |
A stage's upstream output is missing, unreadable or from another run: the message names the stage to re-run. |
RunCancelled |
The run context was cancelled. |
urbansolarcarver.errors
¶
Exception and warning classes shared across the package.
Standard library only. Configuration, input and stage-chain errors also
derive from ValueError so callers that already catch ValueError keep
working.
UrbanSolarCarverError
¶
Bases: Exception
Base class of every error raised on purpose by this package.
ConfigFieldError(field, message)
dataclass
¶
One configuration problem: the field it concerns and what is wrong.
field is None for checks that involve several fields at once.
ConfigError(message, errors=None)
¶
InputError
¶
Bases: UrbanSolarCarverError, ValueError
An input file or input data is missing, unreadable or unusable.
StageChainError
¶
Bases: UrbanSolarCarverError, ValueError
A stage's upstream output is missing, stale or from a different run.
WarpBackendUnavailableError
¶
Bases: UrbanSolarCarverError, RuntimeError
NVIDIA Warp cannot run on the device, so rays cannot be traced; the message says why and how to repair the installation.
MalformedEngineRequest
¶
Bases: UrbanSolarCarverError, ValueError
A request to the engine is not a mapping, names an unknown command,
or lacks or misuses a key (see engine_requests).
RunCancelled
¶
Bases: UrbanSolarCarverError
The run was cancelled through its run context.
UrbanSolarCarverWarning
¶
Bases: UserWarning
Non-fatal configuration warning.
Preprocessing¶
Voxelizes the max volume, samples the test surfaces, generates rays toward sky patches (or sun positions, or the tilted-plane direction), traces them through the voxel grid, and writes per-voxel obstruction scores to scores.npy.
urbansolarcarver.api_core.preprocessing
¶
Preprocessing stage: score every voxel of the maximum volume by what it blocks.
Voxelizes the maximum volume, samples the test surfaces into points with outward normals, traces rays from them
(toward the sky patches, the sun positions or the tilted planes, depending on the mode) through the voxel grid, and
writes each voxel's score to scores.npy with the grid, the footprint, the sample points, the manifest and the
diagnostics. Thresholding reads these files.
PreprocessingResult(out_dir, volume_path, volume_shape, dtype, run_id, device_info='', issues=())
dataclass
¶
Immutable record returned by :func:preprocessing.
Carries paths to persisted artifacts and grid metadata so that downstream
stages (thresholding, exporting) can locate them without re-computation.
volume_path is the scores.npy file. The manifest_path
property points to the JSON manifest that the next stage reads; the
object also implements __fspath__ (returning that manifest path) so
it can be passed directly as a path-like to :func:thresholding.
preprocessing(cfg, out_dir)
¶
First stage of the 3-stage envelope pipeline: per-voxel obstruction scoring.
Converts a maximum-volume mesh and a set of insolation test surfaces into a 3-D scalar field where each voxel carries a score indicating how much it blocks sun or sky from the test surfaces. The steps are:
- Voxelization: the maximum-volume mesh is rasterized into a cubic
occupancy grid with edge length
cfg.voxel_size. This and the next two steps run in a local frame whose origin is the max volume's minimum corner; persisted coordinates are shifted back to world space. - Surface sampling: the test surfaces are point-sampled (spacing
cfg.grid_step), giving test points with outward normals. The test surface PLY file may contain several disjoint mesh components (e.g. separate facade panels, a ground plane and a courtyard, or a PV array). All components are sampled and their ray contributions added into a single score grid. -
Ray casting: for every test point, rays are cast through the voxel grid according to the configured mode. Each voxel that blocks a ray accumulates a weight that depends on the mode:
-
time-based: sun-position rays for the configured analysis period; a voxel's score is the protected-surface area it shades times the duration, in m²·h (each sample point stands for ~grid_step² m²). tilted_plane: one ray per sample point at the plane angle; a non-zero score means the voxel lies on or above at least one plane.- sky-patch modes (
irradiance,benefit,daylight,radiative_cooling): rays go toward the sky patches, each patch carrying a mode-specific weight; a voxel's score is the sum of the weights of the rays it blocks times the area each sample point stands for (grid_step²): the solar energy it blocks in kWh (irradiance, benefit), or the sky it hides in m² of fully hidden sky (daylight, radiative_cooling; their weights sum to 1).
With the optional context (cfg.context_path) and terrain
(cfg.terrain_path) meshes, step 1 also removes every voxel column the
context overlaps and the voxels below the ground, and in the ray-based
modes step 3 drops every ray that hits the context or the terrain before
scoring (unless cfg.context_blocks_rays is off). tilted_plane
loses the voxels only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg
|
user_config | str | Path
|
A validated |
required |
out_dir
|
str | Path
|
Output directory for this stage; created if it does not exist.
Artifacts are written directly into it, diagnostics into its
|
required |
Returns:
| Type | Description |
|---|---|
PreprocessingResult
|
Frozen dataclass with paths and metadata for the completed stage. |
Raises:
| Type | Description |
|---|---|
InputError
|
If the mesh or required EPW file is missing, the voxel grid is empty, the context or the terrain leaves nothing of it, no test-surface points are sampled, or, in radiative_cooling mode, the test surfaces do not face up. |
ConfigError
|
If the grid is too large (more than
|
Persisted artifacts
scores.npy
Flat float32 array of length XYZ (C order of the voxel grid)
with raw obstruction scores; thresholding reshapes it.
voxel_grid.npy
Occupancy grid (uint8, 1 = inside the max volume, without the voxels
context and terrain removed) so downstream stages can skip
re-voxelization.
footprint.json
The max volume's plan projection in world xy ({"polygons": [{"exterior":
[[x, y], ...], "holes": [...]}, ...]}), without the columns context
took, which massing reads instead of the input mesh. An empty list when the projection failed; massing then
uses the voxel footprint.
test_points.npy, test_normals.npy, analysis_mesh.json
Sample points (world coordinates), their normals, and the analysis
mesh, for diagnostics and Grasshopper display.
patch_weights.npy
Per-sky-patch weights (sky-patch modes only).
manifest.json
Machine-readable manifest (PreprocessingManifest) recording a
random run_id (new on every run), grid shape, world origin, voxel
size, mode, score kind and score unit, and file paths relative to the
manifest's folder. Written last, so a failed run leaves no manifest.
diagnostics/
diagnostic.json (summary statistics and wall/CPU timings),
config_snapshot.json, and, with cfg.diagnostic_plots, the
score histogram and sky-patch weight plots.
Thresholding¶
Converts the score array into a binary carving mask: optional score smoothing, then carve_fraction, head/tail breaks, or a numeric cutoff over the occupied voxels, with carve_above applied through column_postprocessing.carve_above_scores (the cutoff at which carve_above removes each voxel, so that carve_fraction counts what carve_above removes), then the slope limit (max_slope_deg, 75 degrees for the weighted modes; column_postprocessing.limit_column_slope). Writes mask.npy and scores_compared_with_cutoff.npy (float32, the grid shape: the values the cutoff is applied to before the slope limit, which are the carve_above removal cutoffs when carve_above is on and the smoothed scores otherwise); the diagnostics record max_slope_deg, slope_limit_extra_voxels_removed and obstruction_fraction_carved_by_slope_limit.
With after= (the previous criterion's ThresholdingResult, thresholding folder or manifest.json), the stage decides only among the voxels the previous criterion kept and never keeps a voxel it removed. The manifest records after_manifest and after_run_id, the diagnostics record voxels_at_start, and a previous criterion on another grid, one re-run since, or the previous criterion's own output folder as out_dir raises StageChainError.
urbansolarcarver.api_core.thresholding
¶
Thresholding stage: decide which voxels to carve from their scores.
Reads the preprocessing scores, optionally smooths them, applies the threshold (carve_fraction, headtail or a
number) together with carve_above and the slope limit, and writes the kept voxels to mask.npy. With after
(the previous criterion's result) it decides only among the voxels that criterion kept. It can be re-run with other
threshold settings without tracing the rays again.
ThresholdingResult(out_dir, mask_path, run_id, upstream_run_id, upstream_manifest, threshold_method='', threshold_value=0.0, voxels_kept=0, voxels_removed=0, retention_pct=0.0, issues=())
dataclass
¶
Immutable record returned by :func:thresholding.
Stores the path to the binary mask, the provenance chain back to the
upstream preprocessing run (upstream_run_id and upstream_manifest
path), the resolved threshold, and voxel counts over occupied voxels.
Implements __fspath__ (returning the manifest path) so it can be
passed directly as a path-like to :func:exporting.
thresholding(volume, cfg, out_dir, after=None)
¶
Second stage of the 3-stage pipeline: score-to-mask binarisation.
Loads the per-voxel obstruction scores produced by :func:preprocessing
and applies a threshold strategy to produce a Boolean mask indicating
which voxels to retain in the final envelope (True = keep,
False = carve away).
For violation_count scores (time-based / tilted_plane modes), only
a numeric threshold (cutoff) is accepted and applied directly.
Threshold strategies (set via cfg.threshold; the config layer
normalizes every accepted spelling into a ThresholdSpec, and
cfg.resolved_threshold() fills in the mode default when it is
unset):
cutoff(shorthand: a bare number): a literal cutoff; voxels withscore <= valueare kept.headtail: head/tail breaks (Jiang 2013). The scores are split at their mean; while the part above the mean (the head) holds at most 40 % of the values, the head is split again at its own mean. The last such mean is the cutoff. Suited to the heavy-tailed score distributions common in urban solar access studies.carve_fraction(default for weighted modes): cumulative-score cutoff. It finds the cutoff at which the removed voxels hold the given fraction of the building's total score mass, counting the voxels that carve_above removes along with them.
All threshold statistics, retention counts and smoothing use occupied
voxels only; the mask is False on empty cells. With carve_above
(the default), occupied voxels above a carved run in their column are
removed as well. Then, for the score-cutoff methods of the weighted
modes (or whenever max_slope_deg is set), columns that rise more
steeply than max_slope_deg above their surroundings are cut down
(:func:~urbansolarcarver.column_postprocessing.limit_column_slope); this removes
some score beyond the fraction, reported as
obstruction_fraction_carved_by_slope_limit. mask.npy is the
final mask that gets exported.
After a previous criterion (after): in a chain of criteria on one
voxel grid, each criterion decides only among the voxels the previous
one kept. The base of this run is then the occupied voxels that the
previous criterion's mask.npy keeps, instead of all occupied voxels:
smoothing, the threshold statistics, carve_fraction, carve_above
and the slope limit all act on those voxels, and the mask is never True
where the previous mask is False. Both runs must share the grid (max
volume, context, terrain, voxel size and margin); otherwise a
StageChainError is raised. When the previous criterion kept no voxel,
the mask is empty and the issue nothing_left_to_carve is reported.
The manifest then records after_manifest and after_run_id, and
the diagnostics after_run_id and voxels_at_start (the voxels this
criterion decides about).
Score smoothing (cfg.score_smoothing):
Before thresholding, a Gaussian blur can be applied to the continuous score volume to smooth resolution-dependent noise. This produces a cleaner binary mask (and carved mesh) at fine voxel sizes.
None(default): auto,1.1 × voxel_sizemetres.0: disabled, no smoothing.- Positive float: explicit radius (Gaussian sigma) in metres. Rule of
thumb: keep close to
voxel_size(1.0–1.2×). Values above 2×voxel_sizeover-smooth and round features.
Only applied to weighted-score modes (irradiance, benefit, daylight, radiative_cooling). Violation-count modes (time-based, tilted_plane) are unaffected.
To tune carve_fraction against a performance target, compare
obstruction_fraction_carved in diagnostics/diagnostic.json
across runs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume
|
PreprocessingResult | str | Path
|
Either the :class: |
required |
cfg
|
user_config | str | Path
|
Validated config or path to config file. |
required |
out_dir
|
str | Path
|
Output directory for this stage; created if it does not exist. All artifacts are written directly into it. |
required |
after
|
ThresholdingResult | str | Path | None
|
The previous criterion's :class: |
None
|
Returns:
| Type | Description |
|---|---|
ThresholdingResult
|
Frozen dataclass carrying the mask path and provenance metadata. |
Persisted artifacts
mask.npy
3-D Boolean array (same shape as the voxel grid), True = keep.
scores_compared_with_cutoff.npy
3-D float32 array (same shape as the voxel grid): the values the
cutoff is applied to before the slope limit. With carve_above
these are the cutoffs at which each voxel is removed
(:func:~urbansolarcarver.column_postprocessing.carve_above_scores);
otherwise the scores after score smoothing (the raw scores for the
violation-count modes). A voxel is kept when it is occupied and its
value is at most the threshold.
manifest.json
ThresholdingManifest recording a random run_id (new on every
run), the mask path, the path of scores_compared_with_cutoff.npy,
the path and run_id of the upstream
preprocessing manifest and, with after, of the previous
criterion's thresholding manifest (paths relative to the manifest's
folder), and
the resolved threshold strategy, score smoothing radius (m) and slope
limit this run applied. The
outputs of an earlier run in out_dir are deleted first and the
manifest is written last, after the diagnostics.
diagnostics/
diagnostic.json (resolved threshold, voxel retention, smoothing
and carve_above statistics, wall/CPU timings) and, with
cfg.diagnostic_plots, a score histogram with the threshold line.
Raises:
| Type | Description |
|---|---|
StageChainError
|
If the preprocessing manifest cannot be read, out_dir is the previous
criterion's own thresholding folder (with |
ValueError
|
If a non-numeric threshold is used with violation-count scores. |
Exporting¶
Reconstructs a triangle mesh from the binary mask, either as cubic voxel faces or as SDF-smoothed marching cubes with Taubin polishing. Writes export.<format> (ply by default, set by final_mesh_format), manifest.json and diagnostics, and the run's run_report.md. The report has a Massing section too when the run's massing folder was built from the same thresholding run.
urbansolarcarver.api_core.exporting
¶
Exporting stage: convert a carved binary mask into a triangle mesh.
Reads the thresholding manifest, builds a mesh from the binary voxel field
(voxel cubes, or a smoothed surface with apply_smoothing), and writes it
to disk (PLY/OBJ/STL/GLB) together with a run report. This is the final
pipeline stage.
ExportingResult(out_dir, export_path, retention_pct=0.0, mesh_volume_m3=None, vertices=0, faces=0, issues=())
dataclass
¶
Immutable record returned by :func:exporting.
Holds the filesystem path to the exported triangle mesh, the voxel
retention percentage, and mesh statistics (volume, vertex/face counts).
Implements __fspath__ so the result can be used directly as a
path-like pointing to the exported mesh file.
exporting(threshold_manifest, cfg, out_dir)
¶
Third stage of the 3-stage pipeline: mesh extraction from the binary mask.
Loads the Boolean voxel mask produced by :func:thresholding and the
occupancy grid persisted during :func:preprocessing, combines them
(logical AND), and converts the resulting carved voxel field into a
triangle mesh suitable for downstream CAD / BIM / visualisation workflows.
Mesh extraction proceeds through :func:~urbansolarcarver.meshing.finalize_mesh,
which supports two strategies (selected by cfg.apply_smoothing):
- cubic (
apply_smoothing=False, default): a 3x3x3 neighbour filter first drops isolated voxels, then the exposed faces of the occupied voxels are emitted; fast, produces the classic voxel look. - smoothed (
apply_smoothing=True): the binary field is converted to a signed-distance field, smoothed, and iso-surfaced with Marching Cubes, then polished withcfg.smooth_itersTaubin passes (0-6).
On both paths, connected voxel clusters smaller than cfg.min_voxels
and mesh fragments with fewer than cfg.min_face_count faces are
removed. The mesh uses the voxel size and origin recorded by
preprocessing; the config's voxel_size is not read.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
threshold_manifest
|
ThresholdingResult | str | Path
|
Either the :class: |
required |
cfg
|
user_config | str | Path
|
Validated config or path to config file. |
required |
out_dir
|
str | Path
|
Output directory for this stage; created if it does not exist. All artifacts are written directly into it. |
required |
Returns:
| Type | Description |
|---|---|
ExportingResult
|
Frozen dataclass with the exported mesh path and provenance metadata. |
Persisted artifacts
export.{ply,obj,stl,glb}
Triangle mesh in the format specified by cfg.final_mesh_format
(default ply), in world coordinates.
diagnostics/diagnostic.json
Mesh statistics (vertex/face counts, watertightness, volume, bounding
box), voxel retention percentage, and wall/CPU timings.
run_report.md
Markdown summary of the stages, written to the parent folder when
out_dir is named exporting, otherwise into out_dir; it keeps
a Massing section when the run's massing folder was built from the
same thresholding run.
manifest.json
ExportingManifest with a random run_id (new on every run), the
mesh path and the thresholding manifest's path and run_id (paths
relative to the manifest's folder). The outputs of an earlier
run in out_dir (any mesh format) are deleted first and the
manifest is written last, so a failed run leaves no manifest.
Raises:
| Type | Description |
|---|---|
StageChainError
|
If a manifest cannot be read, preprocessing was re-run after the thresholding run, or the mask or occupancy grid is missing or does not match the grid shape (a ValueError; the message names the stage to re-run). |
Massing¶
Builds stacked floor plates that follow the footprint from the carving mask (see Floor-plate massing). Writes plates.json, plates.obj, the same plates as plates.<format> when final_mesh_format is not obj, manifest.json and diagnostics, and adds a Massing section to the run report. Returns a MassingResult with the paths, the floor areas per floor and in total, and the number of plates. The geometry is in urbansolarcarver.floor_plates.
urbansolarcarver.api_core.massing
¶
Massing stage: stacked floor plates from the carved envelope.
Reads the thresholding manifest, builds floor plates that follow the
maximum volume's footprint, which preprocessing saved as footprint.json
(urbansolarcarver.floor_plates), and writes them
as plates.json (outlines in world coordinates) and plates.obj (one
closed prism per plate), and as plates.<format> too when
final_mesh_format is not OBJ, with a manifest, diagnostics and the run
report.
MassingResult(out_dir, plates_path, mesh_path, export_mesh_path, floor_areas, total_floor_area, n_plates, issues=())
dataclass
¶
Immutable record returned by :func:massing; path-like to plates.json.
mesh_path is plates.obj; export_mesh_path is the plates in
final_mesh_format (mesh_path itself for OBJ).
massing(threshold_manifest, cfg, out_dir)
¶
Fourth stage: floor plates that follow the footprint, from the carved envelope.
Floors are ground_floor_height then floor_height tall, counted
from the lowest point of the maximum volume. The footprint (the plan
projection of the maximum volume that preprocessing saved as
footprint.json, not the mesh named in cfg) is split into faces, one per
facade, and each face into square modules of min_plate_dimension, cut
along its facade and in depth behind it. A module is built on a floor when it stays in
the maximum volume over the floor's full height, at most
plate_tolerance of its volume lies outside the carved envelope, and
(with plate_stacking: supported) it is built on the floor below.
See :mod:urbansolarcarver.floor_plates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
threshold_manifest
|
ThresholdingResult | str | Path
|
Thresholding result, or a path to its folder or manifest.json. |
required |
cfg
|
user_config | str | Path
|
Validated config or path to config file. |
required |
out_dir
|
str | Path
|
Output directory for this stage; created if it does not exist. |
required |
Returns:
| Type | Description |
|---|---|
MassingResult
|
|
Persisted artifacts
plates.json
One entry per plate: floor, z bottom and top, outline and holes in
world coordinates, floor area, bay count and outside share; plus
floor areas per floor and in total.
plates.obj
One closed mesh per plate, named floor_<n>_plate_<m>; written
whatever the format chosen.
plates.<format>
The same plates in final_mesh_format when it is not OBJ: one mesh
for PLY and STL, one named part per plate for GLB.
manifest.json, diagnostics/diagnostic.json, run_report.md
The report goes to the parent folder when out_dir is named
massing, otherwise into out_dir; it keeps an Export section
when the run's exporting folder was built from the same
thresholding run. The outputs of an earlier run in out_dir are
deleted first and the manifest is written last.
Raises:
| Type | Description |
|---|---|
StageChainError
|
If a manifest cannot be read, preprocessing was re-run after the thresholding run, or the mask, occupancy grid or footprint is missing or damaged (a ValueError; the message names the stage to re-run). |
ValueError
|
If a massing size is smaller than the preprocessing run's voxel size. |