Skip to content

Latest commit

 

History

History
1000 lines (702 loc) · 39.5 KB

library-api.md

File metadata and controls

1000 lines (702 loc) · 39.5 KB

Library API reference

Everything here is what library code (generators, PartScripts, loss and friction functions) may use. It reaches library code through its context: context["hvac_api"] is the geometry API, context["loss_api"] the loss API. Library code never imports FreeCAD, Part or internal HVAC modules; how to write a library, and what library code may do with the shapes the API returns, is in the library guide.

A change to any public name or context key raises the matching API_VERSION; a library declares the versions it was written for in its library.json ("requires_api") and is refused by any other (see CHANGELOG.md, "Compatibility policy").

Geometry API: HVACLibraryAPI (version 4)

Constants

API_VERSION

Value: 4.

EPS

Length tolerance, mm: 1e-09.

PUBLIC

The set of public names (this page).

STANDARD_FITTINGS

The fitting names build_fitting and measure_fitting accept: ahu, cross_tee_straight, double_wye_mitered, double_wye_radius, duct_closure, elbow, elbow_mitered, inline_damper, inline_obstruction, inline_vav, plenum, star_branch, star_cross, star_multiport, star_wye, tap_saddle, tap_shoe, tap_straight, tee_lateral, tee_lateral_mitered, tee_lateral_radius, tee_mitered_shoe, tee_radius_center, tee_radius_edge, tee_straight, terminal_bellmouth, terminal_body, terminal_cone, terminal_diffusing, terminal_frame, terminal_hood, terminal_plain, terminal_round, terminal_slot, terminal_square, through, transition, transition_mitered, transition_radiussed, wye_mitered, wye_radius.

Ports, vectors and lines

angle_between(u1, u2)

Return the smaller angle between two vectors in radians.

arc_center_from_points_tangents_radius(p0, p1, u0, u1, radius)

Compute the center of a circular arc joining p0 -> p1 with given radius, using tangent directions u0 at p0 and u1 at p1.

Parameters

p0, p1 : FreeCAD.Vector Arc end points. u0, u1 : FreeCAD.Vector Tangent directions at p0 and p1. radius : float Arc radius.

Returns

FreeCAD.Vector Arc center.

Notes

  • The bend plane is derived from u0 x u1.
  • The chosen center is the one whose radius vectors are most perpendicular to the supplied tangents.

average_point(points)

Return the arithmetic mean of points, or the origin for an empty input.

build_trim_rec_from_context_uniform(context, length_value)

Same as build_trim_rec_from_port_lengths, but trims every connected port by the same length_value.

build_trim_rec_from_port_lengths(port_lengths)

Build the connection_lengths a generator returns from a list of (port, trim_length) pairs -- how far each connected segment is trimmed back from its own endpoint to make room for this fitting. Ports with no real edge_key/segment_end (e.g. a synthetic port) are silently skipped.

center_from_context(context)

The junction's center point, or (if not given) the average of its connected ports' positions.

closest_points_on_lines(p0, d0, p1, d1)

Return closest points c0 on L0 and c1 on L1 for:

L0(t) = p0 + t d0
L1(s) = p1 + s d1

Returns (None, None) for nearly parallel lines.

collinear_port_index_pairs(context)

Index pairs (into connected_ports(context)) the network classifier already found collinear (~180 deg apart -- see NetworkParser._collinear_pairs), read straight off the junction's own context["analysis"]["collinear_pairs"] payload (NetworkParser.JunctionAnalysis, propagated via Component._parentAnalysis/AnalysisJson).

A "which two of this node's ports form the straight run" generator (a radiused/mitered tee's trunk, a tap's main run, ...) should use this rather than re-deriving collinearity itself, so it agrees exactly with the classifier's own family_key decision (same tolerance, same data) instead of risking a second, possibly divergent judgment call. Empty if no analysis payload is present (e.g. a synthetic/unit-test context) -- callers need their own geometric fallback for that case.

connected_ports(context)

Return a copy of the context's connected-port list.

copy_port(port, position=None, direction=None, profile_x_axis=None, edge_key=None, segment_end=None)

Copy a port dict, optionally overriding position/direction/ profile_x_axis/edge_key/segment_end (everything else unchanged).

edge_key/segment_end are useful when synthesizing a port that doesn't correspond to the original port's own connection any more (e.g. an internal seam between two chained junction components).

grow_port_section(port, delta)

Copy of port with its cross-section grown by delta (uniformly, on every side) -- position/direction/profile are unchanged, only section_params grows. Shared helper for building an insulation (or any other wrap-around) shape's own outer profile from a casing port's profile, without duplicating this per fitting generator. Used for a flange collar (it sits on the outside of the wall) and for any other shape wrapped around a port's own section.

is_zero(v, eps=None)

Return whether v is no longer than the requested tolerance.

port_area(port)

Cross-section area (m^2) of a port, from its profile/section_params (in mm).

port_diameter(port)

Return a circular port's diameter in millimetres, defaulting to zero.

port_direction(port)

Return a port's outward direction as a unit vector.

port_height(port)

Return a rectangular or oval port's height in millimetres.

port_param(context, name, port, default=None)

A property value for one port.

Works for a per-port property (a type-def property marked "per_port": true, resolved to one value per connected port) and for an ordinary property (one value shared by every port), so a generator need not know which of the two a type declares. default is returned when the property is missing or not set for that port.

port_position(port)

Return a port's position as a FreeCAD vector.

port_profile(port)

Return the normalized profile name stored on a port.

port_profile_x_axis(port)

Return a port's profile x-axis, or None when it is unavailable.

port_roles(context)

The connected ports of the current node, by role name. The roles depend only on how many ports there are and how they are arranged:

  • 1 port: neck
  • 2 ports: inlet, outlet (by flow direction; port order if unknown)
  • 3 ports with a straight run (a tee, a lateral): run_a, run_b, branch
  • 3 ports with no straight run (a wye): main, branch_a, branch_b
  • 4 ports with a straight run (a cross, a double wye): run_a, run_b, branch_a, branch_b
  • anything else, including 5 or more ports: port_1 .. port_n

"Straight run" is the classifier's own collinear pair, so this never disagrees with the family the node was given. For port_1..n the order is geometric (by outward direction), so it does not depend on the order the ports happen to be listed in.

port_section_params(port)

Return a copy of a port's section-parameter mapping.

port_width(port)

Return a rectangular or oval port's width in millimetres.

rotate_vector(v, axis, angle)

Rotate vector v by angle radians around a unit axis (Rodrigues' formula).

run_branch_ports(context)

Return (run_a, run_b, branch) for a degree-three tee/tap.

The run pair comes from the network classifier's collinear-pair analysis. Port roles are not guessed again from raw geometry here.

unit(v, eps=None)

Return a normalized copy of v, rejecting a zero-length vector.

vec(v)

Return v as a FreeCAD vector.

xyz(v)

Return a vector-like value as an (x, y, z) tuple.

Section wires and frames

make_circular_wire(center, normal, diameter)

A circular section wire, centered on center, lying in the plane perpendicular to normal.

make_circular_wire_split_at(center, normal, diameter, directions)

A circle drawn as one arc per entry of directions, with a corner where each direction (from the centre, projected onto the circle's plane) crosses it.

Use it where a sweep or loft goes from a section with corners (one half of a split profile) to a circle: a circle with the same number of corners, placed to match, keeps the solid from twisting.

make_profile_frame(direction, preferred_x=None, origin=None)

Build a right-handed section frame whose z-axis follows direction.

make_rectangular_wire(center, x_axis, y_axis, width, height)

A rectangular section wire, centered on center and aligned to x_axis/y_axis.

make_split_circular_wire(center, x_axis, y_axis, diameter, width, height)

A circle drawn as four arcs, split where the lines from its centre to the corners of a width x height rectangle (on the same axes) cross it.

A plain circle is one edge with its seam wherever OCC puts it, so a loft from it to a rectangle twists. This one has a corner for each corner of the rectangle, in the same order as make_rectangular_wire, so the two loft edge for edge.

Profiles and solids

extrude(profile, vector, *, solid=False)

Extrude a profile or wire along a nonzero vector.

With solid=True the wire is first converted to a face, producing a solid extrusion. Otherwise the wire itself is extruded into a shell.

loft(profiles, *, solid=False, ruled=True, closed=False)

Loft through at least two profiles and return the resulting shape.

make_face(profile)

A flat face filling a closed profile or planar wire (its outline only, no holes).

make_profile(profile_type, params, frame=None, *, center=None, direction=None, profile_x_axis=None)

Build a closed section wire in a local placement frame.

profile_type accepts rectangular, circular, oval, rounded- rectangle, and polygon aliases. frame may be a mapping with origin/normal/x-axis entries or a three-item sequence; explicit frame keyword arguments fill any values omitted by a mapping.

Returns an :class:HVACProfile. Invalid or collapsed dimensions raise ValueError.

offset_profile(profile, distance)

Return a new profile offset uniformly in its local section plane.

Positive distances grow the clear-air boundary and negative distances shrink it. The input must be an HVACProfile returned by this API.

offset_wire(wire, distance)

Grow (positive distance) or shrink (negative) any closed planar wire in its own plane, keeping sharp corners sharp.

Use offset_profile() for a normal section profile -- it rebuilds the section exactly from its own dimensions. This is for a wire that is no longer a plain section, e.g. one half of a split profile or a section cut off a mitred body.

profile_from_port(port, offset=0.0)

Build an HVACProfile from a library port.

A positive offset grows the port section uniformly before the profile is built; a negative value shrinks it.

profile_projection_bounds(profile, direction)

Return the minimum and maximum projection of a profile along direction.

revolve(profile, axis, angle=360.0, *, solid=False)

Revolve a profile around (origin, direction) by degrees.

axis may also be a mapping with origin and direction (or axis) entries. solid=True revolves the profile's filled face.

rotate(shape, origin, axis, degrees)

A copy of shape turned by degrees about the line through origin along axis.

sample_path(path, spacing)

Points along a path edge (or a wire of edges), spacing apart, as [(point, unit tangent), ...]. The stations are centred: whatever length is left over is split evenly between both ends, so a row of ribs or hangers sits symmetrically. Fewer than one spacing of path gives an empty list.

split_profile_face_by_extent(profile, split_direction, positive_ratio)

Split a profile at a linear ratio of its projected extent.

The requested direction snaps to the nearest local horizontal or vertical axis. The positive face points with that oriented axis.

stretch_profile_one_sided(profile, direction, extension)

Stretch a profile along direction while keeping its heel side fixed.

The profile's minimum projection along direction is treated as the heel. The opposite side is extended by extension. No assumption is made about profile type or geometry.

sweep(profiles, path, *, solid=False, frenet=False, transition=0)

Sweep one or more section profiles along a path wire.

frenet and transition are forwarded to OCC's pipe-shell builder. A failed, null, or non-solid result (when solid=True) raises RuntimeError with a stable library-facing message.

translate(shape, vector)

A copy of shape moved by vector.

Booleans and shape tools

clip_plane(shape, plane, side='positive')

Keep one half of shape relative to an infinite plane.

plane is (origin, normal) or a mapping. side accepts positive/front/normal or negative/back/opposite aliases.

common(*shapes, refine=False)

Intersect nested shape arguments, optionally removing splitters.

compound(shapes)

Create a compound from nested non-null shape sequences.

cut(shape, *tools, refine=False)

Subtract each non-null tool from shape in argument order.

fuse(*shapes, refine=False)

Fuse nested shape arguments, optionally removing splitters.

make_line(start, end)

Create a line edge between two distinct points.

make_sphere(center, diameter)

Create a sphere from its center and positive diameter.

refine(shape)

Remove boolean splitters when OCC can do so safely.

Merging faces sometimes turns a valid shape into an invalid one (seen on fused swept bodies, where a later cut then gives a wrong result). In that case the original, unrefined shape is returned.

reverse(shape)

Return a copy with reversed topology orientation.

section_face(shape, plane)

Return the exact planar cross-section where shape meets a plane.

plane is (origin, normal) or a mapping, same as clip_plane. This is the ready-made face a neighbouring piece should be built against after clip_plane trims a shape back to a cut line (e.g. a mitre plane) -- reading the real cut face back off the trimmed shape avoids any mismatch against an independently built, idealised profile that might not land exactly on the plane.

Reads the face directly off shape.Faces rather than intersecting with a fresh plane face: a plane coincident with (part of) the shape's own boundary -- exactly the case right after clip_plane cut it there -- is a tangential/degenerate boolean for OCC, which is unreliable (it can silently return empty). The cut face is already a real face of shape; this just finds it.

trim(shape, boundary, keep='inside')

Trim shape with a plane or another Part shape.

Shape boundaries support intersection (inside) and difference (outside). Plane mappings use their own optional side value and default to the positive half-space.

validate(shape, *, raise_on_error=False, require_solid=False)

Return a stable diagnostic dictionary for a Part shape.

Set require_solid to treat shapes without solids as invalid and raise_on_error to raise ValueError instead of only reporting accumulated messages.

Paths, fittings and layers

build_envelopes(envelope_builder, construction_layers, params)

Build the nested outer envelopes of a multilayer wall, from the clear-air boundary outward.

envelope_builder(offset) builds the fitting's whole outer boundary shape uniformly offset outward by offset from the clear-air boundary (an offset of 0 is the air envelope itself) -- a generator builds this closure once, from its own profiles/path/ mitre-plane logic (typically via profile_from_port(..., offset)), and this method is the only thing that ever calls it, so every layer reuses exactly the same axes/stations/trim planes.

construction_layers is the type-def's own declared construction layers, in order (context["construction_layers"], a list of library/construction.py's ConstructionLayerDef). Each layer's thickness is read from params[layer.thickness_property]; a layer with no thickness_property contributes zero thickness (e.g. a purely descriptive layer with no wall thickness of its own).

Returns [air, envelope_1, envelope_2, ..., envelope_N] -- one more shape than there are layers. A zero-thickness layer's envelope is the same object as the envelope before it (no redundant rebuild), which is how envelopes_to_layers recognizes it below.

build_fitting(name, context)

Build one of the standard fittings (see STANDARD_FITTINGS) for the given geometry context: its hollow, layered shape plus its trims, as the usual {"layers": ..., "connection_lengths": ...} dict. The wall build-up comes from the context's construction layers and their thickness properties; flanges are the type's construction feature, not part of this result.

build_layered_fitting(context, envelope_builder, connection_lengths, port_roles=None)

Finish a custom fitting the same way the standard ones are finished.

envelope_builder(offset) returns the fitting's outer boundary as a solid, grown outward by offset from the air space. This cuts every declared construction layer out of it, adds flanges at the fitting ends when the type declares FlangeThickness/FlangeHeight, and returns the result dict with connection_lengths attached. port_roles optionally maps edge_key -> role name (e.g. "Branch") for per-port ShowFlange switches.

build_layered_geometry(envelope_builder, construction_layers, params)

Convenience wrapper: build_envelopes() + envelopes_to_layers(), packaged as the {"layers": {id: {"shape": ...}}} dict a geometry backend returns (see library/geometry_result.py's normalize()).

This is the one call most multilayer fitting generators need: build envelope_builder(offset) once from the fitting's own geometry context, then hand it here together with context["construction_layers"] and the resolved params -- no per-fitting casing/insulation-specific layer helpers required.

envelopes_to_layers(envelopes)

Cut HVACLibraryAPI.build_envelopes()'s nested envelopes into each layer's own physical solid: Layer 1 = Envelope 1 - Air, Layer 2 = Envelope 2 - Envelope 1, ..., innermost layer first.

A layer whose envelope is the same object as the one before it (a zero-thickness layer, see build_envelopes) is reported as None without running a boolean at all.

make_elbow_path(port0, port1, radius)

Create the tangent arc and trimmed ports for a two-port elbow.

Returns a dict containing path, tangent ports, and trim_lengths. Callers can build matching offset profiles at those ports and pass them to :meth:sweep.

make_flange(port, inward_direction, thickness, height)

Build a flat annular flange collar around any supported port profile.

make_radiussed_path(port0, port1, length, radius)

Create a radiussed offset path between two parallel ports.

The path consists of:

straight -> circular arc -> diagonal -> circular arc -> straight

The fitting has an axial length of length. The theoretical sharp turn points are located at 1/4 of the fitting length from each generated port. radius specifies the radius of both circular bends.

The input port directions are outward and must therefore be opposite.

Returns a dict containing path, trimmed ports, trim_lengths, and turn_points.

measure_fitting(name, context)

The trim records of a standard fitting, without building any shape.

offset_transition_axis(port0, port1, length)

Shared axis geometry for a two-port lateral-offset transition.

Both ports face outward in opposite, parallel directions but sit on offset (non-coincident) axes -- the generic "through.offset" case. This works out the end points and theoretical sharp turn points that every offset-transition builder needs, so the radiussed (arc-filleted) and mitered (flat-cut) builders agree on exactly the same axis and only differ in how the corner itself is finished.

Step 1: find the travel direction and the two generated end points, length apart, that preserve the ports' lateral (transverse) offset. Step 2: find the theoretical sharp turn points -- a quarter of the body length in from each end point -- and the direction/angle of the diagonal segment connecting them.

Returns a dict with keys p0/p1/u0/u1 (the original port positions/outward directions), d (unit travel direction, port0 -> port1), s0/s1 (generated end points), corner0/ corner1 (turn points), diagonal (unit corner0 -> corner1 direction), and turn_angle (radians, the deflection between the end run and the diagonal -- zero for a plain straight run with no lateral offset).

resolve_library_file(context, relative_path)

Resolve a path relative to the current type-def's own library folder (e.g. a data file it ships with).

shape_from_fcstd(fcstd_path, context, params=None, result_object='Result', port_names=None, tol_mm=0.5, tol_deg=0.5)

Build a shape from an FCStd template file (a parametric sketch-driven model) -- see template_shapes.py.

single_layer(context, shape, **extra)

The {"layers": ...} result for a fitting built as one solid (a marker, a cap, a fitting with no wall): the shape goes on the type's first declared construction layer, or on a layer named "shape" when it declares none. Any extra keys (connection_lengths, ...) are added to the result. The {"shape": ...} result form was removed: every backend returns layers.

Loss API: HVACLossAPI (version 1)

Constants

API_VERSION

Value: 1.

APPROXIMATION

A LossStatus constant.

CUSTOM

A LossStatus constant.

EXACT

A LossStatus constant.

FALLBACK

A LossStatus constant.

PUBLIC

The set of public names (this page).

UNSUPPORTED

A LossStatus constant.

Loss functions

branch_loss(context)

Converging (merging) or diverging (splitting) tee/wye fitting loss. Expects exactly 3 connected_ports: one "common"/trunk port (the sole inlet if diverging, the sole outlet if converging) and two "secondary" ports (branch + straight-through), identified by which secondary port's direction is closest to anti-parallel with the common port's direction (the straight-through continuation of the duct run).

properties["BranchStyle"] picks how the branch is joined (see _tee_zetas for the table each reads): "straight" (default), "conical", "45_entry", "damper", "45_entry_damper", "extractor".

Returns two LossPaths (branch, straight), each referenced to that leg's own velocity: EXACT when every lookup was inside a printed table made for this fitting, APPROXIMATION (with the reason) when not, UNSUPPORTED for an ambiguous/degenerate flow pattern or invalid geometry.

branch_loss_bullhead(context)

Bullhead tee/wye: the single common-flow port sits on the geometric branch leg instead of the run (see NetworkParser's qualifiers["common_leg"] == "branch" -- library JSON loss.variants route here for exactly that case, distinct from the ordinary common_leg == "run" case branch_loss() above already handles correctly). Expects exactly 3 connected_ports.

This is a generic APPROXIMATION (see _no_straight_leg_branch_zetas), not a validated SMACNA table entry for a bullhead arrangement -- never presented to a caller as an EXACT table result.

Returns one LossPath per run leg, each already referenced to that leg's own velocity, or UNSUPPORTED for an ambiguous/degenerate flow pattern or invalid geometry.

damper_loss(context)

Loss of a damper at its current blade position (SMACNA Table 14-18 A to G). properties["DamperType"] picks the kind:

  • "butterfly" (default): single thin blade. BladeAngle (0 = fully open).
  • "butterfly_airfoil": single airfoil blade, rectangular. BladeAngle.
  • "gate": sliding gate. GateOpening = open height over duct height (0 to 1).
  • "parallel_blade" / "opposed_blade": multi-blade, rectangular. BladeAngle, BladeCount; the blades run along the duct width.

elbow_loss(context)

Loss of an elbow (SMACNA Table 14-10), for any turn angle. properties["ElbowConstruction"] picks how the elbow is made:

  • "smooth" (default): smooth radius. Round: 14-10 A. Rectangular: 14-10 F, or 14-10 G when SplitterVanes is 1 to 3. Needs CenterlineRadius.
  • "gored": made of straight pieces, NumberOfCuts + 1 of them. Round with 3 to 5 pieces: 14-10 B (needs CenterlineRadius). Two pieces is a plain mitered elbow (below). A gored rectangular elbow has no table; the smooth one is used and flagged.
  • "mitered": one mitre joint. Round: 14-10 C. Rectangular: 14-10 D.
  • "turning_vanes": rectangular, mitered, with turning vanes: 14-10 H for the VaneDesign given (see loss_tables.elbows.TURNING_VANES).

Expects exactly 2 connected ports (one inlet, one outlet). Returns one LossPath referenced to the outlet's velocity: EXACT when the point was inside the printed table, APPROXIMATION (with the reason) when it was not, UNSUPPORTED when the fitting cannot be worked out.

entry_loss(context)

Loss of an entry: air entering the duct system from a room or from outdoors (SMACNA Table 14-15). properties["EntryType"] picks the shape:

  • "duct_in_wall" (default): plain duct end. WallThickness, ProjectionLength (how far it sticks out of the wall; 0 = flush).
  • "bellmouth": rounded lip (round ducts). LipRadius, EndWall.
  • "conical": cone or pyramid. ConeAngle (included), ConeLength, EndWall.
  • "intake_hood": weather hood. HoodAngle (0 or 15), HoodHeight.
  • "tapered_hood": capture hood. HoodAngle (included).
  • "canopy_hood": kitchen canopy, one fixed coefficient.

ScreenFreeArea (0 to 1) adds a screen in the opening; OpeningAreaRatio is that opening's area over the duct area (default 1).

exit_loss(context)

Loss of an exit: air leaving the duct system (SMACNA Table 14-16). properties["ExitType"] picks the shape:

  • "abrupt" (default): plain duct end, C = 1.
  • "conical": round diffusing cone. ConeAngle (included), AreaRatio (exit area over duct area).
  • "plane_diffuser": rectangular, one pair of sides diverging. ConeAngle, AreaRatio.
  • "pyramidal_diffuser": rectangular, all sides diverging. ConeAngle, AreaRatio.
  • "exhaust_hood": weather hood. HoodAngle (0 or 15), HoodHeight.

ScreenFreeArea (0 to 1) adds a screen in the exit opening.

fan_connection_loss(context)

The system-effect loss where a duct leaves a fan (an AHU's supply connection), from properties["FanConnection"]:

  • "Transition symmetric" / "... asymmetric top level" / "... top 10 down" / "... top 10 up" / "... pyramidal": a transition from the fan outlet to the duct, SMACNA 14-11 F to J, at TransitionAngle and the area ratio duct / fan outlet.
  • "Discharge into casing": the fan blows freely into the unit's own casing (a plenum) and the duct leaves that, 14-16 I, by FanWheel.

The fan outlet is the equipment port the end is connected to (context "equipment_port"). The tables are printed against the fan outlet's velocity; the result is referenced to the duct's, K = C (A_duct / A_outlet)^2. Only for air leaving the unit into the duct. "None" or no FanConnection: UNSUPPORTED (no fan connection to cost), as is a duct that carries air into the unit.

fixed_pressure_drop_loss(context)

A device rated by a pressure drop instead of a coefficient (an air terminal or a VAV box from a manufacturer's data sheet): properties["PressureDrop"] in Pa, taken as given at the current flow.

The solver only works in coefficients, so the drop is turned into the K that gives exactly that many Pa at the device's present velocity: K = PressureDrop / (rho * V^2 / 2). Works for a 1-port terminal and for a 2-port inline device (referenced to its outlet). UNSUPPORTED when PressureDrop is not set.

inline_device_loss(context)

Generic inline device (damper, VAV box, ...) loss: a single dimensionless coefficient K taken directly from properties["LossCoefficient"], applied to the connecting duct's own velocity pressure at the device's outlet. No neck-size conversion is needed here (unlike terminal_component_loss) since these devices carry the same duct through both ports rather than stepping down to a separate neck size.

Expects exactly 2 connected_ports (one inlet, one outlet). Returns one EXACT LossPath referenced to the outlet's own velocity (matching the inline-chain convention analysis/pressure.py already uses), or UNSUPPORTED if LossCoefficient isn't set (nothing to compute) or the topology can't be resolved.

manifold_loss(context)

Cross (4-port) or multiport (5+ port) fitting loss, for the common single-trunk case: exactly one port on one flow side (all inlet, or all outlet) and the rest ("secondaries") on the other side.

No dedicated SMACNA/ASHRAE table exists for 4+ port fittings, so this decomposes the junction into a sequence of pairwise branch (tee/wye) calculations, reusing the exact same diverging_branch_zetas / converging_branch_zetas tables as branch_loss: secondaries are peeled off one at a time, least-straight (most branch-like) first, straightest last -- mirroring how a real header/manifold is typically laid out (larger/sharper takeoffs nearer the main connection, the straightest path continuing furthest). Each pairwise step is referenced against the PRIMARY port's own duct size and direction (and, for the branch-angle lookup, the straightest secondary's direction) as a stand-in for the intermediate duct geometry this addon doesn't actually model between successive virtual merges/splits -- an APPROXIMATION, not a literal per-leg geometry readout. With exactly 2 secondaries this reduces to exactly the same numbers as branch_loss's 3-port calculation.

Returns one LossPath per secondary port (each already referenced to that leg's own velocity and to the primary port's own edge_key), or UNSUPPORTED for a mixed multi-inlet/multi-outlet ("true cross") flow pattern -- which has no single trunk to decompose against -- or on any missing/invalid geometry.

obstruction_loss(context)

Loss of a smooth cylinder (a pipe, a rod) crossing the duct (SMACNA Table 14-18 H). properties: ObstructionDiameter, and OffsetFromCentre (distance of the cylinder axis from the duct centreline; 0 = centred). In a rectangular duct the cylinder runs along the width and is offset along the height.

Needs the air's kinematic viscosity and the duct velocity from the solver context. With no flow the coefficient cannot be read (it depends on the Reynolds number), so a zero loss is returned.

offset_loss(context)

Lateral-offset (jog) fitting loss: a same-size collinear pair whose axes are transversely displaced -- the "through.offset" case (see TOPOLOGY_CLASSIFICATION.md), as opposed to transition_loss's area change. Expects exactly 2 connected_ports and the offset body's own axial length in properties: "OffsetLength" (an offset type) or "TransitionLength" (a transition-style type used for an offset).

Modelled as two corner deflections in series, each at the fitting's own turn angle (HVACLibraryAPI.offset_transition_axis), using SMACNA's generic-angle mitered-elbow tables (A7C/A7D) -- unlike the 90-deg-only smooth-radius tables (elbow_zeta_round/rect), these are indexed by angle directly, which an offset's shallow corners need. An "OffsetRadius"/"TransitionRadius" entry in properties (the radiussed style) still borrows the mitered coefficient, since SMACNA has no generic-angle smooth-radius table -- that case comes back as APPROXIMATION rather than EXACT.

plenum_loss(context)

Loss of a plenum box, for any number of inlets and outlets.

The box is large enough for the air to come to rest in it, so each inlet is an abrupt exit into the box (SMACNA Table 14-16, C = 1 on the inlet velocity) and each outlet is a flush entry from it (Table 14-15 A, C = 0.5 on the outlet velocity). One LossPath per inlet/outlet pair, referenced to the outlet:

K = C_entry + C_exit * (V_inlet / V_outlet)^2

Always APPROXIMATION: the tables are for an opening in a large space, which a real plenum only approaches.

screen_loss(context)

Loss of a screen or perforated plate across the duct (SMACNA Table 14-17). properties["FreeAreaRatio"] is the open fraction (0 to 1). A perforated plate also sets PlateThickness and HoleDiameter; with no HoleDiameter the fitting is treated as a wire screen.

sum_losses(first, second)

Two LossEvaluations of the same one-path fitting added together (e.g. a unit's own coefficient plus its fan connection). An UNSUPPORTED one is left out; the status is the weaker of the two (EXACT only when both are), and warnings are joined.

terminal_component_loss(context)

Generic terminal air device (diffuser/grille/register) loss: a dimensionless coefficient K (from properties["LossCoefficient"]), referenced to velocity at the device's own neck (properties["NeckSize"]) rather than the connecting duct's own velocity -- the neck is often a different size than the duct feeding it. Converted to a K_effective referenced to the connecting duct's velocity (K_effective = K * (V_neck / V_duct)^2, since velocity pressure ~ V^2 at constant density) so it composes with the solver's existing K * velocity_pressure(duct) convention used for every other fitting -- no special-casing needed downstream.

Expects exactly 1 connected port (a terminal). Returns one EXACT LossPath (the port's open-atmosphere side is None), or UNSUPPORTED if NeckSize/LossCoefficient aren't set (nothing to compute) or the port geometry is invalid.

transition_loss(context)

Loss of a transition: a change of duct size, and possibly of shape, along a straight axis (SMACNA Tables 14-11 and 14-12).

  • Round to round: expansion 14-11 A (by Reynolds number), contraction 14-12 A.
  • Rectangular to rectangular: expansion 14-11 E when only one pair of sides diverges ("sides straight"), else 14-11 B (pyramidal); contraction 14-12 A. The angle is the larger of the two side-pair angles (the "major angle" of the tables).
  • Round to rectangular, either way: the equivalent angle of 14-11 C/D, then 14-11 B for an expansion or 14-12 A for a contraction (the latter is not printed for this shape: approximation).
  • Oval is read as the rectangle of the same width and height: approximation.

properties["TransitionLength"] is the body length; 0 uses the duct size (at least 100 mm), as the geometry does. Returns one LossPath referenced to the outlet's velocity: EXACT when every lookup was inside a table printed for this fitting, APPROXIMATION (with the reason) when not, UNSUPPORTED when it cannot be worked out.

uniform_fallback_loss(context, k, warning=None)

Explicit generic-K policy for a fitting shape with no dedicated formula (e.g. a true multi-in/multi-out cross): applies k uniformly to every outlet port, same as the old "return a bare float" convention used to mean -- but now an explicit FALLBACK result instead of a silently-applied default.

wye_loss(context)

True Wye (branch.wye) fitting loss: three ports where no pair is a Tee-style collinear run -- NetworkParser never assigns a qualifiers["common_leg"] to a Wye, since there's no run/branch split to name (see TOPOLOGY_CLASSIFICATION.md). This is therefore a distinct API entry point from branch_loss()/branch_loss_bullhead() rather than routing a Wye through either of those Tee-oriented methods -- it never guesses a "straight-through" secondary leg, since a true Wye has none by definition.

Internally this reuses the same "no independent straight leg" calculation a bullhead tee/wye needs (see _no_straight_leg_branch_zetas): each non-common leg is evaluated independently against the common leg with the diverging/converging branch-zeta tables. A symmetric wye (equal legs at equal angles whose areas add up to the common duct's) reads its own tables instead (see _symmetric_wye_loss); anything else is a reasonable engineering APPROXIMATION, never presented as an EXACT table value.

Expects exactly 3 connected_ports. Returns one LossPath per leg, each already referenced to that leg's own velocity, or UNSUPPORTED for an ambiguous/degenerate flow pattern or invalid geometry.

Context keys

Each call into library code gets a context dict with exactly these keys (fewer when a key does not apply). library/contexts.py is the source.

Geometry builders and connection lengths

Key Meaning
hvac_api HVACLibraryAPI, the geometry API (see the reference above).
hvac_api_version HVACLibraryAPI.API_VERSION.
loss_api HVACLossAPI, the loss API.
loss_api_version HVACLossAPI.API_VERSION.
construction_layers The type-def's construction layers, in order (for build_layered_geometry).
properties The type's resolved property values: {name: value}.
type_id The type-def id being built.
library_id The library id.
family The classifier family (e.g. 'branch.tee', 'curved_segment').
connected_ports Junction: the ports, one dict per connected duct, pointing out of the node.
center_point Junction: the node position.
analysis Junction: the node's topology analysis (collinear pairs, common leg, ...).
topology Junction: 'through', 'branch', 'cross', 'multiport' or 'end'.
start_point Segment: the trimmed start point.
end_point Segment: the trimmed end point.
start_direction Segment: the path tangent at the start, pointing along the duct.
end_direction Segment: the path tangent at the end, pointing along the duct.
profile Segment: 'Circular', 'Rectangular' or 'Oval'.
profile_x_axis Segment: the section's x axis (Width direction), or None.
segment_key Segment: its stable key in the network.
source_object_name Segment: the base sketch or Draft object it was drawn from.
source_index Segment: its edge index in that object.
path_kind Segment: 'straight' or 'curved'.
path_edge Segment: the trimmed path edge of a curved segment, else None.
flange_ports Set by a PartScript elbow: its flange ends, for fittings/features.py.
branch_jog Set by fittings/taps.with_branch_jog: a side branch moved in to fit the run.
position Marker fallback position.
equipment_port An end connected to an equipment port: that opening as a port-like dict (profile, section_params, profile_x_axis, position). Absent otherwise.

Loss functions

Key Meaning
hvac_api HVACLibraryAPI.
hvac_api_version HVACLibraryAPI.API_VERSION.
loss_api HVACLossAPI, the loss API.
loss_api_version HVACLossAPI.API_VERSION.
construction The component's construction (layers and materials).
hydraulic_roughness_mm Roughness of the air-side surface, mm.
center_point The node position.
properties The type's resolved property values.
connected_ports The ports, each with flow_rate_lps, velocity_ms and reynolds added by the solver.
family The classifier family.
flow_class 'diverging', 'converging', 'expansion', ... or '' when unknown.
qualifiers Classifier qualifiers, e.g. {'common_leg': 'branch'}.
derived_values Values the fitting or classifier derived, e.g. {'area_ratio': 0.5}.
type_id The type-def id.
library_id The library id.
air_density Air density, kg/m3.
air_kinematic_viscosity Air kinematic viscosity, m2/s.
equipment_port As for geometry: the equipment port an end is connected to, when it is.

Friction model factories

Key Meaning
friction The analysis.friction module (DarcyWeisbach, ScaledFriction, ...).
properties The segment type's property values.
roughness_mm Roughness of the duct surface, mm.
base_model The network's own friction model, for a factory to scale or wrap.
type_id The segment type-def id.
library_id The library id.