Skip to content

compas_acoustics.hybrid

The DSP of compas_acoustics.Binaural and compas_acoustics.Ambisonics.

Image sources driving a directional FDN. Needs pyFDN and spharpy, installed on Python >= 3.11.

Modules

ambisonics

Ambisonic rendering of a HybridCore.

Early paths are encoded at their directions and delay lines projected through the output matrix. The order sets the number of delay lines (default_num_delays) and their projection (ambisonic_output_matrix).

Classes

Functions:

ambisonic_output_matrix
ambisonic_output_matrix(sh_order: int, directions: Coordinates) -> ndarray

Output matrix C (n_channels, N) from delay lines to ambisonic channels, ACN.

Column i is the spherical harmonic vector of direction i over sqrt(N), so the output energy does not grow with the number of lines. The basis is spharpy's "NM", N3D with W = 1 for a unit plane wave, orthonormal: on an ideal grid C @ C.T is a multiple of the identity. Its largest off-diagonal entry over its mean diagonal is the leakage between channels; a grid leaking more than 5 % (the package's choice) does not support sh_order and raises ValueError.

default_num_delays cached
default_num_delays(sh_order: int) -> int

Smallest workable number of delay lines for an ambisonic order.

The grid must hold exactly one point per line and support the order within the leakage limit of ambisonic_output_matrix. The counts that do are irregular (20, 23, 24, 27, 28 ... at second order), so they are searched from 4 (N + 1) ** 2, for echo density (the package's choice), and never below MIN_DELAYS: 96 lines at orders 0 to 3, 100 at fourth order.

render_ambisonics
render_ambisonics(core: HybridCore, sh_order: int = 1, normalization: Literal['SN3D', 'N3D'] = 'SN3D') -> HybridResult

The core as an ambisonic response, ACN channels at sh_order.

Every early path is encoded at its direction and every line projected through the output matrix (ambisonic_output_matrix). Everything is computed in N3D; normalization sets the output, SN3D (AmbiX) or N3D, both with W = 1 for a unit plane wave. An order the core's grid cannot carry raises.

bands

The octave band grid of the hybrid synthesis, shared with the decay estimators.

Functions:

check_bands
check_bands(bands: ndarray) -> None

Raise if bands is not the package grid, which would misalign every band-indexed array.

binaural

Binaural rendering of the hybrid: every early path and delay line through the HRIR measured nearest its direction.

Classes

HrtfSet dataclass
HrtfSet(hrirs: ndarray, directions: ndarray, sampling_rate: int)

Head-related impulse responses and the directions they were measured from.

hrirs is (directions, 2, taps), ears left then right; directions are unit vectors in the listener's frame (x front, y left, z up), as SOFA stores them.

Methods:
from_sofa classmethod
from_sofa(path, sampling_rate: int) -> HrtfSet

Read a SOFA HRIR set, resampled to sampling_rate with its frequency response kept.

nearest
nearest(doa) -> ndarray

Index of the measured direction nearest each direction of arrival, by angle.

Functions:

hrir_groups
hrir_groups(hrtf: HrtfSet, doa) -> tuple[ndarray, ndarray]

The measured directions nearest the directions of arrival doa (M, 3), and the (M, G) one-hot weights that sum the paths sharing one onto a channel per measured direction.

render_binaural
render_binaural(core: HybridCore, hrtf: HrtfSet) -> HybridResult

A HybridCore at the two ears, (n, 2).

Every image, diffracted path and BTMS contribution goes through the HRIR measured nearest its direction, the paths sharing an HRIR summed first. Line i, after the late envelope (shaped_lines, fitted against the paths' omnidirectional sum) and over sqrt(N) (the W row of the ambisonic output matrix), goes through the HRIR nearest core.line_directions[i].

render_groups
render_groups(monos: ndarray, groups: ndarray, hrtf: HrtfSet, n_samples: int) -> ndarray

The two ears, (n, 2): channel g of monos (n, G) through the HRIR of measured direction groups[g].

btms

Edge diffraction by the Biot-Tolstoy-Medwin-Svensson (BTMS) model.

Svensson, Fred and Vanderkooy (1999), "An analytic secondary source model of edge diffraction impulse responses", J. Acoust. Soc. Am. 106(5), 2331-2344. Time-domain kernels in the edge-cylindrical coordinates of EDtoolbox: z along the edge, theta from the reference face into the open region, closed wedge angle 2 pi - theta_w, free field 1/r.

wedge1st_ir follows EDwedge1st_ir, with _edge_z_of_path and _slot_integrals (its integration intervals and seven-point start), wedge2nd_ir EDwedge2nd, _coordtrans1 EDcoordtrans1 and element_grid EDcreindexmatrix and EDmakeHODirs of Svensson's Edge Diffraction Toolbox v0.504; btms_paths and coplanar_thetas in compas_acoustics.hybrid.diffraction take their rules for the angles of coplanar edges (EDed2geo), the scaled geometric component on a zone boundary (EDfindconvexGApaths), its split between two samples (EDmakefirstorderirs) and the doubled thin-plate path (EDmakeHODirs) from the same toolbox:

Copyright (c) 2018, Peter Svensson All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

- Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDEN- TAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUD- ING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTER- RUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The first-order integrand (_btm_integrand) is the published line integral: Calamia and Svensson (2007), "Fast time-domain edge-diffraction calculations for interactive acoustic simulations", EURASIP J. Adv. Signal Process. 2007, 63560, Eqs. (2)-(4). It is integrated by the standard adaptive Simpson rule with Richardson extrapolation (_adaptive_simpson).

Functions:

element_grid
element_grid(lengths, c, fs)

Edge-element midpoints of an edge pair as fractions of the two edge lengths, rows in the order of EDcreindexmatrix (edge 2 fastest), and the element lengths dz (EDmakeHODirs.m, order 2, element size c / fs).

wedge1st_ir
wedge1st_ir(fs, c, closed_angle, rs, thetas, zs, rr, thetar, zr, zw, r_irstart=0.0)

First-order diffraction impulse response of a finite rigid wedge for a point source (free field 1/r), EDwedge1st_ir.m, method 'New'.

Returns (ir, singular); ir[0] is the sample at r_irstart / c, singular flags the beta terms on a zone boundary.

wedge2nd_ir
wedge2nd_ir(cyl_s, cyl_r, cyl_e2_r1, cyl_e1_r2, nu, edge_limits, dz, steps, path_along_plane, r_irstart, c, fs)

Edge-to-edge (second-order) diffraction impulse response of a pair of rigid wedges, EDwedge2nd.m with method 'n' and swapbigmatrix = 0.

cyl_s, cyl_r are (r, theta, z) of source and receiver about edges 1 and 2; cyl_e2_r1 are the two ends of edge 2 about edge 1, cyl_e1_r2 the ends of edge 1 about edge 2; nu = (pi / theta_w1, pi / theta_w2); edge_limits rows are [start, end] along each edge; steps and dz are the element_grid midpoints and element lengths; path_along_plane selects the form for two edges bounding a common plane. ir[0] is the sample at r_irstart / c.

diffraction

Edge diffraction around obstacles and at the room's own corners, as paths of the early field.

The geometry is here: which edges diffract (diffraction_edges: the free edges of closed convex and planar obstacles and, on a closed boundary, every room edge opening wider than pi), what blocks a path (Occluders) and the path over an edge (wedge_path); the filters are in udfa and btms. diffraction_paths renders first order by UDFA (Kirsch and Ewert 2023), an object being the sum of its edges' paths (Sec. VI); the three-sided barrier of Kirsch and Ewert (2024, Sec. 3.3) is defined for an infinite double edge and is not used. btms_paths renders first order by BTMS and, on the direct path, second order. With max_order >= 1 a first-order path may have one enclosure reflection before or after the edge.

Classes

BtmsContribution dataclass
BtmsContribution(start: int, ir: ndarray, doa: ndarray, band_gain: ndarray, order: int, edges: tuple[int, ...], singular: bool)

One BTMS segment (first order) or segment pair (second order).

ir is the BTMS response (free field 1/r) starting at sample start; doa in the receiver frame; edges indexes diffraction_edges; singular flags a path on a zone boundary. Order 0 is the scaled geometric component of a path exactly on a zone boundary of edge edges[0].

DiffractionPath dataclass
DiffractionPath(delay: float, distance: float, doa: ndarray, band_gain: ndarray, transfer: Callable[[ndarray], ndarray], order: int, zone: str, edge: int)

One diffracted contribution.

Pressure on the package scale: band_gain (reflections, air) times transfer(f) times exp(-j 2 pi f delay) / (4 pi distance). doa is in the receiver's frame, edge indexes diffraction_edges, order counts the wall reflections on the path (0 or 1) and zone is the receiver's zone around the edge (compas_acoustics.hybrid.udfa.WedgePath.zone).

Edge dataclass
Edge(start: ndarray, end: ndarray, face_a: ndarray, face_b: ndarray, theta_w: float, faces: tuple[int, ...] = (), component: int = -1, regions: tuple[int, ...] = ())

A straight rigid edge and its two faces.

face_a and face_b point from the edge into each face, perpendicular to it; theta_w is the open (exterior) angle from face A to face B, 2 pi for a knife edge (one face). faces indexes the Occluders polygons meeting at the edge. component is the obstacle component (obstacle_components; -1 on the room's boundary) and regions the coplanar surfaces of faces A and B (room boundary only); both serve shared_face.

Methods:
cylindrical
cylindrical(point: ndarray) -> tuple[float, float, float]

(r, z from the centre, open angle from face A) of a point.

point_at
point_at(z: float) -> ndarray

The point at axial coordinate z, measured from the edge's centre.

ObstacleEdgeWarning

Bases: UserWarning

An obstacle component whose edges are not modelled.

Occluders dataclass
Occluders(polygons: tuple[ndarray, ...], normals: ndarray, offsets: ndarray, n_obstacle: int)

Every polygon that can block a path: obstacles first, then the enclosure.

Obstacle polygons keep the indices of RoomGeometry.obstacle_faces; enclosure normals point out of the room.

Methods:
blocked
blocked(p: ndarray, q: ndarray, skip: frozenset[int] = frozenset()) -> bool

Does the open segment p-q cross a polygon not in skip?

on_polygons
on_polygons(point: ndarray, tol: float, polygons) -> bool

Does a point lie within tol of one of the given polygons?

ShellEdgeWarning

Bases: UserWarning

Edges of the room's boundary opening less than pi at a non-integer wedge index, which are not rendered, or a boundary that is not closed.

Functions:

btms_paths
btms_paths(pair: Pair, *, max_order: int = 1, second_order: bool = True) -> list[BtmsContribution]

First-order BTMS over every edge segment, with at most one wall reflection before or after, plus the order-0 geometric components on zone boundaries; second order (direct paths) when second_order.

coplanar_thetas
coplanar_thetas(e1: Edge, e2: Edge) -> tuple[float, float]

theta of e2 about e1 and of e1 about e2 for two edges along a common plane: 0 in an edge's reference face (A), theta_w in its other face, by face membership as EDed2geo.m assigns them. Points give no usable angle: a shared corner lies on the other edge's line, and rounding puts a point of a knife edge's panel at 0 or 2 pi - eps.

Two knife edges of one panel must refer to the same side of it. e1's frame (edge_frame) sets the side: 0 about e1; about e2, 0 if its frame has the same side, else 2 pi.

diffraction_edges
diffraction_edges(geometry: RoomGeometry) -> list[Edge]

Every diffracting edge: the obstacles' (obstacle_edges), then the room boundary's (enclosure_edges).

diffraction_paths
diffraction_paths(pair: Pair, *, max_order: int = 1) -> list[DiffractionPath]

Every first-order UDFA path, with at most one wall reflection before or after it.

For max_order >= 1 the source's image in a wall gives the paths that reflect before they diffract, and the receiver's image those that reflect after, which is the same construction by reciprocity.

edge_cyl
edge_cyl(edge: Edge, points: ndarray) -> ndarray

(r, theta, z) of points in the toolbox's frame of the edge, (n, 3).

Rounding puts points on face A's plane at theta = 2 pi - eps; on a wedge that is face A, theta = 0. On a knife edge 2 pi is the panel's other side.

edge_frame
edge_frame(edge: Edge) -> tuple[ndarray, ndarray]

The edge's ends in EDtoolbox order and the reference face's normal into the air: x into face A, y = z cross x into the open region.

edge_segments
edge_segments(edge: Edge, source: ndarray, receiver: ndarray) -> ndarray

Limits (k, 2) of equal segments along the edge in the toolbox's z, each at most 0.087 times the distance of the nearer of source and receiver from the edge's line (about 5 deg subtended there), that bound floored at 0.01 m for a point (nearly) on the line (the package's choice).

enclosure_edges
enclosure_edges(geometry: RoomGeometry) -> list[Edge]

The diffracting edges of the room's own boundary: every edge whose air side opens wider than pi.

A re-entrant room corner or the corners of a room within a room (Kirsch and Ewert 2024, Sec. 3.1: a 270 deg wedge "often used to approximate room corners"). Two faces with opposite normals in one plane (a panel of zero thickness drawn into the enclosure) meet at a knife edge, theta_w = 2 pi.

Not edges: a seam between coplanar faces and a rectangular corner, whose wedge index nu = pi / theta_w is an integer, where the diffracted field vanishes (Kirsch and Ewert 2023, after Eq. (3)); a piece lying on another face of the enclosure (a partition standing on an unsplit floor), as in obstacle_edges. Edges opening less than pi at a non-integer nu are left out with ShellEdgeWarning: Edge takes theta_w in (pi, 2 pi] only. A boundary that is not closed gives no edges, with the same warning.

The package's own rules: sides are split at T-junctions by the enclosure's vertices and matched by vertex index; pieces between the same two surfaces join where they share a vertex and stay on one line. "Coplanar" and "integer" are judged in metres to _MERGE_TOLERANCE, "on one line" to the larger of that and the mesh's T-junction tolerance. The direction into each face comes from its winding, which RoomGeometry makes outward and consistent. regions names the coplanar connected surface of each face (shared_face).

encode_btms
encode_btms(contributions: list[BtmsContribution], sh_order: int, n_samples: int, fs: float, *, normalization: str = 'NM', extra_weights: ndarray | None = None) -> ndarray

Encode BTMS contributions at their directions; free field 1/r to 1/(4 pi r).

extra_weights (M, K) adds K channels after the ambisonic ones, as encode's does.

encode_diffraction
encode_diffraction(paths: list[DiffractionPath], sh_order: int, n_samples: int, fs: float, *, normalization: str = 'NM', extra_weights: ndarray | None = None) -> ndarray

Encode diffracted paths at their arrival directions, as encode does images.

extra_weights (M, K) adds K channels after the ambisonic ones, as encode's does: each path's transfer function is evaluated once for all of them.

obstacle_components
obstacle_components(geometry: RoomGeometry) -> list[list[int]]

Obstacle polygons grouped by shared vertex positions.

obstacle_edges
obstacle_edges(geometry: RoomGeometry) -> list[Edge]

The diffracting edges of a mesh's obstacles.

A closed convex component gives wedges, theta_w = pi + the angle between its faces' outward normals; a planar component gives knife edges along its outline. Any other component is skipped, with one ObstacleEdgeWarning counting them by material. Edges lying on an enclosure face or on another obstacle are dropped, and a component whose rim lies there (a bottomless box on the floor) still counts as closed. Edge.component indexes obstacle_components.

pair_valid
pair_valid(e1: Edge, e2: Edge, theta_2_about_1: float, theta_1_about_2: float) -> bool

Is a point of e2 at theta_2_about_1 (edge_cyl of e1) outside e1's solid, and a point of e1 at theta_1_about_2 outside e2's?

second_order_start
second_order_start(source, receiver, seg1, seg2, c: float, fs: float) -> int

A sample before the first arrival over segment 1 then segment 2: the path is at least max(|SR|, the distance from S to segment 1 plus that from segment 2 to R), less one sample against rounding at an exact bound.

segment_distance
segment_distance(point: ndarray, a: ndarray, b: ndarray) -> float

Distance from a point to the segment a-b.

shared_face
shared_face(e1: Edge, e2: Edge, tol: float = 1e-06) -> int | None

The face of e1 (0 = A, 1 = B) lying in a face plane of e2, or None.

Obstacle edges: of one component only, compared by plane, so a face split into several polygons counts; a knife edge's one plane is found as A. Room-boundary edges: compared by regions, so coplanar walls of two separate boxes are not one face. A room edge and an obstacle edge share none.

wedge_path
wedge_path(edge: Edge, source: ndarray, receiver: ndarray) -> WedgePath | None

The wedge-frame path over edge, or None if a point is in the solid.

Angles are referenced to the face nearer the source (Kirsch and Ewert 2023, Fig. 1): when the source is further from face A than the receiver is, both are measured from face B instead.

directional

Direction-dependent boundary absorption on the delay line outputs.

Wendt et al. (2014, Sec. 1.2) weight "the signal of each incidence direction ... with the reflection coefficient of the room wall corresponding to the respective parallel cube side face". Kirsch et al. (2023, Sec. 1.3, Eqs. 4-5) generalise it to arbitrary geometry: rays from the receiver along v_s take the absorption alpha_s of the first face they meet, and with fewer lines than their 96 scanned directions, line k of K, along v_k, takes

a_k = sum_s w_s,k alpha_s / sum_s w_s,k,   w_s,k = max(v_s . v_k, 0) ** (K / 6).

With 96 lines each takes the absorption of its own scanned direction there; the weighted mean at every K, 96 included, is the package's choice (the scan is fixed in the room, the lines turn with the receiver). The output filter has the magnitude sqrt(1 - a_k) per band and sits outside the loop: every line still decays at target.rt, and the late level falls by 10 log10(mean_k (1 - a_k)) dB, left uncompensated; neither paper describes a compensation.

Classes

Functions:

absorption_filters
absorption_filters(absorption: ndarray, fs: float) -> ndarray

Output filters of magnitude sqrt(1 - a), shape (n_sections, 6, n_lines).

One graphic EQ per delay line on the band grid, its two extrapolated edges held at the outermost bands.

directional_absorption_filters
directional_absorption_filters(pair: Pair, directions: Coordinates) -> ndarray

The per-line output filters of this room, line_eq of run_network.

scanned_absorption
scanned_absorption(pair: Pair, directions: Coordinates) -> ndarray

Absorption coefficient per delay line and band, shape (n_lines, 8).

Each of the 96 scan directions of Kirsch et al. (2023, Sec. 1.3), the lines' grid in room coordinates, takes the absorption of the first face its ray from the receiver meets, which holds in a concave room too.

early

Image sources of one pair, read from a search over the whole scene, and their encoding to ambisonics.

Classes

ImageSourceSet dataclass
ImageSourceSet(delay: ndarray, gain: ndarray, doa: Coordinates, order: ndarray, bands: ndarray, fs: float, scattered: ndarray | None = None, wall: ndarray | None = None)

Delay, band gains and direction of every image source, independent of the output format.

Functions:

encode
encode(iss: ImageSourceSet, sh_order: int, n_samples: int) -> ndarray

An image source set as an ambisonic impulse response, ACN, N3D (spharpy's "NM": W = 1 for a plane wave).

The band gains are interpolated onto the FFT grid in log frequency and dB, the delay applied as a phase ramp (a band-limited fractional delay), and the images summed in the frequency domain. Above the top band the magnitude continues its slope (_extrapolated_top_db); below the lowest it is tapered to zero at DC (_dc_block).

image_sources
image_sources(room, source_index: int, mic_index: int, pair: Pair, directivity=None, damping=None, scattered=None) -> ImageSourceSet

The image sources of one source at one microphone of a searched room.

room holds every source and microphone of the scene; this pair's images are those visible at mic_index, the direct sound being order zero. An image found twice (a path through an edge is accepted from both wall orderings) is kept once. The gains are the reflection products times 1 / (4 pi d), the air absorption over the path d (whatever the room's own setting) and directivity along the image's emission direction from the real source; wall is each image's generating face.

damping, the source's reflection products (n_bands, n_images) in another build of the room (damping_as_searched), replaces the room's own. With surface scattering (Ewert et al. 2025, Sec. 2.1.3) it is the specular product prod sqrt(1 - s_i) of the room built with ray_tracing=True, and scattered the product prod sqrt(s_i) of the same build of complementary_scattering; the direct sound has no scattered part.

render_images
render_images(iss: ImageSourceSet, weights: ndarray, n_samples: int) -> ndarray

Image sources accumulated onto output channels, (n, n_ch), with weights (M, n_ch) per image.

weights are spherical harmonics for ambisonic channels or a routing onto delay lines or HRIRs; every image gets the same band magnitude, band-limited fractional delay and radiation taper (encode).

render_signals
render_signals(signals: list[tuple[int, ndarray]], gains: ndarray, bands: ndarray, fs: float, n_samples: int) -> ndarray

As render_images, for sampled responses (start_sample, block (length, n_ch)) weighted per channel.

Blocks whose band gains agree to 0.01 dB are summed in the time domain and filtered once.

render_transfers
render_transfers(delays: ndarray, transfers, gains: ndarray, weights: ndarray, bands: ndarray, fs: float, n_samples: int) -> ndarray

As render_images, for paths whose band magnitude gains[m] is multiplied by transfers[m](freq).

envelope

A ray-traced energy envelope imposed on the network's delay lines.

In a room with unevenly distributed absorption the late field does not decay exponentially from the transition order, while the network of Wendt et al. (2014) assumes a diffuse field from its input on. In the hybrid approach for such rooms (Vorlaender 2020, Secs. 11.9 and 16.5.5) ray tracing estimates the envelope M^2(dt, f) and a synthetic fine structure is shaped to it (Heinz 1993; Schroeder 2011, Sec. 5.3.4). Here the fine structure is the network's output. Per octave band b, with E the energies of the omnidirectional signals on the package scale, smoothed with a Hann window of SMOOTH_MS,

g_b(t) = min(1, sqrt(max(E_ref,b - E_early,b, 0) / E_late,b))

scales every line. A ray is logged only after the image source order, so the reference minus the image sources is what the lines must carry. The gain is held from where the reference band's energy decay curve is 20 dB down, never before the early images end (_early_end) plus the window. The bank has nine bands, 63 Hz to 16 kHz, or eight when 16 kHz is at or above Nyquist; the 16 kHz band keeps the energy above about 11.2 kHz out of the 8 kHz estimate and takes the 8 kHz gain.

With a directional histogram (late_envelope="directional") each line is also scaled, per band, by sqrt(p_i / q_i): its direction's share of the rays' energy over its share of the lines' (directional_shares). The histogram is the detection sphere divided into directivity groups, each with a histogram per frequency band (Lentz et al. 2007, Sec. 2.4 and Fig. 6; Schroeder 2011, Sec. 5.3.4). Schroeder averages the bands into one hit probability per group; here each band keeps its own, a per-line, per-band gain as the boundary filters of Kirsch et al. (2023, Eqs. 4-5) are.

The package's own choices, in none of these sources:

  • Shaping the lines of a feedback delay network, by the omnidirectional gains and by the directional shares: Schroeder steers a Poisson noise process with one probability per group, and Kirsch's gains are fixed boundary filters.
  • The late target E_ref - E_early, and gains capped at 1, so a hybrid quieter than its reference stays so.
  • The end of the early images (_early_end): 13 dB below the reference, both smoothed over 10 ms.
  • Pooling each time bin over neighbouring directions with the weights of Kirsch et al. (2023, Eq. 4), max(u_i . u_j, 0) ** (N / 6), which they use to map their 96 scanned directions onto fewer sources; with 96 sources each takes its own scanned direction (Sec. 1.3).
  • SMOOTH_MS and the holds, 20 dB down for the gains and 60 dB down for the shares.
  • The ray count (histogram_rays): the 1 dB that Schroeder (2011, Sec. 12.1) takes for a response's envelope, applied to one direction's share.

Functions:

directional_shares
directional_shares(histogram, lines: ndarray, fs: float, band: int) -> ndarray

The factor on every line, (n, n_lines), that gives one band of the lines the rays' distribution over directions.

histogram is a DirectionalHistogram on the lines' directions; lines (n, n_lines) are one octave band of the network's lines as heard and band the histogram's row of that band; both start at the emission. Per time slot p_i is direction i's share of the rays' energy in the band and q_i the line's share of the lines', both after smooth_over_directions and over SMOOTH_MS. The shares are held once the band's rays have decayed 60 dB (detections per bin do not thin out with the energy, as a reference's late part does), never before the lines start.

envelope_gains
envelope_gains(reference: ndarray, early_w: ndarray, late_w: ndarray, fs: float) -> ndarray

Per-band gains in [0, 1] for the late field, shape (n_bands, len(late_w)), on the bank's bands.

reference is an omnidirectional response of the same pair on the package's scale; early_w and late_w are the W channels of the hybrid's two parts. A reference shorter than the late field has its last gain held.

histogram_rays
histogram_rays(volume: float, receiver_radius: float, speed_of_sound: float, directions: ndarray) -> int

The rays at which a direction's energy over one slot has a standard deviation of SHARE_ERROR_DB.

Vorlaender (2020, Sec. 11.3.7): the hits of a detection sphere of radius r_d within dt are Poisson distributed, N pi r_d^2 c dt / V of them on average, so the level of their energy has the standard deviation 4.34 / sqrt(hits) dB (Eq. 11.20). One of n directions holds 1 / n of the hits. The Hann window of SMOOTH_MS and smooth_over_directions weight them, and a weighted sum of Poisson counts has the error of sum(w) ** 2 / sum(w ** 2) equal ones: 2/3 of the window, and the mean of that ratio over the kernel's rows. The methods trace their own reference with this count in both late-envelope modes, so that "omni" and "directional" shape the late field to one reference.

octave_band_split
octave_band_split(x: ndarray, fs: float) -> ndarray

The bank's octave bands of x (_reconstructing_bank), which sum back to it, (n_bands, n[, C]).

The amplitude-preserving linear-phase bank with its delay removed, as one FFT per channel and one inverse per band, zero-padded past n + _N_FILT - 1 so the circular product is the linear convolution.

shape_late
shape_late(signals: ndarray, early_w: ndarray, late_w: ndarray, reference: ndarray, fs: float, histogram=None) -> ndarray

The network's lines signals (n, K) with the gains of envelope_gains on every column.

late_w is the lines' sum through C, early_w the early field's W channel, and reference is on the same scale; if early_w + late_w and the reference differ by more than SCALE_WARN_DB over the first 50 ms, a warning says the reference is on another scale. histogram, a DirectionalHistogram on the lines' directions, also gives every band of the lines its directional_shares. Its bands are the octaves from 62.5 Hz (the bank's to within 2 %), at least to 8 kHz; without a 16 kHz row that band takes the 8 kHz one.

smooth_over_directions
smooth_over_directions(energy: ndarray, directions: ndarray) -> ndarray

energy (n_directions, ...) pooled over neighbouring directions, same shape.

Direction i takes the mean of all directions weighted by max(u_i . u_j, 0) ** (N / 6), the weights of Kirsch et al. (2023, Eq. 4); pooling a grid onto itself with them is the package's choice. The rows of the kernel are normalised, so on a grid whose columns sum alike (an equal-area grid) the energy of every bin is kept to within the grid's unevenness.

late

The directional feedback delay network: one delay line per direction.

Classes

Functions:

design_fdn
design_fdn(target: RoomTarget, delays: ndarray | Sequence[ndarray], *, rng: int = 0) -> list[tuple[DSS, dict]]

One network per decay slope of target, as (pyFDN.DSS, filters) pairs.

delays (samples) is one array for every slope or one per slope. Each network has a random orthogonal feedback matrix seeded rng + slope, the attenuation filters["post_delay"] following target.rt (geq_bands) and, as C, the lines' omnidirectional sum, 1 / sqrt(N) each, which the late envelope compares with its reference; the renderers project the lines themselves.

With several slopes the networks share their input, and filters["post_output"] weights each per band by level_k / sqrt(sum_j level_j ** 2), which keeps the slopes' level ratios and one network's initial energy; with one slope it is None. One network per slope is the package's choice; Kirsch et al. (2023, Sec. 2.1.2) superpose one network per room of two coupled rooms.

directional_delays
directional_delays(pair: Pair, directions: Coordinates, *, rng: int | Generator = 0) -> ndarray

Delay line lengths in samples, each the room's free path along its direction.

The room-dimension delays of Kirsch et al. (2021, Sec. VI.B; 2023, Sec. 3.3), taken per direction and for any closed geometry: a uniform field along u meets the boundary at the rate c sum_f A_f |n_f . u| / (2 V), so line i is 2 V / sum_f A_f |n_f . u_i| long, in a shoebox 1 / (|u_x| / L_x + |u_y| / L_y + |u_z| / L_z). The rates average over the sphere to c S / (4 V), the mean free path 4 V / S.

u and -u share a free path, so each length is jittered uniformly by up to 0.1 of it, drawn from rng, before the lengths are made coprime (_nearest_coprime), lest opposite lines ring together. The jitter and the coprime lengths are the package's choice; Wendt et al. (2014, Eq. 1) add up to 0.1 of the mean room dimension. directions are in the receiver's frame.

fdn_directions cached
fdn_directions(num_delays: int = MIN_DELAYS) -> Coordinates

The direction each delay line radiates from, an equal-area grid of num_delays points.

The one grid the image sources are routed onto, directional_delays reads the room along, the directional histogram bins the rays on, and the renderers project the lines from.

run_network
run_network(builds: Sequence[tuple[DSS, dict]], drive: ndarray, *, tap: ndarray | None = None, line_eq: ndarray | None = None) -> ndarray

Run the networks with one input per delay line; the lines' outputs, (n, num_delays), summed over the slopes.

drive (n, num_delays) enters line i in column i. line_eq, an SOS bank (n_sections, 6, num_delays), and the slope weights (post_output) filter each line after the feedback is taken, so they colour a line without changing its decay: the directional boundary absorption of Kirsch et al. (2023, Sec. 1.2). The ambisonic late field is the result times C.T.

tap (n, num_delays) enters each line skipping its delay (Ewert et al. 2025, Sec. 3.1.2): with f the attenuation filters, f(tap) is heard at once and A f(tap) enters the lines, which needs a static A. The scattered parts of compas_acoustics.hybrid.scattering enter there.

pair

One source-receiver pair of a scene, as the hybrid modules take it.

Classes

Pair dataclass
Pair(geometry: RoomGeometry, source: ndarray, receiver: ndarray, receiver_rotation: ndarray, fs: float, speed_of_sound: float, air_absorption: bool = True, air: Optional[AirConditions] = None)

A source and a receiver in a closed room, positions in metres.

The columns of receiver_rotation are the receiver's axes in room coordinates; air None is AirConditions().

Methods:
air_attenuation
air_attenuation() -> ndarray

Energy attenuation coefficient per metre on the band grid in the pair's air, zero without air absorption.

Functions:

scattering

Surface scattering of image sources.

After Ewert, Goessling, Buttler, van de Par and Hu, "Computationally-efficient rendering of diffuse reflections for geometrical acoustics based room simulation", Acta Acustica 9, 9 (2025). image_sources splits each image into a specular and a scattered part; here are the room that split needs (complementary_scattering), the scattered part's temporal spread (Eqs. 12-13) and its weights on the delay lines.

Functions:

allpass_delays
allpass_delays(decay_time: float, fs: float) -> ndarray

Delays in samples of the four-allpass cascade, Ewert et al. (2025, Eq. 13).

tau_s = T_s log10(1/g) / 3 and tau_i = tau_s fs / eta**(i-1), g = 1/sqrt(2), eta = pi, rounded, never below one sample.

complementary_scattering
complementary_scattering(geometry)

geometry with every material's scattering s replaced by 1 - s.

In a room built for ray tracing an image's damping takes sqrt(1 - s) at every wall of non-zero scattering it reflects off: the specular part, prod sqrt(1 - s_i). Built from this geometry it is the scattered part, prod sqrt(s_i). The two are power-complementary for a single reflection, as the decomposition filters of Ewert et al. (2025, Sec. 2.1.3) are. A material without coefficients scatters DEFAULT_SCATTERING.

scattering_decay_time
scattering_decay_time(distance: float, speed_of_sound: float) -> float

Local decay time T_s of an ideal diffuse reflection, in seconds.

Ewert et al. (2025, Sec. 2.1.2): T_s = 6 (10**(1/5) - 1) 2R / c, about 7 R / c, for a reflector at distance R; for a general room "the mean free path length".

scattering_weights
scattering_weights(doa: Coordinates, directions: Coordinates, opposite: bool = False) -> ndarray

Weights of each image on the delay lines of a hemisphere, shape (M, n_lines).

Ewert et al. (2025, Sec. 3.1.2) map a scattered part onto the "FDN channels on the same hemisphere" by a dot product (Sec. 2.1.2), and the last order's specular part onto "those FDN channels representing the spatially opposite hemisphere": w = clip(v . u, 0) / ||clip(v . u, 0)||_2, v the image's direction of arrival (-v with opposite) and u a line's, in one frame. The unit l2 norm weighs every image alike; an image with no line in its hemisphere has no weights.

smear
smear(signal: ndarray, decay_time: float, fs: float) -> ndarray

The surface-scattering allpass cascade along axis 0 of signal.

Four allpasses (g + z^-tau) / (1 + g z^-tau), g = 1/sqrt(2) (Ewert et al. 2025, Eq. 12), with the delays of allpass_delays.

synthesis

The format-neutral core of one pair's hybrid response: its early paths and delay lines (prepare).

A renderer, ambisonics or binaural, turns it into a response.

Classes

HybridCore dataclass
HybridCore(pair: Pair, n_samples: int, fs: float, max_order: int, target: RoomTarget, images: ImageSourceSet, diffraction_paths: tuple[DiffractionPath, ...], btms_contributions: tuple[BtmsContribution, ...], builds: list[tuple[DSS, dict]], lines: ndarray, line_directions: ndarray, late_envelope: ndarray | None, directional_envelope: DirectionalHistogram | None, drive_gain: float, driving_images: int)

The hybrid of one pair before it has a format: its early paths and its delay lines.

The renderer evaluates each early path once; the late envelope compares the lines with the omnidirectional early field, every renderer's first channel, so it is applied there (shaped_lines).

Methods:
shaped_lines
shaped_lines(early_w: ndarray) -> ndarray

The lines after the late envelope, given early_w, the omnidirectional (N3D W) early field.

HybridResult dataclass
HybridResult(core: HybridCore, rir: ndarray, early: ndarray, late: ndarray, late_lines: ndarray, normalization: str | None)

A rendered response of a HybridCore, in the renderer's format.

Functions:

prepare
prepare(pair: Pair, iss: ImageSourceSet, target: RoomTarget, *, max_order: int, duration_s: float, num_delays: int = MIN_DELAYS, directional_absorption: bool = True, late_envelope: ndarray | None = None, directional_envelope: DirectionalHistogram | None = None, diffraction: Literal['udfa', 'btms'] | None = None, rng: int = 0, scattering: bool = False) -> HybridCore

The format-neutral part of the hybrid for one pair: its early paths and its delay lines.

After Wendt et al. (2014) and Kirsch et al. (2021, 2023):

  1. Early field: the images of iss up to max_order and, with diffraction, the diffracted paths, kept path by path.
  2. Network: one delay line per direction of fdn_directions, as long as the room's free path along it (directional_delays), decaying at target.rt.
  3. Drive: the images of order max_order, each spread over the lines of the hemisphere opposite its arrival (scattering_weights with opposite; Ewert et al. 2025, Sec. 3.1.2) and scaled by sqrt(num_delays): the input "must equal the total energy of the Nth-order reflections" (Wendt et al. 2014, Sec. 1.3).
  4. With directional_absorption, each line is weighted with the reflection of the boundary in its direction (directional).

duration_s is the response length in seconds. rng seeds the delay jitter and the feedback matrices, rng + slope for each slope.

late_envelope, a package-scale omnidirectional reference, attenuates the lines per band to its late energy: the envelope of Vorlaender (2020, Sec. 11.9) imposed on the network's lines, the package's choice. directional_envelope, a DirectionalHistogram on the lines' directions in room coordinates, gives each band of them the rays' distribution (envelope). The renderer applies both (HybridCore.shaped_lines).

diffraction="udfa" (Kirsch and Ewert 2023) covers obstacles and room edges wider than pi (diffraction_edges), for the direct sound and, when max_order >= 1, one enclosure reflection before or after the edge. "btms" (Svensson et al. 1999) is first order with at most one wall reflection and second order between visible edges, direct paths only, and far slower. The late field is not affected.

scattering (Ewert et al. 2025, Sec. 3.1.2) needs iss.scattered; iss.gain is then the specular part. The scattered part of every image of orders 1 to max_order enters the lines of its own hemisphere skipping their delays (run_network's tap), through the allpass cascade of Eqs. 12-13 with R the mean free path, weighted as a driving image.

target

The decay the late field must reproduce.

Classes

RoomTarget dataclass
RoomTarget(rt: ndarray, bands: ndarray, fs: float, level: ndarray | None = None)

What the late field must reproduce: decay and spectral shape per band.

level is a relative spectral envelope that only weights the slopes of a multi-slope target against each other, so a single slope needs none; the late field's absolute level comes from the image sources driving the network.

Methods:
from_rir classmethod
from_rir(rir: ndarray, fs: float, *, n_slopes: int = 1, decay_db: float = 30.0) -> RoomTarget

Estimate the target from a reference impulse response.

n_slopes=1 fits one slope to the backward-integrated energy decay curve from -5 dB over decay_db (30: T30, 20: T20). The shorter range stays above the late tail, where a reference whose decay is carried by few long-lived rays is least repeatable. Any other n_slopes uses DecayFitNet (Goetz et al. 2022): 0 infers the count per band and keeps the slopes every band has, as coupled rooms need, and 2 or 3 force that many; decay_db is then ignored.

A forced count is returned even on a single-slope decay: the estimator cannot decline, so the caller must. Slopes are returned fastest first; slopes close in level are not resolved and come back near-identical.

from_room classmethod
from_room(pair: Pair, *, model: str = 'eyring') -> RoomTarget

A single-slope target predicted from geometry and materials.

model is that of predicted_rt. Air absorption follows pair.air_absorption, which keeps the decay and the image source gains consistent.

geq_bands
geq_bands(slope: int = 0) -> ndarray

One slope's RT on the ten-band attenuation grid: 31.25 Hz, the eight octaves, 16 kHz.

The outer bands are held to DC and Nyquist, the top one halved, where air and boundary absorption dominate (the package's choice).

Functions:

udfa

Edge diffraction by the universal diffraction filter approximation (UDFA).

Single wedges: Kirsch and Ewert (2023), "A universal filter approximation of edge diffraction for geometrical acoustics", IEEE/ACM Trans. Audio Speech Lang. Process. 31, 1636-1651. Three-sided barriers (DoubleEdgePath): Kirsch and Ewert (2024), "Filter-based first- and higher-order diffraction modeling for geometrical acoustics", Acta Acustica 8, 73, Sec. 3.3, with beta = 1 at all angles and no low-frequency gain compensation (both allowed at the end of Sec. 3.3.1; the compensation is in its Appendix); where the paper is silent the comments say "the package's choice". The barrier is defined for an infinite double edge; neither diffraction nor the simulation methods use it. Equations of the 2024 paper carry its year.

A wedge path carries exp(-j k d) / d * udfa_transfer(path, f) relative to a unit free field exp(-j k r) / r, d being WedgePath.d_constrained. The transfer function includes the factor 1/2 and the signs of Eq. (2): its incident term tends to +1/2 on the shadow side of the incident shadow boundary and to -1/2 on the lit side, making up the direct sound's unit step. Diffraction is therefore rendered on both sides of every boundary, and the geometric sound must be switched by the same geometry.

Classes

DoubleEdgePath dataclass
DoubleEdgePath(theta_w1: float, theta_w2: float, width: float, source: ndarray, receiver: ndarray, phi: float = pi / 2)

Source and receiver around a three-sided barrier, in its cross-section.

Edge 1 at (0, 0), edge 2 at (-width, 0), the face between them along y = 0 with the barrier below (Fig. 7). Side face 1 leaves edge 1 at angle pi - theta_w1, side face 2 leaves edge 2 at angle theta_w2. phi is the incidence angle on both edges (Fig. 1); cross-section distances divided by sin(phi) are path lengths.

RouteTerm dataclass
RouteTerm(length: float, last_edge: int, zone: str, transfer: Callable[[ndarray], ndarray])

One rendered contribution: pressure exp(-jkL)/L * transfer(f).

WedgePath dataclass
WedgePath(theta_w: float, theta_s: float, theta_r: float, r_s: float, r_r: float, z_s: float, z_r: float, length: float = inf)

Source, receiver and one rigid wedge in the wedge's cylindrical frame.

The edge runs along z from -length / 2 to +length / 2 (length = inf for an infinite wedge), Fig. 1. Azimuths are measured through the open region from the face nearer the source, so 0 <= theta_s <= theta_r <= theta_w; compas_acoustics.hybrid.diffraction.wedge_path builds this from Cartesian points.

Attributes
d_constrained property
d_constrained: float

Path length over the apex clamped onto the physical edge (Sec. VI).

Methods:
infinite classmethod
infinite(theta_w: float, theta_s: float, theta_r: float, d_s: float, d_r: float, phi: float) -> WedgePath

An infinite wedge from distances to the apex and the incidence angle.

Angles may come in either order; measuring from the other face swaps them, which leaves the diffracted field unchanged.

length_via
length_via(z: float) -> float

Path length from source to receiver through the edge point at z.

Functions:

double_edge_terms
double_edge_terms(path: DoubleEdgePath, *, c: float) -> list[RouteTerm]

2024, Eq. (11) as rendered terms, each with its own path length and last edge.

fractional_lowpass
fractional_lowpass(freq: ndarray, fc: float, blend: float = _B, q: float = _Q) -> ndarray

Eq. (6) with the paper's alpha = 1/2, b = blend = 1.44, Q = q = 0.2 and r = 1.6. fc = inf gives a flat response.

single_term_cutoff
single_term_cutoff(path: WedgePath, c: float, *, flat_outside_shadow: bool = True) -> float

Eq. (8): one low-pass with unit DC gain, matching Eq. (2) asymptotically.

Eq. (7) taken with each term's polarity, which is what Eq. (8) writes out. Outside the shadow zone the single filter is flat (Sec. II-B and Kirsch and Ewert 2024, Sec. 3.1) unless flat_outside_shadow is False, which the double-edge weighting (2024, Eq. (12)) needs.

term_parameters
term_parameters(path: WedgePath, c: float) -> tuple[ndarray, ndarray, ndarray]

Cutoff (Eq. (4)), gain (Eq. (3)) and polarity of the (+, -) terms of Eq. (2).

The polarity is the sign of N_nu (Eq. (5)), i.e. of cos(nu pi) - cos(nu theta). On [0, 2 theta_w - pi] that is Eq. (2)'s sign(theta - pi); beyond, in the reflection zone of the second face (Sec. II), it flips again, as the reflected sound from that face appears there. Eq. (2) as printed keeps sign(theta - pi) there; the flip is the package's reading.

udfa_single_transfer
udfa_single_transfer(path: WedgePath, freq: ndarray, *, c: float) -> ndarray

Eq. (8) as one filter with unit DC gain; on a finite wedge with the half wedges of Sec. III, as Sec. VII proposes ("including a DC gain"). Flat outside the shadow zone.

udfa_transfer
udfa_transfer(path: WedgePath, freq: ndarray, *, c: float) -> ndarray

Two-term UDFA, Eq. (2), with the finite-wedge forms of Sec. III.