API reference

The names most scripts need are also importable from the package itself: acoustic_spaces.Room, Scene, Source, Listener, Material and simulate.

Scenes and rooms

Scene model: what a simulation needs to know about a room.

class acoustic_spaces.scene.Air(*, temperature_c: Annotated[float, Ge(ge=-20.0), Le(le=50.0)] = 20.0, humidity_percent: Annotated[float, Ge(ge=0.0), Le(le=100.0)] = 50.0, pressure_kpa: Annotated[float, Gt(gt=0)] = 101.325)[source]
temperature_c: float
humidity_percent: float
pressure_kpa: float
class acoustic_spaces.scene.ArrayElement(*, position: tuple[float, float, float], orientation: ~acoustic_spaces.scene.model.Orientation = <factory>, gain_db: ~typing.Annotated[float, ~annotated_types.Ge(ge=-100.0), ~annotated_types.Le(le=60.0)] = 0.0, delay_ms: ~typing.Annotated[float, ~annotated_types.Ge(ge=0.0), ~annotated_types.Le(le=1000.0)] = 0.0, invert: bool = False)[source]

One loudspeaker or driver of a coherent array, in the array’s (the source’s) frame: x forward, y left, z up.

position: Vector3
orientation: Orientation
gain_db: float
delay_ms: float
invert: bool
class acoustic_spaces.scene.Atmosphere(*, preset: str | None = None, wind: Wind | None = None, temperature_gradient_k_m: Annotated[float, Ge(ge=-0.2), Le(le=0.2)] = 0.0, temperature_log_k: Annotated[float, Ge(ge=-5.0), Le(le=5.0)] = 0.0, roughness_m: Annotated[float, Le(le=2.0), Gt(gt=0)] = 0.05, table: list[tuple[float, float, float]] | None = None, turbulence: Turbulence | None = None, zones: list[WeatherZone] | None = None)[source]

How the speed of sound changes with height outdoors, which bends sound: the temperature (warmer air carries sound faster) and the wind (sound goes faster with it). Both vary with height only. The scene’s air temperature is the temperature at the ground. Heights are in metres above the ground. Eddies of both (turbulence) make the sound flicker.

preset: str | None
wind: Wind | None
temperature_gradient_k_m: float
temperature_log_k: float
roughness_m: PositiveFloat
table: list[tuple[float, float, float]] | None
turbulence: Turbulence | None
zones: list[WeatherZone] | None
zone_names() → list[str][source]

The weather zones’ names, weather_<n> for those without one.

weathers() → list[Atmosphere][source]

The atmosphere’s own weather (first) and each zone’s, as an atmosphere each, without zones or eddies: a zone’s preset gives it that weather whole, and its other fields replace the atmosphere’s (see WeatherZone).

under(given: WeatherClass) → Atmosphere[source]

This atmosphere in a weather class: the class’s weather over its own (see _WeatherOverride), the class’s eddies or its own, and its zones.

ground_temperatures(ground_c: float) → list[float][source]

The temperature at the ground (°C) under the atmosphere’s own weather (ground_c, the scene’s) and in each zone, in weathers() order.

to_wind() → ndarray[source]

(2,) the unit vector the wind blows along.

temperature(z, ground_c: float) → ndarray[source]

The temperature (°C) at heights z (m) above the ground, the ground’s being ground_c (a table gives its own).

wind_speed(z) → ndarray[source]

The wind’s speed (m/s) at heights z (m) above the ground.

sound_speed(z, ground_c: float, towards=None) → ndarray[source]

The speed of sound (m/s) at heights z (m) above the ground: in still air, or the effective speed along the horizontal direction towards (2,), the wind’s component along it added.

property still: bool

Whether sound goes in straight lines: no wind and one temperature, over the whole scene (the zones too).

class acoustic_spaces.scene.ArraySpec(*, element: Literal['omni', 'subcardioid', 'cardioid', 'supercardioid', 'hypercardioid', 'figure8'] | Literal['lambert'] | DirectivitySpec = 'omni', elements: list[ArrayElement] | None = None, count: Annotated[int | None, Ge(ge=2), Le(le=256)] = None, spacing_m: Annotated[float, Gt(gt=0)] | None = None, steer_deg: Annotated[float, Ge(ge=-90.0), Le(le=90.0)] = 0.0)[source]

A coherent array: elements fed the same signal, each with its own gain, delay and polarity, whose sound adds up with its phase. Either elements one by one, or a straight column of count elements spacing_m apart along the up axis, centred on the source’s position.

element: PatternName | Literal['lambert'] | DirectivitySpec
elements: list[ArrayElement] | None
count: int | None
spacing_m: PositiveFloat | None
steer_deg: float
layout() → list[ArrayElement][source]

The elements, a column’s laid out.

class acoustic_spaces.scene.Barrier(*, name: str | None = None, path: Annotated[list[tuple[float, float]], MinLen(min_length=2)], height: Annotated[float, Gt(gt=0)])[source]

A thin screen standing on the ground along a path (surfaces <name> and barriers).

name: str | None
path: list[tuple[float, float]]
height: PositiveFloat
class acoustic_spaces.scene.BlumleinPair(*, pair: Literal['blumlein'])[source]

Two figure-eights in one place, aimed 45 degrees to each side.

pair: Literal['blumlein']
class acoustic_spaces.scene.Building(*, name: str | None = None, footprint: Annotated[list[tuple[float, float]], MinLen(min_length=3)], height: Annotated[float, Gt(gt=0)])[source]

A building standing on the ground: its footprint raised to a height (surfaces <name>_wall_1…, <name>_walls, <name>_roof, and walls, roofs and buildings for all of them).

name: str | None
footprint: list[tuple[float, float]]
height: PositiveFloat
class acoustic_spaces.scene.BuildingFile(*, file: Path, height: str | Annotated[float, Gt(gt=0)] = 'height', default_height: Annotated[float, Gt(gt=0)] | None = None, name: str = 'name', without: list[str] | None = None)[source]

Buildings from a map: a GeoJSON file whose Polygon and MultiPolygon features are footprints (see acoustic_spaces.geometry.terrain), each raised to the height a property gives. Its coordinates are in the geometry’s units on a plane (not longitude and latitude), and ground.map_origin is subtracted from them.

file: Path
height: str | PositiveFloat
default_height: PositiveFloat | None
name: str
without: list[str] | None
class acoustic_spaces.scene.Coverage(*, surfaces: list[str] | None = None, height: Annotated[float, Gt(gt=0)] = 1.2, spacing: Annotated[float, Gt(gt=0)] = 1.0, rays: Annotated[int | None, Ge(ge=1)] = None, noise_db: list[float] | float | None = None, spread: bool = False)[source]

A coverage map: room parameters on a grid over the audience area (see acoustic_spaces.engine.coverage).

surfaces: list[str] | None
height: float
spacing: float
rays: int | None
noise_db: list[float] | float | None
spread: bool
class acoustic_spaces.scene.DirectivitySpec(*, pattern: list[Literal['omni', 'subcardioid', 'cardioid', 'supercardioid', 'hypercardioid', 'figure8'] | Annotated[float, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=0.0), Le(le=1.0)])]] | None = None, file: Path | None = None, array: ArraySpec | None = None, measurement: Annotated[int | None, Ge(ge=0)] = None, near_field: bool | None = None)[source]

A source’s directivity per octave band: first-order patterns (a name, or the a of a + (1 - a) cos(theta), for each band), a measured balloon from a SOFA file or a CSV table, or the far-field pattern of a coherent array, given here or in a YAML file (see acoustic_spaces.directivity).

pattern: list[PatternName | Coefficient] | None
file: Path | None
array: ArraySpec | None
measurement: int | None
near_field: bool | None
class acoustic_spaces.scene.Foliage(*, preset: Literal['dense', 'none'] | None = None, attenuation: list[Annotated[float, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=0.0), Le(le=10.0)])]] | None = None, leaf_area_per_m3: Annotated[Annotated[float, Gt(gt=0)] | None, Le(le=50.0)] = None, leaf_width: Annotated[Annotated[float, Gt(gt=0)] | None, Le(le=1.0)] = None, albedo: Annotated[float, Ge(ge=0.0), Le(le=1.0)] = 0.0, asymmetry: Annotated[float, Ge(ge=-0.9), Le(le=0.9)] = 0.0)[source]

What the leaves and twigs of a vegetation volume take from sound passing through it, per metre: a preset, an attenuation per band, or the leaves themselves, their area per cubic metre and their width, from which the engine works out what they scatter and absorb in each band. albedo is the share of an attenuation that they scatter on, the rest they absorb; asymmetry how far forward they scatter it (the mean cosine of the angle, as in a Henyey-Greenstein phase function); leaves given by their size and density work both out for themselves.

preset: Literal['dense', 'none'] | None
attenuation: list[Annotated[float, Field(ge=0.0, le=10.0)]] | None
leaf_area_per_m3: PositiveFloat | None
leaf_width: PositiveFloat | None
albedo: Coefficient
asymmetry: float
property bare: bool

Whether there is no foliage.

attenuation_db(resolution: Literal['octave', 'third_octave'] = 'octave', speed_of_sound: float = 343.0) → ndarray[source]

dB per metre in each band at resolution: what the foliage takes in all, scattered on or absorbed; leaves given by their area and width take it for sound at speed_of_sound (m/s).

describe() → str[source]
class acoustic_spaces.scene.Geometry(*, file: Path | None = None, box: tuple[Annotated[float, Gt(gt=0)], Annotated[float, Gt(gt=0)], Annotated[float, Gt(gt=0)]] | None = None, floor_plan: Annotated[list[tuple[float, float]] | None, MinLen(min_length=3)] = None, height: Annotated[float, Gt(gt=0)] | None = None, units: Literal['m', 'cm', 'mm', 'in', 'ft'] | None = None, up_axis: Literal['y', 'z'] | None = None, space: str | None = None, ground: Ground | None = None, buildings: list[Building] | None = None, buildings_file: BuildingFile | None = None, barriers: list[Barrier] | None = None, vegetation: list[Vegetation] | None = None)[source]

The room’s surfaces: a CAD file, or a box or extruded floor plan built from dimensions (surfaces floor, ceiling, walls and wall_1, wall_2…).

Outdoors, ground lays flat ground under an open sky, with buildings and barriers built on it and, from file, any other objects standing on it. vegetation adds trees, hedges and belts of them, which are no surfaces: sound passes through them, losing some of itself.

file: Path | None
box: tuple[PositiveFloat, PositiveFloat, PositiveFloat] | None
floor_plan: list[tuple[float, float]] | None
height: PositiveFloat | None
units: Literal['m', 'cm', 'mm', 'in', 'ft'] | None
up_axis: Literal['y', 'z'] | None
space: str | None
ground: Ground | None
buildings: list[Building] | None
buildings_file: BuildingFile | None
barriers: list[Barrier] | None
vegetation: list[Vegetation] | None
building_names() → list[str][source]

The buildings’ names, building_<n> for those without one: the scene’s own buildings, then the buildings file’s.

all_buildings() → list[Building][source]

The scene’s own buildings, then those of buildings_file, every one named (building_<n> for those without a name).

file_buildings(first: int = 0, all: bool = False) → list[Building][source]

The buildings of buildings_file as Building objects, in the geometry’s units with ground.map_origin subtracted, named building_<n> from first + 1 where the file gives no name, and those in without left out (kept with all).

footprint_notes() → list[str][source]

What is worth knowing about the buildings file: footprints with holes, which are built over.

barrier_names() → list[str][source]

The barriers’ names, barrier_<n> for those without one.

vegetation_names() → list[str][source]

The vegetation’s names, vegetation_<n> for those without one.

part_names() → list[str][source]

The names of an outdoor scene’s buildings, barriers and vegetation, in turn: what an insertion loss can be given for (simulation.insertion_loss_of).

describe() → str[source]
class acoustic_spaces.scene.Ground(*, height: float = 0.0, terrain: Terrain | None = None, map_origin: tuple[float, float] | None = None, extent: tuple[tuple[float, float], tuple[float, float]] | None = None, margin: Annotated[float, Gt(gt=0)] = 30.0, sky: Annotated[float, Gt(gt=0)] | None = None, zones: list[GroundZone] | None = None)[source]

Flat ground under an open sky, or a terrain, which makes the scene an outdoor one (see acoustic_spaces.geometry.outdoor). Lengths are in the geometry’s units.

height: float
terrain: Terrain | None
map_origin: tuple[float, float] | None
extent: tuple[tuple[float, float], tuple[float, float]] | None
margin: PositiveFloat
sky: PositiveFloat | None
zones: list[GroundZone] | None
zone_names() → list[str][source]

The zones’ names, zone_<n> for those without one.

height_grid()[source]

The terrain as a HeightGrid in the geometry’s units, map_origin subtracted and height not yet added; None for flat ground.

class acoustic_spaces.scene.GroundZone(*, name: str | None = None, polygon: Annotated[list[tuple[float, float]], MinLen(min_length=3)])[source]

A part of the ground with a material of its own (a road through a field, a lawn, a pond): a polygon on the ground, its surfaces <name>, zones and ground (an assignment to the zone’s name wins over one to ground). The part of it past the ground’s edge is left out.

name: str | None
polygon: list[tuple[float, float]]
class acoustic_spaces.scene.Impedance(*, preset: str | None = None, model: Literal['miki', 'delany_bazley', 'two_parameter'] = 'miki', flow_resistivity: Annotated[float, Gt(gt=0)] | None = None, porosity_rate: Annotated[float | None, Ge(ge=0.0)] = None, thickness: Annotated[float, Gt(gt=0)] | None = None, reaction: Literal['local', 'extended'] | None = None)[source]

The acoustic impedance of a porous ground (grass, soil, snow, gravel, asphalt), from its flow resistivity by an empirical model (see acoustic_spaces.materials.ground): a preset, one of the ground classes of Nord2000, or a flow_resistivity; with a thickness, a layer of it on a hard backing.

A material with an impedance takes its absorption from it, and reflects sound as a ground does: the spherical wave’s reflection (Weyl-van der Pol), with its phase and the ground wave near grazing incidence, in place of the absorption.

preset: str | None
model: Literal['miki', 'delany_bazley', 'two_parameter']
flow_resistivity: PositiveFloat | None
porosity_rate: float | None
thickness: PositiveFloat | None
reaction: Literal['local', 'extended'] | None
property resistivity: float

The flow resistivity (kPa s/m²), the preset’s when a preset is given.

property extended: bool

Whether the impedance changes with the angle of incidence.

admittance(f, speed_of_sound: float = 343.0, cosine=None) → ndarray[source]

The normalised admittance (1 / impedance) at frequencies f (Hz), in the engine’s sign convention, e^(jωt): with the extended reaction, the one met at the incidence cosine (broadcasting with f; 1 by default, normal incidence); with the local, the same at every angle.

describe() → str[source]

In a few words: the preset or the flow resistivity, and the rest.

class acoustic_spaces.scene.Keyframe(*, time_s: Annotated[float, Gt(gt=0)], position: tuple[float, float, float], orientation: Orientation | None = None)[source]

Where a listener or a source is at one moment of its movement, and how it faces (Walk, keyframes).

time_s: PositiveFloat
position: Vector3
orientation: Orientation | None
class acoustic_spaces.scene.Listener(*, name: str, group: str | None = None, enabled: bool | None = None, position: tuple[float, float, float], orientation: ~acoustic_spaces.scene.model.Orientation = <factory>, walk: ~acoustic_spaces.scene.model.Walk | None = None, pattern: ~typing.Literal['omni', 'subcardioid', 'cardioid', 'supercardioid', 'hypercardioid', 'figure8'] | list[~typing.Literal['omni', 'subcardioid', 'cardioid', 'supercardioid', 'hypercardioid', 'figure8'] | ~typing.Annotated[float, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=0.0), Le(le=1.0)])]] | ~typing.Annotated[~acoustic_spaces.scene.model.XYPair | ~acoustic_spaces.scene.model.BlumleinPair | ~acoustic_spaces.scene.model.MSPair, FieldInfo(annotation=NoneType, required=True, discriminator='pair')] | None = None)[source]
name: str
group: str | None
enabled: bool | None
position: Vector3
orientation: Orientation
walk: Walk | None
pattern: CapsulePattern | MicrophonePair | None
property in_use: bool

Whether simulations and maps take it: not left out (enabled: false).

class acoustic_spaces.scene.MSPair(*, pair: Literal['ms'], mid: Literal['omni', 'subcardioid', 'cardioid', 'supercardioid', 'hypercardioid', 'figure8'] | list[Literal['omni', 'subcardioid', 'cardioid', 'supercardioid', 'hypercardioid', 'figure8'] | Annotated[float, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=0.0), Le(le=1.0)])]] = 'cardioid', side_db: Annotated[float, Ge(ge=-40.0), Le(le=20.0)] = 0.0)[source]

A mid capsule aimed forward and a figure-eight aimed left, decoded to left and right.

pair: Literal['ms']
mid: CapsulePattern
side_db: float
class acoustic_spaces.scene.Material(*, preset: str | None = None, file: Path | None = None, entry: str | int | None = None, absorption: list[Annotated[float, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=0.0), Le(le=1.0)])]] | None = None, scattering: list[Annotated[float, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=0.0), Le(le=1.0)])]] | Annotated[float, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=0.0), Le(le=1.0)])] | str | None = None, transmission: list[Annotated[float, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=0.0), Le(le=1.0)])]] | Annotated[float, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=0.0), Le(le=1.0)])] | None = None, transmission_loss: list[float] | float | None = None, audience: bool = False, impedance: Impedance | None = None, source: str | None = None, uncertainty: AbsorptionUncertainty | None = None)[source]

Random-incidence absorption and scattering per octave or third-octave band, and the share of sound that passes through.

Coefficients come from, in order of precedence: values given here (8 per octave band or 24 per third-octave band), a coefficient file (file), or a built-in database entry (preset). The file may also be a material library of CATT-Acoustic or ODEON, with entry naming the material in it (see acoustic_spaces.materials.libraries). scattering may also name a scattering entry of the built-in database; a material that gives none scatters DEFAULT_SCATTERING in every band, and GROUND_SCATTERING, nothing, where it has an impedance. Data at other frequencies is mapped onto third-octave bands when it has more than one value in some octave band, else onto octave bands; bands without data take the nearest band’s value, and source says which ones. coefficients() gives both lists in the bands a simulation runs in.

transmission (a share from 0 to 1) or transmission_loss (the sound reduction index R in dB, the transmission being 10^(-R/10)) makes a surface let sound through: a partition between two rooms, a door, or with a transmission of 1 an opening. What passes through counts as absorbed on the side it comes from, so the absorption must be at least the transmission in every band; without absorption values, a preset or a file, the absorption is the transmission (an opening absorbs 1, a heavy wall no more than it lets through). transmission_coefficients() gives it in the bands a simulation runs in.

preset: str | None
file: Path | None
entry: str | int | None
absorption: list[Coefficient] | None
scattering: list[Coefficient] | Coefficient | str | None
transmission: list[Coefficient] | Coefficient | None
transmission_loss: list[float] | float | None
audience: bool
impedance: Impedance | None
source: str | None
uncertainty: AbsorptionUncertainty | None
property clipped: list[str]

What of the coefficients taken from a preset or file lay outside 0 to 1 and was taken as 0 or 1: one note each for the absorption and the scattering.

property builtin: bool

Whether the absorption is a built-in database entry’s (preset, with no other absorption values given): the database does not name where its values come from, so a spread takes simulation.uncertainty.presets for it. By value: a copy with other absorption is not.

coefficients(bands: Literal['octave', 'third_octave'] = 'octave') → tuple[list[float], list[float]][source]

Absorption and scattering in octave or third-octave bands: an octave value holds for its three third octaves, and an octave takes the mean of its three.

transmission_coefficients(bands: Literal['octave', 'third_octave'] = 'octave') → list[float] | None[source]

The share of sound that passes through, in octave or third-octave bands (converted as coefficients() does), or None for a surface that lets nothing through.

to_data() → dict[source]

The material as scene data, as Scene.to_data() writes it: its absorption, scattering and source only where they are not what the rest of the entry gives (a preset, a file and entry, an impedance, a transmission, a scattering entry, written by its name, or the default scattering), so that the entry read again has the same values, and with another preset, file or entry the values of that.

model_post_init(context: Any, /) → None

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Args:

self: The BaseModel instance. context: The context.

class acoustic_spaces.scene.Orientation(*, yaw: float = 0.0, pitch: float = 0.0, roll: float = 0.0)[source]

Yaw, pitch and roll in degrees; all zero looks down +x with +z up.

Yaw turns left (from +x towards +y), pitch looks up, and roll tilts the head to the right (the left ear goes up), applied in the order roll, pitch, yaw.

yaw: float
pitch: float
roll: float
forward() → tuple[float, float, float][source]

Unit vector of the look direction: yaw turns from +x towards +y, pitch up.

rotation() → list[list[float]][source]

3 x 3 matrix whose columns are the forward, left and up axes in room coordinates; it turns head coordinates (x forward, y left, z up) into room ones.

class acoustic_spaces.scene.Output(*, format: Literal['mono', 'binaural', 'ambisonics', 'loudspeakers'], order: Annotated[int, Ge(ge=0), Le(le=7)] = 1, hrtf: Path | None = None, layout: str | None = None, speakers: list[Speaker] | None = None)[source]

A format every response is rendered in: mono, binaural, ambisonics (AmbiX) or loudspeakers. A bare name stands for the format with its defaults.

format: Literal['mono', 'binaural', 'ambisonics', 'loudspeakers']
order: int
hrtf: Path | None
layout: str | None
speakers: list[Speaker] | None
class acoustic_spaces.scene.Scene(*, name: str = 'untitled', geometry: ~acoustic_spaces.scene.model.Geometry, materials: ~typing.Annotated[dict[str, ~acoustic_spaces.scene.model.Material], ~annotated_types.MinLen(min_length=1)], assignments: dict[str, str] = <factory>, default_material: str | None = None, recording: ~pathlib.Path | str | None = None, sources: ~typing.Annotated[list[~acoustic_spaces.scene.model.Source], ~annotated_types.MinLen(min_length=1)], listeners: ~typing.Annotated[list[~acoustic_spaces.scene.model.Listener], ~annotated_types.MinLen(min_length=1)], air: ~acoustic_spaces.scene.model.Air = <factory>, atmosphere: ~acoustic_spaces.scene.model.Atmosphere | None = None, simulation: ~acoustic_spaces.scene.model.Simulation = <factory>, outputs: list[~acoustic_spaces.scene.model.Output] = <factory>, coverage: ~acoustic_spaces.scene.model.Coverage | None = None, long_term: ~acoustic_spaces.scene.model.LongTerm | None = None)[source]
name: str
geometry: Geometry
materials: dict[str, Material]
assignments: dict[str, str]
default_material: str | None
recording: Path | str | None
sources: list[Source]
listeners: list[Listener]
air: Air
atmosphere: Atmosphere | None
simulation: Simulation
outputs: list[Output]
coverage: Coverage | None
long_term: LongTerm | None
property recording_file: Path | None

The scene’s recording when it is a file of its own (not a free one), or None.

level_inputs(source: str) → tuple[ndarray | float, list[float] | float | None, Literal['male', 'female']][source]

(sound power, noise, talker) that the levels and the speech results of the source named source are found with at a listener: its sound power per octave band (dB re 1 pW, Source.power_db()) and its talker, 94 dB in all and a male talker for a source the scene does not have; and the background noise of coverage (dB SPL, in all bands or per octave band), None without.

property still: bool

Whether sound goes in straight lines in every run of the scene: in its own weather (Atmosphere.still, the zones too) and in each weather class of long_term (Atmosphere.under()).

under(given: WeatherClass) → Scene[source]

This outdoor scene in a weather class: its atmosphere under the class’s weather (Atmosphere.under()), the air at the class’s ground temperature when it gives one, and without long_term.

without(names: Sequence[str]) → Scene[source]

This outdoor scene without the buildings, barriers and vegetation of these names (see Geometry.part_names()), and without insertion_loss_of.

classmethod from_yaml(path: str | Path) → Scene[source]

Load a scene file; relative paths in it are resolved against its folder.

to_data() → dict[source]

The scene as plain YAML data, dicts and lists. Settings left unset are left out, apart from those whose null is not their default, and so are a material’s coefficients and source where its preset, file or other settings give them (Material.to_data()).

yaml_text(file_name: Callable[[str], str], *, readable: bool = False) → str[source]

The scene file’s text, with each file it names written as file_name(file). readable writes each list of numbers or names on one line in brackets and letters outside ASCII as they are, as the example scenes do; the data are the same.

file_text(folder: str | Path, *, readable: bool = False) → str[source]

The text of the scene’s file in folder: paths to files under it relative to it, so the folder can move, others absolute (readable as in yaml_text()).

to_yaml(path: str | Path) → None[source]

Write the scene file (file_text() for its folder).

files() → list[Path][source]

The files the scene uses, each once: its model, terrain and map of buildings, material tables, source directivities (with the files a coherent array names for its element, in the scene or in its YAML file), the sources’ signals, the scene’s recording when it is a file, and HRTFs.

class acoustic_spaces.scene.Source(*, name: str, group: str | None = None, enabled: bool | None = None, position: tuple[float, float, float], orientation: ~acoustic_spaces.scene.model.Orientation = <factory>, directivity: ~typing.Literal['omni', 'subcardioid', 'cardioid', 'supercardioid', 'hypercardioid', 'figure8'] | ~typing.Literal['lambert'] | ~acoustic_spaces.scene.model.DirectivitySpec = 'omni', line_m: ~typing.Annotated[float, ~annotated_types.Gt(gt=0)] | None = None, surface_m: tuple[~typing.Annotated[float, ~annotated_types.Gt(gt=0)], ~typing.Annotated[float, ~annotated_types.Gt(gt=0)]] | None = None, spacing_m: ~typing.Annotated[float, ~annotated_types.Gt(gt=0)] = 0.5, level_db: float | list[float] = 94.0, spectrum: ~typing.Literal['flat', 'speech_male', 'speech_female'] = 'flat', gain_db: ~typing.Annotated[float, ~annotated_types.Ge(ge=-100.0), ~annotated_types.Le(le=60.0)] = 0.0, eq_db: list[~typing.Annotated[float, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=-100.0), Le(le=60.0)])]] | None = None, delay_ms: ~typing.Annotated[float, ~annotated_types.Ge(ge=0.0), ~annotated_types.Le(le=10000.0)] = 0.0, walk: ~acoustic_spaces.scene.model.Walk | None = None, signal: ~pathlib.Path | None = None, channel: ~typing.Literal['left', 'right', 'mono'] | None = None)[source]
name: str
group: str | None
enabled: bool | None
position: Vector3
orientation: Orientation
directivity: PatternName | Literal['lambert'] | DirectivitySpec
line_m: PositiveFloat | None
surface_m: tuple[PositiveFloat, PositiveFloat] | None
spacing_m: PositiveFloat
level_db: float | list[float]
spectrum: Literal['flat', 'speech_male', 'speech_female']
gain_db: float
eq_db: list[Annotated[float, Field(ge=-100.0, le=60.0)]] | None
delay_ms: float
walk: Walk | None
signal: Path | None
channel: Literal['left', 'right', 'mono'] | None
property in_use: bool

Whether simulations and maps take it: not left out (enabled: false).

property extended: bool

Whether the source is a line or a surface rather than a point.

elements() → ndarray[source]

Positions (n, 3) of the point sources that make up the source: its position alone for a point source; along a line or over a surface evenly spaced, each in the middle of an equal share of it.

outline() → ndarray[source]

Corners (n, 3) of the source’s extent: a line’s two ends, a surface’s four corners in turn, or a point source’s position alone.

property talker: Literal['male', 'female']

The speech the STI weights for: female for speech_female, else male.

feed_db(bands: Literal['octave', 'third_octave'] = 'octave') → ndarray[source]

The gain of the feed per band (dB): gain_db and eq_db together.

property sound_power_db: float

Sound power level in all (dB re 1 pW) that level_db gives, summed over its bands when given per band, without the feed’s gain.

power_db(bands: Literal['octave', 'third_octave'] = 'octave') → ndarray[source]

Sound power level per band (dB re 1 pW), the feed’s gain included: an octave’s power is split evenly between its third octaves.

class acoustic_spaces.scene.Speaker(*, name: str, azimuth: float, elevation: Annotated[float, Ge(ge=-90.0), Le(le=90.0)] = 0.0, lfe: bool = False)[source]
name: str
azimuth: float
elevation: float
lfe: bool
class acoustic_spaces.scene.Stems(*, per_m2: Annotated[float, Le(le=100.0), Gt(gt=0)], diameter: Annotated[float, Le(le=5.0), Gt(gt=0)])[source]

The trunks and stems of a vegetation volume: upright rigid cylinders, which scatter sound sideways, all of it (Bullen and Fricke 1982).

per_m2: PositiveFloat
diameter: PositiveFloat
class acoustic_spaces.scene.Terrain(*, file: Path | None = None, heights: list[list[float]] | None = None, origin: tuple[float, float] = (0.0, 0.0), spacing: Annotated[float, Gt(gt=0)] | None = None)[source]

Uneven ground: its heights on a square grid, from a file or given here (see acoustic_spaces.geometry.terrain). Between the grid’s nodes the ground is bilinear, past its edge it goes on at the height of the edge, and the scene’s ground is the grid sampled over the ground’s extent, so the extent must lie inside the grid. Lengths are in the geometry’s units.

file: Path | None
heights: list[list[float]] | None
origin: tuple[float, float]
spacing: PositiveFloat | None
class acoustic_spaces.scene.Turbulence(*, preset: str | None = None, temperature_structure: Annotated[float, Ge(ge=0.0), Le(le=10.0)] = 0.0, wind_structure: Annotated[float, Ge(ge=0.0), Le(le=10.0)] = 0.0, outer_scale_m: Annotated[float, Le(le=1000.0), Gt(gt=0)] = 10.0, height_m: Annotated[Annotated[float, Gt(gt=0)] | None, Le(le=100.0)] = None, falloff: Annotated[float, Ge(ge=0.0), Le(le=2.0)] = 0.6666666666666666)[source]

The eddies of the wind and of the temperature, which make sound outdoors flicker: the paths of one sound that take different ways stop adding in step (the ground dip fills in), and sound is scattered into shadow zones. Their strength is given by the structure parameters of the temperature and of the wind, C_T² and C_v², with a von Kármán spectrum whose largest eddies are outer_scale_m across.

preset: str | None
temperature_structure: float
wind_structure: float
outer_scale_m: PositiveFloat
height_m: PositiveFloat | None
falloff: float
property calm: bool

Whether there are no eddies at all.

class acoustic_spaces.scene.Vegetation(*, name: str | None = None, footprint: ~typing.Annotated[list[tuple[float, float]] | None, ~annotated_types.MinLen(min_length=3)] = None, path: ~typing.Annotated[list[tuple[float, float]] | None, ~annotated_types.MinLen(min_length=2)] = None, width: ~typing.Annotated[float, ~annotated_types.Gt(gt=0)] | None = None, tree: tuple[float, float] | None = None, crown_diameter: ~typing.Annotated[float, ~annotated_types.Gt(gt=0)] | None = None, height: ~typing.Annotated[float, ~annotated_types.Gt(gt=0)], base: ~typing.Annotated[float, ~annotated_types.Ge(ge=0)] = 0.0, foliage: ~acoustic_spaces.scene.model.Foliage = <factory>, stems: ~acoustic_spaces.scene.model.Stems | None = None)[source]

Plants standing on the ground outdoors: a volume through which sound loses some of itself, scattered on or absorbed. Its shape is one of a footprint raised from base to height (a tree belt, a wood), a path of a width (a hedge), or a lone tree’s crown over tree: a spheroid crown_diameter across from base to height. Lengths and heights are in the geometry’s units, over the ground; foliage and stems say what fills it.

name: str | None
footprint: list[tuple[float, float]] | None
path: list[tuple[float, float]] | None
width: PositiveFloat | None
tree: tuple[float, float] | None
crown_diameter: PositiveFloat | None
height: PositiveFloat
base: float
foliage: Foliage
stems: Stems | None
property kind: Literal['belt', 'hedge', 'tree']

belt (a footprint), hedge (a path) or tree.

describe() → str[source]

What fills it, as text: its foliage and stems.

class acoustic_spaces.scene.Walk(*, enabled: bool = True, to: list[tuple[float, float, float]]=<factory>, keyframes: Keyframe] | None, ~annotated_types.MinLen(min_length=1)] = None, speed_m_s: Annotated[float, ~annotated_types.Gt(gt=0)] = 1.2, face_forward: bool = True, turn_deg_s: Annotated[float, ~annotated_types.Gt(gt=0)] = 90.0, doppler: bool = False)[source]

A path a listener or a point source walks along, for a walkthrough (acoustic_spaces.walkthrough): from its position through to at speed_m_s, or through keyframes, each timed.

enabled: bool
to: list[Vector3]
keyframes: list[Keyframe] | None
speed_m_s: PositiveFloat
face_forward: bool
turn_deg_s: PositiveFloat
doppler: bool
class acoustic_spaces.scene.LongTerm(*, periods: Annotated[list[Period] | None, MinLen(min_length=1)] = None, classes: Annotated[list[WeatherClass], MinLen(min_length=1)])[source]

The levels over a long term, outdoors: the weather changes from day to day, and the level over a year is the energy mean of the levels in each weather, weighted by the share of the time it holds (ISO 1996-2, CNOSSOS-EU, Nord2000). The scene is run once in each weather class, and the results give the level in each class, in each period of the day (the classes’ levels, each by its share in that period) and the rating level over the day (the periods’ levels, each by its hours, with its penalty: L_den with the default periods).

periods: list[Period] | None
classes: list[WeatherClass]
class_names() → list[str][source]

The classes’ names, class_<n> for those without one.

period_list() → list[Period][source]

The periods of the day, L_den’s when none are given.

period_names() → list[str][source]
shares() → ndarray[source]

(classes, periods) the share of each period’s time each class holds; a class that gives no share for a period, in a mapping, holds none of it.

hours() → ndarray[source]

(periods,) how many hours a day each period lasts.

penalties() → ndarray[source]

(periods,) the penalty added to each period’s level in the rating (dB).

class acoustic_spaces.scene.Period(*, name: Annotated[str, MinLen(min_length=1)], hours: Annotated[float, Le(le=24.0), Gt(gt=0)], penalty_db: Annotated[float, Ge(ge=0.0), Le(le=20.0)] = 0.0)[source]

A part of the day the rating level over a long term is taken over: its hours and the penalty added to its level in the rating (5 dB in the evening and 10 dB at night for L_den).

name: str
hours: PositiveFloat
penalty_db: float
class acoustic_spaces.scene.WeatherClass(*, name: str | None = None, preset: str | None = None, wind: ZoneWind | None = None, temperature_gradient_k_m: Annotated[float | None, Ge(ge=-0.2), Le(le=0.2)] = None, temperature_log_k: Annotated[float | None, Ge(ge=-5.0), Le(le=5.0)] = None, roughness_m: Annotated[Annotated[float, Gt(gt=0)] | None, Le(le=2.0)] = None, table: list[tuple[float, float, float]] | None = None, temperature_c: Annotated[float | None, Ge(ge=-20.0), Le(le=50.0)] = None, share: float | dict[str, float], turbulence: Turbulence | None = None)[source]

A weather that holds for a share of the time, for the levels over a long term (LongTerm): downwind, upwind, a clear night’s inversion… Its weather is given over the scene’s atmosphere’s (see _WeatherOverride), the eddies too, and the scene’s weather zones hold in every class.

name: str | None
share: float | dict[str, float]
turbulence: Turbulence | None
class acoustic_spaces.scene.WeatherZone(*, name: str | None = None, preset: str | None = None, wind: ZoneWind | None = None, temperature_gradient_k_m: Annotated[float | None, Ge(ge=-0.2), Le(le=0.2)] = None, temperature_log_k: Annotated[float | None, Ge(ge=-5.0), Le(le=5.0)] = None, roughness_m: Annotated[Annotated[float, Gt(gt=0)] | None, Le(le=2.0)] = None, table: list[tuple[float, float, float]] | None = None, temperature_c: Annotated[float | None, Ge(ge=-20.0), Le(le=50.0)] = None, polygon: Annotated[list[tuple[float, float]], MinLen(min_length=3)])[source]

A part of the scene over which the weather differs: the wind slowed in the lee of buildings or over a wood, a sea breeze over the water, an inversion over a lake. A polygon on the ground, in the geometry’s units; where zones overlap the first wins, and outside every zone the atmosphere’s own weather holds. Its weather is given over the atmosphere’s (see _WeatherOverride); the eddies are the atmosphere’s.

name: str | None
polygon: list[tuple[float, float]]
class acoustic_spaces.scene.Wind(*, speed_m_s: Annotated[float, Ge(ge=0.0), Le(le=40.0)] = 0.0, direction_deg: float = 0.0, height_m: Annotated[float, Gt(gt=0)] = 10.0, profile: Literal['log', 'linear', 'constant'] = 'log')[source]

The wind over the ground: its speed at a height, the way it blows, and how the speed grows with height.

speed_m_s: float
direction_deg: float
height_m: PositiveFloat
profile: Literal['log', 'linear', 'constant']
class acoustic_spaces.scene.XYPair(*, pair: Literal['xy'], angle_deg: Annotated[float, Gt(gt=0.0), Le(le=180.0)] = 90.0, capsule: Literal['omni', 'subcardioid', 'cardioid', 'supercardioid', 'hypercardioid', 'figure8'] | list[Literal['omni', 'subcardioid', 'cardioid', 'supercardioid', 'hypercardioid', 'figure8'] | Annotated[float, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=0.0), Le(le=1.0)])]] = 'cardioid')[source]

Two capsules of one pattern in one place, aimed apart in the horizontal plane.

pair: Literal['xy']
angle_deg: float
capsule: CapsulePattern
class acoustic_spaces.scene.ZoneWind(*, speed_m_s: Annotated[float | None, Ge(ge=0.0), Le(le=40.0)] = None, direction_deg: float | None = None, height_m: Annotated[float, Gt(gt=0)] | None = None, profile: Literal['log', 'linear', 'constant'] | None = None)[source]

The wind over a weather zone: what it gives replaces the atmosphere’s wind, and what it leaves out (None) stays the atmosphere’s.

speed_m_s: float | None
direction_deg: float | None
height_m: PositiveFloat | None
profile: Literal['log', 'linear', 'constant'] | None

A scene with its geometry loaded: a material on every surface, and checks.

Room is what the simulation stages consume. It also gives the classic statistical estimates (Sabine and Eyring reverberation times) so a model can be sanity-checked before any ray is traced.

acoustic_spaces.room.MIN_SOURCE_DISTANCE_M = 0.01

A listener closer than this (metres) to a source has no response: the direct sound’s level grows without bound as the distance goes to zero.

acoustic_spaces.room.ON_SURFACE_M = 1e-06

A source or listener closer than this (metres) to a surface is on it: neither in the room nor out of it (the distance at which two corners count as one).

acoustic_spaces.room.ON_SURFACE_MARGIN = 2.0

In a large model the distance is this many times the least length of a ray traced on the CPU, where that is more (Room.on_surface_m()).

acoustic_spaces.room.NEAR_SURFACE_SHARE = 0.1

The late part’s detector sphere, kept clear of the surfaces, smaller than this share of the smallest one sized for the room (late.RADIUS_RANGE) catches a hundredth of the rays or fewer: a listener that close to a surface gets a noisy late part.

acoustic_spaces.room.every_left_out(kind: str) → str[source]

The problem of a scene whose every kind (source, listener) is left out with enabled: false, for a run that takes those in use.

acoustic_spaces.room.matching_name(label: tuple[str, ...], names: Iterable[str]) → str | None[source]

The first of names that a surface’s label holds: as it is written, or else in any case (brick_rough names SketchUp’s Brick_Rough); None for none.

class acoustic_spaces.room.Room(scene: 'Scene', mesh: 'RoomMesh', report: 'MeshReport', material_names: 'list[str]', face_materials: 'np.ndarray', sources_inside: 'np.ndarray | None', listeners_inside: 'np.ndarray | None', unused_assignments: 'list[str]', directivities: 'list[Directivity]', air_cells: 'np.ndarray', outdoor: 'Layout | None' = None, sources_in_solid: 'np.ndarray | None' = None, listeners_in_solid: 'np.ndarray | None' = None)[source]
material_names: list[str]

Material names in scene.materials order; face_materials indexes this.

face_materials: ndarray

(F,) index into material_names per face, UNASSIGNED (-1) when none matched.

sources_inside: ndarray | None

Whether each source / listener is inside; None when the mesh is not closed.

unused_assignments: list[str]

Assignment keys that match no name in the geometry.

directivities: list[Directivity]

Each source’s directivity, in scene.sources order.

air_cells: ndarray

(R,) the cells of mesh.cells() that hold air: the rooms. Usually the model’s rooms (see acoustic_spaces.geometry.cells); when a source or a listener lies in another enclosed cell (a model with thick walls, whose rooms are cells inside the walls’ shell), the cells they lie in, with those that surfaces letting sound through join to them. Empty when the mesh is not closed.

outdoor: Layout | None = None

Where the ground and the sky lie in an outdoor scene (geometry.ground); None for a room.

sources_in_solid: ndarray | None = None

Whether each source (any of its point sources) / listener stands inside a closed solid: in a cell the faces enclose that holds no air (see air_cells); None when the mesh is not closed.

classmethod from_scene(scene: Scene, *, reuse: Room | None = None) → Room[source]

Load the scene’s geometry and give every surface its material.

reuse is an earlier room: when its geometry settings equal the scene’s, its mesh is kept instead of being loaded and checked again (an editor changing materials or positions), and so are directivities read from the same settings.

directivity(source: str, bands: Literal['octave', 'third_octave'] = 'octave') → Directivity[source]

The directivity of the source with this name, in octave or third-octave bands.

property bands: Literal['octave', 'third_octave']

The bands the scene’s simulation runs in: octave or third_octave.

property band_centres: tuple[int, ...]

Centre frequencies (Hz) of the bands the scene’s simulation runs in.

sky_faces() → ndarray[source]

(F,) the faces of an outdoor scene’s open sky (all False for a room).

building_faces() → ndarray[source]

(F,) the faces of an outdoor scene’s buildings (geometry.buildings).

shown_faces() → ndarray[source]

(F,) the faces worth drawing: all but an outdoor scene’s sky, which would hide the rest.

unassigned_labels() → dict[str, float][source]

Surface area (m2) without a material, by the names the faces carry.

problems(in_use: Collection[str] = ('sources', 'listeners'), named: Mapping[str, Collection[str]] | None = None) → list[str][source]

Issues that would make a simulation wrong; fix these first. Sources and listeners left out (enabled: false) are not checked, unless named names them ({"sources": names, "listeners": names}: those a run takes by name, even when left out); but every one of them left out is a problem for the kinds in in_use: those a run takes as the scene has them in use, rather than by name (a map takes no listeners).

on_surface_m() → float[source]

The distance (m) under which a source or a listener is on a surface: ON_SURFACE_M, or ON_SURFACE_MARGIN times the least length of a ray traced on the CPU in the model (ray_start()) where that is more, which it is in a model more than 500 m from corner to corner.

warnings() → list[str][source]

Things worth a look that do not stop a simulation; about the sources and listeners in use.

property volume_m3: float | None

The volume of air (m3): of all the rooms together; None when the model is not closed.

property room_volumes: ndarray

(R,) volume of each room (m3).

property face_room: ndarray

(F, 2) the room (an index into room_volumes) on the front (the side the face’s normal points to) and on the back of each face, or -1 where a side faces no room: the outside, or the inside of a solid.

room_of(points) → ndarray[source]

The room each point lies in (an index into room_volumes), or -1.

volume_at(points) → ndarray | None[source]

(P,) the volume (m3) of the room each point lies in, where partitions or openings divide the model into rooms, and that of all the rooms together for a point in none; None when the model is not closed.

face_transmission(bands: Literal['octave', 'third_octave'] = 'octave') → ndarray | None[source]

(F, bands) share of sound each face lets through, or None when none does.

area_by_material() → dict[str, float][source]

Surface area (m2) per material, in material_names order.

absorption_area(bands: Literal['octave', 'third_octave'] = 'octave') → ndarray[source]

Equivalent absorption area per octave band, or per third-octave band with bands="third_octave" (m2): the sum of S * alpha over the sides of the faces that face a room. With partitions or openings between rooms, it is that of all the rooms as one: what passes from one room to another is not lost.

air_attenuation(bands: Literal['octave', 'third_octave'] = 'octave') → ndarray[source]

Energy attenuation of the scene’s air per octave band, or per third-octave band with bands="third_octave" (1/m), ISO 9613-1.

reverberation_time(formula: Literal['sabine', 'eyring', 'arau_puchades'] = 'sabine', air_absorption: bool = False, bands: Literal['octave', 'third_octave'] = 'octave') → ndarray[source]

Statistical reverberation time per octave band, or per third-octave band with bands="third_octave" (s).

Sabine and Eyring assume a diffuse field; they are a sanity check, not a prediction. arau_puchades (Arau-Puchades, Acustica 65, 1988) allows for absorption spread unevenly between the room’s directions: an Eyring time for each of the x, y and z axes from the surfaces facing it, combined as a geometric mean weighted by their area. Each face’s area is shared between the axes by the squares of its normal’s components, so in a box aligned with the axes every wall counts for the axis it faces. air_absorption adds the 4 m V term of ISO 9613-1 air.

acoustic_spaces.room.outline_edges(room: Room) → tuple[ndarray, ndarray][source]

The model’s edges seen from above, for a plan of the room: (E, 2, 2) end points (m) of the edges where the surface folds or ends, and (E,) the label of a face beside each. Vertical edges, points from above, are left out.

Source directivity

Source directivity: how a source shares its sound power between directions, per octave band (or third-octave band).

A directivity gives energy weights that average 1 over the sphere in every band, so a source radiates its sound power (level_db) whatever its pattern; the pattern only says where that power goes. Directions are in the source’s own frame: x forward, y left, z up, as acoustic_spaces.scene.Orientation turns them; azimuth turns from the front towards the left and elevation is positive upwards, in degrees.

  • FirstOrder: the patterns a + (1 - a) cos(theta) from omni (a = 1) to figure-8 (a = 0), one per band, so a loudspeaker can be omni in the bass and narrow in the treble.

  • Balloon: measured levels at any set of directions, read from a SOFA file (AES69, the FreeFieldDirectivityTF convention) or a CSV table, interpolated over the sphere; or the far-field pattern of a coherent array (array_directivity()).

load_directivity turns a source’s directivity entry of a scene file into one:

directivity: cardioid                       # one pattern for every band
directivity: {pattern: [omni, omni, subcardioid, cardioid, cardioid, supercardioid,
                        hypercardioid, hypercardioid]}
directivity: {file: speaker.sofa}           # or speaker.csv
directivity: {array: {count: 8, spacing_m: 0.15, steer_deg: -8}}
directivity: {file: line_array.yaml}        # an array's fields in a YAML file

The CSV table has a header row azimuth, elevation followed by band centre frequencies in Hz (octaves, thirds or any other layout), then one row per direction with the level in dB in each band (any reference; only differences matter). Lines starting with # are comments.

Measured data is averaged into octave bands. A simulation in third-octave bands takes each octave band’s directivity for its three third octaves (Directivity.in_bands()).

acoustic_spaces.directivity.FAR_FIELD_HZ = 1000.0

The frequency (Hz) at which far_field_distance() is given in warnings.

acoustic_spaces.directivity.GRID_STEP_DEG = 5.0

Angular step of the grid measured data is interpolated on (degrees).

acoustic_spaces.directivity.PATTERNS: dict[str, float] = {'cardioid': 0.5, 'figure8': 0.0, 'hypercardioid': 0.25, 'omni': 1.0, 'subcardioid': 0.7, 'supercardioid': 0.37}

The first-order patterns by name: the pressure is a + (1 - a) cos(theta).

acoustic_spaces.directivity.SPEED_OF_SOUND = 343.21462268256795

Speed of sound (m/s) an array’s phases take when no room gives one: air at 20 C.

class acoustic_spaces.directivity.Balloon(table: ndarray, name: str = '', extrapolated: tuple[int, ...] = (), near: NearField | None = None)[source]

Measured energy at some directions, interpolated over the sphere.

The measurements are first spread onto a regular grid of elevations and azimuths (GRID_STEP_DEG apart), each of its points from the measured directions nearest to it (from_measurements), then read off it bilinearly, which the compiled tracer does the same way. Each band is scaled to average 1 over the sphere.

table: ndarray

Interpolation grid: energy weights (elevations, azimuths, bands).

name: str = ''

Short description, for listings and reports.

extrapolated: tuple[int, ...] = ()

Octave bands (Hz) without data of their own, copied from the nearest band.

near: NearField | None = None

A coherent array’s elements, for its sound added up element by element near it (near_field: true); None reads every weight off the pattern.

classmethod from_measurements(directions, energy, name: str = '', extrapolated: tuple[int, ...] = (), step: float = 5.0) → Balloon[source]

Interpolate energies (n, bands) measured in the directions of vectors (n, 3).

Directions given more than once (a table’s -180 and 180 degrees of azimuth, its rows at a pole) are one direction, the mean of them, with the mean of their energies. Each grid point takes the NEIGHBOURS directions nearest to it, weighted by the inverse squares of their angles from it. Where several are as near as the last of those (within SAME_DIRECTION) and not all of them are among the NEIGHBOURS, none of them is taken, only the nearer ones; or all of them, if none is nearer. So directions equally near a point are taken alike, whatever their order in the data and the last digits of their distances.

classmethod from_table(table, name: str = '', extrapolated: tuple[int, ...] = ()) → Balloon[source]

Energies on the grid of elevations (-90 to 90 degrees) and azimuths (0 up to 360) that table (elevations, azimuths, bands) spans, each band scaled to average 1 over the sphere; silent bands become omnidirectional.

energy(directions) → ndarray[source]

Energy weights (n, bands) for unit vectors (n, 3) in the source’s frame; they average 1 over the sphere in each band.

near_energy(points) → ndarray[source]

Energy weights (n, bands) at points (n, 3) in the source’s frame: for an array with near, its elements added up from where each is; otherwise, and far from the array alike, the pattern’s weights towards the points.

native() → tuple[ndarray, ndarray][source]

What the compiled tracer takes: the first-order a per band, and a table of weights on the interpolation grid (elevations x azimuths x bands, empty for first-order patterns).

in_bands(bands: Literal['octave', 'third_octave']) → Balloon[source]

This directivity in octave or third-octave bands: an octave band’s weights for each of its three third octaves, or the mean of three third octaves’ for their octave.

class acoustic_spaces.directivity.Directivity[source]

Energy weights per direction and octave band; see the module docstring.

name: str = ''

Short description, for listings and reports.

extrapolated: tuple[int, ...] = ()

Octave bands (Hz) without data of their own, copied from the nearest band.

energy(directions) → ndarray[source]

Energy weights (n, bands) for unit vectors (n, 3) in the source’s frame; they average 1 over the sphere in each band.

index() → ndarray[source]

Directivity index per band (dB): the on-axis level above the average.

native() → tuple[ndarray, ndarray][source]

What the compiled tracer takes: the first-order a per band, and a table of weights on the interpolation grid (elevations x azimuths x bands, empty for first-order patterns).

in_bands(bands: Literal['octave', 'third_octave']) → Directivity[source]

This directivity in octave or third-octave bands: an octave band’s weights for each of its three third octaves, or the mean of three third octaves’ for their octave.

class acoustic_spaces.directivity.FirstOrder(a: tuple[float, ...], name: str = '', extrapolated: tuple[int, ...] = ())[source]

a + (1 - a) cos(theta) patterns, one a per octave band.

name: str = ''

Short description, for listings and reports.

extrapolated: tuple[int, ...] = ()

Octave bands (Hz) without data of their own, copied from the nearest band.

classmethod pattern(name: str) → FirstOrder[source]

The same named pattern in every band.

energy(directions) → ndarray[source]

Energy weights (n, bands) for unit vectors (n, 3) in the source’s frame; they average 1 over the sphere in each band.

native() → tuple[ndarray, ndarray][source]

What the compiled tracer takes: the first-order a per band, and a table of weights on the interpolation grid (elevations x azimuths x bands, empty for first-order patterns).

in_bands(bands: Literal['octave', 'third_octave']) → FirstOrder[source]

This directivity in octave or third-octave bands: an octave band’s weights for each of its three third octaves, or the mean of three third octaves’ for their octave.

class acoustic_spaces.directivity.NearField(positions: ndarray, gains: ndarray, delays: ndarray, turns: ndarray, element: Directivity, speed_of_sound: float, edges: ndarray, scale: ndarray)[source]

A coherent array’s elements (see array_directivity()), to add up their pressures at points near it, each from its own position with its own distance and direction, rather than read the far-field pattern off one point.

positions: ndarray

(elements, 3) positions in the source’s frame (m).

gains: ndarray

(elements,) pressure gains, negative where the polarity is inverted.

delays: ndarray

(elements,) the feed’s delays (s), steering included.

turns: ndarray

(elements, 3, 3) each element’s forward, left and up axes as columns.

element: Directivity

The elements’ own pattern, in third-octave bands.

edges: ndarray

(25,) the third-octave bands’ edges (Hz).

scale: ndarray

(24,) one over the pattern’s mean energy over the sphere in each third-octave band, which scales it to the weights’ average of 1; 0 where the band is silent.

weights(points) → ndarray[source]

Energy weights (n, 24) at points (n, 3) in the source’s frame, per third-octave band, as the pattern’s weights are: the elements’ energy there, averaged over each band (of a flat spectrum) exactly, times the squared distance from the source’s position. Far away they become the pattern’s.

acoustic_spaces.directivity.array_directivity(spec, speed_of_sound: float = 343.21462268256795, near_field: bool = False) → Balloon[source]

The far-field pattern of a coherent array (an ArraySpec), per third-octave band; with near_field, it also keeps the elements (NearField), whose sound the early paths add up element by element.

The elements’ pressures add up with their phases: the path difference towards each direction, the feed’s delays and the steering, the gains and polarities, and each element’s own pattern along its aim (first-order patterns with their sign, measured ones by magnitude). Energies are exact averages over each band (of a flat spectrum), on a grid fine enough for the beam (1 to 5 degrees). The pattern holds in the far field, beyond about the array’s length squared over the wavelength.

acoustic_spaces.directivity.array_files(path: str | Path, _seen: frozenset[Path] = frozenset({})) → list[Path][source]

The files a coherent array’s YAML file names for its element, and those they name in turn; none for other files, or a missing one.

acoustic_spaces.directivity.array_length(spec) → float | None[source]

The largest distance between two elements (m) of the coherent array a source’s directivity entry describes, given in the scene or in a YAML file; None for other directivities.

acoustic_spaces.directivity.directivity_files(spec, _seen: frozenset[Path] = frozenset({})) → list[Path][source]

The files a source’s directivity entry uses: its own file and, for a coherent array, its element’s, whether the array is in the entry or in a YAML file (which names its element’s file relative to itself), and so on down.

acoustic_spaces.directivity.far_field_distance(length_m: float, frequency_hz: float = 1000.0, speed_of_sound: float = 343.21462268256795) → float[source]

From how far (m) an array length_m long acts as one point with its far-field pattern at frequency_hz: its length squared over the wavelength. Nearer, its sound spreads as a line’s and its beam has not formed yet.

acoustic_spaces.directivity.lambert() → Balloon[source]

A vibrating surface’s radiation: energy in proportion to the cosine of the angle to the forward axis, nothing behind (Lambert’s law), in every band.

acoustic_spaces.directivity.load_directivity(spec, speed_of_sound: float = 343.21462268256795) → Directivity[source]

The directivity a scene’s source entry describes: a pattern name (or lambert), or an object with pattern (a name or a value per band), file or array; an array’s phases take speed_of_sound (m/s).

acoustic_spaces.directivity.on_grid(table: ndarray, directions) → ndarray[source]

(n, …) the values table (elevations, azimuths, …) holds on a grid of elevations from -90 to 90 degrees and azimuths from 0 up to 360, each evenly spaced, read bilinearly at unit vectors (n, 3) in the source’s frame.

acoustic_spaces.directivity.read_array(path: str | Path)[source]

A coherent array (ArraySpec) from a YAML file holding its fields; files named in it are found next to it.

acoustic_spaces.directivity.read_directivity(path: str | Path, measurement: int | None = None, speed_of_sound: float = 343.21462268256795, near_field: bool = False) → Balloon[source]

Measured directivity from a .sofa file or a CSV table, or an array’s from a YAML file (.yaml or .yml; see read_array()), with its elements for near_field.

acoustic_spaces.directivity.read_directivity_csv(path: str | Path) → Balloon[source]

A Balloon from a CSV table of levels (see the module docstring).

acoustic_spaces.directivity.read_directivity_sofa(path: str | Path, measurement: int | None = None) → Balloon[source]

A Balloon from a SOFA file of source directivities (the FreeFieldDirectivityTF convention, or impulse responses in Data.IR).

Every receiver of every measurement gives one direction: where it sits relative to the source, in the source’s frame (SourceView and SourceUp). measurement picks one measurement (an instrument’s notes, for example); by default their energies are averaged. Spectra are averaged in energy over each octave band.

acoustic_spaces.directivity.sphere_mean(table: ndarray) → ndarray[source]

(…) the mean over the sphere of what table holds on the grid of on_grid(), read bilinearly as it reads them.

acoustic_spaces.directivity.write_directivity_csv(path: str | Path, balloon: Balloon, comment: str = '') → Path[source]

Write balloon (in octave bands) as the CSV table read_directivity_csv() reads back: a row for each direction of its grid with its level in each band (dB over the sphere’s mean), under comment’s lines.

Geometry

Room geometry: CAD import, cleanup and checks.

Every importer returns a RoomMesh: triangles in metres with +z up, and for each triangle the names it carried in the source file (material, group, object or layer) so the scene’s assignments can map them to acoustic materials. Simple rooms can also be built from dimensions (box_mesh(), extruded_mesh()).

class acoustic_spaces.geometry.MeshCells(side: ndarray, volume: ndarray, rooms: ndarray)[source]

The cells of a mesh (see the module notes).

side: ndarray

(F, 2) cell of the front (the side the face’s normal points to) and of the back of each face.

volume: ndarray

(C,) volume of each cell (m3): positive when enclosed, negative for the space around the model, about 0 for slivers and the inside of an open model.

rooms: ndarray

(R,) the cells that are rooms, in the order of their first face.

property outside: ndarray

(C,) True for the cells of the space around the model.

property enclosed: ndarray

(C,) True for cells with a volume: rooms and solids.

property face_room: ndarray

(F, 2) room (an index into rooms) of the front and back of each face, or -1 where a side faces no room.

property room_volumes: ndarray

(R,) volume of each room (m3).

property open_faces: ndarray

(F,) True for faces with neither side in an enclosed cell: a hole joins the room behind them to the outside, or they stand outside the model.

property closed: bool

At least one room, and every face has a side in an enclosed cell.

class acoustic_spaces.geometry.MeshReport(vertices: 'int', faces: 'int', merged_vertices: 'int', removed_degenerate_faces: 'int', boundary_edges: 'int', non_manifold_edges: 'int', inconsistent_edges: 'int', surface_area_m2: 'float', volume_m3: 'float | None', bounds_min: 'tuple[float, float, float]', bounds_max: 'tuple[float, float, float]', notes: 'list[str]' = <factory>, normals_inward: 'bool | None' = None, odd_edges: 'int' = 0, room_volumes_m3: 'tuple[float, ...]'=(), open_faces: 'int' = 0)[source]
removed_degenerate_faces: int

Faces cleaning removed: degenerate ones, and copies of another face.

normals_inward: bool | None = None

True when face normals point into the room, False outward, None when unknown (open model or inconsistent orientation).

odd_edges: int = 0

Edges shared by three or another odd number of faces: where a partition or an opening between two rooms meets the walls, or a crack.

room_volumes_m3: tuple[float, ...] = ()

Volume of each room (m3): the separate volumes of air the faces enclose, two or more where partitions or openings divide the model (see acoustic_spaces.geometry.cells).

open_faces: int = 0

Faces with no room or solid on either side: a hole joins the room behind them to the outside, or they stand outside the model.

property closed: bool

True when the faces enclose at least one room and every face has a room or a solid (the inside of a closed pillar) on one side at least. Free-standing panels inside a room leave it closed.

class acoustic_spaces.geometry.RoomMesh(vertices: ndarray, faces: ndarray, face_labels: ndarray, labels: list[tuple[str, ...]])[source]

Triangles of a room model.

labels holds, for each distinct combination of names found in the source file, the candidate names in priority order (for OBJ: material, group, object). Each face points at one entry through face_labels.

property triangles: ndarray

(F, 3, 3) corner coordinates of every face.

face_normals() → ndarray[source]

Unit normals following the right-hand rule on the vertex order.

cells()[source]

The rooms and other cells the faces enclose (MeshCells), worked out once.

label_names() → list[str][source]

Every distinct name that appears in any label, in first-seen order.

acoustic_spaces.geometry.box_mesh(size: tuple[float, float, float]) → RoomMesh[source]

A rectangular room from (0, 0, 0) to size = (length, width, height).

acoustic_spaces.geometry.check_mesh(mesh: RoomMesh, merged: int = 0, removed: int = 0) → MeshReport[source]

Topology, size and orientation checks on a cleaned mesh.

acoustic_spaces.geometry.clean_mesh(mesh: RoomMesh) → tuple[RoomMesh, int, int][source]

Merge duplicate vertices, drop degenerate faces, copies of a face and the vertices no face uses, split faces at T-junctions and orient the faces alike.

A copy is a face with the same corners as an earlier one, turning the same way: the same face given twice, which would leave every edge of it shared by three faces and the model with no inside. Two faces with the same corners turning opposite ways both stay: that is where two closed models touch, each with its own face.

A face whose edge runs past a corner of the faces on its other side (a T-junction, which CAD exporters leave, or close with a zero-area sliver that is dropped here) is split at that corner, so the faces share the edge and the model can close. Faces that meet along an edge are turned to agree with each other, so a closed model with a few faces flipped by its exporter still has a volume and an inside test that works; each connected part keeps the orientation most of its area had. Returns the cleaned mesh, the number of merged vertices and of removed faces.

acoustic_spaces.geometry.distance_to_surface(mesh: RoomMesh, points: ndarray) → ndarray[source]

Distance from each point to the nearest triangle of the mesh (metres).

acoustic_spaces.geometry.extruded_mesh(plan: ndarray, height: float) → RoomMesh[source]

A room whose floor is the polygon plan (N, 2) at z = 0 and whose ceiling is the same polygon at z = height. The plan must be a simple polygon (see plan_problem()).

acoustic_spaces.geometry.ifc_spaces(path: str | Path) → list[tuple[str, str]][source]

The rooms (IfcSpace) of an IFC file: for each, what space names it by (its name, or its GlobalId when it has none) and how it reads (name and long name).

acoustic_spaces.geometry.load_mesh(path: str | Path, units: str | None = None, up_axis: str | None = None, *, space: str | None = None) → RoomMesh[source]

Load a room model and convert it to metres with +z up.

units are those of the file’s coordinates; None takes the units a DXF, IFC or Collada file records, and metres for other files. up_axis overrides the format’s convention (“y” for glTF, the axis a Collada file records, “z” otherwise); Blender’s OBJ exporter, for example, writes +y up. space names a room of an IFC file (an IfcSpace) to take on its own, from its space boundaries; None reads all building elements.

acoustic_spaces.geometry.mesh_cells(vertices: ndarray, faces: ndarray) → MeshCells[source]

The cells of the mesh with vertices (V, 3) and faces (F, 3).

acoustic_spaces.geometry.missing_extra(path: str | Path) → str | None[source]

The extra that reading path needs (see READER_EXTRAS) when it is not installed; None when none is needed or it is installed.

acoustic_spaces.geometry.plan_problem(plan: ndarray) → str | None[source]

Why the polygon plan (N, 2) cannot be a floor plan, or None: too few corners, two corners in one place, no area, or walls that cross or touch.

acoustic_spaces.geometry.points_inside(mesh: RoomMesh, points: ndarray) → ndarray[source]

Whether each point lies inside a room of a closed mesh (any of its rooms, when partitions or openings divide it; see acoustic_spaces.geometry.cells).

acoustic_spaces.geometry.room_of(mesh: RoomMesh, points: ndarray) → ndarray[source]

The room each point lies in (an index into the rooms of mesh.cells()), or -1 outside every room. Generalised winding numbers: the signed solid angles that a room’s faces subtend at the point add up to 4 pi inside it and 0 outside.

acoustic_spaces.geometry.triangle_gaps(one: ndarray, other: ndarray) → ndarray[source]

The least distance (metres) between each of the triangles one (n, 3, 3: the three corners of each) and the one of other at its place: nothing where the two touch or cross.

acoustic_spaces.geometry.triangles_near(triangles: ndarray, points: ndarray, reach: float) → tuple[ndarray, ndarray, ndarray][source]

The pairs of one of points and one of triangles (n, 3, 3: the three corners of each) no farther apart than reach metres: the points’ indices, the triangles’ and the distances (metres), in no order.

Only the points in a triangle’s box, grown by the reach, are measured against it: along the axis that leaves the fewest, each box takes the run of the sorted points that its span holds.

Materials

Acoustic material data: the built-in database, coefficient files and the material libraries of CATT-Acoustic and ODEON.

class acoustic_spaces.materials.LibraryMaterial(name: str, number: int | None, frequencies: tuple[float, ...], absorption: tuple[float, ...], scattering: tuple[float, ...] | None = None, category: str | None = None)[source]

One material of a library.

name: str

Its name: CATT’s material name, or ODEON’s description.

number: int | None

ODEON’s material number; None in CATT libraries.

frequencies: tuple[float, ...]

Centre frequencies (Hz) of the values.

absorption: tuple[float, ...]

Random-incidence absorption coefficients, from 0 to 1.

scattering: tuple[float, ...] | None = None

Scattering coefficients at the same frequencies, or None.

category: str | None = None

ODEON’s category of the material ({Category=...}), or None.

property label: str

How the material is named in messages: with its number, if it has one.

class acoustic_spaces.materials.MaterialEntry(id: 'str', kind: 'Kind', category: 'str', description: 'str', frequencies: 'tuple[float, ...]', coefficients: 'tuple[float, ...]', source: 'str')[source]
octave_bands() → tuple[list[float], list[int]][source]

Coefficients on OCTAVE_BANDS_HZ and the octaves that had to be extrapolated.

acoustic_spaces.materials.band_centres(resolution: Literal['octave', 'third_octave'] = 'octave') → tuple[int, ...][source]

Nominal centre frequencies (Hz) of the bands at resolution.

acoustic_spaces.materials.find_material(path: str | Path, entry: str | int) → LibraryMaterial[source]

The material of a library named entry: a name or description (any case), or an ODEON material’s number.

acoustic_spaces.materials.read_coefficients_csv(path: str | Path) → tuple[list[float], list[float], list[float] | None][source]

Return (frequencies, absorption, scattering or None) as read from path.

acoustic_spaces.materials.read_library(path: str | Path) → list[LibraryMaterial][source]

Every material of a CATT-Acoustic or ODEON library, in file order.

The format is found from the contents: ABS definitions make a CATT file, and numbered descriptions followed by a line of coefficients an ODEON one.

acoustic_spaces.materials.to_bands(frequencies: Sequence[float], values: Sequence[float], resolution: Literal['octave', 'third_octave'] = 'octave') → tuple[list[float], list[int]][source]

Map coefficients given at arbitrary centre frequencies onto the bands at resolution.

Values whose centre falls inside a band (third-octave data in an octave band, for example) are averaged. A band with no data takes the value of the nearest band that has some; those bands are returned as the second element so callers can say so.

acoustic_spaces.materials.to_octave_bands(frequencies: Sequence[float], values: Sequence[float]) → tuple[list[float], list[int]][source]

Map coefficients given at arbitrary centre frequencies onto OCTAVE_BANDS_HZ (to_bands() at octave resolution).

Material libraries of other room acoustics programs: CATT-Acoustic and ODEON.

A scene’s material can take its coefficients from an entry of such a library, with file naming the library and entry the material in it, and acoustic-spaces materials --file lists a library’s entries.

CATT-Acoustic writes materials in its geometry and library files as ABS name = <a125 a250 a500 a1k a2k a4k> L <s125 s250 s500 s1k s2k s4k> {r g b}: absorption and scattering in percent from 125 Hz to 4 kHz, with values at 8 and 16 kHz optional (after a colon, <a125 ... a4k : a8k a16k>, or without one). ABS1 gives them as fractions from 0 to 1 instead. L <...> and the colour may be left out, ; starts a comment, and ABS name = other gives a material the coefficients of another in the same file. Scattering that CATT estimates itself (L <estimate(...)>) is not read.

ODEON’s library (Material.Li8) has each material on two lines: its number and description, then eight absorption coefficients from 63 Hz to 8 kHz. ODEON’s own library writes the description as {Product name*=...}, {Category=...}, and the materials its Material calculator made carry the calculator’s settings after the description and, after the eight values, /Area and /A with the sample area and third-octave values, which are not read: ODEON simulates with the octave values. Libraries of six values (125 Hz to 4 kHz) are read too. ODEON gives scattering to surfaces, not to materials, so these entries have none.

Simulation

Propagation: early specular paths, the late tail, and the responses they make.

The usual entry point is simulate():

from acoustic_spaces.engine import simulate

result = simulate("scene.yaml")
response = result["talker", "seat-a"]
print(response.parameters().table())
ir = response.impulse_response(48_000)

coverage_map() gives the same parameters on a grid over the audience area.

class acoustic_spaces.engine.CoverageMap(source: str, grid: MapGrid, values: dict[str, ndarray], spread: MapSpread | None = None)[source]

Parameters at every map point for one source, or for all of them together.

values: dict[str, ndarray]

Parameter name (see MAP_PARAMETERS) -> (points, bands) or (points,).

spread: MapSpread | None = None

Their uncertainty from the materials’ absorption, where the map was run with its spread (coverage_map()).

parameters() → list[str][source]

The parameters the map has, in the order of MAP_PARAMETERS: those of OUTDOOR_MAP_PARAMETERS outdoors only, those of INSERTION_LOSS_MAP_PARAMETERS when the map was also run without some of the scene’s buildings, barriers or vegetation, those of LONG_TERM_MAP_PARAMETERS when it was run in weather classes, and those of LONG_TERM_INSERTION_LOSS_MAP_PARAMETERS when it was run both ways.

value(name: str, band: int | None = None) → ndarray[source]

One value per point: a parameter in one band (index into OCTAVE_BANDS_HZ), or a parameter that has no bands.

spread_of(name: str, part: str = 'standard', band: int | None = None) → ndarray[source]

One value per point of the spread of parameter name (as value() takes it): its standard uncertainty; the low or the high end of the interval that holds it with the spread’s coverage probability; or the value it is at_least or at_most with the spread’s one-sided probability. The interval and the bounds take the result as normal about the map’s value (GUM, JCGM 100:2008, 6.3 and G.2): the value less and plus the normal quantile times the standard uncertainty (1.96 for 95 %; 1.645 for a one-sided 95 %), held to what the parameter can be (LIMITS).

as_dict() → dict[source]

Points and values as plain lists, None where undefined (JSON friendly); with its spread, uncertainty holds the probabilities, each parameter’s standard uncertainty and each material’s part of it (materials).

class acoustic_spaces.engine.CoverageResult(room: ~acoustic_spaces.room.Room, settings: ~acoustic_spaces.scene.model.Coverage, grid: ~acoustic_spaces.engine.coverage.MapGrid, maps: dict[str, ~acoustic_spaces.engine.coverage.CoverageMap], combined: ~acoustic_spaces.engine.coverage.CoverageMap | None = None, details: dict[str, dict[str, float]] = <factory>, removed: tuple[str, ...] = ())[source]

Coverage maps of every source, and of all of them together.

combined: CoverageMap | None = None

All sources playing together at their levels; None with one source.

removed: tuple[str, ...] = ()

The buildings, barriers and vegetation the map was also run without, for the insertion loss (coverage_map()).

parameters() → list[str][source]

The parameters of its maps (see CoverageMap.parameters()).

get(source: str | None = None) → CoverageMap[source]

The map of one source; None gives all sources together (or the only one).

as_dict() → dict[source]

The settings, the points and every map as plain lists (JSON friendly).

class acoustic_spaces.engine.EarlyReflections(order: ndarray, delay_s: ndarray, distance_m: ndarray, direction: ndarray, energy: ndarray, points: list[ndarray] = <factory>, faces: list[ndarray] = <factory>, edge: ndarray | None = None, crossings: ndarray | None = None, spectrum: ndarray | None = None, point: ndarray | None = None, wander: Wander | None = None, lag: ndarray | None = None, cosines: list[ndarray] = <factory>, own_phase: ndarray | None = None, fine: ndarray | None = None, fine_delay: ndarray | None = None)[source]

Paths from one source to one listener: specular (order 0 is the direct sound), and diffracted at an edge when edge diffraction is on.

edge: ndarray | None = None

(n,) the edge a path bends over (an index of the model’s diffracting edges, see find_edges()), -1 for specular paths, -2 for a path over the crests of the terrain (crests), or -3 for the path that carries the sound of the solver for whole rows (row_paths).

crossings: ndarray | None = None

(n,) how many surfaces that let sound through a path passes, openings aside.

spectrum: ndarray | None = None

(n, C, M) in the lowest C bands, where the paths add in pressure (see coherent): each path’s pressure at M frequencies in each band (sample_frequencies()), relative to its delay and to its level in the band, which its energy gives (the mean of its squared magnitude over a band’s frequencies is 1). None when the paths add in energy in every band.

point: ndarray | None = None

(n,) which of the uncorrelated points of a line or surface source each path comes from (outdoors, where those paths carry a spectrum): in the coherent bands the paths of one point add in pressure, those of different points in energy.

wander: Wander | None = None

Outdoors in turbulence, how the eddies delay the paths at random (Wander): on average two paths’ pressures add with their coherence factor. None without turbulence, and at a moment of it (frozen()).

lag: ndarray | None = None

(n, bands) at a moment of turbulence, each path’s delay (s) in each band beyond delay_s, its delay in the highest band (the eddies part paths near the ground less at low frequencies); None otherwise.

cosines: list[ndarray]

Where the paths carry a spectrum: for each path, the cosine of the angle at which it meets the face of each of its reflections (as faces), whose phase its spectrum takes from that face’s absorption (reflection_phases()), so that re-weighting for other absorption can turn it ( turned_paths()); NaN for a reflection whose phase comes from elsewhere (a ground’s impedance). Empty without a spectrum.

own_phase: ndarray | None = None

(n,) in the bands above the coherent ones, the phase factor a rendered response gives each path beyond the one held from those bands (with_own_phases()); None outside one.

fine: ndarray | None = None

(n, C, K) where a path carries the field the parabolic equation gives over the open ground (outdoors in wind or temperature gradients, out of the shadow): in each coherent band its pressure, unnormalised, relative to its delay, at the frequencies of the layout (fine_frequencies()) the equation ran at there (in the lowest band down to an octave below it, in its top band through the upper crossover too where a response is rendered or the band filters read it); NaN where a path has none. Its band’s shape is drawn from these and its neighbours’ (shaped()); its level stays the one its energy gives. None when no path carries one.

fine_delay: ndarray | None = None

(n,) the delay (s) past delay_s whose phase fine’s samples follow on average (reference_delay()), relative to which they are interpolated; 0 for paths without them. None with fine.

property coherent_bands: int

How many of the lowest bands the paths add in pressure in.

frozen(seed: int) → EarlyReflections[source]

The paths at a moment of the turbulent air drawn with seed: each delayed in each band as the eddies have it then, adding in pressure (the same paths without turbulence).

wander_roots() → list[source]

How the eddies delay the paths, band by band, as roots() (empty without turbulence).

at_moment(roots: list, draws: list[ndarray]) → EarlyReflections[source]

The paths delayed as delays() has it for the normal variables draws (one array per group of roots, wander_roots()).

property diffracted: ndarray

(n,) True for paths that bend over an edge or the terrain’s crests, and for the one that carries the sound of the solver for whole rows.

sorted() → EarlyReflections[source]

The same paths in order of arrival.

class acoustic_spaces.engine.LateEnergy(energy: ndarray, time_step: float, escaped_rays: int = 0, rays: int = 0, traced_rays: int = 0, directions: ndarray = <factory>, directional: ndarray = <factory>, direction_step: float = 0.01, moments: ndarray = <factory>, moment_step: float = 0.0, plan: Plan | None = None, batches: ndarray = <factory>, batch_step: float = 0.01)[source]

Energy per listener, band and time slot (time-integrated intensity).

traced_rays: int = 0

Rays traced, counting those split off (stochastic ray tracing only).

directions: ndarray

Arrival directions (room coordinates, towards where the energy comes from) and the same energy split between them (listeners, directions, bands, slots of direction_step); empty without directions.

moments: ndarray

With face groups (stochastic_energy(groups=...)): per listener, the energy in slots of moment_step times 1, the reflections the rays had off each group n_i, and n_i n_j (i <= j) (listeners, terms, bands, slots), for re-weighting the response for new absorption (acoustic_spaces.engine.reweight); else empty.

plan: Plan | None = None

Where the rays were traced (stochastic ray tracing only).

batches: ndarray

With stochastic_energy(batches=...) of 2 or more: energy as each batch of rays gives it (listeners, batches, bands, slots of batch_step), each an estimate of its own and their mean energy; else without batches.

class acoustic_spaces.engine.MapGrid(origin: tuple[float, float], cell: float, index: ndarray, points: ndarray, columns: ndarray, surface: ndarray, low: ndarray, high: ndarray, volume: ndarray, footprint: ndarray, cover: ndarray, room: ndarray, level: ndarray)[source]

Map points over the audience area: columns cell metres wide from the corner origin (x, y), each holding up to index.shape[2] points.

index: ndarray

(ny, nx, slots) the points of each column, by level and then by room, -1 for none.

points: ndarray

(n, 3) the points, at listening height above the column’s centre, or above the middle of their part of the column when the centre is not in it.

columns: ndarray

(n, 2) column (x, y) of each point.

surface: ndarray

(n,) height of the surface under each point (m).

low: ndarray

(n,) bottom and top of each point’s slab of air (m), and the volume of the slab in the air of the point’s room, outside buildings (m^3).

footprint: ndarray

(m, 3, 2) the surfaces under the map seen from above: x, y of their triangles.

cover: ndarray

(n, 25) which fifths of the column, by x then y, lie over the surfaces (in the point’s room, where the model holds several).

room: ndarray

(n,) the room each point lies in (an index into Room.room_volumes) where the model holds several, else -1. A point’s slab counts the rays in its room alone.

level: ndarray

(n,) the level of each point in its column, from 0 at the lowest surface under it (the stalls; a balcony above them is 1). Where a wall between rooms crosses a column, it holds a point on each side that holds at least a fifth of it, on the same level.

squares() → ndarray[source]

(n, 4, 3) corners of each point’s column, at the point’s height.

tiles() → tuple[ndarray, ndarray][source]

Squares at the points’ height over the part of each column above the surfaces (in the point’s room): (m, 4, 3) corners and the point each belongs to. A column only partly over them, or split between rooms, is cut into fifths along each side.

class acoustic_spaces.engine.Particles(times: ndarray, positions: ndarray, energy: ndarray, order: ndarray, band_hz: int, source: str = '')[source]

Positions of sound particles at a series of times.

energy: ndarray

Energy relative to a particle’s share at emission (frames, particles).

order: ndarray

Reflections so far (frames, particles).

source: str = ''

Name of the source the particles left.

class acoustic_spaces.engine.Response(source: str, listener: str, early: EarlyReflections, late: ndarray, time_step: float, length_s: float, direct_delay_s: float, transition_s: float, volume_m3: float | None, speed_of_sound: float, seed: int = 0, orientation: ndarray = <factory>, late_directions: ndarray = <factory>, late_directional: ndarray = <factory>, direction_step: float = 0.01, wave: WaveResponse | None = None, source_direction: ndarray | None = None, feed: ndarray | None = None, feed_delay_s: float = 0.0, late_moments: ndarray = <factory>, moment_step: float = 0.0, late_batches: ndarray = <factory>, batch_step: float = 0.01, free_field: ndarray | None = None)[source]

Early specular paths plus late energy per band and time slot, and the lowest bands from the wave solver when it ran (wave), which then replace the rays’. The bands are the 8 octave bands or the 24 third-octave bands the simulation ran in; room parameters are given in octave bands either way.

Energies are time-integrated intensity for a source of unit energy (the direct sound at r metres carries 1 / (4 pi r^2)); times are measured from emission.

The late part’s arrays (late, late_directional, late_moments and late_batches) may each be given as a Deferred: the response then keeps that, and reading the field makes the array, which a read of the field again gets until that of another response is made.

direct_delay_s: float

Arrival time of the direct sound (s), whether or not the direct path is blocked.

transition_s: float

Early paths end here (s, from emission); the late part covers everything else.

volume_m3: float | None

Volume of the listener’s room (m3; None in a model that is not closed): how densely the synthesized late part’s reflections come.

seed: int = 0

Seed for the noise of the synthesized late part.

orientation: ndarray

The listener’s head axes (forward, left, up) as columns, in room coordinates.

late_directions: ndarray

Arrival directions of the late energy (room coordinates) and the late energy split between them (directions, bands, slots of direction_step). Without them the late part arrives evenly from all directions.

wave: WaveResponse | None = None

The lowest octave bands from the wave solver, or None.

source_direction: ndarray | None = None

Unit vector from the listener towards the source (room coordinates); None takes the direct path’s, or the listener’s forward axis without one.

feed: ndarray | None = None

The energy gain per band of the source’s feed (its gain and equalizer), which the energies include, or None for none. G is taken against the same source in free field, so the feed does not change it.

feed_delay_s: float = 0.0

How much later the feed makes every arrival (s), which the times include.

late_moments: ndarray

With face groups (simulate(groups=...)): the moments of the late energy’s reflection counts off each group (terms, bands, slots of moment_step), for reweighted(); else empty.

late_batches: ndarray

With the late rays traced in batches (simulation.late.batches of 2 or more): late as each batch gives it (batches, bands, slots of batch_step, a whole number of time_step), each an estimate of its own and their mean late, for standard_errors(); else empty.

free_field: ndarray | None = None

Outdoors: the energy per band of the same source at the listener in free field (its direct sound over the straight line, with the air’s attenuation and the source’s directivity, without the feed), for relative_to_free_field(); else None.

property coherent_bands: int

How many of the lowest bands the early paths add in pressure in (coherent); the wave solver’s take the place of those it covers.

property band_hz: tuple[int, ...]

Centre frequencies (Hz) of the bands: octave or third-octave bands.

energy(time_step: float | None = None) → ndarray[source]

Echogram: energy per band and time slot (bands, slots), early paths included.

octave_energy(time_step: float | None = None) → ndarray[source]

Echogram in octave bands (8, slots): each octave the mean of its three third-octave bands, when the simulation ran in those.

weighted_energy(axis: ndarray, exponent: int = 2, time_step: float | None = None) → ndarray[source]

Echogram of a figure of eight facing axis (a unit vector, room coordinates): each arrival’s energy times the cosine of its angle to the axis, taken without its sign, to the power exponent. With 2 that is the energy the figure of eight picks up; with 1 the magnitude of its product with the pressure, as LFC takes it. Late energy without directions counts as arriving evenly from all of them.

lateral_axis() → ndarray[source]

The axis of a figure of eight with its null on the source (ISO 3382-1): level, across the direction of the source, towards the listener’s left side of it.

fed(gain_db: Sequence[float] | ndarray, delay_s: float = 0.0) → Response[source]

This response with the source’s feed: gain_db per band (dB, the bands of the response) on every energy, and every arrival delay_s later.

reweighted(face_group: np.ndarray, ratio: np.ndarray, absorption: tuple[np.ndarray, np.ndarray] | None = None, admittance_of=None, redraws: Redraws | None = None) → Response[source]

This response for other absorption, without tracing again (acoustic_spaces.engine.reweight): face_group the group of each face (-1 for none) as traced, ratio the change per reflection off each group, ln((1 - new) / (1 - old)) per group and band (log_ratio()), and absorption each group’s absorption (groups, bands) as traced and as ratio changes it, (old, new). The early paths re-weight exactly (but for reflections off a ground with an impedance or with zones, whose factor is not 1 - absorption: see the module), the late part from its moments, which the response needs (simulate(groups=...)). Where the early paths add in pressure (coherent), the phase of their reflections depends on the absorption too, and turns with it (turned_paths(), with admittance_of if given): that needs absorption, unless no path reflects off a group whose absorption changes. redraws (a Redraws of this response’s early paths), for one of many draws of the absorption, holds what does not depend on the draw; the response is the same with it as without it.

parameters(energy: ndarray | None = None) → RoomParameters[source]

ISO 3382-1 parameters per octave band, straight from the energies.

Those of a figure of eight with its null on the source (LF, LFC, LJ) and the decay times of figures of eight along the listener’s axes come from the directions the energy arrives from; stage support only for a listener 0.9 to 1.1 m from the source (STAGE_DISTANCE_M and STAGE_TOLERANCE_M), as the standard measures it 1 m away. IACC needs a binaural response: interaural_cross_correlation(). Outdoors (with free_field), G of a band that does not decay as a room’s does is that of the energy the response holds. energy: its octave_energy(), when already at hand.

standard_errors() → RoomParameters | None[source]

The standard error of each of parameters() from the late rays’ batches (simulation.late.batches): one standard deviation of how much it would change between runs with other random seeds and as many rays. A jackknife: the parameters again without each of the n batches in turn, whose spread, times (n - 1) / n under the root, is the standard error. The early paths and the wave solver’s bands do not depend on the seed, and add none. Those from the directions the late energy arrives from (LF, LFC, LJ and the decay times along the listener’s axes) are NaN, as IACC is; so is a parameter some batches leave undefined or infinite (a clarity without late energy). None without 2 batches or more.

The batches hold the energy in slots of batch_step; without a batch, each slot of time_step keeps its share of its slot of batch_step, so a strong arrival in one of them (a ray through the listener long after the rest, in a room whose walls keep a few going) leaves with the batch it came in.

relative_to_free_field() → ndarray[source]

The level relative to free field per octave band (dB): how much louder (or, negative, quieter) the source is here than the same source the same distance away in free field, which the air between them attenuates as here. The ground, the weather, buildings, barriers and vegetation make the difference; with the sign turned, it is the excess attenuation of outdoor acoustics. It compares the energy the response holds (nothing is extrapolated past its end, as G does for a room’s decay) with the free field’s; -inf where no sound arrives, NaN in every band of a response without free_field.

levels(level_db: float | Sequence[float] = 94.0, parameters: RoomParameters | None = None) → ndarray[source]

Sound pressure level per octave band (dB SPL) of a source of sound power level_db (dB re 1 pW, the feed’s gain included): one value spread evenly over the octave bands, or one per octave band (power_db()). It is the band’s sound power plus its G, less 31 dB, the level of a source of 0 dB at 10 m in free field.

levels_or_held(level_db: float | Sequence[float] = 94.0, parameters: RoomParameters | None = None) → ndarray[source]

levels(), but in a band whose G is undefined (the few rays that reach a far place may carry no energy in it, or too little of its decay to read), the level of the energy the response holds from the direct sound’s arrival, as outdoors: -inf where none arrives. The level a listener is given in simulate’s report, the editor’s results, the demos’ captions and each place of pass_by(); the coverage maps and speech() leave such a band undefined.

speech(level_db: float | Sequence[float] = 94.0, noise_db: float | Sequence[float] | None = None, parameters: RoomParameters | None = None, talker: Literal['male', 'female'] = 'male') → SpeechParameters[source]

STI, STIPA and U50 for speech from a source of sound power level_db (dB re 1 pW: in all, spread evenly over the octave bands, or per octave band), with background noise noise_db (dB SPL, one value or one per band), as the coverage maps take them, weighted for a male or female talker; the STI and STIPA are NaN when a band from 125 Hz up has no level (its G is undefined). parameters are this response’s, when already at hand.

levels_and_speech(level_db: float | Sequence[float] = 94.0, noise_db: float | Sequence[float] | None = None, talker: Literal['male', 'female'] = 'male', parameters: RoomParameters | None = None, energy: ndarray | None = None) → Levels[source]

The levels and speech results at the listener for a source of sound power level_db (dB re 1 pW, in all or per octave band), as a run’s report gives them: levels_or_held() and its A-weighted sum; the STI, STIPA and U50 of speech() with background noise noise_db for talker; and relative_to_free_field(), with its A-weighted value (the A-weighted level less that of the same source in free field). parameters are this response’s, and energy its octave_energy(), when already at hand.

level_errors(level_db: float | Sequence[float] = 94.0, noise_db: float | Sequence[float] | None = None, talker: Literal['male', 'female'] = 'male') → Levels | None[source]

The standard error of each of levels_and_speech() from the late rays’ batches, by the jackknife of standard_errors(): NaN where some batch leaves the value undefined or infinite, None without 2 batches or more. Where G is defined, a band’s level is its G and the source’s power, so its error is G’s; where it is not, the level is that of the energy held (levels_or_held()) and has an error of its own.

impulse_response(sample_rate: int = 48000, seed: int | None = None) → ndarray[source]

Mono impulse response; the direct sound at r metres is an impulse of height 1 / r.

Early paths become fractional-delay impulses filtered per band, in the lowest bands with the phase of their reflections (coherent), in turbulence as at one moment (moment()); the late energy drives a random-sign Dirac sequence with the density of reflections in the room. From 50 ms after the direct sound the late energy is smoothed over 10 ms first, so a single strong ray late in the tail does not become a click. The wave solver’s bands, when it ran, take the place of the lowest ones: through the crossover the early paths make way for them in pressure and the noise, which does not interfere with them, in energy (WaveResponse.high_pass).

moment(seed: int | None = None) → EarlyReflections[source]

The early paths at a moment of the turbulent air, drawn with seed (default the response’s): outdoors in turbulence the eddies delay each path at random, and an impulse response is one moment of them, whose levels scatter about the echogram’s average. Without turbulence, the early paths.

spatial_impulse_response(fmt, sample_rate: int = 48000, seed: int | None = None, *, threads: int = 1) → ndarray[source]

Impulse responses (samples, channels) in a format of acoustic_spaces.spatial: Ambisonics(order), Loudspeakers.layout(name), Binaural(hrtf) or Mono(), its channels rendered on threads threads (the same result with any number; at most the computer’s cores).

class acoustic_spaces.engine.SimulationResult(room: Room, settings: SimulationSettings, responses: dict[tuple[str, str], Response], details: dict[str, dict[str, float]] = <factory>, removed: tuple[str, ...] = (), insertion_loss: dict[tuple[str, str], np.ndarray] = <factory>, long_term: LongTermLevels | None = None, spreads: dict = <factory>)[source]

Responses for every (source, listener) pair, plus run details.

details: dict[str, dict[str, float]]

Per source: rays, escaped rays, receiver radius, seed and timings.

removed: tuple[str, ...] = ()

The buildings, barriers and vegetation of an outdoor scene that it was also run without (simulate()), and their insertion loss per (source, listener) in each octave band (dB): the level without them less the level with them. Empty otherwise.

long_term: LongTermLevels | None = None

The levels over a long term, when the scene has weather classes (long_term; simulate()): the responses are the scene’s own weather’s, this holds each class’s run and the levels combined. None otherwise.

spreads: dict

The spread of each response’s parameters from its materials’ absorption uncertainty, by (source, listener) (material_spread()), where it was drawn. Empty otherwise.

parameters() → dict[tuple[str, str], RoomParameters][source]

ISO 3382-1 parameters of every response.

class acoustic_spaces.engine.TraceModel(room: 'Room', bvh: 'object', face_plane: 'np.ndarray', plane_normal: 'np.ndarray', plane_offset: 'np.ndarray', oriented: 'bool', absorption: 'np.ndarray', scattering: 'np.ndarray', plane_two_sided: 'np.ndarray | None' = None, transmission: 'np.ndarray | None' = None, face_room: 'np.ndarray | None' = None, room_volumes: 'np.ndarray | None' = None, surface_size: 'np.ndarray | None' = None, vector_scattering: 'bool' = True, by_band: 'bool' = True, bands: 'Resolution' = 'octave', size_from_order: 'int' = 1, ray_tree: 'str' = 'sah', sky: 'np.ndarray | None' = None, ground: 'float | None' = None, face_impedance: 'np.ndarray | None' = None, admittance: 'np.ndarray | None' = None, grazing_admittance: 'np.ndarray | None' = None, impedance_extended: 'np.ndarray | None' = None, impedances: 'tuple' = (), ground_part: 'np.ndarray | None' = None, part_face: 'np.ndarray | None' = None, plants: 'object | None' = None, deciding: 'np.ndarray | None' = None)[source]
face_plane: ndarray

(F,) plane index of every face.

plane_normal: ndarray

(P, 3) unit plane normals, pointing into the room when oriented (and the plane is not two-sided).

plane_offset: ndarray

(P,) plane offsets: points x on plane p satisfy normal[p] . x == offset[p].

oriented: bool

True when the rooms are known (a closed model): each face’s normal then points into the room on its side.

absorption: ndarray

(F, bands) random-incidence absorption and scattering coefficients.

plane_two_sided: ndarray | None = None

(P,) planes with a room on both sides of some face: a partition between two rooms or a free-standing panel; every plane when the model is not oriented.

transmission: ndarray | None = None

(F, bands) share of sound each face lets through (see acoustic_spaces.scene.Material.transmission_coefficients()), or None.

face_room: ndarray | None = None

(F, 2) the room on the front (the side the mesh’s face normal points to) and the back of each face (an index into room_volumes), or -1.

room_volumes: ndarray | None = None

(R,) volume of each room (m3).

surface_size: ndarray | None = None

(F, 2) width and length (m) of the surface each face belongs to (see surface_sizes()), when the scattering of a surface’s size is added; else None.

vector_scattering: bool = True

Vector-based scattering (the scene’s simulation.scattering.method).

by_band: bool = True

Each band traced with rays of its own where the bands scatter differently (simulation.scattering.by_band).

bands: Literal['octave', 'third_octave'] = 'octave'

The bands the coefficients (and so every energy traced) are in.

size_from_order: int = 1

Reflections of this order and higher add the scattering of the surface’s size. Below it, the early stage’s edge diffraction accounts for the size of surfaces: its terms add coherently to the direct sound and the reflections off the faces of an edge (with direct diffraction), and to the reflections of first-order reflections off them too (first_order), so those waves keep their full specular share.

ray_tree: str = 'sah'

How bvh was split (simulation.performance.ray_tree); trees built from this model’s mesh later take the same.

sky: ndarray | None = None

(F,) the faces of an outdoor scene’s open sky, whose edges diffract nothing; None in a room.

ground: float | None = None

Height (z) of an outdoor scene’s ground, whose edges on it diffract nothing; None in a room.

face_impedance: ndarray | None = None

(F,) for faces whose material has an impedance (a ground’s: see Impedance), its row of admittance; -1 for the others. None when no material has one.

admittance: ndarray | None = None

(K, bands, M) the normalised admittance of each material with an impedance at the frequencies the early paths are evaluated at (band_frequencies()), at normal incidence (a locally reacting ground’s at every angle).

grazing_admittance: ndarray | None = None

(K, bands, M) the same at grazing incidence, which differs for grounds of extended reaction (impedance.reaction), for the parabolic equation.

impedance_extended: ndarray | None = None

(K,) whether each material with an impedance reacts extendedly: its admittance changes with the angle of incidence, and impedances[k] gives it.

impedances: tuple = ()

The materials’ impedances (Impedance), row by row.

ground_part: ndarray | None = None

(F,) for an outdoor scene whose ground has zones (geometry.ground.zones), the part of the ground each face of it lies in (0 outside the zones, then each zone), whose reflections share their Fresnel zone with the parts round them; -1 for the faces that are not the ground. None without zones.

part_face: ndarray | None = None

(parts,) a face of each part of the ground, whose material it has; -1 for a part with no faces (the zones may cover all the ground).

plants: object | None = None

An outdoor scene’s vegetation in bands (Plants); None without any.

deciding: ndarray | None = None

(F, bands) the absorption that decides for a map’s rays in place of absorption, wherever the energy a ray carries decides what happens to it (the splitting and thinning out, whether it passes a partition): the run then follows the rays of the run with this absorption (stochastic_map_energy()). None: its own.

classmethod from_room(room: Room, settings=None) → TraceModel[source]

The model of room with the simulation settings (default: the scene’s).

property transparent: ndarray

(F,) faces that let all sound through in every band: openings (worked out once, as the early stage asks for every reflection point it places).

property height_error: float

The rounding (m) allowed for in a height over a plane worked out from the model’s coordinates: 16 units in the last place of the largest of them.

property face_spread: ndarray

(F,) the largest distance (m) of a vertex of each face from its plane (face_plane); 0 where all lie within height_error of it. Faces whose normals and offsets round to the same multiples of PLANE_TOLERANCE make one plane, the plane of the first of them, without lying in it exactly (worked out once).

property plane_spread: ndarray

(P,) the largest face_spread of each plane’s faces (worked out once).

property face_two_sided: ndarray

(F,) the faces with a room on both sides: a partition between two rooms or a free-standing panel; every face when the model is not oriented. A wall with a room on one side has one side, also where its plane holds such a face (plane_two_sided).

property geometric_plane: ndarray

(P,) for each plane the first of the planes that lie where it does, whichever way they face: two walls with a room on one side in line with each other that face opposite ways (the wall between two rooms drawn once for each, the two sides of a step in a room’s plan) are two planes in one geometric plane, and a point has one image in both (worked out once); a partition or a panel in line with them lies in the plane of one of them. Two planes lie in one place where their normals and offsets, in multiples of PLANE_TOLERANCE and with the signs of one plane’s turned where it faces the other way, round to numbers at most one apart: always where they differ by less than that tolerance in each, on whichever side of a rounding step either falls. So do two planes that each lie where a third does.

property face_planes: tuple[ndarray, ndarray]

(F, 3) unit normals and (F,) offsets of the plane each face itself lies in, the normal facing the way of its plane’s; its plane’s own where its face_spread is 0 (worked out once).

property face_grids: dict

The faces of planes whose faces do not all lie in them, binned in squares by _face_grid of acoustic_spaces.engine.early, by plane and distance allowed (each worked out when first asked for).

property partition: ndarray

(F,) partitions: faces that let some sound through and reflect some, so a path that meets one goes on both ways. Openings reflect nothing, and neither does a face that absorbs all the sound it does not let through.

in_front(distance: ndarray, tolerance: float) → ndarray[source]

Whether points at signed distance (…, P) from every plane, farther than tolerance, can see it: in front of it, or on either side of a two-sided plane.

passes(origins: ndarray, directions: ndarray, lengths: ndarray, ignore: ndarray, transparent_only: bool = False, counted: ndarray | None = None) → tuple[ndarray, ndarray][source]

(n, bands) share of sound that travels from each origin lengths along its direction (unit): the product of the transmission of the faces it crosses, 0 where a face lets nothing through; and (n,) how many of those faces it crosses that are not openings, or (n, m) how many of each column of counted (F, m). With transparent_only, only openings let sound through.

property band_hz: tuple[int, ...]

Centre frequencies (Hz) of the model’s bands.

mirror(points: ndarray, planes: ndarray) → ndarray[source]

Mirror each point across the plane with the same row index.

impedance_faces(faces: ndarray) → ndarray[source]

(n,) whether each of faces has a material with an impedance.

factor_faces(faces: ndarray) → ndarray[source]

(n,) whether reflections off each of faces take a reflection factor that depends on the path (see ground_factors()): faces with an impedance, and the ground of a scene with ground zones.

reflection(faces: ndarray, incoming: ndarray, order: int, impedance: bool = False) → ndarray[source]

(n, bands) specular energy share of reflections off faces (n,) of sound that travelled incoming (n, 3) from the source or the previous reflection, the order-th reflection of its path: (1 - absorption) (1 - scattering), with the scattering of the surface’s size when that applies, as the stochastic tracer reflects its rays. With impedance, the faces of factor_faces() give (1 - scattering) alone: their reflection factor, which depends on the path, takes the place of the absorption.

acoustic_spaces.engine.coverage_map(room: Room | Scene | str | Path, *, settings: Coverage | None = None, simulation: Simulation | None = None, sources: Sequence[str] | None = None, threads: int | None = None, progress: Callable[[str], None] | None = None, grid: MapGrid | None = None, rays_of: Scene | None = None) → CoverageResult[source]

Coverage maps of the scene’s sources (all by default) over its audience area.

settings default to scene.coverage (surfaces, height, spacing, rays and background noise); simulation (default: scene.simulation) gives the early order, late method, response length, seed and threads (threads overrides them) as for simulate(). Each source radiates its sound power per band (power_db(): its level, spectrum, gain and equalizer), which the speech transmission index takes as the speech level, weighted for female speech when the source’s spectrum is speech_female. In the map of all sources together, each source’s sound arrives delay_ms later. Outdoors, every point also has its level relative to free field (re_free_field).

Maps do not run the wave solver: whatever simulation.wave says, the lowest bands come from the early paths, in pressure up to early.coherent_max_band_hz, and the rays.

grid takes the place of the one the settings give, so that two runs of a scene share their points (coverage_map()); the rooms its points lie in and the air in their slabs are those of room.

rays_of is the scene as it was before its materials’ absorption was moved: with the same seed, the map then follows the rays of that scene’s map, whose materials’ absorption decides for them ( deciding), and counts on them the energy this scene’s absorption leaves. The two maps differ by what the absorption does, and not by their rays (sensitivity).

acoustic_spaces.engine.early_paths(room: Room | Scene | str | Path, source: str | None = None, listener: str | None = None, *, max_order: int | None = None, method: str | None = None, diffraction: str | None = None, threads: int | None = None) → EarlyReflections[source]

Specular and diffracted paths from one source to one listener, without the late part: those a simulation keeps as early paths, up to scene.simulation’s transition_ms after the direct sound (the mixing time with the statistical late method) and within ir_length_s.

Names default to the first source and listener; max_order, method and diffraction default to scene.simulation.early, threads to scene.simulation.performance.threads. Useful for drawing paths. The room’s checks, with which a simulation refuses to run, are not made (problems()): a listener nearer a surface than a ray can meet it, say, may lack the reflection off it here.

acoustic_spaces.engine.map_grid(room: Room, surfaces: Sequence[str] | None = None, *, height: float = 1.2, spacing: float = 1.0) → MapGrid[source]

Map points spacing metres apart, height metres above the named surfaces (default: audience_surfaces()). Only faces that can be walked on count, not walls, and only points inside the room are kept (outdoors, in the open air: not inside a building). Where the model holds several rooms, a column that a wall between them crosses gets a point in each that holds at least a fifth of it.

acoustic_spaces.engine.mixing_time(volume_m3: float | ndarray | None) → float | ndarray[source]

Time after the direct sound when the late field is diffuse (s): sqrt(V) ms, V the volume of the room the listener is in (one per listener in an array).

acoustic_spaces.engine.simulate(room: Room | Scene | str | Path, *, settings: Simulation | None = None, sources: Sequence[str] | None = None, listeners: Sequence[str] | None = None, threads: int | None = None, progress: Callable[[str], None] | None = None, groups: ndarray | None = None, late_from: Mapping[str, Mapping[str, float]] | None = None, share_waves: Collection[str] | None = None) → SimulationResult[source]

Simulate the room’s impulse responses as set in scene.simulation.

room may be a Room, a Scene or a scene file. sources and listeners pick names from the scene, simulated even when left out (enabled: false); by default, those in use. threads overrides simulation.performance.threads (0 uses every core). Raises ValueError if Room.problems() reports anything (it checks the sources and listeners in use and those named; every source, or every listener, left out is a problem when they are not named), if a name is not the scene’s, or if there is no listener to simulate.

groups (the group of each face, or -1; face_groups()) keeps in each response the moments of the late part’s reflections off each group, so that Response.reweighted() gives it for other absorption (stochastic ray tracing only).

late_from gives listeners or sources the late part of others, mixed: {name: {other: weight}}, the others being listeners (for a listener) or sources (for a source) that keep their own. Only those are traced by the stochastic ray tracer, by far the costliest stage; the statistical method gives everyone their own. Walks use it (acoustic_spaces.walkthrough.simulate_walk()): the late field changes slowly from place to place, the early sound does not. The traced late parts are kept once, and a response makes its mix of them when it reads its late part (Deferred); only a line’s or a surface’s is mixed for every listener as it is traced.

share_waves names sources whose runs of the parabolic equation (outdoors in wind or temperature gradients) may serve one another: those at one height over one ground, the sound going the same way to their listeners, where the weather and the grounds have no zones (solve()), each listener getting what its own source’s run would give it. Walks give it the places of a walking source, which would otherwise each run the equation anew.

acoustic_spaces.engine.trace_particles(room: Room, source: str | None = None, *, count: int = 4000, duration: float = 0.1, frames: int = 100, band: int = 4, seed: int = 0) → Particles[source]

Trace count particles from source (default: the first) for duration seconds and sample them at frames evenly spaced times from 0 to duration.

band picks the octave band whose absorption and scattering apply (4 = 1 kHz).

Coverage maps

acoustic_spaces.engine.coverage_map() and the classes it returns are listed under Simulation above; the module also has the parameters a map shows and the A-weighting.

Coverage maps: room acoustic parameters on a grid over the audience area.

The audience surfaces, picked by name, are covered with square columns spacing metres wide. Each column holds a map point at listening height above the surface (two or more where surfaces lie above each other, such as a balcony over the stalls, or where a wall between rooms crosses it), with a slab of air around it. For every source:

  • the direct sound and the specular reflections up to simulation.early.max_order are found exactly at each point, as at a listener;

  • everything else comes from one stochastic ray tracing run in which every leg of every ray adds its track length through each slab it crosses (stochastic_map_energy()), so a map costs about as much as one listener; with the statistical late method, the exponential decay of statistical_energy(), as at a listener.

Each point’s parameters follow from its energy per band and time slot as at a listener (ISO 3382-1), together with the speech transmission index (IEC 60268-16) and sound pressure levels from the sources’ sound power.

acoustic_spaces.engine.coverage.MAP_PARAMETERS: dict[str, MapParameter] = {'c50': ('C50 (dB)', 'clarity, 50 ms', True, 1.0, '{:.1f}'), 'c80': ('C80 (dB)', 'clarity, 80 ms', True, 1.0, '{:.1f}'), 'd50': ('D50', 'definition', True, 1.0, '{:.2f}'), 'edt': ('EDT (s)', 'early decay time', True, 1.0, '{:.2f}'), 'g': ('G (dB)', 'strength', True, 1.0, '{:.1f}'), 'insertion_loss': ('Insertion loss (dB)', 'insertion loss of the buildings, barriers or vegetation the map was also run without', True, 1.0, '{:.1f}'), 'insertion_loss_a': ('Insertion loss (dB(A))', 'A-weighted insertion loss of the buildings, barriers or vegetation', False, 1.0, '{:.1f}'), 'long_term': ('Long-term level (dB)', 'level over a long term, outdoors: the mean over the weather classes and the day', True, 1.0, '{:.1f}'), 'long_term_insertion_loss': ('Long-term insertion loss (dB)', 'insertion loss over a long term: the long-term level without the buildings, barriers or vegetation less that with them', True, 1.0, '{:.1f}'), 'long_term_insertion_loss_a': ('Long-term insertion loss (dB(A))', 'A-weighted insertion loss over a long term of the buildings, barriers or vegetation', False, 1.0, '{:.1f}'), 'rating_level': ('Rating level (dB(A))', "level over a long term with each period's penalty, A-weighted (L_den)", False, 1.0, '{:.1f}'), 're_free_field': ('Re free field (dB)', 'level relative to free field, outdoors: the excess attenuation with its sign turned', True, 1.0, '{:.1f}'), 'spl': ('SPL (dB)', 'sound pressure level', True, 1.0, '{:.1f}'), 'spl_a': ('SPL (dB(A))', 'A-weighted sound pressure level', False, 1.0, '{:.1f}'), 'sti': ('STI', 'speech transmission index', False, 1.0, '{:.2f}'), 't20': ('T20 (s)', 'reverberation time from a 20 dB decay', True, 1.0, '{:.2f}'), 't30': ('T30 (s)', 'reverberation time from a 30 dB decay', True, 1.0, '{:.2f}'), 'ts': ('Ts (ms)', 'centre time', True, 1000.0, '{:.0f}')}

The parameters of every map point.

acoustic_spaces.engine.coverage.OUTDOOR_MAP_PARAMETERS = ('re_free_field',)

The map parameters of an outdoor scene alone, those of a map also run without some of its buildings, barriers or vegetation (simulation.insertion_loss_of), those of a map run in weather classes (long_term), and those of a map run both ways.

acoustic_spaces.engine.coverage.ROOM_MAP_PARAMETERS = ('spl', 'spl_a', 'g', 'c50', 'c80', 'd50', 'edt', 't20', 't30', 'ts', 'sti')

The parameters of every map; an outdoor map, one also run without some of its buildings, barriers or vegetation, and one run in weather classes have the others as well.

acoustic_spaces.engine.coverage.SPREAD_PARTS = ('standard', 'low', 'high', 'at_least', 'at_most')

What a map’s spread gives of a parameter: its standard uncertainty, the ends of its interval, and the value it is at least and at most (CoverageMap.spread_of()).

acoustic_spaces.engine.coverage.TIME_STEP = 0.001

Time resolution of each point’s energy response (s).

class acoustic_spaces.engine.coverage.MapParameter(label: str, description: str, per_band: bool, scale: float, format: str)[source]

How a map parameter is shown: label with its unit, what it is, whether it has a value per octave band, and the scale and number format of the shown value (the stored value is in SI units: Ts in seconds shows in milliseconds). The label and description are marked for translation; show them through _().

label: str

Alias for field number 0

description: str

Alias for field number 1

per_band: bool

Alias for field number 2

scale: float

Alias for field number 3

format: str

Alias for field number 4

class acoustic_spaces.engine.coverage.MapSpread(standard: dict[str, ~numpy.ndarray], materials: dict[str, dict[str, ~numpy.ndarray]], coverage: float = 0.95, one_sided: float = 0.95, assumed: dict[str, str] = <factory>, held: dict[str, list[int]] = <factory>)[source]

The uncertainty of a map’s parameters that the uncertainty of the materials’ absorption leads to, by the law of propagation of uncertainty (coverage_map()).

standard: dict[str, ndarray]

Parameter -> its combined standard uncertainty, shaped as the map’s values: the root of the sum of the squares of the materials’ parts. NaN where the value is undefined, in the map or in a run of the spread.

materials: dict[str, dict[str, ndarray]]

Material -> parameter -> its part: half of the map with its absorption one standard uncertainty up less the map with it one down (negative where more absorption lowers the value).

coverage: float = 0.95

The probability of the interval, and that of the one-sided bounds.

assumed: dict[str, str]

As a listener’s spread has them ( Spread): the built-in materials that took the scene’s default uncertainty, and the bands in which a material absorbs everything, which no run moved.

acoustic_spaces.engine.coverage.audience_surfaces(room: Room) → list[str][source]

The surfaces a map covers when none are named: those whose names contain “audience”, else “floor” (outdoors, “ground”).

acoustic_spaces.engine.coverage.uncertainty_text(value: float) → str[source]

A standard uncertainty as a map shows it: to two significant digits, which are as many as it has (GUM, JCGM 100:2008, 7.2.6), and to four decimals at most.

The uncertainty of a coverage map from its materials’ uncertain absorption.

A listener’s spread is a Monte Carlo over the absorption that re-weights its traced response for each draw (uncertainty). A map keeps no response at its points to re-weight (no count of the reflections off each material, no batches of rays), so its spread comes from the law of propagation of uncertainty instead (GUM, JCGM 100:2008, 5.1.2), with the sensitivities found numerically (5.1.3, note 2). The inputs are those of the listeners’ draws: one deviate per material, which its bands share, the materials independent of one another. For each material the map is traced again twice, with its absorption where a deviate of plus and of minus one standard deviation puts it (absorption_nodes(): its own plus and minus its standard uncertainty, held to a draw’s limits; in a run in third octaves, each third octave of a material given in them), on the same points and with the same seed. Half the difference of the two maps is that material’s part of the uncertainty of each value at each point, and the root of the sum of the parts’ squares the value’s combined standard uncertainty (MapSpread). A map with M such materials is run 2 M + 1 times.

The two runs of a material have to follow the same rays, or their difference is the rays’ as much as the absorption’s. A seed alone does not see to that, because the tracer lets the energy a ray carries decide for it: the late part splits and thins out its rays by it (simulation.late.splitting), a ray passes a surface that lets sound through or reflects off it at random in proportion to the two shares, plants scatter it at the rate of the bands it still carries, and it ends where too little is left. Each of these comes out otherwise once the absorption is moved. So a material’s two runs take these choices from the scene’s own absorption (rays_of of coverage_map()): they follow the rays of the map itself, and count on them the energy that the moved absorption leaves. In a box of 8 by 6 by 3.5 m (2 000 rays) the walls’ part of T30 at 1 kHz, for an uncertainty of 0.001, is that uncertainty times a slope of -2.4 to -2.6 s at each of the 12 points; with rays of their own the two runs gave -1.6 to -4.1 s.

The runs are whole map runs, in the weather classes and without the parts an insertion loss names where the map has those ( coverage_map()), so each kind of value a map holds gets its uncertainty. A value that one of a material’s two runs leaves undefined (a decay too short for its T30, say) has none.

It is first order: where a value bends over a material’s uncertainty, as a decay time does in a room with little absorption for a tolerance of 0.1, the standard uncertainty comes out low. A material whose absorption lies within its uncertainty of 0, or of the most a draw takes, has its draws held there, which the two runs follow in part only.

Not counted: the rays’ random error, and what a listener’s spread does not count either (the scattering, the method, a ground’s absorption uncertainty beside its impedance). The uncertainty has that error itself: where a value changes from one seed to the next, so does its uncertainty, and a material’s small part of it more. How far both go is measured in docs/coverage-maps.md (“Uncertainty”): the law against the Monte Carlo of a listener at a point of the map, and the uncertainty between two seeds of a map.

The interval and the one-sided bounds take the result as normal (spread_of()), where a listener’s are its draws’ quantiles.

acoustic_spaces.engine.sensitivity.coverage_map(room: Room | Scene | str | Path, *, spread: bool | None = None, long_term: LongTerm | None = None, without: Sequence[str] | None = None, settings: Coverage | None = None, simulation: Simulation | None = None, sources: Sequence[str] | None = None, threads: int | None = None, progress: Callable[[str], None] | None = None) → CoverageResult[source]

coverage_map(), and with spread (default: the map settings’ spread) the uncertainty of the values of every map from the materials’ absorption uncertainty (spread): the map is run twice more for each material of spread_materials(), on the same points and along the rays of the map itself. The one-sided bounds’ probability is simulation.uncertainty.one_sided. A map none of whose materials has an uncertainty is run once and has no spread.

acoustic_spaces.engine.sensitivity.spread_materials(room: Room) → list[str][source]

The materials whose absorption a map’s spread moves: those on room’s surfaces that have an uncertainty a spread takes (uncertainty_of()) and absorb less than everything in some band.

Edge diffraction

Edge diffraction: sound that bends around the edges of the room, after the uniform theory of diffraction (UTD) for a rigid wedge (Kouyoumjian and Pathak, 1974).

The edges that diffract are those where two faces meet at an angle that opens more than 180 degrees towards the room (the corner of a pillar, a balcony front, the end of a wall) and the free edges of open surfaces (panels and screens). Corners of the room itself open less than 180 degrees towards the room, cast no shadow and are left out, as are the slight bends between the facets of a curved surface.

Sound from a source reaches a listener over an edge along the shortest path that touches it, at the point where the path makes equal angles with the edge on both sides. The diffracted wave splits into terms that each belong to one geometric wave: the direct sound, or its reflection off either face of the edge. Where that wave arrives, its terms are added to it coherently, frequency by frequency, which changes its energy per band; on the far side of its boundary, where the edge cuts the wave off, the terms make a new path. At the boundary itself both sides carry a quarter of the wave’s energy, so levels stay continuous where the direct sound or a reflection disappears behind an edge.

In the bands where the paths add in energy, each specular path interferes with the terms of its own wave only, as it adds to the other paths in energy: each term counts in two waves (clusters), the geometric wave it continues, by c, and the edge’s diffracted wave, by sqrt(1 - c^2). On the lit side of its boundary c is the term’s coherence with the geometric wave over the band; on the dark side, where the term stands in for the wave, c = sqrt(1 - |F|^2) with F its transition function, 0 well off the boundary. So in the diffracted path the terms of all the waves add up coherently, as they must deep in the shadow, except near each wave’s boundary, where they add in energy too. Coherent all the way, levels would step by up to 4 dB where one wave’s boundary is crossed while another’s terms are there; in energy all the way, the shadow of a screen would be 3 dB deeper than Maekawa’s chart. As it is, deep behind the corner of an L-shaped room the 63 Hz band is 0.7 dB below the coherent sum, the 125 Hz band 0.4 dB, and from 500 Hz up the two agree within 0.1 dB.

With first_order diffraction the same is done for the first-order reflections: sound that reflects off a plane and then bends over an edge, and sound that bends over an edge and then reflects. Where the path touches the edge closer to that plane than the rays that test it start from the edge, it counts by where the path itself reflects: at that very point where it lies in the plane, off a face that lies there (the ground an upright edge stands on), not off a face of the plane elsewhere (a roof level with a barrier’s top).

With second_order the direct sound also bends over two edges in turn: over a thick wall or a pillar, round both of its corners. Its shortest path touches each edge where the path makes equal angles with it on both sides. The wave from the first edge reaches the second as a wave of its own, which the second bends again: where the path runs along a face between them (the top of a thick wall), that wave already holds the face’s reflection, so the second edge’s coefficient is halved; as it is where the path only leaves the first edge along a face, which ends before the second (a roof’s corner, then a barrier level with the roof), or only reaches the second along one, so that the path is the same both ways round. Along a face that absorbs, it is a point source’s wave along a locally reacting surface at grazing incidence (Weyl-van der Pol): both edges take the face as rigid, and the path the ground wave’s loss F(w) over the way along it. Near the first edge’s boundaries its wave still curves like the source’s, not like a wave from the edge, and the second edge’s distance parameter takes that curvature where the wave reaches it; seen from the listener, the same holds for the second edge’s wave at the first. Each edge takes the other’s curvature by how much nearer the other’s boundary is, so the path is the same both ways round. In the bands where the paths add in energy, each term splits at each edge as at one: near the first edge’s boundary it is part of the wave of the path over the second edge alone, near the second’s of the path over the first alone, and well off both the waves of the two edges add coherently. Where the source’s wave reaches the listener past both edges, the paths over each edge alone both take their terms off it, and the path over both gives back what they take twice: over a block’s top that the source and the listener both just clear, the direct sound and its reflection off the top less the two corners’ terms come to nothing, and the path over both is all there is, half the direct sound. Only with the source or the listener exactly in the plane of a face that the path runs along at the edge next to them (the first edge’s, or the second’s) is it left out, where the paths over one edge count once already (_in_front()).

Openings are not there for diffraction: the edges of a doorway are the free edges of the wall round it, and diffracted paths pass through openings as through air. Outdoors, the open sky is an opening too, but the edges it meets diffract nothing (the ground goes on past them), nor do edges that lie on the ground, which closes the corner of a wall or a barrier standing on it (see acoustic_spaces.geometry.outdoor). Any other surface stops them, even one that lets some sound through: the sound diffracted through a wall is left out, as it is far weaker than the sound that passes it straight.

acoustic_spaces.engine.diffraction.DIFFRACTION_MODES = ('none', 'direct', 'first_order', 'second_order')

Diffraction settings: none, of the direct sound only, of the direct sound and first-order reflections, or also of the direct sound over two edges in turn.

acoustic_spaces.engine.diffraction.FREQUENCIES_PER_BAND = 8

Frequencies per octave band at which the diffracted waves are evaluated, one in the middle of each equal slice of the band; energies are averaged over the band. A third-octave band has a third as many, rounded up.

acoustic_spaces.engine.diffraction.MIN_BEND_DEG = 15.0

Faces that bend away from each other by less than this (degrees) make no diffracting edge: the facets of a curved surface, for example.

acoustic_spaces.engine.diffraction.MIN_RELATIVE_ENERGY = 0.0001

A diffracted path is dropped when its energy is this far below that of the direct sound in free field, in every band.

class acoustic_spaces.engine.diffraction.EdgeDiffraction(model: TraceModel, source: ndarray, *, speed_of_sound: float, air: ndarray, directivity: Directivity | None = None, orientation: ndarray | None = None, mode: str = 'first_order', edges: Edges | None = None, coherent: int = 0, both_sides: bool = False, threads: int = 0)[source]

Diffraction of one source’s sound at the edges of a model, for any number of listeners: apply() adds it to the specular paths of one listener.

mode is "direct" (the direct sound only), "first_order" (also the first-order reflections, before or after the edge) or "second_order" (also the direct sound over two edges in turn); with both_sides the paths over one edge may also reflect both before and after it (the four paths over a barrier on the ground). air is the energy attenuation per metre per band; directivity and orientation are the source’s, as for find_paths(). In the lowest coherent bands the terms of every wave add coherently, the faces of the edges and the planes on the way reflect with the phase of their reflection factors, and the diffracted paths carry their pressure (EarlyReflections.spectrum) to add to the specular paths in pressure (coherent) instead of through cross terms. Only the pairs of an edge and a plane that a reflection between them can take are tested (_reflecting_pairs(), on threads threads, 0 for every core).

ledger: tuple[EarlyReflections, Clusters] | None

The paths apply() returned last and the waves of their pieces.

unheard: tuple[EarlyReflections, EarlyReflections] | None

The paths apply() returned last and its paths over edges in a row (_in_line()) that carry too little to be among them, or None.

apply(listener: ndarray, paths: EarlyReflections, max_delay_s: float) → EarlyReflections[source]

paths (the specular paths from the source to listener) with the diffracted sound up to max_delay_s: specular paths near the edges’ shadow and reflection boundaries change their energy, and paths over the edges into the shadows are added. In the bands where the paths add in energy, the waves of their terms (clusters) are kept in ledger with the paths returned, for the edge fade to add to.

clusters(listener: ndarray, paths: EarlyReflections) → Clusters | None[source]

The waves of the specular paths paths at listener in the bands where the paths add in energy, each path its own; None without such bands.

settled(paths: EarlyReflections, energy: ndarray, has: ndarray)[source]

paths with the energy (n, bands where the paths add in energy) the waves give the paths that has says are in them.

class acoustic_spaces.engine.diffraction.Edges(start: ndarray, direction: ndarray, length: ndarray, along: ndarray, normal: ndarray, wedge: ndarray, face: ndarray, plane: ndarray, reflection: ndarray, fade: ndarray | None = None, corner: ndarray | None = None, closed: ndarray | None = None)[source]

The diffracting edges of a model, as straight segments.

Each edge is a wedge between face 0 and face n that is open over wedge times pi radians (between 1 and 2; exactly 2 for the free edge of a surface, where face 0 and face n are the two sides of the same face). Angles around an edge are measured from face 0 towards its normal, through the open side.

fade: ndarray | None = None

(E, 2) how far the paths over each edge fade at its start and end, (E, 2, 2) the edge it meets at a corner there in the plane of face 0 and of face n, or -1, and (E, 2) whether a face across it closes the end (end_fades)

bisector() → ndarray[source]

(E, 3) unit vectors from each edge into the middle of its open side.

distances(index: ndarray, points: ndarray)[source]

Position along edge index of each point and distance from it, as frame() has them.

frame(index: ndarray, points: ndarray)[source]

Position along edge index of each point, distance from it and angle around it from face 0, and whether the point lies in the open side of the wedge.

acoustic_spaces.engine.diffraction.band_frequencies(per_band: int | None = None, bands: Literal['octave', 'third_octave'] = 'octave') → tuple[ndarray, ndarray][source]

(bands, per_band) frequencies at the middle of equal slices of each octave band (from its centre over the square root of 2 to its centre times it) or third-octave band (over and times the sixth root of 2), and the width of the slices per band (bands,). per_band defaults to FREQUENCIES_PER_BAND per octave.

acoustic_spaces.engine.diffraction.diffract(model: TraceModel, source: ndarray, listener: ndarray, paths: EarlyReflections, *, speed_of_sound: float, air: ndarray, max_delay_s: float, directivity: Directivity | None = None, orientation: ndarray | None = None, mode: str = 'first_order', edges: Edges | None = None, coherent: int = 0) → EarlyReflections[source]

paths from one source to one listener with the sound diffracted at the model’s edges added; see EdgeDiffraction.

acoustic_spaces.engine.diffraction.find_edges(model: TraceModel, min_bend_deg: float = 15.0) → Edges[source]

The edges of model that diffract (see the module notes); collinear pieces of one edge between the same two planes are joined.

acoustic_spaces.engine.diffraction.fresnel_tail(z: ndarray) → tuple[ndarray, ndarray][source]

1/2 - C(z) and 1/2 - S(z) for z >= 0, where C and S are the Fresnel integrals of cos(pi t^2 / 2) and sin(pi t^2 / 2) from 0 to z.

Power series below z = 3.5 and the asymptotic expansion above, good to about 1e-8 where they meet and better elsewhere; computing the tails directly keeps their accuracy for large z.

acoustic_spaces.engine.diffraction.transition(x: ndarray) → ndarray[source]

The UTD transition function F(X) = 2j sqrt(X) e^(jX) times the integral of e^(-j t^2) from sqrt(X) to infinity, for X >= 0. It rises from 0 at X = 0 to 1 for large X, where the diffracted wave no longer depends on the shadow boundary.

acoustic_spaces.engine.diffraction.wedge_prefactor(n: ndarray, k: ndarray, sin_beta: ndarray) → ndarray[source]

-e^(-j pi/4) / (2n sqrt(2 pi k) sin beta0), the factor in front of the terms.

acoustic_spaces.engine.diffraction.wedge_terms(n: ndarray, phi: ndarray, phi_source: ndarray, kl: ndarray, lit: ndarray | None = None) → ndarray[source]

The four cotangent terms of the UTD wedge coefficient, without its prefactor.

n is the open angle of the wedge over pi; phi and phi_source are the angles of the listener and source around the edge, from face 0; kl is the wave number times the distance parameter L. Arrays broadcast; the result has a last axis of 4: the two terms of the incident wave, then those of the reflections off face n and off face 0. Each term is singular on its shadow or reflection boundary, where it is replaced by its limit; exactly on a boundary, lit (a last axis of 3: the incident wave, the reflections off face 0 and off face n) says which side’s limit to take (default: the lit side).

The terms at the edges of every specular path, so that each path fades in and out at the edges that cut it off instead of stepping.

The edge diffraction (diffraction) bends the direct sound round each edge and, with first_order, the first-order reflections, one event at a time: each term it adds stands alone. A path with more reflections, such as the copy of a first-order reflection off the ground, or a second-order reflection, would come or go at full strength where an edge cuts it off: where a leg of it passes an edge, or where a point it reflects at passes the edge of the face. Here every specular path, found or just missed, takes the terms of the uniform theory of diffraction (Kouyoumjian and Pathak, 1974) at each of its events.

An event is a leg of the path, where it passes edges, or a reflection, near the edges of the face it reflects off. Its term at an edge is the UTD’s term of the boundary that belongs to it: the incident wave’s at a leg, the reflection’s off the face at a reflection. It runs from the path’s image on the source side (the source mirrored in the reflections before) to its image on the listener side (the listener mirrored in the reflections after), so that the path over the edge has the path’s own length near the boundary, relative to the path.

The terms of one event add: every edge counts on its own side of its boundary, as the edges round an opening do in the boundary diffraction wave (Rubinowicz, 1917), so that both edges of a gap count where the path goes through it, and both where one of them cuts it off. The events of a path multiply, as the path must get past each in turn: with b = 1 where the path gets past an event and 0 where it does not, and G the sum of the event’s terms, the path carries the product of b + G over its events. Each product of terms in it is a path of its own, which arrives later by the detours of all its terms. Off the terms comes what the edge diffraction already adds where it has the path over the edge (the term on the lit side where the path is found, on the dark side where it is not), so that both together make the product.

A path that is not found is followed where one event stops it and an edge of what stops it explains that, on the dark side of its boundary: a leg blocked by a face of the edge (where the path crosses the face right at a point of reflection, as at the foot of a barrier standing on the ground it reflects off, the leg that crosses the face’s plane), or a point of reflection past the edge of its face. Where a point of reflection lies past the end of its plane’s faces at an edge that stands on one of them (a corner of the room on the floor; not a wall as high as a roof elsewhere in the plane, nor a building’s corner under its roof, where the roof’s plane does not go on round it), the face of the edge that blocks a leg next to it stops the path, and the reflection takes the face nearest to that point. Where several events stop it, in at most two runs (the events with no reflection on its face between them), the path is followed where one edge explains each run, with its images in the planes it has a face in or stands on (its blocked legs blocked by the edge’s faces, its reflections past the end of their faces in such a plane, in front of the edge’s face where it has one there: not under a roof), or two edges explain the stops between them, each a part in a row; the path then takes the terms of both stops. Its reflection points are those of the image method; of the orders of reflections off perpendicular planes, which have one image, the one that can be (each is tried, as the early stage may have found only one). Paths that pass through a surface that lets sound through take no terms, as they are not the geometric wave the terms continue.

Reflections off perpendicular planes commute: in either order they give one image, and the path takes the order its points come in along the way. The path over an edge may take another, such as off the floor after a corner that stands on it rather than before, so each path also takes the terms of the events of every other order of its reflections that gives its image, those that differ from its own once each (all orders up to four reflections, beyond that those that swap two next to each other).

At a leg, the terms of the edge’s reflections whose paths cannot be, with the source or the listener side behind the face’s plane, stand in for those reflections, which the early stage follows in front of the plane only for paths of a lower order than the highest; they take what the face gives the reflection where it meets the plane, the scattering of its surface’s size included where the early stage weakens the reflection for it (size_scattering()).

A leg that gets past an edge on the dark side of its boundary, as beside the end of a strip, takes the edge’s term where the edge’s face crosses the leg’s line on the leg: where the line crosses the plane of the edge’s face (of a solid wedge, the plane through the middle of its solid side), it must lie on the leg’s side of the planes the leg reflects off at its ends. Beyond one of them the edge belongs to the next leg (a barrier’s top past the reflection off the ground that ends a leg, which blocks the leg after it), save for an edge along the plane’s normal, its own image there. A point of another edge in such a plane (on a barrier’s top level with the roof a path reflects off) belongs to the leg it stands beside: the one before the point of reflection or the one after it.

Each term makes a path over its edge, which must be clear from the edge to where it reflects first before and after it (where the line from the edge to the image on either side first meets a plane it may reflect off there), save where two events stop the path and it reflects next to the other’s blocked leg, which blocks the way there too. Where it stands in for a missed path (at an event that stops it, and where several do, at the legs next to a stopped reflection) it must be clear on from there too, leg after leg off the path’s planes to the source and the listener, as it reflects at other points than the path does (past a barrier’s foot, behind another barrier), up to another event that stops the path, whose terms go on from there: the terms of one event add, each one way past all that stops the path there, so each must get past all of it on its own. At an event the path gets past, the term goes on with the path’s wave, and an obstacle on its further legs is mostly another event of the path, whose terms multiply it already: checked there too, that obstacle would count twice (in validation/edge_diffraction.py’s hall with alcoves the level then steps by 4.2 dB at 63 Hz over 2 cm, against 1.7 dB). In the bands where paths add in pressure it carries its phase. In the others it is a piece of two waves (clusters): it continues the geometric wave of its boundary, the path’s, by c, its coherence with that wave over the band on the lit side of the boundary and the UTD’s sqrt(1 - |F(X)|^2) on the dark side, where the wave is gone, and is part of its event’s diffracted wave by sqrt(1 - c^2), with the terms the edge diffraction adds there (round a narrow face the two edges’ terms nearly cancel). A product of terms is split alike, term by term, and so are the events the path gets past before a term: the part of their terms in an event’s diffracted wave, times what continues the path at its other events, is part of that wave. A term stops where the point it diffracts at leaves the end of its edge (the UTD has no terms for the corners of edges), so the level can still step slightly there; where that end lies in a plane the path reflects off next to the event, the edge goes on as its image in the plane, and the leg on one side of the reflection or the other takes the term. Where such a leg stops a path and the edge belongs to the obstacle that stops it (its own face, or one joined to it by no inside corner, as the far part of a bent or curved barrier or another wall of a building), the term of the edge’s image, found on the leg on the other side, is the stopping leg’s: in the plane’s image the two legs are one line, and the edge is one more way round that one obstacle.

class acoustic_spaces.engine.edge_fade.EdgeFade(diffraction: EdgeDiffraction, candidates: list[ndarray])[source]

The terms at the edges of diffraction’s model of one source’s specular paths (see the module notes), for any number of listeners. candidates are the plane sequences the early stage tests at each listener (as find_paths() takes them); those not found there may still be found past an edge.

covered(before: int, after: int) → bool[source]

Whether the edge diffraction bends the waves from a source side mirrored in before planes to a listener side mirrored in after planes.

terms(listener: ndarray, paths: EarlyReflections, max_delay_s: float, bent: EarlyReflections | None = None) → dict[source]

The terms at the edges of paths (the specular paths at listener) and of the paths just missed there, up to max_delay_s: for join(). With bent, the paths the edge diffraction finds at listener, the terms leave out exactly those of its paths over an edge (also those it keeps unheard); without, those it adds where it bends an event, as it does where nothing else stops its paths.

join(paths: EarlyReflections, terms: dict) → EarlyReflections[source]

paths (the specular paths of terms() with the edge diffraction’s) with the terms of terms(): in the bands where the paths add in energy, the terms’ pieces join the waves of paths (those the edge diffraction keeps for them in its ledger, or the specular paths’ own), which give every path its energy; and the paths over the edges that carry at least the edge diffraction’s least energy (MIN_RELATIVE_ENERGY of the direct sound in free field) in some band.

The waves that are one wave, in the bands where the early paths add in energy.

Indoors, above simulation.early.coherent_max_band_hz, the early paths add in energy, as if their phases were random. The sound bent round an edge does not: near its boundary each term of the uniform theory of diffraction continues the geometric wave it belongs to, and its pressure adds to that wave’s, so that the two together change smoothly where the geometric wave stops (diffraction, edge_fade). Away from it the term is a wave of its own, bent round the edge, whose terms (one for each boundary of the edge) add up as one wave by how far each lies from its boundary.

Each term therefore counts in two waves. It continues its geometric wave by c and is part of its diffracted wave by s = sqrt(1 - c^2): its own energy stays |t|^2 = (c^2 + s^2) |t|^2, and two terms cohere by the products of their shares, through every wave both are part of. On the lit side of its boundary, where the geometric wave arrives, c is the term’s coherence with it over the band, as the term goes X / k farther (X the argument of its transition function); on the dark side, where the wave is gone, c = sqrt(1 - |F(X)|^2), so that the term continues it near the boundary only, and deep in the shadow all the terms of an edge are one wave (transition()). All the edges of an event are one diffracted wave, as the edges round an opening are in the boundary diffraction wave (Rubinowicz, 1917): the terms whose paths over an edge run from the same image of the source to the same image of the listener, whatever the edge, so that round a narrow face the two edges’ terms nearly cancel as they do in pressure, and the many edges of a curved surface’s facets add up to the surface’s own reflection.

A wave’s energy is that of the pressures of its pieces added up, averaged over each band’s frequencies and over the slice of the band each frequency stands for, where two pieces that arrive t seconds apart interfere by sinc(t times the slice’s width) of what they would at its frequency: it is never negative, as it is for the pressures of any set of waves. A wave of a few pieces takes them pair by pair; in one of more, the slice is averaged over with a Gauss-Legendre rule of as many points as the pieces’ spread in arrival needs (within 1e-10 of sinc), so that the work grows with the pieces, not with their pairs: the facets of a curved surface give events of hundreds of thousands of terms.

The wave of a specular path, found by the early stage, is that path’s: the cross terms of the pieces that continue it go to its energy, and each piece keeps its own; where the cross terms take more than the path has, the rest comes off the pieces in proportion to their energy, which is always enough. In every other wave each piece takes its own energy and half its cross term with each other piece; where that comes to less than nothing it takes none, and the others give it in proportion, so that the wave’s energy stays what it is.

class acoustic_spaces.engine.clusters.Pages[source]

The pressure of pieces, kept in pages of _PAGE bytes. The C library maps an array that large on its own and hands it back to the system once it is let go, where it keeps smaller ones in its heap: the millions of pieces of a room of many facets (BRAS CR3), let go at one listener, left gigabytes there that the next could not use.

keep(values: ndarray) → ndarray[source]

values (n, …) in single precision, copied into a page.

acoustic_spaces.engine.clusters.hand_back() → None[source]

Hands back to the system the memory the C library keeps free (glibc’s malloc_trim; elsewhere nothing). The pieces of a room of many facets come and go by gigabytes at each listener, many of them in blocks too small for the library to map on their own, and it kept what they freed: at the start of BRAS CR3’s second listener in octave bands, 1.3 GiB free of a heap of 1.5 GiB, and in third-octave bands more at each listener, until the third ran out of memory.

class acoustic_spaces.engine.clusters.Clusters(slice_hz: ndarray, speed_of_sound: float, size: float)[source]

The pieces of the waves that are one wave (see the module notes), in the bands where the early paths add in energy, whose slices are slice_hz (Hz) wide, for sound at speed_of_sound; images closer than _STEP times size (m) are the same.

geometric(image: ndarray, order: ndarray) → ndarray[source]

The waves of the specular paths of order (n,) reflections whose image of the source is image (n, 3).

diffracted(source_side: ndarray, listener_side: ndarray) → ndarray[source]

The diffracted waves whose paths over an edge run from the image of the source source_side (n, 3) to that of the listener listener_side (n, 3).

private(count: int) → ndarray[source]

count waves of their own.

add(rows: ndarray, keys: ndarray, pressure: ndarray, distance: ndarray, anchor: bool = False, own: ndarray | None = None) → None[source]

Pieces of the rows rows (-1 for a row left out) in the waves keys: their pressure (n, bands, M) with the phase of their whole way, which is distance (n,) metres long. anchor: the rows are specular paths, whose waves they are, with energy own (n, bands). Pressure in single precision with something in every piece is kept as given (the edge fade’s comes so, in its own Pages); any other is copied into a page. The energy of pieces in single precision without own is not kept but worked out again from their pressure when it is needed.

alone(rows: ndarray, energy: ndarray) → None[source]

Pieces of the rows rows that are waves of their own, with energy (n, bands).

renumber(mapping: ndarray) → None[source]

Rows i become mapping[i] (-1: left out).

resolve(count: int) → tuple[ndarray, ndarray][source]

(count, bands) the energy of each of count rows from its pieces, and (count,) which rows have any.

Insertion loss

The insertion loss of an outdoor scene’s buildings, barriers and vegetation.

The scene is run as it is and again without them ( without()), with the same settings and seed, so that the two runs’ rays start alike; the insertion loss is the level without them less the level with them, per octave band (and A-weighted, for the sound power of each source). A barrier that takes 10 dB off has an insertion loss of 10 dB; a building that sends sound back towards the listener can have a negative one.

simulation.insertion_loss_of names what to take away; simulate() and coverage_map() read it unless given without, and are simulate() and coverage_map() when it names nothing.

acoustic_spaces.engine.insertion.a_weighted_loss(spl: ndarray, loss: ndarray) → float[source]

The A-weighted insertion loss (dB) from the levels with the parts per octave band (dB SPL) and their insertion loss per band: the A-weighted level without them less that with them.

acoustic_spaces.engine.insertion.bare_room(room: Room, names: Sequence[str]) → Room[source]

The room without the buildings, barriers and vegetation of these names.

acoustic_spaces.engine.insertion.coverage_map(room: Room | Scene | str | Path, *, without: Sequence[str] | None = None, settings: Coverage | None = None, simulation: Simulation | None = None, sources: Sequence[str] | None = None, threads: int | None = None, progress: Callable[[str], None] | None = None, grid: MapGrid | None = None, rays_of: Scene | None = None) → CoverageResult[source]

coverage_map(), and the insertion loss of the buildings, barriers and vegetation named in without (default: simulation.insertion_loss_of) at every map point: each map gains insertion_loss (dB per octave band) and insertion_loss_a (dB(A), for the sources’ sound power), the level without them less the level with them. Both runs share the map’s points, those of the scene as it is (or grid, as coverage_map() takes it, as it does rays_of, for both runs).

acoustic_spaces.engine.insertion.simulate(room: Room | Scene | str | Path, *, without: Sequence[str] | None = None, settings: Simulation | None = None, sources: Sequence[str] | None = None, listeners: Sequence[str] | None = None, threads: int | None = None, progress: Callable[[str], None] | None = None, groups: ndarray | None = None) → SimulationResult[source]

simulate(), and the insertion loss of the buildings, barriers and vegetation named in without (default: simulation.insertion_loss_of) at every listener: the result is the scene’s as it is, with removed and insertion_loss (dB per octave band, the level without them less the level with them; NaN where either level is undefined). groups are for the run of the scene as it is.

Early reflections in pressure

Early paths that add in pressure at low frequencies.

The echogram adds the early paths in energy, band by band, as if their phases were random. At low frequencies they are not: a band’s filter rings longer than the early paths lie apart, and their pressures add. The impulse response has always added them that way (its paths are impulses that add sample by sample), so the parameters of the 63 and 125 Hz bands read from it differed from the echogram’s by up to 2 dB.

In the lowest bands, up to simulation.early.coherent_max_band_hz, every early path therefore carries its pressure (EarlyReflections.spectrum) at the frequencies the edge diffraction is evaluated at: the phase of each reflection factor on the way, and for paths over an edge the whole complex UTD coefficient, whose terms then add to the specular paths in pressure, as the theory has them, rather than through the cross terms of the higher bands. Its level in each band stays the energy that band gives it. A surface reflects like a locally reacting one whose admittance has the material’s absorption in every band (fit_admittance()), so the phases in a band do not depend on how many bands add in pressure: R = (cos theta - Y) / (cos theta + Y) at the angle of incidence theta. A hard surface reflects in phase at every angle; an absorbing one turns the phase of sound that grazes it, by half a turn at grazing incidence. Above those bands each path keeps the phase it has at their top (held_phase()).

But for the paths over an edge: in those bands the energy of a wave bent round edges is that of its pieces added up in pressure already (clusters), and each piece carries its share of it. Added in pressure once more, with the phases held from the bands below, the pieces of one wave counted their interference twice: the facets of BRAS’s hall, thousands of pieces within a period, rendered 16 times their energy at 250 Hz at the dummy head. A rendered response therefore turns each path over an edge by a phase of its own (own_phases()), drawn from the path and the response’s seed, as far as other paths’ sound reaches it where it arrives, so that it adds to them in energy on average, as in the echogram. One that arrives alone keeps its held phase, which its bands need to join the coherent ones. Reflections keep theirs: two that arrive together add in pressure, as at a point of a real room, where the echogram gives their average over the band.

The impulse response builds those bands’ early part from the pressures, and the echogram reads each band’s early energy from the same signal through the band filters of the analysis of measured responses (band_filter_gains()), as for the wave solver’s bands: an impulse response and the echogram it came from now give the same parameters in those bands. The filters let in a little of the bands above, where the echogram gives each path over an edge the mean over seeds of the phase factor a rendered response turns it by (with_mean_phases()): with the phases held, the pieces’ interference counted twice reached it through them, twice the early energy at 125 Hz at BRAS’s hall’s dummy head. The late part still adds in energy, and so do the uncorrelated points of a line or surface source.

acoustic_spaces.engine.coherent.FILTERED_MAX_BAND_HZ = 500

The coherent bands up to this octave band are read through the analysis’s band filters (EarlyPressure); outdoors, the bands above it from the interference of each pair of paths averaged over the band (pair_energy()), which costs the same however far the sound travels.

class acoustic_spaces.engine.coherent.EarlyPressure(paths: EarlyReflections, weights: np.ndarray | None = None, kept: SameDelays | None = None)[source]

The early part of an impulse response at a low sample rate, as the echogram reads the coherent bands from it: as spectra from 0.2 s before emission, the pressure and the three components of the paths’ arrival directions times it, or with weights (paths, K) the sums of the paths weighted by each column.

Each band is scaled so that every path alone carries its energy in it: the analysis filters also let in a little of the neighbouring bands, whose levels differ, and the filters of the impulse response’s bands overlap with them. What is left is the paths’ interference, which in turbulence takes each two paths’ coherence factor: there each path’s spectrum is kept, and energy() adds the filtered paths’ products.

With kept (a SameDelays), the paths’ delay phases are taken from it and kept in it, and each band’s filtered pressure is kept for the next reading.

band(b: int, time_step: float, slots: int, origin: float = 0.0, start: float | None = None) → tuple[ndarray, ndarray, float][source]

The spectra through band b’s analysis filter (K, T) at the samples that fall into the slots of time_step, slot 0 at origin (s from emission); the slot of each sample (T,); and the factor that makes a squared sample energy.

The filters ring before an arrival as much as after it: what they spread to before start (s from emission; default origin), the arrival of the direct sound, counts as arriving with it, as in the analysis of a measured response. Kept for the next reading of the same arguments (read-only) when the pressure was made with a SameDelays.

energy(time_step: float, slots: int, axis: ndarray | None = None, exponent: int = 2, origin: float = 0.0, start: float | None = None) → ndarray[source]

(count, slots) energy per coherent band and time slot, as energy() reads the wave solver’s bands, through each band’s analysis filter (origin and start as for band()). With axis, that of a figure of eight facing it (exponent as there).

class acoustic_spaces.engine.coherent.SameDelays(limit: int = 134217728)[source]

What EarlyPressure and arriving_with() take from the early paths’ delays alone (and which paths carry a band), kept for paths that differ in nothing else but their energies and spectra: those of one traced response re-weighted for draw after draw of the absorption (material_spread()). Each value is kept under the bytes of the arrays it is made from, as every echogram slices each point’s paths anew, and is read-only. An EarlyPressure given one also keeps each band’s filtered pressure (EarlyPressure.band()) for the echograms that read it.

The delay phases are the most of it: a complex value for each path and frequency of the echogram’s spectra, about 6 MB for a hall’s response of 200 paths, up to 110 MB for a line source of 10 points outdoors (examples/street, in wind and turbulence too). What is kept stops at limit bytes in all (128 MiB by default); past it, each value is worked out again each time, as without one. The filtered pressures and what coherent_energy() keeps for a draw’s echograms are not counted in it: they go with the draw’s response, about 25 MB for the street’s.

delay_phases(shift: ndarray, n_fft: int, rate: float) → ndarray[source]

exp(-2j pi outer(shift, f)): the phase of paths shift s late at the frequencies f of an rFFT of n_fft points at rate.

band_grid(delay: ndarray, b: int, bands: int, live: ndarray) → tuple[ndarray, ndarray, int, ndarray, ndarray][source]

_band_grid() of these arguments.

acoustic_spaces.engine.coherent.absorption_phases(absorption: ndarray, cosines: ndarray, f: ndarray, admittance_of=None) → ndarray[source]

(n, count, M) e^(j arg R) at the frequencies f (count, M) of reflections at incidence cosines cosines (n,) off locally reacting surfaces whose admittance gives the absorption absorption (n, bands) in every band, as reflection_phases() has them. admittance_of(row) gives the admittance (a callable of the frequency) of an absorption row; by default the one fitted to it (fit_admittance()).

acoustic_spaces.engine.coherent.amplitude_spectra(paths: EarlyReflections, f: np.ndarray, gains: np.ndarray, only_coherent: bool = False) → np.ndarray[source]

(n, len(f)) each path’s pressure at frequencies f relative to its delay, as the impulse response has it: its amplitude in each band through the synthesis’s band gains (bands, len(f)) at those frequencies, in the coherent bands times its spectrum’s shape in that band (shaped()) and above them times its held_phase(); with only_coherent, the coherent bands alone.

acoustic_spaces.engine.coherent.arriving_with(paths: EarlyReflections, kept: SameDelays | None = None) → np.ndarray[source]

(n,) for each path, the largest over the bands above the coherent ones of how loud the other paths’ sound is where it arrives against its own, each path with the phase held from the coherent bands: the magnitude of the sum over the others of their pressure times the band filter’s autocorrelation at the difference of their delays, over its pressure. Zero for a path that arrives alone; about one or more for one that others arrive with. kept (a SameDelays) keeps what each band’s reading takes from the delays and which paths carry the band alone, for the same paths with other energies and phases.

acoustic_spaces.engine.coherent.band_count(max_band_hz: int | None, bands: int, wave_max_band_hz: int | None = None) → int[source]

How many of the lowest of bands (8 octave or 24 third-octave bands) add in pressure: those of the octave bands up to max_band_hz (None: none), and none when the wave solver runs up to that band or higher (wave_max_band_hz), as its bands take their place.

acoustic_spaces.engine.coherent.band_impulses(paths: EarlyReflections, n: int, sample_rate: float, gains: np.ndarray | None = None) → tuple[np.ndarray, np.ndarray | None][source]

The band signals (bands, n) of the early paths above the coherent bands, each path times gains (paths,) (default ones), as synthesis.place_impulses() has them, and those of the quarter turn of their held_phase() for synthesis.combine_bands() (None when no path has one).

acoustic_spaces.engine.coherent.coherent_energy(paths: EarlyReflections, time_step: float, slots: int, axis: np.ndarray | None = None, exponent: int = 2, origin: float = 0.0, start: float | None = None, cache: dict | None = None, kept: SameDelays | None = None) → np.ndarray[source]

(coherent bands, slots) the coherent bands’ energy per time slot (arguments as for EarlyPressure.energy()): through the band filters up to FILTERED_MAX_BAND_HZ and by pair_energy() above. The paths of each of a line’s or a surface’s points add in pressure, those of different points in energy. The band filters let in a little of the bands above, where each path over an edge has the mean of the phase a rendered response turns it by (with_mean_phases()). cache (a dict) keeps the EarlyPressure of each point between calls on the same paths; kept (a SameDelays) what they take from the paths’ delays alone, between calls on paths that differ in their energies and spectra only.

acoustic_spaces.engine.coherent.filtered_bands(paths: EarlyReflections) → int[source]

How many of the paths’ coherent bands are read through the band filters: those up to FILTERED_MAX_BAND_HZ.

acoustic_spaces.engine.coherent.ground_factors(model: TraceModel, faces: np.ndarray, cosines: np.ndarray, distance: np.ndarray | None, spherical: bool = True, ends: tuple[np.ndarray, np.ndarray, np.ndarray] | None = None) → np.ndarray[source]

(n, bands, M) the reflection factors off faces (n,) of sound that meets them at incidence cosines cosines (n,), at the frequencies of every band’s samples (band_frequencies()): for surfaces with an impedance, that of the spherical wave (Weyl-van der Pol, see spherical_reflection()) along paths distance (n,) m long from the image source, or with spherical False the plane wave’s; 1 for the others.

On the ground of a scene with ground zones, a reflection is the sum of the factors of the grounds its Fresnel zone covers, each weighted by the share it covers (see fresnel_shares()), from the points ends (n, 3) before the reflection, of the reflection and after it; without ends, the ground’s own. There, a ground without an impedance reflects with the square root of (1 - its absorption) and the phase of reflection_phases().

acoustic_spaces.engine.coherent.ground_wave_factors(model: TraceModel, faces: np.ndarray, distance: np.ndarray) → np.ndarray[source]

(n, bands, M) the Weyl-van der Pol factor Q of the sound that runs distance (n,) m along faces (n,) at grazing incidence, from a point on them, at the frequencies of every band’s samples: the field there is (1 + Q) = 2 F(w) times the free one (see spherical_reflection()). Faces with an impedance of their own take ground_factors()’ spherical wave, the others, a ground zone’s among them, that of the admittance fitted to their absorption (as reflection_phases() has it); a hard face gives 1.

acoustic_spaces.engine.coherent.held_phase(paths: EarlyReflections) → np.ndarray[source]

(n,) the phase factor of each path at the top of the coherent bands, which it keeps in the bands above them: there the paths add in energy, and a path whose phase stepped back to zero at the crossover would cancel itself in it, as two bands half a turn apart do (ones without coherent bands). Times the path’s own phase (own_phase) where a rendered response gives it one (with_own_phases()).

acoustic_spaces.engine.coherent.own_phases(paths: EarlyReflections, seed: int | None, angles: np.ndarray | None = None) → np.ndarray[source]

(n,) the phase factor beyond the one held from the coherent bands that a rendered response gives each path above them. A path over an edge is turned by an angle drawn uniformly from the path (its edge, order, faces, crossings and source point, and which of the paths alike it is) and seed, times how loud the other paths’ sound is where it arrives against its own (arriving_with()), up to one: so it adds to the paths it arrives with in energy on average, and one that arrives alone keeps its phase. A reflection keeps its phase (one). angles: their path_angles(), when worked out already.

acoustic_spaces.engine.coherent.pair_energy(paths: EarlyReflections, bands: range, time_step: float, slots: int, axis: np.ndarray | None = None, exponent: int = 2, origin: float = 0.0, memo: dict | None = None) → np.ndarray[source]

(len(bands), slots) energy per time slot of time_step (slot 0 at origin, s from emission) in bands of the paths’ coherent ones, adding them in pressure: each path’s own energy where it arrives, and the cross term of each pair of paths, averaged over the band’s frequencies as in total_energy() (with their coherence factor in turbulence), shared between the two paths’ slots as their energies are (a slot that would go below zero is left at zero). With axis, that of a figure of eight facing it (exponent as in EarlyPressure.energy(); with 1 the cross terms take the geometric mean of the two paths’ weights). memo (a dict), if given, keeps what each band takes whatever the axis (_pair_terms()) for the next call on the same paths.

acoustic_spaces.engine.coherent.path_angles(paths: EarlyReflections, seed: int | None) → np.ndarray[source]

(n,) an angle in [-pi, pi) for each path over an edge, zero for the others, drawn from what the path is and seed: wherever the source and the listener stand, the same path gets the same angle, and at every moment of the eddies.

acoustic_spaces.engine.coherent.reflection_phases(model: TraceModel, faces: np.ndarray, cosines: np.ndarray, count: int) → np.ndarray[source]

(n, count, M) e^(j arg R) of the reflections off faces (n,) of sound that meets them at incidence cosines cosines (n,), at the frequencies of sample_frequencies() of the lowest count bands: R is that of a locally reacting surface whose admittance gives the face’s absorption in every band; 1 for the faces whose reflection ground_factors() gives (see factor_faces()).

acoustic_spaces.engine.coherent.sample_frequencies(bands: int, count: int) → ndarray[source]

(count, M) the frequencies (Hz) a spectrum holds in each of the lowest count of bands bands: those the edge diffraction is evaluated at.

acoustic_spaces.engine.coherent.shaped(spectrum: ndarray, bands: int, f: ndarray, amplitude: ndarray, gains: ndarray, fine: ndarray | None = None, fine_delay: ndarray | None = None) → ndarray[source]

(n, len(f)) the coherent bands’ amplitudes (n, count) through the synthesis’s band gains (count, len(f)) at frequencies f (Hz), each band’s times the shape its spectra (n, count, M, EarlyReflections.spectrum) give it: the magnitude and the unwrapped phase interpolated linearly in log frequency between the band’s own samples and held beyond them. A band so carries its own sound into the crossovers with its neighbours, not theirs: outdoors a path’s bands below the parabolic equation’s top band hold the whole sound over the ground and those above it the path’s own, and a shape drawn across that edge would notch the sum.

Paths with the parabolic equation’s samples in a band (fine (n, count, K) and fine_delay (n,), EarlyReflections.fine) take its shape through those and the neighbouring bands’ instead ( fine_shape()), so that both bands of a crossover give the field it has there.

acoustic_spaces.engine.coherent.signal(paths: EarlyReflections, n: int, sample_rate: float, weights: np.ndarray | None = None) → np.ndarray[source]

(n, K) the coherent bands’ part of the early paths’ impulse response, at sample_rate, each path weighted by weights (paths, K) (default: one column of ones). Zero without coherent bands.

acoustic_spaces.engine.coherent.total_energy(paths: EarlyReflections) → np.ndarray[source]

(bands,) the paths’ energy together in each band: their sum, and in the coherent bands that of their pressures added at each of the band’s frequencies, averaged over them; each frequency stands for its slice of the band, over which the interference of two paths that arrive far apart averages out; in turbulence it takes their coherence factor (coherence()). Paths of different points of a line or a surface source add in energy.

acoustic_spaces.engine.coherent.with_mean_phases(paths: EarlyReflections, kept: SameDelays | None = None) → EarlyReflections[source]

paths as the echogram reads the coherent bands from them (EarlyPressure), through filters that let in a little of the bands above: each path over an edge with the mean over seeds of the phase factor own_phases() gives it there, sinc of how far it is turned. One turned all the way adds nothing to the others there in pressure, as on average in a rendered response. The same paths without such bands or such paths. kept: as for arriving_with().

acoustic_spaces.engine.coherent.with_own_phases(paths: EarlyReflections, seed: int | None, angles: np.ndarray | None = None) → EarlyReflections[source]

paths as a rendered response has them: each path over an edge turned by its own_phases() in the bands above the coherent ones. The same paths without such bands or such paths. angles: their path_angles() for seed, when worked out once for every moment of the same paths.

Leak finder

The leak finder: where rays escape from a model that is not closed.

The mesh checks count the open edges of a model, but do not show where its holes are. find_leaks() traces rays from the sources, reflecting them diffusely off every surface (a Lambert direction each time, whatever the materials, so that they reach every corner) and passing them through surfaces that let sound through with the share they let through. A ray that finds no surface ahead has escaped. Each escape is put down to the gap whose open edges it passes closest to; gaps whose edges come within a short distance of each other are one gap (a ceiling that stops short of a wall leaves open edges on both). An escape right after a ray passed through a surface that lets sound through (an open window to the outside) is put down to that surface. The surfaces next to a gap say where to look, and its area is estimated from how often rays find it: in a field of diffuse reflections, each reflection meets a share of the boundary in proportion to its area, so a gap takes the share of reflections that escape through it, times the area of the surfaces.

acoustic-spaces validate --leaks prints the report and acoustic-spaces view --leaks draws the escaping rays in 3D, as does the editor’s View menu.

acoustic_spaces.engine.leaks.MAX_REFLECTIONS = 100

Reflections each ray makes at most.

acoustic_spaces.engine.leaks.RAYS = 5000

Rays that the finder traces by default, shared by the sources.

class acoustic_spaces.engine.leaks.Gap(rays: int, centre: ndarray, surfaces: tuple[str, ...], open_edges_m: float, area_m2: float, size_m: tuple[float, float] = (0.0, 0.0), kind: str = 'gap')[source]

A place where rays left the model.

rays: int

Rays that escaped through it.

centre: ndarray

(3,) the mean of the points where they left (m).

surfaces: tuple[str, ...]

Names of the surfaces next to it, the longest open edges first; for a surface that lets sound through, its own name.

open_edges_m: float

Length of the open edges round it (m); 0 for a surface that lets sound through, or where rays slipped between faces that the mesh joins.

area_m2: float

Its area (m2): the area its open edges run round, when they close up into loops; else as the rays found it, from the share of reflections that met it. 0 for a surface that lets sound through and a source outside the room.

size_m: tuple[float, float] = (0.0, 0.0)

Its length and width (m): how far its open edges reach along the two directions they spread out most in; zeros where there are no open edges.

kind: str = 'gap'

"gap": open edges round a hole; "surface": a surface that lets sound through (an opening the scene means to have, not a leak); "between faces": an edge of a closed mesh that rays slipped through; "outside": rays that left a source outside the room without meeting a surface (surfaces names the source).

class acoustic_spaces.engine.leaks.Leaks(rays: int, reflections: int, max_reflections: int, starts: ndarray, directions: ndarray, points: ndarray, gap: ndarray, gaps: list[Gap], surface_area_m2: float)[source]

Where the rays of find_leaks() escaped.

rays: int

Rays traced.

reflections: int

Reflections they made in all (passes through surfaces included).

max_reflections: int

Reflections each ray made at most.

starts: ndarray

(k, 3) where each escaping ray last reflected (or left its source).

directions: ndarray

(k, 3) its direction from there.

points: ndarray

(k, 3) where it left the model: where it crosses the plane of its gap’s open edges (for a gap that is not flat, its point nearest them; for an edge between joined faces, its point nearest that), or starts when it left through a surface or straight from its source.

gap: ndarray

(k,) the gap each escaping ray left through (an index into gaps).

gaps: list[Gap]

The gaps, the one the most rays escaped through first.

surface_area_m2: float

Total area of the surfaces (m2).

property leaked: int

Rays that escaped through a gap, not through a surface that lets sound through.

summary() → str[source]

A few lines for people: how many rays escaped, and where.

acoustic_spaces.engine.leaks.find_leaks(room: Room, *, rays: int = 5000, max_reflections: int = 100, seed: int = 0) → Leaks[source]

Trace rays rays from the room’s sources (shared by them; from the middle of the model when it has none) for up to max_reflections diffuse reflections each, and find where they escape.

acoustic_spaces.engine.leaks.open_edges(room: Room) → tuple[ndarray, ndarray][source]

The edges of the room’s mesh that only one face has: (E, 2) their corners (indices into the mesh’s vertices, in the order the face runs along them) and (E,) that face.

Audience seating

Grazing incidence over the audience: sound that reaches a listener low over rows of seats loses much more than the seats’ absorption says, as it passes heads and seat backs on the way.

The model is the fit of Jurkiewicz, Rummler, Green, Wulfrank and Kahle (“Impact of grazing incidence attenuation on early reflection design”, Proc. IOA 47 Pt. 1, 2025) to measurements over a seated audience in a 1:20 scale model. Sound arriving at an elevation φ above the audience plane, having travelled d metres over the audience, keeps

min(1, (3.40 sin²φ + 2.17 sin φ + 0.02) ^ ((d - 1) / 10))

of its energy: 17 dB less at grazing incidence after 11 m, 0.6 dB per metre at 5°, and nothing lost from 17.8° up. It was fitted in the 500 Hz to 2 kHz octave bands, where the attenuation hardly changed with frequency, and applies there only (in third octaves, 400 Hz to 2.5 kHz). Lower down the seat dip depends on the seats themselves, and higher up the fit has no data.

Here it applies to the last leg of each early path (the direct sound, a reflection or a diffracted path) to a listener above a surface whose material is audience: φ is the leg’s elevation above that surface’s plane, and d how far the leg runs over audience surfaces no higher than CLEARANCE_M above the listener’s own height over the audience (so the stalls do not shade a balcony seat). The leg from the source to the first reflection is not attenuated, as in the fit, which therefore errs on the side of too little attenuation. The late part is left as it is; the statistical method reckons its diffuse field less the early paths as they would come without the audience, so what the seats take from them is lost and not made up by the tail.

acoustic_spaces.engine.grazing.CLEARANCE_M = 2.0

How much higher than the listener’s ears above the audience a leg still counts as running over it (m).

acoustic_spaces.engine.grazing.FIT = (3.4, 2.17, 0.02)

Coefficients of the fit’s polynomial in sin φ: a sin²φ + b sin φ + c.

acoustic_spaces.engine.grazing.FIT_RANGE_HZ = (400, 2500)

The bands the fit covers (Hz): the 500 Hz to 2 kHz octaves and their third octaves.

acoustic_spaces.engine.grazing.MAX_EAR_HEIGHT_M = 2.0

Highest a listener’s ears may be above an audience surface for it to count (m).

acoustic_spaces.engine.grazing.apply_grazing(model: TraceModel, listener: ndarray, paths: EarlyReflections)[source]

paths to listener with the grazing attenuation over the audience applied to their energies; unchanged when the model has no audience surfaces.

acoustic_spaces.engine.grazing.attenuation(elevation_rad, distance_m) → ndarray[source]

The share of energy left after distance_m over the audience at elevation_rad above its plane (the fit above; the first metre is free).

acoustic_spaces.engine.grazing.audience_faces(model: TraceModel) → ndarray[source]

(F,) faces whose material is audience seating.

acoustic_spaces.engine.grazing.fit_bands(model: TraceModel) → ndarray[source]

(bands,) the model’s bands the fit covers.

acoustic_spaces.engine.grazing.grazing_factors(model: TraceModel, listener: ndarray, paths: EarlyReflections, audience: ndarray) → ndarray | None[source]

(paths, bands) share of each path’s energy left by grazing incidence over the audience (1 outside the fit’s bands), or None when the listener is not above an audience surface.

Wave-based solver

Wave-based simulation of the lowest octave bands (or their third-octave bands).

Rays and image sources treat sound as rays, which holds while the room is large next to the wavelength. At low frequencies it is not: small rooms ring at their modes, and sound bends round everything. The wave solver computes the sound field itself, with the finite-difference time-domain method (FDTD) on a cubic grid over the room, and its octave bands replace the ray-traced ones.

  • One grid covers every octave band up to max_band_hz, with points_per_wavelength cells per wavelength at the top of that band’s crossover. In a simulation in third-octave bands, those are the third octaves of these octave bands, and the grid is set by the top of the highest of them. Each octave higher costs about 16 times as much (cells 8 times smaller, steps twice as many). All bands share the grid, so a mode near a crossover is the same mode on both sides of it.

  • Waves on the grid travel slower the shorter they are. scheme picks the stencil: the interpolated isotropic one (19 points, ISOTROPIC_COURANT) is 0.67 % slow at 8 cells per wavelength, within 0.03 % the same in every direction; the standard one (7 points, COURANT) up to 1.7 %, along the grid’s axes. auto takes the isotropic one but round an open model, where only the standard one has the matched layer. Along the axes both are slowest (slow_by()); the run’s details give how slow the top of the highest band is there (wave_slow_percent).

  • The surfaces absorb as their materials do in each band: each material becomes a locally reacting surface whose admittance changes with frequency, fitted so that its random-incidence absorption matches the material’s in every wave band (acoustic_spaces.engine.impedance). One run covers all the wave bands.

  • Cells are air when the source reaches them without crossing a surface, so closed rooms, open models and thin screens all work. Round an open model, whose air reaches the edge of the grid, the grid grows by a perfectly matched layer of LAYER_CELLS cells that takes in the sound leaving it, and leaves room (LAYER_ROOM) for sound that runs along it, on the sides where no surface of the model lies between that sound and the layer (_open_sides()). Openings are not surfaces here: the air flows through them. Surfaces that let only part of the sound through are not modelled, so a model with any stops the wave solver with an error.

  • walls says where the grid’s walls lie: "cell_faces", each surface on the cell faces nearest it, or "fitted", where the model has it, cut exactly through the cells. Fitted walls take the standard stencil (auto takes it for them) and still air with one speed of sound: they are refused with the isotropic stencil, outdoors and in moving air.

  • At these frequencies the source radiates the same way in all directions. The listener records the pressure and, from its gradient, the direction the sound comes from (first-order Ambisonics), so spatial outputs keep the low end’s direction.

  • The bands join the ray-traced ones through the zero-phase crossovers the impulse response synthesis uses, which sum to one; the lowest starts at LOW_EDGE_HZ (22 Hz) instead of 0 Hz. Their energies, for the room parameters, are counted through the octave filters of the analysis of measured responses.

  • Outdoors, in wind and temperature that change with height (Atmosphere), the speed of sound changes from cell to cell: the still air’s at the cell’s height above the ground, plus the wind’s component along the horizontal from the source, the effective speed of sound the rays and the parabolic equation take (acoustic_spaces.engine.refraction). The grid is then fine enough for the slowest sound and steps in time for the fastest, so it costs a little more than in still air. Sound that turns back towards the source, off a building, keeps the speed of sound of sound going away from it.

  • With wind="moving" the air moves instead: each cell keeps the still air’s speed of sound, and before each step both of the leapfrog’s pressure levels are carried along with the wind, dq/dt = -v . grad q (the strong-stability-preserving Runge-Kutta method of third order); the still air’s step follows, its boundaries, the matched layer and the source fixed to the ground. In the air’s own frame that is the still air’s step exactly, so a uniform wind gives the convected wave equation: downwind sound at c + v, upwind at c - v whichever way it turned. Where the wind changes, the term of the linearised Euler equations that the wind’s shear puts on the air’s velocity is left out, about |dv/dz| / omega of the rest. That scheme keeps the sound’s energy only where no wind crosses a surface of the model and no cell gains or loses air, so the atmosphere’s wind is first made to flow round the model’s solids: on the faces between the cells, the wind of least change from the given one (each face’s change weighed by one over the given speed there) that crosses no surface and leaves every cell as much as it enters it. A dead end, such as a room with one opening, then holds nearly still air whatever the wind’s profile. It is a flow without wakes or eddies behind the solids, and at a sharp edge it speeds up, the more the finer the grid; the run says how fast it gets through a face between two cells (wave_wind_fastest_m_s), which must stay under half a cell a step. The carrying is of fourth order where the wind is the same along a row of cells and of second order where it changes; over open, flat ground, where the given wind already crosses nothing, it is carried as given, by fourth-order central differences. Over open ground it takes four to five times as long as the effective speed of sound’s run; round solids its steps take about eight times as long, after the solve of the wind (see validation/wave_wind.py). It runs on the CPU (asked for the GPU, it says so and stays there). The matched layer’s air is still: where the wind crosses its border, each cell’s own sound is carried out and silence in, which takes energy and adds none, and a wave that leaves the moving air for the layer comes back by about half the wind’s Mach number (see the notes of fdtd.hpp). The run is watched all the same: once the source’s pulse has ended, the pressure squared over the grid’s air, averaged over pieces of WATCH_S, may not rise to WATCH_RISE times its lowest so far (a ValueError).

  • The grid is laid out on the CPU and stepped there, or with device on a GPU, through WebGPU (acoustic_spaces.engine.gpu); the two agree to rounding, in wind and temperature too (with the effective speed of sound).

The levels follow the ray tracer’s convention: in free field, the direct sound at r metres is an impulse of height 1 / r.

acoustic_spaces.engine.wave.COURANT = 0.5773502691896258

Courant number of the 7-point (standard rectilinear) stencil: its stable limit.

acoustic_spaces.engine.wave.ISOTROPIC_COURANT = 0.8660254037844386

Courant number of the 19-point (interpolated isotropic) stencil: its stable limit.

acoustic_spaces.engine.wave.HIGH_PASS_S = 0.12

The source’s high-pass, applied twice: once so that the air the source pushes into the room stops flowing, twice so that as much flows out again and a closed room’s pressure comes back to rest. Its length in seconds; twice, it is flat within 0.2 dB above 20 Hz.

acoustic_spaces.engine.wave.LAYER_CELLS = 8

Cells of the matched layer round an open model, and its damping at the grid’s edge (the damping rate times half a time step). Sound leaving the model comes back from it 72 to 74 dB down; from the grid’s edge alone, 7 to 14 dB down (docs/validation.md, Open models).

acoustic_spaces.engine.wave.LOW_EDGE_HZ = 22.273863607376246

The wave solver’s part of a response starts here (Hz), with the synthesis’s crossover shape round it: an octave below the 63 Hz band’s lower edge, so that band, skirts and all, comes from the wave solver. Further down a closed room’s air is squeezed as a whole (the wave solver’s source leaves no air in it, so this falls away), and the rays’ response stays.

acoustic_spaces.engine.wave.MAX_CELLS = 40000000

Grids with more cells than this are refused (about 20 bytes each).

Each stencil’s link weights, by its points: of an axial link and of an edge link (the Courant number squared shared out over the links, as the update takes them).

acoustic_spaces.engine.wave.STENCILS = {'isotropic': (19, 0.8660254037844386), 'standard': (7, 0.5773502691896258)}

The stencils’ points, and their Courant numbers, by scheme.

acoustic_spaces.engine.wave.WAVE_BANDS_HZ = (63, 125, 250, 500)

The highest bands the solver may compute (simulation.wave.max_band_hz).

acoustic_spaces.engine.wave.Scheme

Which stencil steps the grid (see wave_responses()).

alias of Literal[‘auto’, ‘standard’, ‘isotropic’]

acoustic_spaces.engine.wave.Walls

Where the grid’s walls lie (see wave_responses()).

alias of Literal[‘cell_faces’, ‘fitted’]

acoustic_spaces.engine.wave.WindModel

How the wave solver takes the wind (see wave_responses()).

alias of Literal[‘effective’, ‘moving’]

class acoustic_spaces.engine.wave.Admittance(beta: float, conductance: ndarray = <factory>, quality: ndarray = <factory>, frequency_hz: ndarray = <factory>, achieved: ndarray | None = None, relaxation: ndarray = <factory>, relaxation_hz: ndarray = <factory>)[source]

A locally reacting surface’s specific admittance: beta plus one resonant branch per entry of conductance (its admittance at resonance, 1 / R), quality and frequency_hz, and one branch without mass per entry of relaxation (its admittance at high frequencies, 1 / R) and relaxation_hz (its corner frequency, S / (2 pi R)), as a porous ground’s admittance needs.

achieved: ndarray | None = None

The band absorption the fit reached, or None when not fitted.

branches(rate: float) → ndarray[source]

The branches as the wave solver takes them (branches, 3): mass over the time step, resistance, and stiffness times the time step.

class acoustic_spaces.engine.wave.BandGrid(band: int, cell: float, rate: float)[source]

The grid of one band’s run.

cell: float

Cell size (m).

rate: float

Sample rate of the run (Hz): the output rate over or times a whole number.

class acoustic_spaces.engine.wave.WaveResponse(rate: float, signals: ndarray, bands: int, cell: float, total_bands: int = 8, lead_s: float = 0.0, band_gain: ndarray | None = None, delay_s: float = 0.0)[source]

The lowest octave bands (or third-octave bands) of one response, from the wave solver.

signals holds the run at rate: the pressure and the first-order directional parts (samples, 4), AmbiX W, X, Y and Z in room coordinates, from lead_s before emission on. Only the frequencies of the wave bands count.

bands: int

The bands 0 to bands - 1 come from the wave solver.

cell: float

Cell size of the grid (m).

total_bands: int = 8

How many bands the whole response has: 8 octave or 24 third-octave bands.

lead_s: float = 0.0

How long before emission signals start (s): the source’s pulse is centred on emission, so a listener near the source hears it start before then.

band_gain: ndarray | None = None

The energy gain of each wave band from the source’s feed, or None for none.

delay_s: float = 0.0

How long after emission the source starts playing (s).

fed(gain: ndarray, delay_s: float) → WaveResponse[source]

These bands with the energy gain of each and delay_s later.

field(sample_rate: float, n: int) → ndarray[source]

The first-order sound field (n, 4) of the wave bands together, from emission: W, X, Y, Z. The bands’ filters take the run before emission too, and what they spread to before emission is left out, as it is of the rays’ sound. They take the run after the n samples as well, where it goes on (PAST_END_S).

high_pass(signals: ndarray, sample_rate: float, late: bool = False) → ndarray[source]

signals (n, channels) without the frequencies the wave bands cover, which take them at a gain g: the rays’ early paths at 1 - g, as they add to the wave bands’ sound in pressure, or with late their noise at sqrt(1 - g^2), as it adds to the wave bands’ tail in energy.

energy(time_step: float, slots: int, axis: ndarray | None = None, exponent: int = 2) → ndarray[source]

Energy per band and time slot (bands, slots), as the ray tracer counts it: the energy of the pressure through each band’s filter (those of the analysis of measured responses, acoustic_spaces.parameters.band_filter_gains()) over that filter’s share of the spectrum. The filters spread each arrival a little both ways in time; what they spread to before emission counts in the first slot.

With axis (a unit vector in room coordinates), that of a figure of eight facing it instead, from X, Y and Z: with exponent 1, the magnitude of its product with the pressure.

acoustic_spaces.engine.wave.absorption_of_impedance(impedance: ndarray) → ndarray[source]

Random-incidence absorption of a locally reacting surface with a real normalised impedance (Paris’s formula, for a diffuse field).

acoustic_spaces.engine.wave.admittance(absorption: ndarray) → ndarray[source]

Real specific (normalised) admittance of a locally reacting surface whose random-incidence absorption is absorption: the inverse of Paris’s formula, on the side of hard surfaces. Coefficients from MAX_ABSORPTION up get the most absorbing admittance.

acoustic_spaces.engine.wave.fit_admittance(absorption: Sequence[float], total: int, rate: float | None = None) → Admittance[source]

The admittance whose random-incidence absorption, at rate steps a second (None: exactly), matches absorption in each of the lowest len(absorption) of the total (8 octave or 24 third-octave) bands.

acoustic_spaces.engine.wave.band_grid(band: int, sample_rate: float, speed_of_sound: float, points_per_wavelength: float = 8.0, total: int = 8, courant: float = 0.5773502691896258) → BandGrid[source]

The coarsest grid with points_per_wavelength cells per wavelength at the top of band band (of total, 8 octave or 24 third-octave bands) whose time step is a whole number of the output’s sample periods, or one of them over a whole number where the grid needs more steps per second than the output has samples. courant is the stencil’s Courant number.

acoustic_spaces.engine.wave.band_top(band: int, total: int = 8) → float[source]

Highest frequency band band of the total (8 octave or 24 third-octave) bands has (Hz): the top of its upper crossover.

acoustic_spaces.engine.wave.grid_phase(theta, stencil: int, ratio: float = 1.0) → ndarray[source]

The phase w T a wave turns through in a time step on the stencil-point grid, from the phase it turns through across a cell along each axis, theta (…, 3), k h: the stencil’s dispersion relation, 2 - 2 cos(w T) = ratio^2 sum over the links of g_k (1 - cos(k . d_k)). ratio is the speed of sound over the one the grid’s time step is set by (in wind and temperature, below 1 in all but the fastest air).

acoustic_spaces.engine.wave.slow_by(stencil: int, per_wavelength: float, ratio: float = 1.0) → float[source]

How much slower than it should (a fraction) a wave of per_wavelength cells per wavelength travels on the stencil-point grid along its axes, the way it is slowest with either stencil; ratio as in grid_phase() (below 1, slower still). The 19-point stencil at 8 cells per wavelength: 0.67 %, at 5: 1.85 %; the 7-point one 1.74 % and 4.56 %.

acoustic_spaces.engine.wave.source_signal(rate: float, cell: float, courant: float = 0.5773502691896258, speed: float = 1.0, *, level: bool = True) → tuple[ndarray, int][source]

What the source adds to the grid on each step, and its delay in steps.

An impulse, low-passed (so the grid carries no frequencies it cannot) and high-passed twice (so it leaves no air in the room), scaled so that in free field the pressure at r metres is that impulse over r. courant is the stencil’s Courant number, which says which stencil it is for and sets the low-pass’s cutoff (_cutoff()); speed the speed of sound at the source over the grid’s (1 where it is the same everywhere).

On the 19-point grid a point source’s sound comes out louder than what the source adds, the more the higher the frequency: by 9 / (5 + 4 cos wT) in pressure, w T the frequency’s turn over a time step (the far field of the scheme’s own response to one cell, by stationary phase: 3 / (2 + cos kh) along an axis, kh the turn over a cell there, which the scheme ties to the frequency by cos kh = 1 - 4 (1 - cos wT) / 3). That is the gain along the axes and the cube’s diagonals; along a face’s diagonals it is up to 0.03 dB more at eight cells per wavelength, and the same within 0.01 dB over a band: 0.06 and 0.35 dB over the 63 and 125 Hz bands of a grid up to the 125 Hz band. Three taps, 2/9, 5/9 and 2/9, have the inverse gain exactly and are part of the signal, with a step of delay (where the source’s speed of sound is speed times the grid’s, the side taps are over the square of speed, the middle one what is left of one); level=False gives the signal without them, the impulse that the signal with them stands for. The 7-point grid’s gain changes with the direction (twelve cells away, over that 125 Hz band: none along an axis, 0.25 dB along a face’s diagonals and 0.32 to 0.34 dB along the cube’s, by the places of the source and the listener within their cells; validation/wave_solver.py), so no signal can undo it.

acoustic_spaces.engine.wave.wave_gains(n_fft: int, sample_rate: float, bands: int, total: int = 8) → ndarray[source]

Zero-phase gains (bands, n_fft // 2 + 1) of the lowest bands of the total (8 octave or 24 third-octave) bands as the wave solver covers them: the synthesis’s band gains, the lowest one starting at LOW_EDGE_HZ.

acoustic_spaces.engine.wave.wave_responses(model, source: ndarray, listeners: ndarray, names: Sequence[str], *, max_band_hz: int, length_s: float, sample_rate: float, speed_of_sound: float, points_per_wavelength: float = 8.0, threads: int = 0, device: Literal['cpu', 'gpu', 'auto'] = 'cpu', scheme: Literal['auto', 'standard', 'isotropic'] = 'auto', say: Callable[[str], None] | None = None, label: str = '', wind: Literal['effective', 'moving'] = 'effective', walls: Literal['cell_faces', 'fitted'] = 'cell_faces') → tuple[list[WaveResponse], dict[str, float]][source]

The wave bands of the responses from source to each of listeners in the room of model (a TraceModel), and run details. device says where the grid is stepped (see gpu); scheme which stencil steps it: "isotropic" (19 points), "standard" (7 points) or "auto", the isotropic one but round an open model, where only the standard one has the matched layer. wind says how it takes the wind outdoors: "effective", as a speed of sound changed by the wind’s component along the horizontal from the source, or "moving", as air that moves (see the module’s notes). walls says where the grid’s walls lie: "cell_faces", on the cell faces nearest the surfaces, or "fitted", where the model has them, cut through the cells; fitted walls take the standard stencil whatever the scheme but "isotropic", which they refuse, as they refuse an outdoor model and moving air. The fit’s own refusals of a model (a crack, faces laid on one another, a model reaching into the matched layer) are ValueError starting “fitted walls:”, raised before any step.

Locally reacting surfaces for the wave solver: frequency-dependent admittances fitted to a material’s absorption coefficients.

A material table gives each band’s random-incidence absorption. The wave solver needs the surface’s specific admittance (the normal velocity times rho c over the pressure), as a function of frequency it can step in time. Admittance is a constant conductance beta plus parallel mass-resistance-stiffness branches,

Y(s) = beta + sum_j 1 / (M_j s + R_j + S_j / s),

each resonant (at f_j, with quality factor Q_j) and passive, so the scheme stays stable whatever the values. fit_admittance() chooses beta and the branches so that the random-incidence absorption of Y (Paris’s formula for a locally reacting surface), counted through the analysis’s band filters, matches the material’s in every band the wave solver covers: one branch at each band’s centre and one beyond each end. It fits the admittance the scheme actually has at its time step, which bends a little from Y towards the grid’s Nyquist frequency.

A locally reacting surface absorbs at most MAX_ABSORPTION (0.951) at random incidence; higher coefficients get that. The band filters overlap, so bands whose coefficients change steeply from one to the next (0.1 to 0.6 in an octave) are matched only roughly; Admittance.achieved holds what the fit reached.

acoustic_spaces.engine.impedance.MAX_ABSORPTION = 0.951

Highest random-incidence absorption a locally reacting surface reaches (Paris’s formula), and the normalised impedance that reaches it.

class acoustic_spaces.engine.impedance.Admittance(beta: float, conductance: ndarray = <factory>, quality: ndarray = <factory>, frequency_hz: ndarray = <factory>, achieved: ndarray | None = None, relaxation: ndarray = <factory>, relaxation_hz: ndarray = <factory>)[source]

A locally reacting surface’s specific admittance: beta plus one resonant branch per entry of conductance (its admittance at resonance, 1 / R), quality and frequency_hz, and one branch without mass per entry of relaxation (its admittance at high frequencies, 1 / R) and relaxation_hz (its corner frequency, S / (2 pi R)), as a porous ground’s admittance needs.

achieved: ndarray | None = None

The band absorption the fit reached, or None when not fitted.

branches(rate: float) → ndarray[source]

The branches as the wave solver takes them (branches, 3): mass over the time step, resistance, and stiffness times the time step.

acoustic_spaces.engine.impedance.absorption_of_impedance(impedance: ndarray) → ndarray[source]

Random-incidence absorption of a locally reacting surface with a real normalised impedance (Paris’s formula, for a diffuse field).

acoustic_spaces.engine.impedance.admittance(absorption: ndarray) → ndarray[source]

Real specific (normalised) admittance of a locally reacting surface whose random-incidence absorption is absorption: the inverse of Paris’s formula, on the side of hard surfaces. Coefficients from MAX_ABSORPTION up get the most absorbing admittance.

acoustic_spaces.engine.impedance.band_absorption(admittance: Admittance, bands: int, total: int, rate: float | None = None) → ndarray[source]

The random-incidence absorption of admittance in the lowest bands of the total bands, counted as fit_admittance() counts it.

acoustic_spaces.engine.impedance.band_weights(f: ndarray, bands: int, total: int) → ndarray[source]

How much each of the frequencies f (on a log grid) counts in each of the lowest bands of the total (8 octave or 24 third-octave) bands (bands, len(f)): the energy of white noise through the analysis’s band filters.

acoustic_spaces.engine.impedance.fit_admittance(absorption: Sequence[float], total: int, rate: float | None = None) → Admittance[source]

The admittance whose random-incidence absorption, at rate steps a second (None: exactly), matches absorption in each of the lowest len(absorption) of the total (8 octave or 24 third-octave) bands.

acoustic_spaces.engine.impedance.fit_impedance(admittance: Callable[[ndarray], ndarray], bands: int, total: int, rate: float | None = None) → Admittance[source]

The admittance whose value, at rate steps a second (None: exactly), matches that of a surface with an impedance, admittance(f) (normalised, complex, in the engine’s convention, at frequencies f in Hz), over the lowest bands of the total bands: its reflection at every angle and its phase, not only its random-incidence absorption, as a ground’s dip needs.

A porous ground’s admittance grows with frequency at a nearly constant phase, as no resonant branch does: the fit is beta and branches without mass whose corner frequencies are spread evenly in log frequency, whose sum makes that shape (as a ladder of resistors and capacitors makes a fractional-order element). With the corners fixed the admittance is linear in the branches’ conductances, which the fit finds by least squares, at least 0 each, with the misses relative to the admittance’s size.

acoustic_spaces.engine.impedance.random_incidence_absorption(admittance: ndarray) → ndarray[source]

Random-incidence absorption of a locally reacting surface with the complex specific admittance admittance: Paris’s formula, the integral over incidence of 1 - |R|^2 weighted by sin(2 theta), in closed form.

The wave solver’s time steps on a GPU, through WebGPU.

GpuWaveSolver takes a grid that the C++ solver (acoustic_spaces._native.WaveSolver) has set up, with its air, boundaries, branches, matched layer, source and probes, and a speed of sound per cell where the grid has one (outdoors in wind and temperature), and steps it with one WGSL compute shader on any GPU that wgpu reaches: Vulkan (AMD, Intel, NVIDIA, and Mesa’s software lavapipe), Metal or Direct3D 12. It needs the optional gpu extra (pip install "acoustic-spaces[gpu]"). Its arithmetic is the CPU’s, in single precision, so the two agree to rounding.

Each time step is one dispatch: one thread for each cell of the grid (the interior air cells take the plain update and the rest return), then one for each boundary cell, each matched-layer cell and each probe. The two pressure fields swap from one step to the next, and so do the two sets of branch velocities, by the step’s parity.

acoustic_spaces.engine.gpu.Device

Where the wave solver runs: "auto" takes a GPU when wgpu finds a hardware one (and acoustic-spaces tune did not find the CPU faster for the run’s length).

alias of Literal[‘cpu’, ‘gpu’, ‘auto’]

class acoustic_spaces.engine.gpu.GpuWaveSolver(solver)[source]

Steps the grid of solver (a fresh or reset acoustic_spaces._native.WaveSolver) on the GPU: run() does what the solver’s run does, from the GPU’s own state.

run(signal: ndarray) → ndarray[source]

Advances one step per sample of signal (added at the source) and returns the pressure at every probe before each step (probes, steps).

acoustic_spaces.engine.gpu.gpu_name() → str | None[source]

The GPU the wave solver would run on, as "<device> (<backend>, <type>)", or None when wgpu is missing or finds none.

acoustic_spaces.engine.gpu.hardware_gpu() → bool[source]

Whether wgpu finds a hardware GPU (not a software renderer such as lavapipe).

acoustic_spaces.engine.gpu.use_gpu(device: Literal['cpu', 'gpu', 'auto'], steps: int | None = None) → bool[source]

Whether the wave solver runs on the GPU for the setting device, for a run of steps steps. auto takes a hardware GPU: when acoustic-spaces tune timed both on this computer, only if it steps that many times clearly faster (see acoustic_spaces.engine.tuning).

How big a run is: the threads it works on and the memory its late part needs.

What grows without bound with the settings is the late part’s energy: one array per listener (or map point) and band, as long as the response, and at a listener one more per arrival direction. Every source’s is kept to the end of the run, and while one is traced the tracer needs more: on the CPU a copy for each thread that sums rays (at most _native.COPY_MEMORY together, one at least), on a GPU its buffers. So a run needs memory in proportion to simulation.ir_length_s, the listeners and late.directions, the map points (coverage.spacing) and the sources: those traced for their late part, as a source or a listener whose late part is a mix of others’ (a walk’s places between the traced ones, simulate’s late_from) holds none. On the CPU the rays cost time, not memory. A run whose late part would need more memory than the computer has is refused before it starts (check()), and warnings() notes one that would need more than half of it. A map is checked again once its first source point is traced, with the early paths found there at every point (held_bytes()). The estimate takes the threads and the devices of the computer it runs on: with late.device gpu, both or auto (where there is a hardware GPU), the worst of the CPU, the GPU and the two together.

Threads above the computer’s cores run as its cores: more would only take turns on them, each with its copy (worker_threads()).

class acoustic_spaces.engine.run_size.Need(bytes: float, what: str, advice: str)[source]

Bytes of memory a run’s late part needs, what for and what to change for less.

note(memory: int) → str[source]

What the run needs against memory bytes (the computer’s).

acoustic_spaces.engine.run_size.check(need: Need, memory: int | None = None) → None[source]

Raises ValueError when need is more than memory bytes (by default the computer’s, machine_memory()).

acoustic_spaces.engine.run_size.each_on_threads(function: Callable[[_Item], _Result], items: Iterable[_Item], threads: int) → list[_Result][source]

function of each of items, in their order, on at most threads threads at once, so that at most threads of the calls are in progress at any time. With one thread (or one item) the calls run one after another in the calling thread, with no pool.

acoustic_spaces.engine.run_size.held_bytes(value: object) → float[source]

Bytes the arrays in value take (in lists, tuples and dataclasses, each array once, with its header), such as a map’s early paths at every point.

acoustic_spaces.engine.run_size.late_call(results: float, bands: int, groups: int, *, splitting: bool, threads: int, rays: int, devices: Sequence[str] = ('cpu',), estimates: float = 0.0) → float[source]

Bytes one run of the late part’s tracer takes at its peak, whose arrays take results bytes in bands bands traced in groups groups of bands (band_groups()), and the energy as each batch of rays gives it estimates: the arrays the groups are joined in, the sums of the runs before while the next is traced (splitting: a first batch, or batches traced in runs), a group’s estimates, and a group’s own arrays, on the worst of devices: on the CPU with its threads’ copies (at most _native.COPY_MEMORY together, one at least), on a GPU with its buffers (run_memory()), or on both with the sums of the parts and a part on each.

acoustic_spaces.engine.run_size.late_devices(setting: str | None) → tuple[str, ...][source]

Where the late part may trace its rays on this computer for late.device: always on the CPU, which traces what a GPU declines; on the GPU for gpu; and on both too for both, and for auto where there is a hardware GPU.

acoustic_spaces.engine.run_size.machine_memory() → int | None[source]

Bytes of memory this computer has, or the limit of the container the run is in where that is lower; None where neither can be read.

acoustic_spaces.engine.run_size.map_need(room: Room, settings: Simulation, sources: Sequence, points: int, corners: np.ndarray, grid: float, threads: int) → Need[source]

The memory a coverage map of about points points within corners (those of its extent) needs: grid bytes while its grid is laid out, and with stochastic ray tracing the late energy at every point from each point of every source, kept to the end, and while one is traced, the tracer’s own (late_call(); maps are traced on the CPU).

acoustic_spaces.engine.run_size.simulation_need(room: Room, settings: Simulation, sources: Sequence, listeners: Sequence, threads: int, groups: int = 0, mixed: Collection[str] = ()) → Need[source]

The memory the late part of a simulation of sources at listeners needs: the energy of every source, kept to the end; that of a line or surface source’s points summed as each is traced; and while one is traced, the tracer’s own (late_call(), on the devices late_devices() gives). Then, for a source with a feed of its own, a listener’s copy at a time while its response takes it (four arrays as large at most). groups face groups (simulate(groups=...)) add their moments to each listener’s arrays, and batches of rays (late.batches) the energy as each gives it.

mixed names the sources and the listeners whose late part is a mix of others’ (simulate’s late_from, with the stochastic ray tracer): such a source is not traced and keeps no energy, and a point source’s energy is traced and kept at the other listeners alone (a line’s or a surface’s is traced at those and mixed for every listener as its points are summed).

Its advice gives what the run would need with each setting it may lower changed on its own (_lowered()), the least first.

acoustic_spaces.engine.run_size.warning(need: Need, memory: int | None = None) → str | None[source]

A note when need is more than half of memory bytes (by default the computer’s), else None.

acoustic_spaces.engine.run_size.worker_threads(threads: int) → int[source]

The threads a run works on for threads asked (performance.threads): as many as the computer has cores for 0 or more.

The late stage on a GPU

Where the late stage traces its rays: on the CPU, on a GPU, or on both at once.

simulation.late.device picks it:

  • cpu (the default): the compiled core, on simulation.performance.threads.

  • gpu: acoustic_spaces.engine.gpu_tracer, through WebGPU (the gpu extra).

  • both: the two share the rays. Each takes the next share of them as soon as it is done with the last, so the faster one traces more.

  • auto: whichever of the three is fastest on this computer for the run’s response length. It takes the choice acoustic-spaces tune kept for that length (see acoustic_spaces.engine.tuning); without one, a short trial traces a few thousand rays on the scene’s own model, for the run’s own length, on the CPU and on the GPU and keeps the fastest for that range of lengths. It takes the CPU, the safe choice, when wgpu finds no GPU or only a software one, or when neither the GPU nor both together would be clearly faster. With the trial switched off (set_trial(), --no-device-trial), auto takes the choice kept for the nearest length, or the CPU when there is none.

What only the CPU traces (sound through partitions and openings, a source or a listener too near a surface or the line where two meet for the GPU’s rays, vegetation of more media than the GPU keeps) runs there, whatever the setting, and so does a run the GPU declines once it has it (one whose results its buffers cannot hold, or a ray through more volumes of vegetation at once than its tables hold): the plan trace() returns says so. Outdoors the GPU bends the rays in the atmosphere and takes them through vegetation as the CPU does.

The two agree statistically, not ray for ray (the GPU works in single precision and draws its own random numbers). With cpu a run gives the same result every time, and with gpu too until the weight window fills a family of copies (max_family): which copies split then depends on the order the GPU’s threads come in. With both which rays each one traces depends on how fast each goes. Results then vary from run to run within the noise of the ray count.

acoustic_spaces.engine.ray_device.TRIAL_FLAG = '--no-device-trial'

The command-line switch (acoustic-spaces simulate and the editor) for set_trial.

acoustic_spaces.engine.ray_device.Device

The settings of simulation.late.device.

alias of Literal[‘cpu’, ‘gpu’, ‘both’, ‘auto’]

class acoustic_spaces.engine.ray_device.Plan(device: str, cpu_rate: float = 1.0, gpu_rate: float = 1.0, reason: str = '')[source]

Where rays go: device is cpu, gpu or both; cpu_rate and gpu_rate (rays per second, from the trial; 1 for unknown) share them; reason says why, when it differs from the setting.

acoustic_spaces.engine.ray_device.choose(setting: str | Plan, values: dict) → Plan[source]

Where to trace a run with the arguments values of _native.trace_stochastic for the device setting, or as the Plan given (as acoustic-spaces tune times each).

acoustic_spaces.engine.ray_device.release() → None[source]

Lets go of what the GPU keeps from one of a run’s calls to the next, as the run ends (nothing where the GPU’s tracer was never loaded).

acoustic_spaces.engine.ray_device.set_trial(enabled: bool) → None[source]

Switch auto’s trial on or off for this session (off: the saved choice).

acoustic_spaces.engine.ray_device.trace(plan: Plan, values: dict, keep: bool = False) → tuple[tuple, Plan][source]

_native.trace_stochastic(**values) where plan says, and the plan it followed: the CPU, with the GPU’s reason, where the GPU declined the rays. With keep, the GPU keeps its rays in flight for the next call, until release().

acoustic_spaces.engine.ray_device.trial(values: dict) → tuple[float, float][source]

Rays per second on the CPU and on the GPU for a run like values (the arguments of _native.trace_stochastic): a few thousand rays traced on each, past the run’s own random streams.

How fast the CPU and the GPU are on this computer, and what auto picks from it.

acoustic-spaces tune (tune()) times the late stage on the CPU, on the GPU and on both at once, for several response lengths, and the wave solver on the CPU and on the GPU, on one scene. It keeps the fastest for each in the user’s cache folder, for the computer (its GPU and CPU thread count):

  • the late stage’s auto (ray_device) takes the choice for the run’s response length: the one for the shortest timed length at least as long, else the longest. Without tune, its trial keeps a choice there too, for its range of lengths (up to 0.5, 1, 2, 4 s and so on).

  • the wave solver’s auto compares the timed costs for the run’s step count: per grid cell, a set-up and a cost per step on each device. Without tune, it takes a hardware GPU when wgpu finds one.

A software GPU (such as lavapipe or SwiftShader) is timed like any other, but auto never takes it.

auto applies to scenes set to it, and to scenes that set no device once tune has made it this computer’s default (set_default()); otherwise those run on the CPU, so that a scene gives the same result on every computer.

acoustic_spaces.engine.tuning.LENGTHS = (0.5, 1.0, 2.0, 4.0)

Response lengths tune times the late stage at (s).

acoustic_spaces.engine.tuning.SCENE = 'concert_hall'

The example scene tune times when given none.

class acoustic_spaces.engine.tuning.Tuning(scene: str, machine: str, rays: int, late: list[LateTiming] = <factory>, wave: WaveTiming | None = None, wave_skipped: str = '', software: bool = False, file: Path = <factory>)[source]

What tune() timed and kept.

keep() → None[source]

Keep the choices for this computer, where auto reads them (tune() does unless told not to).

summary() → str[source]

The timings as a table, and what auto will pick.

acoustic_spaces.engine.tuning.cache_file() → Path[source]

Where the choices are kept: acoustic-spaces/devices.json in the user’s cache folder.

acoustic_spaces.engine.tuning.keep_late(max_time: float, choice: dict) → None[source]

Keep the late stage’s choice for the range of max_time.

acoustic_spaces.engine.tuning.keep_wave(costs: dict) → None[source]

Keep the wave solver’s costs (see wave_costs()).

acoustic_spaces.engine.tuning.late_choice(max_time: float) → dict | None[source]

The late stage’s choice for responses max_time long (s): the one kept for the shortest range at least that long, else for the longest; None when none is kept. It has device, cpu_rate and gpu_rate (rays per second; only their ratio counts) and from (tune or trial).

acoustic_spaces.engine.tuning.late_choices() → dict[float, dict][source]

The late stage’s choices kept for this computer, by range of response lengths (its upper end, s).

acoustic_spaces.engine.tuning.late_entry(max_time: float) → dict | None[source]

The late stage’s choice kept for exactly the range of max_time, or None.

acoustic_spaces.engine.tuning.length_key(max_time: float) → str[source]

The range of response lengths max_time (s) falls in, by its upper end: a power of two seconds (0.5, 1, 2, 4, …).

acoustic_spaces.engine.tuning.machine() → str[source]

The computer the choices are kept for: its GPU and CPU thread count.

acoustic_spaces.engine.tuning.saved() → dict[source]

What is kept for this computer: {"late": {length: choice}, "wave": costs, "default": device}.

acoustic_spaces.engine.tuning.tune(room, *, rays: int | None = None, lengths: Sequence[float] = (0.5, 1.0, 2.0, 4.0), wave_lengths: Sequence[float] | None = (0.05, 0.2), threads: int | None = None, say: Callable[[str], None] | None = None, keep: bool = True) → Tuning[source]

Time the late stage and the wave solver of room (a loaded Room) on the CPU and the GPU, keep the fastest for this computer and return the timings.

The late stage traces the scene’s first source to its listeners with the scene’s settings, rays per band (default: the scene’s), once for each response length of lengths (s) on each device; the listeners too near a surface for the GPU (gpu_tracer.listeners_too_near) are left out. The wave solver runs the scene’s wave settings (enabled or not) for the two wave_lengths; None leaves it out. threads defaults to the scene’s. keep=False returns the timings without saving them; Tuning.keep() saves them later (the editor does that on OK).

acoustic_spaces.engine.tuning.wave_costs() → dict | None[source]

The wave solver’s timed costs, {"cpu": [a, b], "gpu": [a, b]}: seconds per grid cell to set up (a) and per step (b); None when not timed.

acoustic_spaces.engine.tuning.wave_pick(costs: dict) → str[source]

What the wave solver’s auto takes with costs, in words.

acoustic_spaces.engine.tuning.wave_prefers_gpu(steps: int) → bool | None[source]

Whether the GPU steps a grid steps times clearly faster than the CPU did when timed; None when not timed.

The late stage’s stochastic ray tracer on a GPU, through WebGPU.

trace_stochastic() takes the arguments of the compiled core’s acoustic_spaces._native.trace_stochastic and returns what it does, computed by one WGSL compute shader on any GPU wgpu reaches (see acoustic_spaces.engine.gpu). It traces what the CPU does: detector spheres and diffuse or specular rain, vector-based or random scattering, the scattering of a surface’s size, air absorption, the early stage’s paths left out, arrival directions, the weight window that splits rays and thins them out, and the face groups that re-weight the absorption (each ray counts its reflections off each group, in 16 bits, and the listeners sum the moments of those counts); outdoors, the rays bent by the atmosphere, followed in chords as the CPU follows them (cpp/include/acoustic_spaces/atmosphere.hpp), and the plants that absorb and scatter them (vegetation.hpp), with the stems’ and the foliage’s rain. It leaves to the CPU (raising Unsupported) sound through surfaces into other rooms, a source or a listener nearer a surface, or the line where two meet, than its rays tell apart (too_near()), runs whose results its buffers cannot hold, and vegetation of more than MAX_MEDIA media or so many volumes along one ray that its fixed tables run out of room.

Rays start where the CPU’s do (_native.ray_starts: the same directions and energies for the same seed), then go their own way: the GPU draws its random numbers from streams of its own (xoshiro128**) and works in single precision, so the two agree statistically, not ray for ray. Each ray adds its energy to the listeners’ time slots with atomic additions of 64-bit fixed-point numbers (two 32-bit words with a carry, rounded at random to the nearest step, so that sums are exact and unbiased; WGSL has no atomic floating-point addition), scaled so that a window’s sums stay under 2**40 times the reflections per ray, where the listeners’ sums grow with the ray count (and the GPU gives up a run whose sums overflow).

The rays advance in rounds of a few reflections each, so that no dispatch runs long enough for the operating system to reset the GPU. Rays still going at the end of a round, and the copies split off during it, are packed into the other half of a buffer for the next round, and new rays from the source fill it up to half its size; the other half takes the copies, and a split that finds no room left is not made (which leaves every expectation as it was). A ray’s copies so advance together, where the CPU follows each to its end before it takes the next: a family that reaches its limit (max_family) reaches it sooner here, its copies made earlier on their way. That leaves the expected energies as they were too, but where the weight window asks for more copies than a family may have, the GPU traces more reflections in the late tail than the CPU (in the shoebox example, up to twice as many), and its tail varies less. Which of a family’s copies split before it is full depends on the order the threads come in, so such runs differ from one another within the noise of the ray count. Bent rays take many chords to a leg, so their rounds hold fewer rays.

acoustic_spaces.engine.gpu_tracer.MAX_MEDIA = 16

Most media of vegetation (the shader keeps a scattering rate per medium), and most volumes along one piece of a ray (more are dropped, and the run declined).

class acoustic_spaces.engine.gpu_tracer.GpuTracer(bvh)[source]

The tree of bvh (an acoustic_spaces._native.Bvh) and its faces’ normals on the GPU, to trace rays in.

box

The model’s box (its lowest and highest corner) in the shader’s coordinates.

trace(keep: bool = False, **arguments) → tuple[source]

Traces rays (see _trace() for the arguments), one run at a time. With keep, keeps its buffer of rays in flight for the next call, until release().

release() → None[source]

Lets go of the rays in flight it keeps from one call to the next.

bent_chords(origins, directions, budget, away, atmosphere, wind_direction, ground, chord_sagitta) → tuple[source]

As _native.bent_chords, on the GPU: one chord of each ray bent by the atmosphere (see atmosphere.hpp), from origins along directions (unit), at most budget metres of arc, stopping where a ray turns back towards the plane whose normal is its row of away (zeros: none). Returns (ends, directions at the ends, arc lengths, times, turned), for the tests.

exception acoustic_spaces.engine.gpu_tracer.Unsupported[source]

The GPU tracer does not do what a run asks for; the CPU’s does.

acoustic_spaces.engine.gpu_tracer.release() → None[source]

Lets go of the rays in flight that GPU tracers keep from one call to the next (calls with keep), as a run’s late part ends.

acoustic_spaces.engine.gpu_tracer.run_memory(rays: int, bands: int, results: float) → float[source]

Bytes a run of rays rays in bands bands takes on the GPU and off it, for results (the energy and directional arrays, in 64-bit floats) of results bytes: the results, the GPU’s sums of them and one part of those read back at a time; the rays’ starts (_native.ray_starts), their copies for the GPU and a word per ray for its family; and the GPU’s rays in flight (at most _MOST_RAYS of 21 + 3 * bands words and those of the most face groups, twice). A GPU built into the processor takes its buffers from the computer’s memory.

acoustic_spaces.engine.gpu_tracer.trace_stochastic(bvh, source, directivity_a, orientation, directivity_table, absorption, scattering, air, surface_size, band_hz, vector_scattering, size_from_order, transmission, face_room, source_room, receivers, directions, rays, max_time, time_step, dir_time_step, speed_of_sound, receiver_radius, diffuse_rain, specular_rain, covered_order, covered_time, seed, threads, window_time_step, first_ray, split_target, split_ratio, max_split, max_family, room_level, face_group, groups, moment_time_step, atmosphere=None, wind_direction=None, ground=0.0, chord_sagitta=0.02, plants=None, plant_outline=None, plant_absorption=None, plant_scattering=None, plant_asymmetry=None, plant_upright=None, gather_ratio=0.0, face_kind=None, covered_ground=0, *, total: int | None = None, keep: bool = False) → tuple[source]

As acoustic_spaces._native.trace_stochastic, on the GPU. total (default rays) is the number of rays the source’s energy is shared between, for tracing part of a run’s rays here and the rest elsewhere. With keep, the GPU keeps its buffer of rays in flight for the next call, until release(), as a run’s late part does; without, the call makes and lets go of its own. Raises Unsupported for what only the CPU traces: transmission into a room (see passes_sound()), a source or a listener too near a surface (too_near()) and vegetation of more media than MAX_MEDIA.

acoustic_spaces.engine.gpu_tracer.tracer(bvh) → GpuTracer[source]

The GPU tracer of bvh, made once per model.

Ray queries against a room model on a GPU, through WebGPU.

GpuBvh uploads the compiled core’s bounding volume hierarchy (see acoustic_spaces._native.Bvh.layout) and answers the CPU’s batch queries, Bvh.intersect (the nearest face along each ray) and Bvh.occluded (whether any face blocks it), with one WGSL compute shader on any GPU wgpu reaches (see acoustic_spaces.engine.gpu). It needs the optional gpu extra. It is the ray search a tracer on the GPU builds on; validation/rays_gpu.py times it against the CPU’s.

The GPU works in single precision, where the CPU’s double precision needs next to no slack. So the model is moved to centre its box on the origin (which keeps coordinates small), every box of the tree is widened by BOX_PAD of its own size, and every triangle by EDGE across each edge, so that a ray through an edge or a corner two faces share hits one of them instead of slipping between. The nearest face along a ray is then the CPU’s, but for rays meeting two faces at nearly the same point, and the distance agrees to single-precision rounding.

acoustic_spaces.engine.gpu_rays.BVH_WGSL = "\nconst NONE: u32 = 0xffffffffu;\nconst FAR: f32 = 3.0e38;\nconst EDGE: f32 = 0.0001;\nconst STACK: u32 = 64u;\n\nstruct Hit {\n    t: f32,\n    face: u32,\n}\n\n// 1 / d per axis, with axes the ray runs (nearly) parallel to kept finite.\nfn reciprocal(d: vec3<f32>) -> vec3<f32> {\n    let tiny = abs(d) < vec3<f32>(1e-20);\n    let away = select(vec3<f32>(1e-20), vec3<f32>(-1e-20), d < vec3<f32>(0.0));\n    return 1.0 / select(d, away, tiny);\n}\n\n// Where the ray enters the box of `node`, if it does before t_max (else FAR).\nfn enter(node: u32, o: vec3<f32>, inv: vec3<f32>, t_max: f32) -> f32 {\n    let lo = bitcast<vec3<f32>>(nodes[2u * node].xyz);\n    let hi = bitcast<vec3<f32>>(nodes[2u * node + 1u].xyz);\n    let ta = (lo - o) * inv;\n    let tb = (hi - o) * inv;\n    let t_in = min(ta, tb);\n    let t_out = max(ta, tb);\n    let t0 = max(max(t_in.x, t_in.y), max(t_in.z, 0.0));\n    let t1 = min(min(t_out.x, t_out.y), min(t_out.z, t_max));\n    return select(FAR, t0, t0 <= t1);\n}\n\n// Moller-Trumbore, two-sided, the edges widened by EDGE: t, or a negative value.\nfn hit_triangle(place: u32, o: vec3<f32>, d: vec3<f32>) -> f32 {\n    let v0 = bitcast<vec3<f32>>(triangles[3u * place].xyz);\n    let e1 = bitcast<vec3<f32>>(triangles[3u * place + 1u].xyz) - v0;\n    let e2 = bitcast<vec3<f32>>(triangles[3u * place + 2u].xyz) - v0;\n    let p = cross(d, e2);\n    let det = dot(e1, p);\n    let flat = abs(det) < 1e-30;\n    let inv_det = 1.0 / select(det, 1.0, flat);\n    let s = o - v0;\n    let u = dot(s, p) * inv_det;\n    let q = cross(s, e1);\n    let v = dot(d, q) * inv_det;\n    let inside = !flat && u >= -EDGE && u <= 1.0 + EDGE && v >= -EDGE && u + v <= 1.0 + EDGE;\n    return select(-1.0, dot(e2, q) * inv_det, inside);\n}\n\n// The nearest face along o + t d (d of unit length) with t in (t_min, t_max), skipping\n// face `skip`, or (t_max, NONE); with `any_hit`, the first face found, which is enough\n// to know the way is blocked. Of two children the ray enters, the nearer goes first;\n// the other waits and is dropped if a hit nearer than its box turns up meanwhile.\n// (No early exits from the loops: with them, the late tracer's searches on Direct3D 12\n// missed faces and could run forever.)\nfn search_ray(o: vec3<f32>, d: vec3<f32>, t_min: f32, t_max: f32, skip: u32,\n              any_hit: bool) -> Hit {\n    var best = Hit(t_max, NONE);\n    let inv = reciprocal(d);\n    var waiting_node: array<u32, STACK>;\n    var waiting_entry: array<f32, STACK>;\n    var top = 0u;\n    // The node to look in next; NONE once there is none.\n    var node = select(0u, NONE, enter(0u, o, inv, t_max) > t_max);\n    while (node != NONE) {\n        let low = nodes[2u * node];\n        let count = nodes[2u * node + 1u].w;\n        var next = NONE;\n        if (count > 0u) {\n            let end = low.w + count;\n            for (var place = low.w; place < end && !(any_hit && best.face != NONE); place++) {\n                let face = triangles[3u * place].w;\n                if (face != skip) {\n                    let t = hit_triangle(place, o, d);\n                    if (t > t_min && t < best.t) {\n                        best = Hit(t, face);\n                    }\n                }\n            }\n            if (any_hit && best.face != NONE) {\n                top = 0u;\n            }\n        } else {\n            let left = low.w;\n            let right = left + 1u;\n            let to_left = enter(left, o, inv, best.t);\n            let to_right = enter(right, o, inv, best.t);\n            let in_left = to_left <= best.t;\n            let in_right = to_right <= best.t;\n            if (in_left && in_right) {\n                let left_first = to_left <= to_right;\n                waiting_node[top] = select(left, right, left_first);\n                waiting_entry[top] = select(to_left, to_right, left_first);\n                top++;\n                next = select(right, left, left_first);\n            } else if (in_left || in_right) {\n                next = select(right, left, in_left);\n            }\n        }\n        // Else the nearest waiting node the ray still reaches before its best hit, if any.\n        while (next == NONE && top > 0u) {\n            top--;\n            if (waiting_entry[top] <= best.t) {\n                next = waiting_node[top];\n            }\n        }\n        node = next;\n    }\n    return best;\n}\n"

The tree and the search in WGSL, for any shader that binds nodes (two vec4<u32> per node: its box’s low corner and first child or triangle, then its high corner and triangle count, zero for an inner node) and triangles (three vec4<u32> per place in leaf order: the three corners, the first with its face) as read-only storage.

class acoustic_spaces.engine.gpu_rays.GpuBvh(bvh)[source]

The tree of bvh (an acoustic_spaces._native.Bvh) on the GPU, with the CPU’s batch queries.

scale

Length of the model’s box diagonal (m).

centre

Where the model’s box is centred: the GPU’s coordinates are relative to it.

property most_rays: int

The most rays one RayBatch holds on this GPU.

upload(origins, directions, t_max, ignore) → RayBatch[source]

Puts rays on the GPU: origins and unit directions (n, 3), how far to search (n,; inf for no limit) and a face each one skips (n,; -1 for none).

search(batch: RayBatch, any_hit: bool = False) → tuple[ndarray, ndarray][source]

Searches the rays of batch: per ray the distance and the face of the nearest hit, or with any_hit of a hit, (inf, -1) for none.

intersect(origins, directions, t_max, ignore) → tuple[ndarray, ndarray][source]

As Bvh.intersect: per ray, the nearest hit’s distance and face, (inf, -1) for a miss.

occluded(origins, directions, t_max, ignore) → ndarray[source]

As Bvh.occluded: per ray, whether a face lies within its t_max.

class acoustic_spaces.engine.gpu_rays.RayBatch(rays, hits, count: int, t_max: ndarray)[source]

Rays uploaded to the GPU (see GpuBvh.upload()), to search more than once.

acoustic_spaces.engine.gpu_rays.pack_tree(layout: dict[str, ndarray], scale: float)[source]

The tree of a Bvh.layout() as the shader reads it: the centre of the model’s box (the shader’s coordinates are relative to it), the nodes (nodes, 2, 4) and the triangles (places, 3, 4), as 32-bit words (see BVH_WGSL).

Parameters, air and impulse responses

Room acoustic parameters of ISO 3382-1, from energy decays or impulse responses.

All parameters are per octave band and measured from the arrival of the direct sound:

  • edt, t20, t30: decay times (s) from a line fitted to the backward-integrated (Schroeder) curve between 0 and -10 dB, -5 and -25 dB, and -5 and -35 dB.

  • c50, c80: clarity (dB), energy before 50 or 80 ms over the energy after.

  • d50: definition, energy before 50 ms over all of it (0 to 1).

  • ts: centre time (s), the energy-weighted mean arrival time.

  • g: strength (dB), total energy over that of the same source at 10 m in free field.

Where the response has them (see MORE_PARAMETERS), also:

  • lf, lfc: early lateral energy fractions (annex A), the energy a figure of eight with its null on the source picks up from 5 to 80 ms over all the energy up to 80 ms; lfc weights each arrival by the cosine of its angle to the figure’s axis, not the square.

  • lj: late lateral sound level (dB), the figure of eight’s energy from 80 ms on over the free-field energy at 10 m, as for G.

  • iacc_e, iacc_l: interaural cross-correlation coefficients (annex B) of a binaural response, 0 to 80 ms and from 80 ms to the end.

  • st_early, st_late: stage support (dB), measured 1 m from the source: the energy from 20 to 100 ms and from 100 to 1000 ms over that of the first 10 ms. st_early is Gade’s ST1.

  • t30_x, t30_y, t30_z: T30 of figure-of-eight pickups facing forward, left and up from the listener, the directional decay of a first-order Ambisonics response.

speech_transmission_index() gives the STI of IEC 60268-16 from the same energies, or STIPA, useful_to_detrimental() U50, and echo_criterion() the echo criteria of Dietsch and Kraak from an impulse response. time_weighted() gives a level over time through IEC 61672-1’s exponential time weighting, and event_levels() a sound event’s maximum time-weighted level and its sound exposure level over its 10 dB-down time.

A response that stops before it has decayed loses the energy of its missing tail and reads too short; the tail is estimated from the last part of the decay and added back (ISO 3382-1, 5.3.4). One that stops before it has decayed by 20 dB leaves too much to that estimate, and all its parameters are NaN.

acoustic_spaces.parameters.ALL_PARAMETERS = {'c50': ('dB', 'clarity, 50 ms'), 'c80': ('dB', 'clarity, 80 ms'), 'curvature': ('%', 'curvature, 100 (T30 / T20 - 1) (ISO 3382-2)'), 'd50': ('', 'definition'), 'edt': ('s', 'early decay time'), 'g': ('dB', 'strength'), 'iacc_e': ('', 'interaural cross-correlation, 0 to 80 ms'), 'iacc_l': ('', 'interaural cross-correlation, 80 ms on'), 'lf': ('', 'early lateral energy fraction'), 'lfc': ('', 'early lateral energy fraction, cosine weighted'), 'lj': ('dB', 'late lateral sound level'), 'st_early': ('dB', 'early stage support'), 'st_late': ('dB', 'late stage support'), 't20': ('s', 'reverberation time from the -5 to -25 dB decay'), 't30': ('s', 'reverberation time from the -5 to -35 dB decay'), 't30_x': ('s', 'T30 of a figure of eight facing forward'), 't30_y': ('s', 'T30 of a figure of eight facing left'), 't30_z': ('s', 'T30 of a figure of eight facing up'), 'ts': ('s', 'centre time'), 'xi_t20': ('‰', 'non-linearity of the T20 decay, 1000 (1 - r²) of its line (ISO 3382-2)'), 'xi_t30': ('‰', 'non-linearity of the T30 decay, 1000 (1 - r²) of its line (ISO 3382-2)')}

Every parameter, in display order.

acoustic_spaces.parameters.A_WEIGHTING_DB: tuple[float, ...] = (-26.2, -16.1, -8.6, -3.2, 0.0, 1.2, 1.0, -1.1)

A-weighting of the octave bands (dB, IEC 61672-1, rounded).

acoustic_spaces.parameters.C_WEIGHTING_DB: tuple[float, ...] = (-0.8, -0.2, 0.0, 0.0, 0.0, -0.2, -0.8, -3.0)

C-weighting of the octave bands (dB, IEC 61672-1, rounded).

acoustic_spaces.parameters.DECAY_RANGES = {'edt': (0.0, -10.0), 't20': (-5.0, -25.0), 't30': (-5.0, -35.0)}

Fit ranges in dB for EDT, T20 and T30.

acoustic_spaces.parameters.ECHO_CRITERIA: dict[str, tuple[float, float, tuple[int, ...], tuple[float, float]]] = {'music': (1.0, 0.014, (1000, 2000), (1.5, 1.8)), 'speech': (0.6666666666666666, 0.009, (1000,), (0.9, 1.0))}

Echo criteria (Dietsch and Kraak, 1986): the power n of the pressure’s magnitude, the window (s), the octave bands the response is filtered to with one band-pass over them (one octave about 1 kHz for speech, two about 1.4 kHz for music), and the EC at which 10 % and 50 % of listeners hear an echo.

acoustic_spaces.parameters.MORE_PARAMETERS = {'curvature': ('%', 'curvature, 100 (T30 / T20 - 1) (ISO 3382-2)'), 'iacc_e': ('', 'interaural cross-correlation, 0 to 80 ms'), 'iacc_l': ('', 'interaural cross-correlation, 80 ms on'), 'lf': ('', 'early lateral energy fraction'), 'lfc': ('', 'early lateral energy fraction, cosine weighted'), 'lj': ('dB', 'late lateral sound level'), 'st_early': ('dB', 'early stage support'), 'st_late': ('dB', 'late stage support'), 't30_x': ('s', 'T30 of a figure of eight facing forward'), 't30_y': ('s', 'T30 of a figure of eight facing left'), 't30_z': ('s', 'T30 of a figure of eight facing up'), 'xi_t20': ('‰', 'non-linearity of the T20 decay, 1000 (1 - r²) of its line (ISO 3382-2)'), 'xi_t30': ('‰', 'non-linearity of the T30 decay, 1000 (1 - r²) of its line (ISO 3382-2)')}

Parameters only some responses give, in display order: those of a lateral or a binaural response, those 1 m from the source and those of first-order Ambisonics. They are NaN in every band of a response that cannot give them.

acoustic_spaces.parameters.PARAMETERS = {'c50': ('dB', 'clarity, 50 ms'), 'c80': ('dB', 'clarity, 80 ms'), 'd50': ('', 'definition'), 'edt': ('s', 'early decay time'), 'g': ('dB', 'strength'), 't20': ('s', 'reverberation time from the -5 to -25 dB decay'), 't30': ('s', 'reverberation time from the -5 to -35 dB decay'), 'ts': ('s', 'centre time')}

Parameter names, units and short descriptions, in display order.

acoustic_spaces.parameters.STIPA_MODULATION_HZ: tuple[tuple[float, float], ...] = ((1.6, 8.0), (1.0, 5.0), (0.63, 3.15), (2.0, 10.0), (1.25, 6.25), (0.8, 4.0), (2.5, 12.5))

STIPA (IEC 60268-16:2020, annex B): the two modulation frequencies of each band (Hz).

acoustic_spaces.parameters.STI_BANDS_HZ: tuple[int, ...] = (125, 250, 500, 1000, 2000, 4000, 8000)

Speech transmission index (IEC 60268-16:2020, annex A): its octave bands, the modulation frequencies (Hz), the weighting factors alpha and beta of male and female speech (the female ones from the 2011 edition, which leave out the 125 Hz band), and the absolute speech reception threshold of each band (dB).

acoustic_spaces.parameters.SLOW_S = 1.0

The time constant (s) of IEC 61672-1’s slow time weighting, S.

acoustic_spaces.parameters.SPEECH_SPECTRUM_DB: dict[str, tuple[float, ...]] = {'female': (-18.7, -6.7, 5.3, -1.9, -9.1, -15.8, -16.7, -18.0), 'male': (-9.1, 2.9, 2.9, -0.8, -6.8, -12.8, -18.8, -24.8)}

The long-term spectrum of speech (IEC 60268-16:2011, table A.2): octave-band levels (dB) relative to the A-weighted level, OCTAVE_BANDS_HZ. The standard gives none at 63 Hz, nor at 125 Hz for female speech; those are taken 12 dB below the next band up (an assumption; neither counts in the STI).

acoustic_spaces.parameters.TIME_WEIGHTING_STEP_S = 0.01

How far apart (s) time_weighted() works the time-weighted level out by default.

class acoustic_spaces.parameters.EventLevels(max_db: float, exposure_db: float, start_s: float, end_s: float)[source]

The levels of a sound event, from event_levels().

max_db: float

The highest time-weighted level (dB): L_ASmax, A-weighted and slow.

exposure_db: float

The sound exposure level (dB) over the time the time-weighted level is within the chosen drop of its highest: SEL over the 10 dB-down time.

start_s: float

When that time starts and ends (s, as the times given).

end_s: float

Alias for field number 3

class acoustic_spaces.parameters.Levels(spl: ndarray, spl_a: float, sti: float, stipa: float, u50: ndarray, re_free_field: ndarray, re_free_field_a: float)[source]

What a listener gets from a source of a given sound power (levels_and_speech()): the sound pressure level per octave band (spl, dB SPL) and A-weighted (spl_a, dB(A)); the speech transmission index, sti and stipa (0 to 1), and u50 per octave band (dB); outdoors the level relative to free field per octave band (re_free_field, dB) and A-weighted (re_free_field_a), NaN in a room. NaN where undefined.

as_dict() → dict[source]

Plain numbers and lists under the report’s names (spl_db, spl_a_db, sti, stipa, u50, re_free_field_db, re_free_field_a_db), with None for undefined values (JSON friendly).

class acoustic_spaces.parameters.RoomParameters(edt: ndarray, t20: ndarray, t30: ndarray, c50: ndarray, c80: ndarray, d50: ndarray, ts: ndarray, g: ndarray, lf: ndarray | None = None, lfc: ndarray | None = None, lj: ndarray | None = None, iacc_e: ndarray | None = None, iacc_l: ndarray | None = None, st_early: ndarray | None = None, st_late: ndarray | None = None, t30_x: ndarray | None = None, t30_y: ndarray | None = None, t30_z: ndarray | None = None, xi_t20: ndarray | None = None, xi_t30: ndarray | None = None, curvature: ndarray | None = None)[source]

ISO 3382-1 parameters, one value per octave band (NaN where undefined).

Those of MORE_PARAMETERS are NaN in every band unless given.

classmethod from_dict(data: dict) → RoomParameters[source]

The parameters as_dict() gave (None for undefined values); those of MORE_PARAMETERS it lacks are NaN.

as_dict() → dict[str, list[float | None]][source]

Plain lists, with None for undefined values (JSON friendly).

given() → list[str][source]

The parameters with a value in at least one band, and those of PARAMETERS always, in display order.

table() → str[source]

A text table: one row per parameter (see given()), one column per band.

class acoustic_spaces.parameters.SpeechParameters(sti: float, stipa: float, u50: ndarray, signal_db: ndarray)[source]

Speech intelligibility at a listener: STI and STIPA (0 to 1), U50 per octave band (dB), and the speech level (dB SPL per band) they take.

as_dict() → dict[source]

Plain numbers and lists, with None for undefined values (JSON friendly).

acoustic_spaces.parameters.Talker

Speech that talks: male or female.

alias of Literal[‘male’, ‘female’]

acoustic_spaces.parameters.decay_curve(energy: ndarray, time_step: float) → ndarray[source]

Backward-integrated (Schroeder) decay in dB at the start of each slot.

energy is one band’s energy per slot, starting at the direct sound; the curve starts at 0 dB and includes the estimated energy after the end of the response.

acoustic_spaces.parameters.echo_criterion(ir: ndarray, sample_rate: float, kind: str = 'speech', *, filters: str = 'iec') → tuple[float, float][source]

The echo criterion EC of Dietsch and Kraak (1986) of a mono impulse response, and the time (s after the direct sound) where it peaks.

The response, filtered to the bands of ECHO_CRITERIA[kind] (1 kHz for speech, 1 and 2 kHz for music, with one band-pass over both: two octaves about 1.4 kHz, as Dietsch and Kraak have it), gives the build-up of its centre time ts(t), the mean arrival time up to t weighted by the pressure’s magnitude to the power n; EC is the steepest rise of ts over the window, in units of the window. An echo makes ts jump: listeners hear one where EC exceeds 1.0 for speech or 1.8 for music (half of them; 0.9 and 1.5 for a tenth). NaN for a response shorter than the window, or with a band at or above half sample_rate.

acoustic_spaces.parameters.event_levels(times: Sequence[float] | ndarray, levels_db: Sequence[float] | ndarray, time_constant_s: float = 1.0, down_db: float = 10.0, step_s: float = 0.01) → EventLevels[source]

The maximum level and the sound exposure level of a level levels_db (dB) heard at times (s), as ECAC Doc 29 measures an aircraft’s (Volume 2, its glossary and section 4.1): the highest level through the time weighting of time_constant_s (slow by default, time_weighted()), and the sound exposure (the mean square integrated over time with no time weighting, IEC 61672-1), as a level held for 1 s, from the first to the last time the time-weighted level is within down_db of that highest: the “10 dB-down” time of eq. 4-1, which the NPD curves’ SEL is taken over (footnote 15). Doc 29’s eq. 4-2 integrates its L_A(t), which its glossary has slow-weighted; over a flyover’s 10 dB-down time that differs from the sound exposure by under 0.01 dB. Where a pass starts or ends within down_db of its highest, that time is cut there: start_s or end_s is its first or last time.

acoustic_spaces.parameters.from_energy(energy: ndarray, time_step: float, onset_s: float, reference_energy: float | Sequence[float] | ndarray | None = None, *, stage: bool = False, lateral: tuple[ndarray, ndarray] | None = None, directional: Sequence[ndarray] | None = None, open_air: bool = False) → RoomParameters[source]

Parameters from energy per band and time slot (bands, slots), slot 0 at emission.

onset_s is the arrival time of the direct sound. reference_energy is the energy of the same source at 10 m in free field, one value or one per band; without it g and lj are NaN. With stage, st_early and st_late (for a listener 1 m from the source). lateral is the energy a figure of eight with its null on the source picks up and its product with the pressure, each on the slots of energy, for lf, lfc and lj; directional the energies of figure-of-eight pickups facing forward, left and up, for t30_x, t30_y and t30_z. With open_air (an outdoor scene’s response), G is that of the energy the response holds in a band that does not decay as a room’s does, where the other parameters stay undefined: there is no reverberation to extrapolate past its end.

acoustic_spaces.parameters.interaural_cross_correlation(binaural: ndarray, sample_rate: float, *, filters: str = 'iec') → dict[str, ndarray][source]

IACC_E and IACC_L of a binaural impulse response (samples, 2), per octave band.

The interaural cross-correlation coefficient (ISO 3382-1, annex B) is the largest magnitude of the normalised cross-correlation of the two ears’ responses within 1 ms either way; iacc_e takes them from the direct sound’s arrival at the nearer ear to 80 ms later, iacc_l from there to the end. NaN in a band at or above half sample_rate.

acoustic_spaces.parameters.modulation_transfer(energy: ndarray, time_step: float, frequencies: Sequence[float] = (0.63, 0.8, 1.0, 1.25, 1.6, 2.0, 2.5, 3.15, 4.0, 5.0, 6.3, 8.0, 10.0, 12.5)) → ndarray[source]

Modulation transfer function (bands, modulation frequencies) of an energy response e(t) (bands, slots): the magnitude of the sum of e(t) exp(-2 pi j F t) over the sum of e(t), at each F of frequencies (Schroeder’s method).

acoustic_spaces.parameters.speech_transmission_index(energy: ndarray, time_step: float, *, signal_db: Sequence[float] | ndarray | None = None, noise_db: Sequence[float] | ndarray | float | None = None, stipa: bool = False, talker: Literal['male', 'female'] = 'male') → float[source]

STI (0 to 1) of an energy response per octave band (bands, slots), from the modulation transfer function (IEC 60268-16:2020, indirect method), weighted for male speech or, with talker="female", female speech. With stipa, STIPA instead: two modulation frequencies per band, not fourteen (STIPA_MODULATION_HZ).

energy has the bands of OCTAVE_BANDS_HZ (the 63 Hz band is not used) or of STI_BANDS_HZ. signal_db is the speech level per band at the listener (dB SPL); with it, auditory masking and the reception threshold apply, and noise_db (dB SPL per band, or one value for all) lowers the modulation by the signal-to-noise ratio. Without either, the STI is that of the room alone.

acoustic_spaces.parameters.sti_from_impulse_response(ir: ndarray, sample_rate: float, *, filters: str = 'iec', noise: bool = True, stipa: bool = False) → float[source]

STI, or with stipa STIPA, of the room alone from a mono impulse response: from its octave bands (125 Hz to 8 kHz) from the onset on, with noise cut where they sink into the background noise and the noise taken off, as from_impulse_response() takes them. NaN when one of those bands lies at or above half sample_rate (at a sample rate below 11.25 kHz, the 8 kHz band does).

acoustic_spaces.parameters.time_weighted(times: Sequence[float] | ndarray, levels_db: Sequence[float] | ndarray, time_constant_s: float = 1.0, step_s: float = 0.01) → tuple[ndarray, ndarray, ndarray][source]

A level levels_db (dB) heard at times (s, increasing) through IEC 61672-1’s exponential time weighting of time constant time_constant_s (the slow time weighting S by default), as a sound level meter reads it: the mean square at each moment t, 10^(L/10), weighted by exp(-(t - ξ)/τ)/τ over every earlier moment ξ. Between the given times the mean square goes linearly in time; before the first it is taken to have stood at its first value. Returns the times of a uniform grid step_s apart from the first time to the last, the level there, and the time-weighted level there (dB), worked out exactly for a mean square linear from one grid time to the next.

acoustic_spaces.parameters.useful_to_detrimental(d50: Sequence[float] | ndarray, signal_db: Sequence[float] | ndarray | float, noise_db: Sequence[float] | ndarray | float | None = None) → ndarray[source]

U50 (dB) per band (Bradley, 1986): the energy of the first 50 ms over that of the rest and the background noise, from the definition d50 and the speech and noise levels at the listener (dB SPL, one value or one per band). Without noise it is C50.

class acoustic_spaces.parameters.BandDecay(energy: ndarray, sample_rate: float, onset_s: float, crosspoint: ndarray, noise: ndarray, decay_range_db: ndarray)[source]

Squared octave-band responses of one impulse response, from its onset on.

onset_s: float

Arrival of the direct sound in the impulse response (s).

crosspoint: ndarray

Per band: sample where the response sinks into the background noise (the length when no noise floor shows), the noise power per sample, and the decay range (dB).

cleaned(band: int) → ndarray[source]

One band’s energy up to its crosspoint, with the noise taken off.

acoustic_spaces.parameters.FILTER_ORDER = 3

Order of the Butterworth octave filters for impulse responses.

acoustic_spaces.parameters.OCTAVE_RATIO = 1.9952623149688795

Ratio between adjacent octave mid-band frequencies, base 10 (IEC 61260-1).

acoustic_spaces.parameters.a_weighted(levels_db: Sequence[float] | ndarray) → float[source]

The A-weighted level (dB) of levels per octave band (OCTAVE_BANDS_HZ).

acoustic_spaces.parameters.band_decay(ir: ndarray, sample_rate: float, *, filters: str = 'iec', noise: bool = True, start: int | None = None) → BandDecay[source]

Filter ir into octave bands and, with noise, find each band’s noise floor.

ir is (samples,) or (samples, 1), as read_wav() gives a mono file. The bands start at its onset, or at sample start. A band whose lower edge (its exact mid-band frequency over 10^0.15, where its IEC 61260-1 filter is 3 dB down: 5623 Hz for 8 kHz) is at or above half the sample rate holds nothing of its own, and has no energy here; one that reaches past it holds its part below it.

acoustic_spaces.parameters.c_weighted(levels_db: Sequence[float] | ndarray) → float[source]

The C-weighted level (dB) of levels per octave band (OCTAVE_BANDS_HZ).

acoustic_spaces.parameters.band_energy_share(sample_rate: float, filters: str = 'iec') → ndarray[source]

Energy of a unit impulse inside each band, for converting broadband references.

acoustic_spaces.parameters.band_filter_gains(n_fft: int, sample_rate: float, bands: int = 8, order: int = 3) → ndarray[source]

Magnitudes (bands, n_fft // 2 + 1) of Butterworth band-pass filters of the 8 octave bands (as octave_filter_gains()) or the 24 third-octave bands, whose edges are fm G^(+-1/6).

acoustic_spaces.parameters.free_field_reference(ir: ndarray, sample_rate: float, distance_m: float, *, filters: str = 'iec') → ndarray[source]

Per-band reference energies for G from a free-field impulse response.

ir is the source measured at distance_m with no reflections (or with them windowed out); the result is its band energies moved to 10 m (inverse square law). The bands are taken with silence on both sides, as the zero-phase filters spread the sound both ways in time: a response that starts with its direct sound keeps all of each band’s energy.

acoustic_spaces.parameters.from_impulse_response(ir: ndarray, sample_rate: float, reference_energy: float | Sequence[float] | None = None, *, filters: str = 'iec', noise: bool = True, stage: bool = False, lateral: ndarray | None = None, directional: ndarray | None = None) → RoomParameters[source]

Parameters from a mono impulse response, split into octave bands.

ir is (samples,) or (samples, 1); an empty or silent one has every parameter NaN. reference_energy is the energy of the same source at 10 m in free field: per band (as from free_field_reference()), or that of a broadband impulse, which for responses made by this package is 0.01 (0.01 * ir_gain**2 for those written with normalize, ir_gain in their parameters.json). filters picks the band filters (see octave_bands()). With noise, each band is cut where it sinks into the background noise, the noise is subtracted and the decay beyond the cut estimated (ISO 3382-1, 5.3.4); decay times whose range does not clear the noise by 10 dB (EDT 20 dB, T20 35 dB, T30 45 dB) are NaN.

Every parameter is NaN in a band whose lower edge (as band_decay() gives it) is at or above half sample_rate, as the response holds nothing of its own there (at 8 kHz, the 8 kHz band). A band that reaches past it is analysed from its part below it (at 8 kHz the 4 kHz band, at 16 kHz the 8 kHz band); a broadband reference_energy is taken over the same part.

With stage, st_early and st_late as well, for a response measured 1 m from the source. lateral is the response of a figure of eight with its null on the source, measured with ir and at the same sensitivity on its axis, for lf, lfc and lj; directional (samples, 3) those of figure-of-eight pickups facing forward, left and up, as the X, Y and Z of first-order Ambisonics (SN3D), for t30_x, t30_y and t30_z. Both are taken from the onset of ir.

acoustic_spaces.parameters.noise_crosspoint(energy: ndarray, sample_rate: float) → tuple[int, float, float][source]

Where a squared response sinks into its background noise (Lundeby et al., 1995).

energy is one band’s squared response from the direct sound on. Returns the crosspoint (samples), the mean noise power per sample and the decay range (dB, from the loudest 10 ms down to the noise). A response that ends in silence (its last tenth more than 120 dB below the loudest 10 ms), or is still decaying in its last tenth, has no crosspoint (len(energy)), no noise and an infinite range; one with no decay above its noise has a range of 0.

acoustic_spaces.parameters.octave_bands(signal: ndarray, sample_rate: float, filters: str = 'iec') → ndarray[source]

Split a signal into octave bands: (n,) -> (bands, n).

filters="iec" applies the magnitudes of octave_filter_gains() with zero phase, so no band is delayed against another; "crossover" uses the crossovers of acoustic_spaces.synthesis, whose bands sum back to the input.

Zero-phase filters spread a sound both ways in time, and the bands cover the signal’s samples only: what a band spreads before the first sample or after the last is not in it. Of an impulse at the first sample a band keeps about half its energy (0.50 at 63 Hz to 0.71 at 8 kHz with the IEC filters); with the impulse 0.2 s in, all of it. Pad the signal with silence for its energies, as free_field_reference() and from_impulse_response() do.

acoustic_spaces.parameters.octave_filter_gains(n_fft: int, sample_rate: float, order: int = 3) → ndarray[source]

Magnitudes (bands, n_fft // 2 + 1) of Butterworth octave band-pass filters.

A band-pass of order (that of its low-pass prototype; 3 meets IEC 61260-1 class 1) has 1 at mid-band, -3 dB at the band edges fm G^(+-1/2) and about -20 dB at the neighbouring mid-bands.

acoustic_spaces.parameters.octave_midbands() → ndarray[source]

Exact mid-band frequencies (Hz) of OCTAVE_BANDS_HZ, base 10 (IEC 61260-1).

acoustic_spaces.parameters.onset(ir: ndarray, threshold_db: float = -20.0) → int[source]

Sample where the response first rises to threshold_db below its peak (ISO 3382-1).

Sound in air: speed of sound and atmospheric absorption (ISO 9613-1:1993).

acoustic_spaces.air.EXACT_OCTAVE_HZ = (63.09573444801933, 125.89254117941675, 251.188643150958, 501.18723362727224, 1000.0, 1995.2623149688795, 3981.0717055349724, 7943.282347242814)

Exact octave midband frequencies (base-10 series) for the nominal OCTAVE_BANDS_HZ.

acoustic_spaces.air.STATED_F_OVER_P = (0.0004, 10.0)

The ratios of frequency to pressure (Hz/Pa) for which ISO 9613-1:1993, clause 7, states the accuracy of equations 3 to 5, at pressures below 200 kPa: the same in 7.1 to 7.3, which together take in every humidity and temperature a scene can have (±10 % for a molar concentration of water vapour of 0.05 % to 5 %, ±20 % from 0.005 % to 0.05 % and above 5 %, ±50 % below 0.005 %).

acoustic_spaces.air.absorption_db_per_m(frequencies_hz: Sequence[float] | ndarray, temperature_c: float = 20.0, humidity_percent: float = 50.0, pressure_kpa: float = 101.325) → ndarray[source]

Pure-tone atmospheric attenuation coefficient (dB/m), ISO 9613-1 equations 3 to 5.

acoustic_spaces.air.density(temperature_c: float = 15.0, pressure_kpa: float = 101.325) → float[source]

Density of dry air (kg/m³) at the given temperature and pressure, as an ideal gas.

acoustic_spaces.air.energy_attenuation_per_m(temperature_c: float = 20.0, humidity_percent: float = 50.0, pressure_kpa: float = 101.325, bands: Literal['octave', 'third_octave'] = 'octave') → ndarray[source]

Energy attenuation m (1/m) per octave band, or per third-octave band with bands="third_octave", at the exact mid-band frequencies: intensity falls as exp(-m * distance).

This is the m of the 4 m V air term in Sabine’s and Eyring’s formulas.

acoustic_spaces.air.speed_of_sound(temperature_c: float) → float[source]

Speed of sound in air (m/s) at the given temperature.

acoustic_spaces.air.stated_pressures_kpa(bands: Literal['octave', 'third_octave'] = 'octave') → tuple[float, float][source]

The pressures (kPa) at which the frequency-to-pressure ratio of every band lies in the range ISO 9613-1:1993 states its accuracy for (STATED_F_OVER_P).

Impulse response synthesis from octave-band (or third-octave-band) energies.

The filter bank splits the spectrum into the eight octave bands with zero-phase, half-octave raised-cosine crossovers, or into the 24 third-octave bands with crossovers a sixth of an octave wide. The band gains sum to exactly one, so a signal split into bands and summed again comes back unchanged (perfect reconstruction). Each function takes the bands from the number of band signals or energies it is given (8 or 24).

Energy convention: the simulation gives time-integrated intensity for a source of unit energy, so the direct sound at r metres carries 1 / (4 pi r^2). Impulse responses are scaled by ENERGY_TO_IR so that this direct sound is an impulse of height 1 / r: 1 at 1 m, and 0.01 of energy at 10 m (the reference for strength G).

A path or time slot with energy E in every band becomes a broadband impulse or noise burst of energy E. Band energies are spectral levels, so the part of the output inside band b carries E_b times that band’s share of the spectrum.

acoustic_spaces.synthesis.ENERGY_TO_IR = 12.566370614359172

Impulse response energy per unit of simulated energy (time-integrated intensity).

acoustic_spaces.synthesis.REFERENCE_ENERGY_10M = 0.01

Energy of the impulse response of the direct sound at 10 m, the reference for G.

acoustic_spaces.synthesis.CROSSOVER_WIDTH = 0.5

Width of each crossover between octave bands, in octaves: half a band.

acoustic_spaces.synthesis.crossover_frequencies(bands: int = 8) → ndarray[source]

Edges between adjacent bands (Hz) of the 8 octave bands or 24 third-octave bands.

acoustic_spaces.synthesis.crossover_width(bands: int = 8) → float[source]

Width of each crossover (octaves): half a band.

acoustic_spaces.synthesis.band_gains(n_fft: int, sample_rate: float, bands: int = 8) → ndarray[source]

Zero-phase gains (bands, n_fft // 2 + 1) on the rFFT grid of the 8 octave bands or 24 third-octave bands; they sum to one.

acoustic_spaces.synthesis.fft_size(n: int, sample_rate: float) → int[source]

FFT length for filtering n samples with zero padding on both sides.

acoustic_spaces.synthesis.combine_bands(band_signals: ndarray, sample_rate: float, quadrature: ndarray | None = None) → ndarray[source]

Filter each band signal with its band and sum: (bands, n) -> (n,). With quadrature (bands, n), signals to add a quarter turn ahead in phase (their spectra times j).

acoustic_spaces.synthesis.equalized(signal: ndarray, sample_rate: float, gains) → ndarray[source]

signal (n, …) along its first axis through a zero-phase filter whose gain in each band is gains (8 octave bands or 24 third-octave bands), going from one to the next across the bands’ crossovers (band_gains()); the same gain in every band is that gain at every frequency.

acoustic_spaces.synthesis.matched_gains(gains, sample_rate: float, rounds: int = 30) → ndarray[source]

Gains for equalized() (8 octave bands or 24 third-octave bands) whose filter changes the energy of white noise in each band, as split_bands() splits it, by gains squared. Across a crossover equalized() goes from one band’s gain to the next’s, so where they differ a band takes some of its neighbour’s; these are gains nudged until each band’s energy is its own, as near as rounds rounds get it (to 0.001 dB): for gains stepping 12 dB from band to band, the lower ones some 5 dB further down. A band of no gain stays at none.

acoustic_spaces.synthesis.split_bands(signal: ndarray, sample_rate: float, bands: int = 8) → ndarray[source]

Split a signal into the 8 octave bands or 24 third-octave bands: (n, …) -> (bands, n, …), along its first axis; the bands sum to the input. As the bands are zero-phase, what each spreads before the first sample or after the last is not in it (see acoustic_spaces.parameters.octave_bands()).

acoustic_spaces.synthesis.band_energy_share(sample_rate: float, n_fft: int = 65536, bands: int = 8) → ndarray[source]

Energy of a unit impulse inside each band: its share of the spectrum.

acoustic_spaces.synthesis.place_impulses(delays_s: ndarray, amplitudes: ndarray, length: int, sample_rate: float, taps: int = 32) → ndarray[source]

Band signals (bands, length) with a fractional-delay impulse per path.

amplitudes is (paths, bands). Delays between samples use a Hann-windowed sinc.

acoustic_spaces.synthesis.placing_bytes(paths: int, taps: int = 32) → int[source]

Bytes place_impulses() holds beside its output while it places paths impulses: six arrays (paths, taps) of eight bytes an element, one of one byte, and three (paths,).

acoustic_spaces.synthesis.dirac_sequence(length: int, sample_rate: float, volume_m3: float | None, speed_of_sound: float, rng: Generator, time_step: float) → ndarray[source]

Random-sign impulses whose density grows like reflections in a room: 4 pi c^3 t^2 / V.

Every time slot of shape_noise() (time_step long, a whole number of samples or not) gets at least one impulse, so no slot’s energy is lost.

acoustic_spaces.synthesis.smooth_energy(energy: ndarray, time_step: float, start_s: float, window_s: float = 0.01) → ndarray[source]

Spread each slot’s energy after start_s over a window_s window centred on it.

The late energy of a ray tracer is a sum of discrete hits; a single strong ray late in the tail would become a click. Smoothing moves energy by at most half a window and keeps the total. A slot within half a window of start_s or of the end spreads over the part of its window from start_s to the end, so no energy moves ahead of start_s (into the early window of C50, when that is 50 ms after the direct sound) or past the end.

acoustic_spaces.synthesis.shape_noise(energy: ndarray, time_step: float, noise: ndarray, sample_rate: float) → ndarray[source]

Band signals (bands, n): noise scaled so each slot carries energy[band, slot].

Spatial outputs

Spatial outputs: binaural, Ambisonics and loudspeaker impulse responses.

Every format turns the arrival directions of a simulated response into channels:

  • Ambisonics: AmbiX (ACN channel order, SN3D normalisation), orders 0 to 7;

  • Loudspeakers: vector base amplitude panning onto a named layout (stereo, 5.0, 7.0, 5.0.4, 7.0.4, and 5.1 to 7.1.4 with a silent LFE channel) or any list of speakers;

  • Binaural: the two ears, with HRTFs from a SOFA file or a spherical head model;

  • Mono: the omnidirectional response;

  • Microphone: a listener’s microphone, a first-order pattern or a coincident pair (XY, Blumlein, MS) that its mono output picks up through (for_listener()).

Early reflections keep their exact direction. The late part comes from the arrival directions the stochastic ray tracer records (or from all around, for the statistical tail). spatial_impulse_response() (also Response.spatial_impulse_response) renders a response in a format.

class acoustic_spaces.spatial.HRTF(directions: 'np.ndarray', hrir: 'np.ndarray', sample_rate: 'float', name: 'str' = 'hrtf')[source]
nearest(directions: ndarray) → ndarray[source]

Index of the nearest measured direction for each of (dirs, 3).

onsets() → ndarray[source]

(m, 2) onset of each response (samples, fractions included): the lag at which it best matches its minimum-phase version, which starts at once (see _onsets()).

interpolate(directions: ndarray, *, onsets: Literal[False] = False) → ndarray[source]
interpolate(directions: ndarray, *, onsets: Literal[True]) → tuple[ndarray, ndarray]

Responses (dirs, 2, taps) for head directions (dirs, 3), between the measured ones; with onsets, also the onset (dirs, 2) each starts at (samples, fractions included).

The measured directions are triangulated (the faces of their convex hull, as for VBAP). Each direction mixes the responses at the corners of the triangle it falls in, aligned at their onsets, with its barycentric weights, and the mix is delayed by the same mix of the onsets, to a fraction of a sample: that mix is the onset given. A measured direction gives its own response, and the weights, and with them the responses and the interaural time difference, change smoothly with the direction. Where no triangle covers a direction (a set that leaves part of the sphere out), the nearest response is used, and its onset.

onsets_at(directions: ndarray) → ndarray[source]

The onsets (dirs, 2) that interpolate() gives for head directions (dirs, 3) (samples, fractions included), without mixing the responses.

resampled(sample_rate: float) → HRTF[source]

The same responses at another sample rate (band-limited, by FFT).

The responses are filters: their frequency response, and so their gain, stays the same at every rate.

class acoustic_spaces.spatial.Ambisonics(order: int = 1)[source]

AmbiX (ACN / SN3D) encoding of the given order: (order + 1) ** 2 channels.

pressure_gains() → ndarray[source]

(channels,) what each channel picks up of a sound pressure that is the same all over the room (all of it in W, none in the other channels).

gains(directions: ndarray) → ndarray[source]

Encoding gains (dirs, channels) of plane waves from head directions (dirs, 3).

class acoustic_spaces.spatial.Binaural(hrtf: HRTF | None = None, channels: int = 2, label: str = 'binaural')[source]

Left and right ear, through hrtf (default: spherical_head()).

pressure_gains() → ndarray[source]

(channels,) what each channel picks up of a sound pressure that is the same all over the room (all of it in each ear).

at(sample_rate: float) → HRTF[source]

The HRTF at sample_rate.

class acoustic_spaces.spatial.Format(*args, **kwargs)[source]
class acoustic_spaces.spatial.Loudspeakers(speakers: tuple[Speaker, ...], name: str = 'speakers')[source]

A loudspeaker layout: a name from LAYOUTS or a list of speakers.

pressure_gains() → ndarray[source]

(channels,) what each channel picks up of a sound pressure that is the same all over the room: 1/√n in each of the n main speakers, at unit power as the panning plays one direction (on a layout without height speakers, as it plays sound from straight above or below), and none in the LFE.

channel_mask() → int[source]

WAV channel mask of a named layout; 0 (no assignment) for others.

gains(directions: ndarray) → ndarray[source]

VBAP gains (dirs, channels) of unit power for head directions (dirs, 3).

class acoustic_spaces.spatial.Microphone(label: str, names: tuple[str, ...], weights: tuple[float, ...], axes: tuple[tuple[float, float, float], ...], a: tuple[float, ...] | None = None, aims: tuple[tuple[float, float, float], ...] = (), sides: tuple[tuple[float, float, float], ...] = ())[source]

Capsules in one place: channel k picks up weights[k] + axes[k] . v of sound arriving from v in head coordinates.

a: tuple[float, ...] | None = None

For a pattern that changes with frequency, the a of its capsules in each band (8 or 24; the channels share it), each channel’s capsule aim (a unit vector) and what it picks up besides that capsule (an MS pair’s figure-eight); weights and axes then hold the pattern at 1 kHz (SHOWN_BAND). None for one pattern at every frequency.

pressure_gains() → ndarray[source]

(channels,) what each channel picks up of a sound pressure that is the same all over the room: the capsules’ omnidirectional part (in the lowest band, for a pattern that changes with frequency), none of their gradient part.

gains(directions: ndarray) → ndarray[source]

What each channel picks up (n, channels) of sound arriving from directions (n, 3), unit vectors in head coordinates.

parts() → tuple[Microphone, Microphone][source]

A microphone whose pattern changes with frequency as two that do not: what each channel picks up whatever a (d . v and its side’s) and what a scales (1 - d . v), d its capsule’s aim. It picks up the first plus the second through a filter of gain a in each band (a_in()).

a_in(bands: int) → ndarray[source]

a in bands bands (8 octaves or 24 third octaves), as a source’s pattern goes from one to the other.

band_gains(directions: ndarray, bands: int) → ndarray[source]

What each channel picks up (n, channels, bands) in each of bands bands (8 octaves or 24 third octaves) of sound arriving from directions (n, 3).

spectral_gains(directions: ndarray, shapes: ndarray) → ndarray[source]

What each channel picks up (n, channels, bins) of sound arriving from directions (n, 3) at the frequencies of the synthesis’s band filters shapes (bands, bins) (acoustic_spaces.synthesis.band_gains()), which sum to one: each band’s gain across its share of the frequencies.

capsules() → list[tuple[FirstOrder, ndarray]][source]

Each channel as a first-order pattern and the rotation that aims it: columns forward, left and up in head coordinates (an MS pair’s left channel is a first-order pattern aimed between the front and the left).

class acoustic_spaces.spatial.Mono(channels: int = 1, label: str = 'mono')[source]

The omnidirectional response, as Response.impulse_response gives it.

pressure_gains() → ndarray[source]

(channels,) what each channel picks up of a sound pressure that is the same all over the room (all of it).

class acoustic_spaces.spatial.Speaker(name: 'str', azimuth: 'float', elevation: 'float' = 0.0, lfe: 'bool' = False)[source]
acoustic_spaces.spatial.fibonacci_sphere(n: int) → ndarray[source]

n near-uniform unit vectors (n, 3) on a Fibonacci lattice, each standing for an equal share of the sphere.

acoustic_spaces.spatial.for_listener(fmt, listener)[source]

The format listener’s output in fmt is rendered in: its microphone when fmt is mono and it has a pattern, else fmt.

acoustic_spaces.spatial.from_angles(azimuth_deg, elevation_deg) → ndarray[source]

Unit vectors (…, 3) from azimuth and elevation in degrees.

acoustic_spaces.spatial.from_output(output) → Format[source]

The format an outputs entry of a scene file (scene.Output) describes.

acoustic_spaces.spatial.read_sofa(path: str | Path) → HRTF[source]

HRTF from a SOFA file with head-related impulse responses for two ears.

acoustic_spaces.spatial.real_spherical_harmonics(order: int, directions: ndarray) → ndarray[source]

ACN / SN3D spherical harmonics (dirs, (order + 1) ** 2) of unit vectors (dirs, 3).

acoustic_spaces.spatial.spatial_impulse_response(response: Response, fmt: Format, sample_rate: int = 48000, seed: int | None = None, *, threads: int = 1) → np.ndarray[source]

Impulse responses (samples, channels) of response in fmt.

Levels match the mono response: an arrival from straight ahead has the same height in W, in a speaker it is panned to, and (below the head’s influence) at both ears. threads render the channels (binaurally the late part’s bands and the ears) side by side, each as it is rendered alone, so the result is the same with any number. They are at most the computer’s cores (all of them for 0 or fewer, as performance.threads), and each past the first holds one channel’s band signals and their spectra more (some 75 MB for 3.5 s at 48 kHz in 8 bands), so a format’s channels take no more of them than the computer’s memory lets have a channel in progress (channel_threads()).

acoustic_spaces.spatial.spherical_head(sample_rate: float = 48000, *, radius: float = 0.0875, ear_azimuth: float = 100.0, speed_of_sound: float = 343.0, directions: int = 2048) → HRTF[source]

Brown and Duda’s spherical head model on a grid of directions directions.

Each ear sees a one-pole, one-zero head-shadow filter that boosts high frequencies up to 6 dB towards the source and cuts them up to 20 dB on the far side, and the path length around the sphere (Woodworth’s formula). Responses start 1 ms early, so the earliest ear still has room for the filter’s ringing.

acoustic_spaces.spatial.to_angles(directions: ndarray) → tuple[ndarray, ndarray][source]

Azimuth in (-180, 180] and elevation in [-90, 90] degrees of vectors (…, 3).

acoustic_spaces.spatial.to_head(directions: ndarray, rotation: ndarray) → ndarray[source]

Room directions (…, 3) in the head coordinates of a listener whose rotation has the forward, left and up axes as columns (see Orientation.rotation).

Rotating sound fields, and decoding them to the ears:

Rotations: of directions (3 x 3 matrices from angles or quaternions) and of Ambisonics sound fields (one matrix per order of the AmbiX channels).

Angles follow the scene’s Orientation: yaw turns left (from +x towards +y), pitch looks up and roll tilts the head to the right, applied in the order roll, pitch, yaw. A rotation matrix has the turned forward, left and up axes as its columns.

class acoustic_spaces.spatial.rotation.FieldRotation(order: int)[source]

Rotations of an Ambisonics (ACN / SN3D) sound field of order.

matrix() gives the (channels, channels) matrix that turns the channels of any sound field into those of the same field turned by a rotation: a plane wave from d comes from R @ d afterwards. Orders do not mix, so the matrix is block diagonal. The first-order block is the rotation itself, its axes in ACN order (y, z, x), and each higher one follows from the one below by Ivanic and Ruedenberg’s recursion (J. Phys. Chem. 1996, with the 1998 correction), which is exact and takes well under a millisecond at seventh order.

matrix(rotation: ndarray) → ndarray[source]

(channels, channels): the field turned by rotation (3, 3).

acoustic_spaces.spatial.rotation.angles_matrix(yaw: float = 0.0, pitch: float = 0.0, roll: float = 0.0) → ndarray[source]

The rotation (3, 3) of yaw, pitch and roll in degrees.

acoustic_spaces.spatial.rotation.matrix_angles(rotation: ndarray) → tuple[float, float, float][source]

Yaw, pitch and roll in degrees of a rotation (3, 3); the inverse of angles_matrix() (yaw and roll are 0 to 180 either way, pitch up to 90).

acoustic_spaces.spatial.rotation.quaternion_matrix(w: float, x: float, y: float, z: float) → ndarray[source]

The rotation (3, 3) of a quaternion, normalised first (identity if it is zero).

Binaural decoding: filters that turn the AmbiX channels of a sound field into the signals at the two ears (binaural_decoder()), or the channels of a loudspeaker layout, each speaker heard as a virtual one (binaural_filters() gives the filters of either format).

The Ambisonics filters fit the HRTF of every measured direction with the spherical harmonics up to the order (least squares, "ls"). Low orders cannot follow the fast changes of the HRTF’s phase with direction at high frequencies, and least squares then loses level and spaciousness; above a cutoff (the order times 600 Hz, after Schörkhuber, Zaunschirm and Höldrich 2018) the magnitude least squares decoder ("magls", the default) fits only the magnitudes and keeps the phase that varies smoothly from the bin below.

acoustic_spaces.spatial.decoder.DECODERS = ('magls', 'ls')

Decoding methods.

acoustic_spaces.spatial.decoder.MAGLS_HZ_PER_ORDER = 600.0

Above this many hertz per order, magls fits magnitudes only.

acoustic_spaces.spatial.decoder.binaural_decoder(order: int, hrtf: HRTF, method: str = 'magls') → ndarray[source]

Filters (taps, (order + 1) ** 2, 2) from the AmbiX channels of order to the left and right ear, at the HRTF’s sample rate. A plane wave encoded from a direction decodes to about that direction’s HRTF.

acoustic_spaces.spatial.decoder.binaural_filters(fmt: Format, hrtf: HRTF, method: str = 'magls') → np.ndarray[source]

Filters (taps, channels, 2) from the channels of fmt to the left and right ear, at the HRTF’s sample rate, so that a signal in fmt is heard as it plays: for Ambisonics, binaural_decoder() of its order; for Loudspeakers, each speaker as a virtual one, the HRTF of its direction (HRTF.interpolate()), and the LFE channel, which the renders leave silent, as nothing.

Rendering and playback

Rendering: impulse responses applied to dry signals (auralisation).

  • convolve(): offline convolution of a recording with an impulse response (FFT overlap-add in float64), for any number of response channels.

  • resample(): band-limited sample-rate conversion, so a 44.1 kHz recording can go through a 48 kHz response.

  • crossfaded(): a crossfade from one sound to another whose power runs on however alike the two are, broadband or band by band: a tour’s cuts from one seat to the next, a walk’s from one place to the next.

  • auralize(): the sources of a simulation each playing their own signal, heard at one listener in a spatial format (mono, binaural, Ambisonics, loudspeakers), summed. Outdoors in turbulence the early paths change as the eddies drift past: a new moment of them every MOMENTS_PER_CORRELATION-th of their correlation time (at most every MOMENT_MIN_S), each path’s delay going from one moment’s to the next’s, so the sound flickers as it does in gusty air.

  • Convolver: the compiled real-time convolver, block by block. It divides the response into partitions that grow along it, from the block size up to 8192 frames, and multiplies in the frequency domain, so the only latency is the block itself; nothing allocates while it runs.

  • play(): a signal, or live input, through a response on the sound card (needs the measure extra: sounddevice); or through any block processor with one input, such as HeadTrackedBinaural.

class acoustic_spaces.render.Convolver(ir: ndarray, block: int = 256)[source]

Real-time convolution through ir, one block of block frames at a time.

ir is (taps,), (taps, outputs) for one input, or (taps, inputs, outputs), where each output sums its inputs, each through its own response. block is a power of two, and the only latency. The response is split into segments whose partitions grow along it (see segments), and the work of the long partitions is spread over the blocks in between, so the cost per block stays even and grows slowly with the response’s length: a 3 s, 16-channel response in blocks of 128 frames takes about 0.3 ms of the 2.7 ms each block lasts at 48 kHz, on one current x86-64 core.

property segments: list[tuple[int, int, int]]

(first tap, partition length, partitions) of each segment of the response.

process(block: ndarray, out: ndarray | None = None) → ndarray[source]

One block, (block,) or (block, inputs), to (block, outputs) float32.

Given out, a writable C-contiguous float32 (block, outputs) array, the block is written into it and nothing new is allocated for it, as a sound card’s callback needs (a float32 C-contiguous block is not copied either).

run(signal: ndarray) → ndarray[source]

A whole signal, (samples,) or (samples, inputs), through the convolver: (samples + taps - 1, outputs), as convolve() gives it.

reset() → None[source]

Forget all past input.

class acoustic_spaces.render.Playback(frames: int, xruns: int, load: float)[source]

How a play() run went.

xruns: int

Blocks the sound card reported an underflow or overflow for.

load: float

Longest time spent convolving one block, as a share of the block’s duration.

acoustic_spaces.render.auralize(result: SimulationResult, signals: Mapping[str, np.ndarray | tuple[np.ndarray, float]], listener: str | None = None, fmt: Format | None = None, *, sample_rate: int | None = None, seed: int | None = None, equal_power: bool = False) → np.ndarray[source]

Every source in signals playing its signal, heard at listener.

signals maps source names to a signal at sample_rate, or to a (signal, rate) pair, resampled when the rates differ; multichannel signals are mixed down, as sources are points. fmt is a format of acoustic_spaces.spatial (default mono, through the listener’s microphone when it has a pattern: for_listener()); listener may be left out when the result has one listener. Returns (samples, channels) at sample_rate (default: the simulation’s), with the sources at the levels the simulation gives them: the responses carry each source’s feed (gain, equalizer, delay) but are per unit of sound power, so each signal is scaled by its source’s sound power (level_db) against the loudest source’s in signals (power_gains()). equal_power leaves that out, as if every source had the loudest one’s power.

acoustic_spaces.render.convolve(signal: ndarray, ir: ndarray) → ndarray[source]

Full linear convolution: len(signal) + len(ir) - 1 samples.

signal and ir are (samples,) or (samples, channels). A mono signal goes through every channel of the response (a dry source through a binaural or Ambisonics response); a multichannel signal goes through a mono response channel by channel. The result is 1-D only when both inputs are.

acoustic_spaces.render.crossfaded(x0: ndarray, x1: ndarray, ramp: ndarray, sample_rate: float | None = None) → ndarray[source]

x0 fading out and x1 fading in, (n,) or (n, channels): x1’s gain is ramp (n, rising from 0 to 1) and x0’s sqrt(1 - ramp²), equal power for two unlike sounds, both scaled, sample by sample, by how alike the two are over the crossfade (their correlation coefficient, one for all channels), so that the power runs from one’s to the other’s as it would for unlike ones. Alike sounds would otherwise be up to 3 dB louder in the middle, sounds in antiphase silent. The scaling is at most +6 dB: where the two cancel to less than half the amplitude unlike sounds would have (near antiphase, in the middle of the crossfade), their sum stays below it. With sample_rate, each octave band (split_bands()) by its own correlation.

acoustic_spaces.render.play(ir: np.ndarray | Convolver | HeadTrackedBinaural, sample_rate: int, signal: np.ndarray | None = None, *, block: int = 256, gain: float = 1.0, device: object = None, seconds: float | None = None, stop: threading.Event | None = None) → Playback[source]

Play signal through ir (samples, outputs) on the sound card, convolving in real time; without a signal, the sound card’s first input goes through it live.

ir may also be a processor that works block by block, as a Convolver or HeadTrackedBinaural does; its own block size then replaces block. Playback ends with the signal’s reverberation tail; live input runs for seconds, until stop is set, or until Ctrl-C. signal must be at sample_rate.

acoustic_spaces.render.power_gains(sources, names) → dict[str, float][source]

Amplitude gain of each source in names for its sound power: 1 for the loudest of them, 10^(-ΔL/20) for one ΔL dB below it. sources are scene sources, or a mapping of name to sound power level (dB re 1 pW); names it lacks get no gain.

acoustic_spaces.render.resample(signal: ndarray, rate_in: float, rate_out: float) → ndarray[source]

signal (samples,) or (samples, channels) at rate_out.

Polyphase windowed-sinc interpolation (Kaiser, 32 zero crossings each side), with the cutoff just below the lower Nyquist frequency so nothing aliases.

Walkthroughs

Walkthroughs: a listener or a source walking through the room, heard as it goes.

A listener or a point source with a walk in the scene goes from its position through the points of walk.to, at walk.speed_m_s, facing the way it goes unless walk.face_forward is false (it then keeps its orientation):

listeners:
  - name: visitor
    position: [2.0, 3.0, 1.6]
    walk: {to: [[12.0, 3.0, 1.6], [12.0, 8.0, 1.6]], speed_m_s: 1.2}

walk_points() places the walker every step_m along its path, and simulate_walk() simulates a response at each place. The early sound changes quickly from place to place, the late field slowly, so the late part, the costliest to trace, is traced only every late_step_m; the places in between mix the late parts of those on either side, in proportion to how near they are. render_walk() then plays signals through them: the response of the place the walker is nearest to, with a crossfade of crossfade_s half-way between two places, so that the sound changes smoothly as it walks. In each octave band the crossfade’s power goes from one place’s to the next’s along a raised cosine, however alike the two sound (crossfaded()): a tone heard in another phase at the next place keeps its level, except near antiphase, where the two cancel in the middle of the crossfade by more than its gain, at most +6 dB, makes up. Each place’s late part is drawn from the same random sequence, so the crossfades join tails that only differ in their decay. The walker stands at the end of its path once it is there, for as long as the signals last.

At walking speed there is no Doppler shift (it is under half a percent, 8 cents). A walk with doppler: true (a car, a train, an aircraft) plays each early path through a delay that changes as the walker goes (acoustic_spaces.doppler), so the pitch of each shifts as it does on its way; the late part is crossfaded by weights that add up to one (crossfade_weights()), which keep the power of tails this alike, a walking source’s as its sound is sent and a walking listener’s as it is heard; and pass_by() gives the level over time, its maximum and the sound exposure level, also as a sound level meter’s slow time weighting reads them. Outdoors in turbulence the early sound flickers along the walk as in auralize(), through the same eddies from place to place.

A walk may instead give keyframes: where the walker is and how it faces at given times after its start, between which it moves and turns evenly, so that it can wait, turn on the spot or go at any pace (knots() gives either kind of walk as the knots it moves between). Several listeners and sources may move at once, each on its own walk, all on one clock: simulate_movement() simulates them together, every mover as a copy at each place it takes, in one simulation; render_movement() plays the signals through it as heard at every listener in use, still or moving; and save_movement() writes one WAV per listener. A walk with Doppler moves alone, there as in a walk of its own: every listener hears each early path through its changing delay. walk.enabled: false keeps a walk but leaves its walker standing still, and with_moving() picks which walks are on for one run, so that one scene serves both still and moving.

Each copy is named for its walker, its place and its time on the walk (place_name(), car #12 @ 3.40 s), and the simulation’s progress messages name it so; a demo’s video names the moment of each walk it shows (moment_name(), car @ 3.40 s): place_of() reads the walker and the time back from both. A head turned as a demo scripts it is named with its yaw (facing_name(), standing facing 90.0 deg), which facing_of() reads back.

acoustic_spaces.walkthrough.CROSSFADE_S = 0.05

Length (s) of the crossfade from one place’s response to the next.

acoustic_spaces.walkthrough.LATE_STEP_M = 2.0

Distance (m) between the places a walk’s late part is traced at.

acoustic_spaces.walkthrough.STEP_DEG = 20.0

Angle (degrees) a walker turns between the places of a walk along keyframes where it turns without moving on (on the spot, or nearly).

acoustic_spaces.walkthrough.STEP_M = 0.25

Distance (m) between the places a walk is simulated at.

class acoustic_spaces.walkthrough.Knots(times: ndarray, positions: ndarray, angles: ndarray)[source]

The knots of a walk: where the walker is and how it faces at each, moving and turning evenly from one to the next (knots()).

times: ndarray

When it is at each knot (s from the start; the first is 0).

positions: ndarray

Where each knot is (K, 3).

angles: ndarray

How it faces at each knot (K, 3: yaw, pitch and roll in degrees), unwrapped so that it turns the shorter way round from one to the next.

property length_m: float

How far the walk goes.

property top_speed: float

The fastest it goes (m/s), over a leg.

at(times) → tuple[ndarray, ndarray][source]

Where it is and how it faces (yaw, pitch and roll in (-180, 180]) at times (s, a number or an array): at its start before, at its end after.

class acoustic_spaces.walkthrough.Movement(room: Room, times: ndarray, result: SimulationResult, copies: dict[tuple[str, str], tuple[str, ...]], late_places: int = 0, doppler: bool = False)[source]

Responses with every mover at each moment of its walk, from simulate_movement().

room: Room

The scene’s room, as it was given (the movers with their walks).

times: ndarray

The moments the responses are at (s from the start, the first 0).

result: SimulationResult

The simulation: the still sources and listeners under their names, each mover as a copy at each place it takes (copies).

copies: dict[tuple[str, str], tuple[str, ...]]

Each mover ((“listeners” or “sources”, name)) and the name of its copy at each moment of times.

late_places: int = 0

How many of the movers’ places have a late part of their own; the others mix theirs.

doppler: bool = False

Whether the mover, then alone, walks with Doppler (walk.doppler): each pair it is part of plays its early paths through delays that change as it goes.

property places: int

How many places the movers were simulated at in all.

key(source: str, listener: str, k: int) → tuple[str, str][source]

The response of source at listener at moment k, in result.

moves(source: str, listener: str) → bool[source]

Whether either of the pair moves.

class acoustic_spaces.walkthrough.PassBy(source: str, listener: str, times: ndarray, levels: ndarray, levels_a: ndarray)[source]

The level at a listener along a walk, from pass_by(): as a source passes it, or as it passes a source.

times: ndarray

(N,) when the sound of each place is heard (s from the start): for a walking source, when it is there plus its direct sound’s delay; for a walking listener, when it is there.

levels: ndarray

(N, 8) the sound pressure level per octave band (dB) at each place, of the source’s sound power, as it would be with the source standing there (-inf in a band no sound reaches).

levels_a: ndarray

(N,) the same, A-weighted (dB(A)).

property duration_s: float

How long the walk is heard for (s), from the first place’s sound to the last’s.

property max_a: float

The highest A-weighted level along the walk (dB(A)), L_Amax.

property max_time: float

When the highest A-weighted level is heard (s from the start).

property exposure: ndarray

(8,) the sound exposure level per octave band (dB): the level that, held for one second, carries the energy of the whole walk.

property exposure_a: float

The A-weighted sound exposure level (dB(A)), SEL or L_AE.

property equivalent_a: float

The A-weighted equivalent level over the walk (dB(A)), L_Aeq,T with T its duration_s.

property slow_a: EventLevels

The pass as a sound level meter reads an aircraft’s for ECAC Doc 29 (event_levels()): the A-weighted level through IEC 61672-1’s slow time weighting (1 s), its mean square going linearly in time from one place’s times to the next; its highest, L_ASmax (max_db), and the sound exposure level over the time it is within 10 dB of that, the “10 dB-down” time (exposure_db, from start_s to end_s).

class acoustic_spaces.walkthrough.WalkPoints(times: ndarray, positions: ndarray, yaws: ndarray | None, angles: ndarray | None = None)[source]

The places a walker is simulated at.

times: ndarray

When it is at each place (s from the start).

positions: ndarray

Where each place is (N, 3).

yaws: ndarray | None

The way it faces at each place (yaw in degrees), or None when it keeps its own.

angles: ndarray | None = None

Along keyframes, how it faces at each place (N, 3: yaw, pitch and roll in degrees).

class acoustic_spaces.walkthrough.WalkResponses(name: str, kind: str, points: WalkPoints, names: tuple[str, ...], result: SimulationResult, late_places: tuple[int, ...] = (), doppler: bool = False)[source]

Responses along a walk, from simulate_walk().

name: str

The walker’s name.

kind: str

"listeners" or "sources": what walks.

points: WalkPoints

The places it was simulated at.

names: tuple[str, ...]

The names the walker has at its places in result, in order ("<name> #<place> @ <time> s").

result: SimulationResult

The simulation, with the walker at every place.

late_places: tuple[int, ...] = ()

The places that have their own late part (indices); the others mix theirs.

doppler: bool = False

Whether the early paths go through delays that change as it goes (walk.doppler).

acoustic_spaces.walkthrough.crossfade_weights(times, t, crossfade_s: float = 0.05) → ndarray[source]

Each place’s weight (N, len(t)) at times t: 1 while the walker is nearest to it, falling to 0 over the crossfade to the next (a raised cosine centred half-way between them). They add up to 1. They are the gains of the late part of a walk with Doppler, and each place’s share of the power in each band of a walk without.

acoustic_spaces.walkthrough.facing_name(name: str, yaw_deg: float) → str[source]

name turned to the yaw yaw_deg (degrees, as a scene’s orientation gives it), as a demo says what it shows while a head turns: standing facing 90.0 deg.

acoustic_spaces.walkthrough.facing_of(label: str) → tuple[str, float] | None[source]

What a name that says which way it faces (facing_name()) names, and the yaw (degrees); None for any other name.

acoustic_spaces.walkthrough.knots(item) → Knots[source]

The knots of item’s walk (a scene listener or source): along to, its corners at speed_m_s and, facing forward, where each turn through a corner starts and ends; along keyframes, its position at 0 s and each keyframe, facing as it says or as before.

acoustic_spaces.walkthrough.late_mixing(distances: ndarray, late_step_m: float) → dict[int, dict[int, float]][source]

The places of a walk (distances along it, m, rising) that take their late part from others, each with the places it mixes and their weights: places are traced every late_step_m or a little less, from the first to the last.

acoustic_spaces.walkthrough.moment_name(name: str, time_s: float) → str[source]

The walker name time_s (s) into its walk, as a demo’s video says what it shows: car @ 3.40 s.

acoustic_spaces.walkthrough.movers(scene) → list[tuple[str, object]][source]

The listeners and sources of scene that move: in use, with a walk that is enabled, as (“listeners” or “sources”, item), listeners first.

acoustic_spaces.walkthrough.pass_by(walk: WalkResponses, source: str | None = None) → PassBy[source]

The level along walk at its listener (a walking source) or of source (a walking listener; by default the only source): each place’s level, of the source’s sound power, at the time it is heard (quasi-static: as with the source standing there), with its maximum, the sound exposure level and the equivalent level. In a band where a place’s G is undefined (no sound arrives in it, or its decay cannot be read), the place’s level is that of the energy its response holds, as outdoors (levels_or_held()).

acoustic_spaces.walkthrough.place_name(name: str, k: int, time_s: float) → str[source]

The name of the copy of the walker name at its k-th place, time_s (s) into its walk: car #12 @ 3.40 s. Numbered, as places less than 10 ms apart would share a time.

acoustic_spaces.walkthrough.place_of(label: str) → tuple[str, float] | None[source]

The walker and the time (s) of a place’s name (place_name()) or a moment’s (moment_name()); None for any other name.

acoustic_spaces.walkthrough.render_movement(movement: Movement, signals: Mapping[str, ndarray | tuple[ndarray, float] | Emission], fmt=None, *, crossfade_s: float = 0.05, sample_rate: int | None = None, seed: int | None = None, equal_power: bool = False) → dict[str, ndarray][source]

signals (source names to a signal at sample_rate, or a (signal, rate) pair) played through the movement, as heard at every listener in use: each as (samples, channels) in format fmt (default mono; mono through each listener’s microphone when it has a pattern) at sample_rate (default: the simulation’s), all of one length and, as in render_walk(), each signal scaled by its source’s sound power against the loudest one’s unless equal_power. A pair that moves crossfades from each moment’s response to the next’s, as a walk does, or with Doppler (Movement.doppler) plays each early path through its changing delay and crossfades the late part, as render_walk() does; a still pair plays through its one response. A source that moves with Doppler, or that a listener passes with it, may send an Emission at sample_rate, the sound it sends each way, as render_walk() plays it.

acoustic_spaces.walkthrough.render_walk(walk: WalkResponses, signals: Mapping[str, ndarray | tuple[ndarray, float] | Emission], fmt=None, *, crossfade_s: float = 0.05, sample_rate: int | None = None, seed: int | None = None, equal_power: bool = False, followers: Sequence[tuple[float, ndarray | tuple[ndarray, float]]] = ()) → ndarray[source]

signals (source names to a signal at sample_rate, or a (signal, rate) pair) played along the walk, as (samples, channels) in format fmt (default mono; mono through the listener’s microphone when it has a pattern) at sample_rate (default: the simulation’s). As in auralize(), each signal is scaled by its source’s sound power against the loudest one’s, unless equal_power. Along a walk with Doppler, the source that walks (or every source, for a walking listener) may send an Emission at sample_rate, the sound it sends each way: each early path carries what is sent the way it leaves the source, and the late part the emission’s sound averaged over the directions.

followers are more sounds of a walking source with Doppler, each (lag_s, signal) going along its walk lag_s seconds after it, as the wheels and the cars of a train follow its front: each is heard as the walker’s own signal would be, lag_s later, and scaled as it is. The result is long enough for the last follower’s.

acoustic_spaces.walkthrough.save_movement(rendered: Mapping[str, ndarray], out: str | Path, rate: int, fmt=None, *, normalize: bool = False) → tuple[dict[str, Path], float][source]

Write what render_movement() gave: out itself for one listener, else <out stem>_<listener>.wav beside it for each (with -2, -3… where two listeners’ names would give the same file); normalize brings the loudest peak of them all to -1 dBFS, one gain for all, so that the balance between the listeners holds. Gives each listener’s file and the gain applied.

acoustic_spaces.walkthrough.simulate_movement(room: Room, *, step_m: float = 0.25, step_deg: float = 20.0, late_step_m: float | None = 2.0, settings: Simulation | None = None, threads: int | None = None, progress: Callable[[str], None] | None = None) → Movement[source]

Simulate the scene with every mover (movers()) on one clock, in one simulation: the moments are every mover’s places (every step_m along its walk, every step_deg of a turn on the spot, and its knots), and at each moment each mover stands as a copy where its walk has it then, a copy serving every moment it stands still at (once its walk is over, say). Every listener in use hears every source in use, still or moving. The late part is traced every late_step_m along each mover’s walk, and barriers and buildings have the paths over their edges, as in simulate_walk().

Every mover goes slower than sound. A walk with Doppler moves alone: with another mover it is refused. It goes without the wave solver, as in simulate_walk().

acoustic_spaces.walkthrough.simulate_walk(room: Room, name: str | None = None, *, listener: str | None = None, step_m: float = 0.25, late_step_m: float | None = 2.0, settings: Simulation | None = None, threads: int | None = None, progress: Callable[[str], None] | None = None) → WalkResponses[source]

Simulate the responses along a walk: name walks (by default the only listener or source with a walk), placed every step_m.

A walking listener hears every source in use; a walking source is heard at listener, even one left out (enabled: false), by default the only listener in use, with the other sources in use standing still. The walk must go slower than sound.

The late part is traced every late_step_m (see the module’s description), or at every place with late_step_m=None or the statistical late method. settings (default: the scene’s) and threads (default: their performance.threads) go to simulate(), with the paths over the edges of barriers and buildings in place of the solver for whole rows (_over_the_edges()).

acoustic_spaces.walkthrough.walk_points(item, step_m: float = 0.25, step_deg: float = 20.0) → WalkPoints[source]

The places along item’s walk (a scene listener or source), step_m or a little less apart, from its position to the walk’s last point; along keyframes also every step_deg of a turn on the spot.

acoustic_spaces.walkthrough.with_moving(scene, names: Iterable[str] | None)[source]

scene with only names moving: their walks turned on and every other walk off, so that its walker stands where it starts. None keeps the scene’s own. Each name must be a source or listener in use with a walk.

The Doppler shift of a walk: each early path through a delay that changes as the walker goes.

A source moving towards a listener shortens the way its sound has to go while it is on it, so the listener hears its pitch raised by 1 / (1 - M cos theta), M its speed over the speed of sound and theta the angle between the way it goes and the way to the listener; going away, lowered. A listener moving past a source hears the same. Each early path has its own shift (the sound reflected off a wall behind a car falls in pitch while the direct sound still rises), so render() follows every path from place to place along the walk:

  • The paths. A path at one place is the same path at the next when it meets the same planes (the ground, a facade) in the same order over the same edge, failing that when it is of the same kind, and its delay carries on from it: it changes by no more than one and a half times the walker’s longest step over the speed of sound, and is nearest where the path’s last two places lead. Paths that meet the same planes over the same edge are paired so that the most go on, and of those pairings the one with the delays nearest where they lead. Where a path appears or goes, it fades in or out between two places.

  • The delay. Each path’s delay is known at every place: for a walking source, the time its sound takes from there, heard that much later (the retarded time); for a walking listener, at the moment it is there. Between the places a cubic through them gives the delay at every sample, and the signal is read through it with a windowed sinc (Kaiser, 32 zero crossings each side) whose cutoff falls with the shift, so a raised pitch does not alias: 0.97 of the Nyquist frequency over the most the path raises the pitch (as a ratio), rounded down to 32 / n of the Nyquist frequency, n the taps it then needs on each side, so that the paths share a few tables of taps.

  • The spreading. The direct sound’s level, and a reflection’s, falls as one over the path’s length, which is its delay times the speed of sound, and a fast walker close by changes that length by much of itself within one window of the filter. So each sample read is divided by the path’s delay at that sample (the cubic’s, held past the path’s own ends, before the eddies move it and without an ear’s onset; no less than that of MIN_SOURCE_DISTANCE_M, the nearest a listener may stand to a source), and the level follows the distance from sample to sample, as the pitch does.

  • The filter. What else the path does to the sound (the air, the ground’s reflection, a diffracting edge, the source’s directivity, the direction it arrives from in the output format, and in turbulence how the eddies delay its other bands from its top one at that moment) goes into a filter: the path’s spectrum as the impulse response has it, without its delay and times its delay at the place, which the division by the delay takes back there (a path bent over an edge spreads otherwise: what of that is not one over its length stays in the filter). The filter is known at the places, and between two of them it is theirs in proportion to how near they are. It is taken every HOP_S and, between those times, at the time each place’s sound is heard; the delayed signal goes through it in windows that overlap, each rising from the time before its own and falling to the time after (triangles, which add up to one), so the filter goes linearly from each place to the next however fast the walker passes them, and a path heard from one place alone gives exactly the convolution with its response.

  • The ears. Where each ear’s response starts (its onset, as the ears are mixed between measured directions: interpolate()) is a delay too: it goes into that ear’s delay, read through the cubic and the sinc as the path’s is, and out of its filter. Measured ears can start a few samples apart from one direction to the next; filters that start apart, mixed between two places or in the overlapping windows, would cancel the treble there. A walking listener’s ear is, at each moment, that much further along the path than the head’s centre: the onset adds to the path’s delay then. A walking source’s sound passes the head’s centre and reaches the ear an onset later, so at each sample the ear hears what passed the centre an onset earlier: the path’s delay, its spreading and how far its filter is between two places are all taken at that earlier time. And while the onset grows, what passed the centre in one sample takes more than one to reach the ear (less while it shrinks), so the sound is divided by one plus the onset’s slope: the ear’s Doppler factor over the centre’s, which the two ears do not share (the centre’s own, the convective amplification, is left out: see below). The ears then hear what a standing head makes of the pressure at its centre: each moment of it through the ears’ responses to the direction it arrives from. Added to the delay instead, the onset would be a time of the sound sent, not of the sound heard, and the time between the two ears would shrink as the pitch rises and grow as it falls (by up to a fifth at 70 m/s, straight ahead and behind).

  • The eddies. In turbulence the eddies move each path’s delay from one moment to the next (by microseconds, as Gusts draws them): the top band’s goes into the path’s delay, taken between the places and the moments on either side as the filter is, so that two moments’ filters mixed do not cancel the treble either.

  • The sound sent. Every path carries the same signal, unless it is an Emission, the sound a source sends each way: then each path carries what is sent the way it leaves the source (its first leg, in the source’s frame at each place, in between turning from one place’s to the next’s) at the time it leaves, and the source’s directivity is taken out of its filter.

The late part and the wave solver’s bands have no Doppler shift here: the late part of each place is crossfaded to the next’s by weights that add up to one, which keep its power as the places’ tails, drawn from one random sequence, are alike (a walking source’s sound as it is sent, so that each place’s late part follows its early paths at the retarded time; a walking listener’s as it is heard); and the wave solver’s bands are not taken (a walk with Doppler and the wave solver stops with an error). The source radiates as it would standing at each place, as road and rail emission data have it: the convective amplification of a moving source is left out, and emission measured in a pass-by already carries it, as an emission may. Its size depends on the kind of source. For a point monopole (a source of volume flow q) in steady motion the far-field pressure is rho q’ / (4 pi R (1 - M cos theta)^2), R and theta as the sound left: two powers of the Doppler factor, 40 lg(1 / (1 - M cos theta)) dB in level, which is 1.6 dB more straight ahead at 30 m/s and 4.0 dB at 70 m/s, 1.5 and 3.2 dB less straight behind.

acoustic_spaces.doppler.HOP_S = 0.02

How often each path’s filter is taken at least (s): the hop of the blocks, between whose centres it is also taken at each place’s time (_turns()).

acoustic_spaces.doppler.KERNEL_S = 0.3

Length of a path’s filter (s), as the binaural early paths have it.

class acoustic_spaces.doppler.Track(present: ndarray, rows: ndarray, received: ndarray, delays: ndarray)[source]

One path followed along a walk.

present: ndarray

(N,) whether the path is heard from each place.

rows: ndarray

(N,) its row among the paths of each place (-1 where it is not heard).

received: ndarray

(N,) when the sound of each place along it is heard (s from the start).

delays: ndarray

(N,) its delay at each place (s); where it is not heard, carried on from where it is.

property span: tuple[int, int]

The first and last place it is heard from.

acoustic_spaces.doppler.hermite(x: ndarray, y: ndarray, at: ndarray, *, hold: bool = True) → ndarray[source]

The cubic Hermite curve through (x, y) (x rising) at at, its slope at each point the weighted mean of the chords on either side; held at the ends’ values beyond them (or carried on along the end slopes when hold is false).

acoustic_spaces.doppler.plane_ids(mesh) → ndarray[source]

(F,) the plane each face of mesh lies in, numbered: faces in one plane (the triangles of a ground or a wall) share it.

acoustic_spaces.doppler.read(dry: ndarray, positions: ndarray, cutoff: float) → ndarray[source]

dry (n,) read at the fractional sample positions through a windowed sinc cut off at cutoff (a share of Nyquist, below one where the reading runs faster than the samples, so nothing aliases); zero before and after it.

acoustic_spaces.doppler.render(dry: ndarray | Emission, responses: list, times: ndarray, fmt, sample_rate: int, length: int, *, source_walks: bool, planes: ndarray, step_s: float, gusts=None, seed: int | None = None, axes: ndarray | None = None, directivity=None, span: tuple[int, int] | None = None, followers: Sequence[tuple[int, ndarray]] = ()) → ndarray[source]

(length, channels) the early paths of responses (the responses at the places of a walk, in order, the walker there at times) heard as it goes, the mono dry signal through each path’s changing delay and filter (see the module’s description). step_s is the most a path’s delay may jump from one place to the next; gusts gives the moments of the eddies in turbulence, seed the moment of each place’s eddies without them. dry may be the sound the source sends each way, at sample_rate: then axes (N, 3, 3) has the source’s forward, left and up axes as columns at each place, and directivity (the source’s, if it has one) is taken out of the paths’ filters. With span (begin, end), samples begin to end alone: (end - begin, channels).

followers are more mono signals going along the walk after the walker, each (lag, signal) lag samples behind it, as the wheels and the cars of a train follow its front: each goes through the same paths, places and filters, all of it lag samples later (length counts them). They share what the paths cost to follow and filter, so each costs less than a rendering of its own.

acoustic_spaces.doppler.tracks(places: list, times: ndarray, *, source_walks: bool, planes: ndarray, step_s: float) → list[Track][source]

The paths of places (the early paths at each place of a walk, in order), followed from place to place. times (N,) are when the walker is at each place; with source_walks its sound is heard a path’s delay later, otherwise then. step_s is the most a delay may jump between places and stay the same path’s.

The sound a source sends each way, for a walk with Doppler.

A source’s directivity (acoustic_spaces.directivity) weighs each path’s energy per octave band, and every path carries the same signal. The sound of a rotor changes with the direction in more than its band levels: each harmonic of the blades has a pattern and a phase of its own, and the broadband noise has another. An Emission gives the signal itself in every direction, in the source’s own frame (x forward, y left, z up, as acoustic_spaces.scene.Orientation turns it), and a walk with Doppler (acoustic_spaces.doppler.render()) plays down each early path the sound sent the way the path leaves the source, at the time it leaves.

What the early paths carry then comes from the emission alone: each path’s share of the source’s directivity is taken out of its filter. The directivity still gives the levels the simulation reports and the late part, which plays the emission’s sound averaged over the directions (Emission.averaged()). For the two to agree, give the source the emission’s own directivity (Emission.directivity(), written for a scene by acoustic_spaces.directivity.write_directivity_csv()) and, for an emission in pascals 1 m away, its sound power (Emission.sound_power_db()).

  • Mixture is made of signals that do not correlate with one another (harmonics, as a cosine and a sine each, and noises in separate bands), each with an amplitude in every direction on the grid of acoustic_spaces.directivity.on_grid().

  • Periodic is a sound that repeats, such as a rotor’s tones: one period of it in every direction, which keeps a long walk’s emission small.

  • Sum sends several emissions at once, such as a helicopter’s two rotors.

  • Faded fades one in and out, so that it does not start or stop at once.

class acoustic_spaces.emission.Emission[source]

The signal a source sends each way (see the module’s description).

sample_rate: int

Samples per second.

property length: int

How many samples it sends.

sent(start: int, stop: int, directions: ndarray) → ndarray[source]

(stop - start,) the samples start to stop of the sound sent the ways directions ((stop - start, 3) unit vectors in the source’s frame, one for each sample); nothing before 0 or from length on.

averaged() → ndarray[source]

(length,) a signal with the emission’s power spectrum averaged over the sphere: what the late part carries.

scaled(gain: float) → Emission[source]

This emission gain times as loud in amplitude.

directivity(bands: Literal['octave', 'third_octave'] = 'octave', name: str = '') → Balloon[source]

The emission’s directivity: its energy in each band and direction, on the grid GRID_STEP_DEG apart that measured balloons use, over the sphere’s mean. The bands are IEC 61260-1’s, between their base-10 edges (exact_limits()), as in sound_power_db().

sound_power_db(density: float, sound_speed: float, bands: Literal['octave', 'third_octave'] = 'octave') → ndarray[source]

The sound power level (dB re 1 pW) in each band of an emission that sends the far field’s pressure 1 m from the source (Pa): its mean square over the sphere times 4π m² over the air’s impedance, density times sound_speed.

The bands are IEC 61260-1’s octaves or third octaves, as ideal filters between their base-10 edges (exact_limits()): the 63 Hz octave holds what is sent from 44.7 to 89.1 Hz and the 8 kHz octave what is sent from 5.6 to 11.2 kHz. What is sent below the lowest band’s lower edge (such as a rotor’s blade passing at 20 Hz) or above the highest’s upper edge is in no band.

class acoustic_spaces.emission.Faded(part: Emission, fade: int = 0, length_samples: int = 0)[source]

An emission’s first length samples, faded in over the first fade and out over the last, by a squared sine, so that it does not start or stop at once. Its bands and its directivity are the emission’s own.

length_samples: int = 0

How many samples of it are sent.

property sample_rate: int
property length: int

How many samples it sends.

sent(start: int, stop: int, directions: ndarray) → ndarray[source]

(stop - start,) the samples start to stop of the sound sent the ways directions ((stop - start, 3) unit vectors in the source’s frame, one for each sample); nothing before 0 or from length on.

averaged() → ndarray[source]

(length,) a signal with the emission’s power spectrum averaged over the sphere: what the late part carries.

scaled(gain: float) → Faded[source]

This emission gain times as loud in amplitude.

class acoustic_spaces.emission.Mixture(signals: ndarray, weights: ndarray, sample_rate: int = 48000)[source]

Signals that do not correlate with one another, each sent with an amplitude of its own in every direction.

signals: ndarray

(K, samples) the signals.

weights: ndarray

(elevations, azimuths, K) each signal’s amplitude on the grid of on_grid() (elevations from -90 to 90 degrees, azimuths from 0 up to 360, each evenly spaced).

sample_rate: int = 48000

Samples per second.

property length: int

How many samples it sends.

sent(start: int, stop: int, directions: ndarray) → ndarray[source]

(stop - start,) the samples start to stop of the sound sent the ways directions ((stop - start, 3) unit vectors in the source’s frame, one for each sample); nothing before 0 or from length on.

averaged() → ndarray[source]

(length,) a signal with the emission’s power spectrum averaged over the sphere: what the late part carries.

scaled(gain: float) → Mixture[source]

This emission gain times as loud in amplitude.

class acoustic_spaces.emission.Periodic(table: ndarray, period_s: float = 1.0, sample_rate: int = 48000, samples: int = 0, axes: ndarray = <factory>, turn_s: float = 0.0, centre: ndarray = <factory>, speed: float = 0.0, sound_speed: float = 343.0)[source]

A sound that repeats, sent each way: one period of it in every direction of a grid like that of on_grid(), in a frame of its own (axes), read between its samples by a cubic through four of them and between the directions bilinearly.

The sound of a rotor turns with its blades. In hover, heard from an azimuth phi round the axis it is the sound heard from azimuth 0 a share phi / 2 pi of a turn before, and its phase turns that fast between the grid’s directions. The table holds each direction’s sound from that share of a turn (turn_s) later, which makes the directions differ only as slowly as the rotor’s pattern, and sent() puts the delay back. It also takes into account where the sound comes from (centre): from there, the sound sent in a direction d leaves d . centre / (c - v d_x) later than it would from the source’s place, for a source moving at v along its x through still air (speed, sound_speed), and the table holds it as sent from the centre.

table: ndarray

(elevations, azimuths, N) one period in each direction of the grid, in the frame axes, N samples evenly spread over it; each direction’s shifted as above.

period_s: float = 1.0

How long a period lasts (s).

sample_rate: int = 48000

Samples per second.

samples: int = 0

How many samples it sends.

axes: ndarray

(3, 3) the table’s frame: its x, y and z as rows, in the source’s frame.

turn_s: float = 0.0

How long one turn takes (s), a whole number of periods: positive for a turn from the table’s x towards its y, negative the other way, 0 for a sound that does not turn.

centre: ndarray

(3,) where the sound comes from, in the source’s frame (m).

speed: float = 0.0

How fast the source moves along its x through the air (m/s).

sound_speed: float = 343.0

The speed of sound (m/s).

property length: int

How many samples it sends.

sent(start: int, stop: int, directions: ndarray) → ndarray[source]

(stop - start,) the samples start to stop of the sound sent the ways directions ((stop - start, 3) unit vectors in the source’s frame, one for each sample); nothing before 0 or from length on.

averaged() → ndarray[source]

(length,) a signal with the emission’s power spectrum averaged over the sphere: what the late part carries.

scaled(gain: float) → Periodic[source]

This emission gain times as loud in amplitude.

class acoustic_spaces.emission.Sum(parts: tuple[Emission, ...] = ())[source]

Emissions sent at once from the same source, such as a helicopter’s rotors and their broadband noise: what they send adds up. Each part’s sound is taken as not correlating with the others’ when they are averaged and put in bands.

parts: tuple[Emission, ...] = ()

The emissions, all at one sample rate.

property sample_rate: int
property length: int

How many samples it sends.

sent(start: int, stop: int, directions: ndarray) → ndarray[source]

(stop - start,) the samples start to stop of the sound sent the ways directions ((stop - start, 3) unit vectors in the source’s frame, one for each sample); nothing before 0 or from length on.

averaged() → ndarray[source]

(length,) a signal with the emission’s power spectrum averaged over the sphere: what the late part carries.

scaled(gain: float) → Sum[source]

This emission gain times as loud in amplitude.

Helicopters: the sound their rotors send each way, for a walk with Doppler.

A Helicopter is its mass, its fuselage’s drag and two rotors (Rotor). Flying level at an airspeed, trim() balances it the way momentum theory does (Leishman, Principles of Helicopter Aerodynamics, 2nd ed., chapters 2 and 5): the main rotor’s thrust holds the weight up and the fuselage’s drag back, its disc tilting forward by the angle between them; Glauert’s inflow gives the induced velocity through the disc; the shaft power is the induced power (times induced), the blades’ profile power (Leishman’s 1 + 4.65 mu^2) and the parasite power of the drag; and the tail rotor’s thrust balances the main rotor’s torque. emission() then gives the sound the two rotors send, as an Emission from the main rotor’s hub, in the helicopter’s frame: x along its flight, y to its left, z up.

The tones. Each blade is a row of stations at Gauss points (split at 97 % of the radius, where the lift ends), each with a steady lift and drag (the lift growing with the radius, as a uniform inflow through an ideally twisted blade gives it, up to 97 % of the radius; the drag an induced part, even along the blade, and a profile part growing with the square of the radius, sized to the trimmed torque) and a NACA four-digit section’s thickness. Their far field is that of the Ffowcs Williams and Hawkings equation (Farassat’s formulation 1A) for a rotor moving through still air: the loading compact, the thickness a row of sources and sinks at Gauss points along each straight chord, each where it truly is (its radius a little more than the station’s, taken to second order). With loads that do not change round the turn, each harmonic of the blade passing frequency comes in closed form, from Bessel functions, in every direction; its convective amplification is in it, and the walk adds the Doppler shift. They are kept as one period of the sound in each direction (Periodic).

The broadband noise, by the helicopter’s broadband model:

  • "pegg" (the default): Pegg’s semi-empirical method (NASA TM-80200, 1979, equations 7 and 8), a fit to measured rotors’ broadband noise: the third-octave band levels 20 log (V_T / c)^3 + 10 log (A_b / r^2) (cos^2 theta + 0.1) + S + f(C_L) + 130 round a peak at -240 log T + 2.448 V_T + 942 Hz, with the spectrum’s shape S of its figure 9, for each rotor (theta from the thrust’s axis) (pegg_broadband()). It is a level for hovering; in flight it is sent with the convective amplification of a moving dipole, as the tones are. Its bands run from 1/32 to 128 times the peak, the range of the figure.

  • "bpm": each blade’s own noise in the flow past it, Brooks, Pope and Marcolini’s airfoil self-noise (acoustic_spaces.airfoil_noise), summed over 24 sections from the blade’s root to its tip at 144 places round the turn (bpm_bands()). The blades’ pitch is trimmed (pitch()): rigid blades whose sections’ lift is linear in their angle of attack (lift_slope), twisted by twist_deg, in the trim’s inflow, even over the disc, carry its thrust and do not flap. Each section’s speed and angle of attack follow round the turn; its levels hold the convective amplification of its own motion through the air, its bands are shifted by its Doppler shift over the hub’s (the walk adds the hub’s), and each place round the turn counts as long as its sound takes to arrive. The boundary layers turn turbulent by themselves unless tripped, the tips are square unless rounded_tip, the trailing edges trailing_edge_m thick; sections whose flow reverses or whose angle of attack is beyond BPM_ALPHA_DEG are left out, and so is the bluntness noise of sections faster than BLUNT_MACH. It is the blades’ noise in a smooth flow only: the noise of the blades cutting through the wake of those before (blade-wake interaction) and through turbulence is not in it.

What it leaves out. For the tones, loads that change round the turn (in forward flight a blade’s lift changes as it goes round, and the blades flap; BPM’s sections follow their angle of attack round the turn, but do not flap), the blades meeting the tip vortices of those before (blade-vortex interaction), noise from the engine and the gearbox, the fuselage’s reflection and shielding, and wind: the air is still, and the airspeed is the speed over the ground.

acoustic_spaces.rotorcraft.AS350_B3 = Helicopter(mass_kg=2250.0, main=Rotor(blades=3, radius_m=5.345, chord_m=0.35, rpm=394.0, hub_m=(0.0, 0.0, 0.0), thrust=(0.0, 0.0, 1.0), turning='clockwise', root=0.2, thickness=0.09, profile_drag=0.01, twist_deg=-10.0, lift_slope=5.73, trailing_edge_m=0.0005, trailing_edge_deg=14.0, tripped=False, rounded_tip=False), tail=Rotor(blades=2, radius_m=0.93, chord_m=0.185, rpm=2086.0, hub_m=(-6.665, 0.0, -1.0), thrust=(0.0, 1.0, 0.0), turning='counter-clockwise', root=0.2, thickness=0.12, profile_drag=0.01, twist_deg=0.0, lift_slope=5.73, trailing_edge_m=0.0005, trailing_edge_deg=14.0, tripped=False, rounded_tip=False), drag_area_m2=0.674, induced=1.15, name='AS350 B3', broadband='pegg')

An Airbus Helicopters AS350 B3 (Ecureuil, sold as the H125) with the Arriel 2B engine at its maximum mass of 2,250 kg. From its type certificate (EASA.R.008): the mass, the rotors’ diameters (10.69 m and 1.86 m) and blades (three and two), and the main rotor turning between 385 and 394 turns a minute in powered flight (375 and 405 with the Arriel 2B1 or 2D). From NASA’s flight tests of an AS350 SD1 (Greenwood, Sim and Boyd, AHS Forum 72, 2016; Watts et al., NASA TM-2016-219354, table 1): the drag area (f = 7.26 ft², 0.674 m², which they give as f / A = 0.0071, a ratio that fits a larger disc than this one), the main rotor’s speed (394 turns a minute, the Arriel 2B’s most in powered flight; its tip at 220.6 m/s from their weight coefficient), the tail rotor’s speed (2,086 turns a minute, its tip at 203 m/s) and the main rotor’s OA209 blades (9 % thick). Assumed, from no source to hand: the main blades’ chord (0.35 m) and twist (-10 degrees), the tail rotor’s chord (0.185 m), thickness (12 %), untwisted blades and the way it turns, both rotors’ trailing edges (a rotor’s default), and its hub 6.67 m behind the main rotor’s shaft (from Airbus’s 12.94 m overall with the rotors turning, less both rotors’ radii) and 1 m lower. The main rotor turns clockwise seen from above.

acoustic_spaces.rotorcraft.BLUNT_MACH = 0.45

Brooks, Pope and Marcolini’s bluntness noise is left out of blade sections faster than this Mach number, as their appendix C recommends for rotors.

acoustic_spaces.rotorcraft.BPM_ALPHA_DEG = 25.0

Their fits hold for angles of attack up to this (degrees); sections beyond it, in the slow flow next to where it reverses, are left out.

acoustic_spaces.rotorcraft.BPM_SOURCE_BANDS = (7, 46)

The bands (10^(k/10) Hz) BPM’s levels are found in, in a blade section’s frame, and those the noise is sent in from the hub, after each section’s Doppler shift.

acoustic_spaces.rotorcraft.BROADBAND_MODELS = ('bpm', 'pegg')

The ways a helicopter’s broadband noise can be found (Helicopter.broadband).

acoustic_spaces.rotorcraft.GRAVITY = 9.80665

Standard gravity (m/s²).

acoustic_spaces.rotorcraft.PEGG_SPECTRUM_DB = (-29.0, -24.5, -19.5, -15.3, -11.7, -7.5, -11.5, -12.1, -16.5, -17.0, -21.8, -26.4, -30.0)

Pegg’s figure 9: third-octave band levels (dB, over the overall level) at 1/32, 1/16, …, 64 and 128 times the peak frequency, one octave apart.

acoustic_spaces.rotorcraft.QUIET_DB = 90.0

A rotor’s tones keep the harmonics of the blade passing frequency up to the last one within this many dB of the loudest harmonic in any direction.

acoustic_spaces.rotorcraft.TIP_LOSS = 0.97

The share of the radius out to which a blade carries lift (Leishman’s tip loss).

class acoustic_spaces.rotorcraft.Helicopter(mass_kg: float, main: Rotor, tail: Rotor, drag_area_m2: float, induced: float = 1.15, name: str = '', broadband: str = 'pegg')[source]

A single main rotor helicopter with a tail rotor.

drag_area_m2: float

The fuselage’s drag as the area of a flat plate (m²): D = rho V^2 f / 2.

induced: float = 1.15

The induced power over that of momentum theory (Leishman’s kappa).

broadband: str = 'pegg'

How its rotors’ broadband noise is found: “pegg” (Pegg’s semi-empirical method for the whole rotor) or “bpm” (Brooks, Pope and Marcolini’s airfoil self-noise of each blade section round the turn).

property tail_arm_m: float

How far the tail rotor’s thrust acts from the main rotor’s shaft (m).

class acoustic_spaces.rotorcraft.Load(thrust_n: float, axis: ndarray, induced_m_s: float = 0.0, induced_torque_nm: float = 0.0, profile_torque_nm: float = 0.0)[source]

What a rotor carries in a trim.

thrust_n: float

Its thrust (N).

axis: ndarray

(3,) the way the thrust points, in the helicopter’s frame.

induced_m_s: float = 0.0

The induced velocity through the disc (m/s).

induced_torque_nm: float = 0.0

The torque (N m) of its induced and parasite power, and of its blades’ profile drag.

class acoustic_spaces.rotorcraft.Rotor(blades: int, radius_m: float, chord_m: float, rpm: float, hub_m: tuple[float, float, float] = (0.0, 0.0, 0.0), thrust: tuple[float, float, float] = (0.0, 0.0, 1.0), turning: str = 'counter-clockwise', root: float = 0.2, thickness: float = 0.12, profile_drag: float = 0.01, twist_deg: float = 0.0, lift_slope: float = 5.73, trailing_edge_m: float = 0.0005, trailing_edge_deg: float = 14.0, tripped: bool = False, rounded_tip: bool = False)[source]

A rotor: its blades, its speed and where it sits on the helicopter.

chord_m: float

Each blade’s chord (m), the same along it.

rpm: float

Turns a minute.

hub_m: tuple[float, float, float] = (0.0, 0.0, 0.0)

Where its hub is (m), in the helicopter’s frame (x along its flight, y to its left, z up), from the helicopter’s place: the main rotor’s hub is best at the origin, where the sound is sent from.

thrust: tuple[float, float, float] = (0.0, 0.0, 1.0)

The way its thrust pushes the helicopter, before the trim tilts it: up for a main rotor, sideways for a tail rotor.

turning: str = 'counter-clockwise'

How its blades turn, seen from the side its thrust points to: “counter-clockwise” or “clockwise”.

root: float = 0.2

The share of the radius where the blades begin.

thickness: float = 0.12

The blades’ thickness over their chord (a NACA four-digit symmetric section).

profile_drag: float = 0.01

The blade sections’ mean profile drag coefficient.

twist_deg: float = 0.0

How much the blades’ pitch changes from the hub to the tip (degrees, linearly; negative, the tip pitched down), for the blade sections’ angles of attack.

lift_slope: float = 5.73

The sections’ lift curve slope (per radian).

trailing_edge_m: float = 0.0005

The trailing edge’s thickness (m; 0 for a sharp edge, which sends none) and the angle its surfaces meet at (0 to 14 degrees), for Brooks, Pope and Marcolini’s bluntness noise.

tripped: bool = False

Whether the blades’ boundary layers are tripped (else they go turbulent by themselves), and whether their tips are rounded (else square).

property omega: float

How fast it turns (rad/s).

property tip_speed: float

The blade tips’ speed round the hub (m/s).

property blade_area_m2: float

All its blades’ area, as Pegg’s A_b and the solidity count it.

property spin: int

+1 for a turn counter-clockwise seen from where the thrust points, -1 the other way.

class acoustic_spaces.rotorcraft.Trim(helicopter: Helicopter, airspeed_m_s: float, temperature_c: float, pressure_kpa: float, main: Load, tail: Load)[source]

A helicopter balanced in level flight.

airspeed_m_s: float

Its speed through the air (m/s).

property power_w: float

The power both rotors take (W).

lift_coefficient(which: str) → float[source]

A rotor’s mean lift coefficient, 6 C_T / sigma: “main” or “tail”.

acoustic_spaces.rotorcraft.bpm_bands(trim: Trim, which: str, ways: ndarray, *, segments: int = 24, azimuths: int = 144) → tuple[ndarray, ndarray][source]

A rotor’s broadband noise in a trim by Brooks, Pope and Marcolini’s airfoil self-noise (acoustic_spaces.airfoil_noise), sent towards ways (…, 3) in the helicopter’s frame: the third-octave bands’ centres (Hz) and their mean square pressures 1 m from the hub (Pa², (..., bands)), averaged over a turn.

Each blade is segments sections from its root to its tip, each at azimuths places round the turn, with the flow past it and its angle of attack from the trim’s pitch (pitch()). A section’s levels hold the convective amplification of its motion through the air; its bands are shifted by its own Doppler shift over the hub’s (the walk adds the hub’s), and each place round the turn counts as long as its sound takes to arrive. The bluntness noise is left out of sections faster than BLUNT_MACH and sections beyond BPM_ALPHA_DEG, or where the flow reverses, are left out; the tip’s vortex is the outermost section’s.

acoustic_spaces.rotorcraft.bpm_powers(trim: Trim, *, grid_deg: float = 5.0, rotors: tuple[str, ...] = ('main', 'tail')) → tuple[ndarray, ndarray][source]

The rotors’ broadband noise in a trim by bpm_bands() on a grid grid_deg apart in the helicopter’s frame: the third-octave bands’ centres (Hz) and the rotors’ mean square pressures 1 m from the hub, summed, (elevations, azimuths, bands). They do not depend on how long the noise lasts: broadband() takes them as bands to send another length without summing the blades again.

acoustic_spaces.rotorcraft.broadband(trim: Trim, *, samples: int, sample_rate: int = 48000, grid_deg: float = 5.0, seed: int = 0, rotors: tuple[str, ...] = ('main', 'tail'), model: str | None = None, bands: tuple[ndarray, ndarray] | None = None) → Mixture[source]

The rotors’ broadband noise in a trim, samples of it, its pattern on a grid grid_deg apart in the helicopter’s frame, by the helicopter’s broadband model or model: “bpm” (bpm_bands(), a noise in each third-octave band with its level in every direction) or “pegg” (pegg_broadband()). For “bpm”, bands are the bands’ centres and powers that bpm_powers() gives for this trim, grid and rotors, if already found (their shape is checked, not their trim or rotors); by default they are found here.

acoustic_spaces.rotorcraft.emission(trim: Trim, *, seconds: float, sample_rate: int = 48000, grid_deg: float = 5.0, seed: int = 0) → Sum[source]

All the helicopter sends in a trim for seconds: both rotors’ tones and their broadband noise, from the main rotor’s hub.

acoustic_spaces.rotorcraft.pegg_bands(peak_hz: float) → tuple[ndarray, ndarray][source]

The third-octave bands of Pegg’s spectrum round a peak: their centres (Hz, base-10 exact) and their levels S (dB) from his figure 9, the peak in the standard band it falls in.

acoustic_spaces.rotorcraft.pegg_broadband(trim: Trim, *, samples: int, sample_rate: int = 48000, grid_deg: float = 5.0, seed: int = 0, rotors: tuple[str, ...] = ('main', 'tail')) → Mixture[source]

The rotors’ broadband noise in a trim by Pegg’s method (see the module’s description), samples of it, its pattern on a grid grid_deg apart in the helicopter’s frame: one noise for each of rotors.

acoustic_spaces.rotorcraft.pegg_level_db(tip_speed: float, sound_speed: float, blade_area_m2: float, lift_coefficient: float) → float[source]

Pegg’s level (dB) of a rotor’s broadband noise at 1 m, before its pattern (10 log (cos^2 theta + 0.1)) and its spectrum (S): 20 log (V_T / c)^3 + 10 log A_b + f(C_L) + 130.

acoustic_spaces.rotorcraft.pegg_lift_db(lift_coefficient: float) → float[source]

Pegg’s f(C_L) (dB), his appendix B.

acoustic_spaces.rotorcraft.pegg_peak_hz(thrust_n: float, tip_speed: float) → float[source]

Pegg’s peak frequency of a rotor’s broadband noise (Hz), his equation 7 in SI units (thrust in N, tip speed in m/s).

acoustic_spaces.rotorcraft.pitch(trim: Trim, which: str, stations: int = 24, azimuths: int = 64) → ndarray[source]

A rotor’s blade pitch in a trim (radians at the hub, by twist_deg less at the tip): its collective theta_0 and its cyclic theta_1c, theta_1s (with cos psi and sin psi, psi the blade’s azimuth from straight downwind, turning with the rotor), such that its blades carry the trim’s thrust and do not flap round the turn: their lift’s moment about the hub has no part that goes once round with it. The blades are rigid, their sections’ lift linear in the angle of attack (lift_slope), the inflow even over the disc (the trim’s); the lift runs from the root to the tip loss, as the tones’ does.

acoustic_spaces.rotorcraft.tones(trim: Trim, which: str, *, samples: int, sample_rate: int = 48000, harmonics: int | None = None, grid_deg: float = 5.0, stations: int = 24) → Periodic[source]

The tones a rotor (“main” or “tail”) sends in a trim, samples of them, as one period in every direction grid_deg apart round its axis; harmonics of the blade passing frequency (by default up to the last within QUIET_DB of the loudest).

acoustic_spaces.rotorcraft.trim(helicopter: Helicopter, airspeed_m_s: float, temperature_c: float = 15.0, pressure_kpa: float = 101.325) → Trim[source]

The helicopter balanced flying level at airspeed_m_s (see the module’s description).

Airfoil self-noise: the noise an airfoil makes in a smooth flow, by Brooks, Pope and Marcolini’s method (NASA Reference Publication 1218, 1989, “BPM”).

BPM scaled wind tunnel measurements of NACA 0012 sections, 2.5 to 30 cm in chord, at speeds up to 71 m/s, into third-octave band levels from five mechanisms:

  • turbulent boundary layer, trailing edge (TBL-TE): the turbulence of each side’s boundary layer passing the trailing edge, and at an angle of attack the flow separating from the suction side, which takes over past stall;

  • laminar boundary layer vortex shedding (LBL-VS): a laminar boundary layer’s instabilities feeding back from the trailing edge, at low Reynolds numbers;

  • trailing-edge bluntness: vortices shed from a trailing edge of thickness h;

  • tip vortex formation: the turbulence where the tip’s vortex forms.

Each segment of an airfoil is its chord, its span, the speed and the angle of attack of the flow, and where the observer is: r away, at an angle theta from the chord line (pointing downstream, from the leading edge to the trailing edge), and phi from the span to the observer’s projection on the plane of the span and the normal, across the chord (the report’s figure B3). The levels are those of the report’s code (its appendix D), checked against its two sample outputs, tables D2 and D3, and are for a segment moving through still air at the speed of the flow: the high-frequency directivity D_h (its equation B1) and the low-frequency D_l (B2) hold the convective amplification of that motion. The angles of attack are in degrees, from the angle of zero lift.

acoustic_spaces.airfoil_noise.FLOOR_DB = -100.0

The level (dB) the code puts a mechanism at when it gives less.

acoustic_spaces.airfoil_noise.FREQUENCIES_HZ = (100.0, 125.0, 160.0, 200.0, 250.0, 315.0, 400.0, 500.0, 630.0, 800.0, 1000.0, 1250.0, 1600.0, 2000.0, 2500.0, 3150.0, 4000.0, 5000.0, 6300.0, 8000.0, 10000.0, 12500.0, 16000.0, 20000.0, 25000.0, 31500.0, 40000.0)

The report’s third-octave band centres (Hz), as its code gives them.

acoustic_spaces.airfoil_noise.LIGHTLY_TRIPPED = 2

Boundary layers: natural transition, tripped heavily, and tripped lightly.

acoustic_spaces.airfoil_noise.TRIPPED = 1

Boundary layers: natural transition, tripped heavily, and tripped lightly.

acoustic_spaces.airfoil_noise.UNTRIPPED = 0

Boundary layers: natural transition, tripped heavily, and tripped lightly.

acoustic_spaces.airfoil_noise.bluntness(frequencies, chord, span, distance, theta_deg, phi_deg, alpha, speed, thickness, angle_deg, *, trip: int, viscosity: float, sound_speed: float) → ndarray[source]

Trailing-edge bluntness noise (the report’s equations 73 to 85), band levels (dB), for a trailing edge thickness thick (m) whose surfaces meet at angle_deg (14 degrees for a NACA 0012).

acoustic_spaces.airfoil_noise.directivity_high(mach, theta_deg, phi_deg) → ndarray[source]

D_h: a trailing edge’s noise at high frequencies, 1 at theta = phi = 90 degrees, with the eddies convected at 0.8 of the flow’s Mach number.

acoustic_spaces.airfoil_noise.directivity_low(mach, theta_deg, phi_deg) → ndarray[source]

D_l: a translating dipole’s, for a stalled airfoil’s noise.

acoustic_spaces.airfoil_noise.lbl_vs(frequencies, chord, span, distance, theta_deg, phi_deg, alpha, speed, *, trip: int, viscosity: float, sound_speed: float) → ndarray[source]

LBL-VS noise (the report’s equations 53 to 60), band levels (dB).

acoustic_spaces.airfoil_noise.stalled(alpha, mach) → ndarray[source]

Whether an airfoil at alpha (degrees) in a flow at mach has stalled for the TBL-TE noise (the report’s gamma_0 or 12.5 degrees).

acoustic_spaces.airfoil_noise.tbl_te(frequencies, chord, span, distance, theta_deg, phi_deg, alpha, speed, *, trip: int, viscosity: float, sound_speed: float) → tuple[ndarray, ndarray, ndarray][source]

TBL-TE and separation noise (the report’s equations 24 to 30): the band levels (dB, (..., frequencies)) of the pressure side, the suction side and the angle of attack’s part (the flow separating). Stalled, each side keeps only its scaling term, 10 log10(delta*_s M^5 L D_l / r^2), as the report’s code has it (its equations 28 and 29 drop the sides), and the angle of attack’s part is that of a translating dipole.

acoustic_spaces.airfoil_noise.thicknesses(chord: ndarray, speed: ndarray, alpha: ndarray, trip: int, viscosity: float) → tuple[ndarray, ndarray, ndarray][source]

The boundary layer at the trailing edge (the report’s section 3, as its code has it): the pressure side’s thickness, and the suction and pressure sides’ displacement thicknesses (m).

acoustic_spaces.airfoil_noise.tip(frequencies, chord, distance, theta_deg, phi_deg, alpha_tip, speed, *, rounded: bool, sound_speed: float, lift_ratio: float = 1.0) → ndarray[source]

Tip vortex formation noise (the report’s equations 61 to 67), band levels (dB), for a tip at alpha_tip (its lift’s slope near the tip lift_ratio times that of the report’s untwisted blade), rounded or square.

Aircraft noise (ECAC Doc 29)

Aircraft noise by ECAC Doc 29, Report on Standard Method of Computing Noise Contours around Civil Airports (5th edition, endorsed 19 May 2026): the noise of a single movement of an aircraft at receivers on the ground, from its NPD curves along a flight path built of segments.

  • tables reads the aircraft, NPD curves, spectral classes and fixed-point profiles from tables laid out as the ANP database’s (Volume 2 Appendix G);

  • path builds the flight path’s segments (Volume 2 section 3.6);

  • noise gives each segment’s sound exposure and maximum level and the event’s (Volume 2 chapter 4);

  • performance gives an aircraft’s fixed-point profile from its procedural steps, its engine and aerodynamic coefficients and its weight (Volume 2 Appendix B);

  • volume3 holds Volume 3’s three hypothetical reference aircraft: Part 1’s routes, receptors and reference sound exposure levels, and Part 2’s procedures, aerodromes and reference flight profiles;

  • anp reads a copy of the ANP database that the user has downloaded;

  • atmosphere adjusts an aircraft’s NPD curves to the air at the aerodrome (Volume 2 Appendix D);

  • source makes an aircraft a source for the engine: its sound power and directivity from its NPD curves, its spectral class and its installation correction, and its flight path as a walk timed as it flies.

The ANP database’s own aircraft are not part of this package: its terms (EASA’s ANP Database Terms and Conditions, issue 3, 2024) allow their use only for noise contours of an average fleet and traffic and forbid passing them on. The readers of tables, performance and anp take tables with the fields Volume 2 Appendix G lists, as Volume 3’s workbook lays them out; they have not been tried on a download of the database.

class acoustic_spaces.doc29.Aircraft(name: str, description: str, engine_type: str, engines: int, npd: str, power_parameter: str, approach_spectrum: str, departure_spectrum: str, installation: str)[source]

An aircraft of the ANP database’s aircraft table (Volume 2 Appendix G2): what the noise calculation needs of it.

name: str

Its identifier, its description, its engines (“Jet”, “Turboprop” or “Piston”) and how many it has.

npd: str

The identifier of its NPD curves, and the power parameter they are given against.

approach_spectrum: str

The identifiers of its spectral classes on approach and on departure.

installation: str

Its lateral directivity, “Fuselage”, “Wing” or “Prop” (INSTALLATIONS): the engine installation correction of Volume 2 section 4.5.3.

property jet: bool

Whether its engines are jets (the start-of-roll directivity of jets).

property power_in_lb: bool

Whether its NPD curves’ power parameter is in pounds, as “Corrected Net Thrust (lb)” (a percentage of one is not): the corrected net thrust per engine that Appendix B’s procedural steps give.

class acoustic_spaces.doc29.Event(sel: ndarray, lamax: ndarray, segments: tuple[SegmentLevels, ...])[source]

One movement’s levels at the receivers (dB(A)), and each segment’s part.

class acoustic_spaces.doc29.NpdCurves(powers: tuple[float, ...], levels: tuple[tuple[float, ...], ...])[source]

One set of NPD curves (noise-power-distance, Volume 2 section 4.2): a level (dB) at each of NPD_FEET for each power, interpolated linearly in power (eq. 4-3) and in the logarithm of the distance (eq. 4-4), and extrapolated from the last two curves or distances beyond them (eq. 4-5).

levels: tuple[tuple[float, ...], ...]

The levels, a row for each power (as many as powers), a column for each distance.

level(power: ndarray | float, distance_m: ndarray | float) → ndarray[source]

The level at power and distance_m (m), each an array or a number.

exception acoustic_spaces.doc29.NpdExtrapolationWarning[source]

A flight’s power lies so far outside its NPD curves’ powers that their levels, extrapolated in power (eq. 4-3), depart more than NPD_ENVELOPE_DB from the levels at the nearest power of the curves (Volume 2 section 4.2).

class acoustic_spaces.doc29.ProfilePoint(distance_m: float, height_m: float, speed_m_s: float, power: float)[source]

A point of a fixed-point profile: the distance along the ground track (m; from the start of roll on departure, to touchdown on approach, negative before it), the height above the runway (m), the true airspeed (m/s) and the power (the NPD curves’ parameter, per engine).

class acoustic_spaces.doc29.Segment(start: tuple[float, float, float], end: tuple[float, float, float], speeds: tuple[float, float], powers: tuple[float, float], banks: tuple[float, float] = (0.0, 0.0), roll: str = '')[source]

A straight segment of a flight path, from start to end (x, y, z in m), with the speed, power and bank angle at each end, and whether it is part of the take-off roll or the landing roll.

class acoustic_spaces.doc29.SegmentLevels(q: ndarray, slant: ndarray, d1: ndarray, d2: ndarray, lateral: ndarray, npd_distance: ndarray, power: ndarray, elevation: ndarray, climb: float, depression: ndarray, installation: ndarray, lateral_attenuation: ndarray, baseline: ndarray, duration: ndarray, maximum: ndarray, fraction: ndarray, start_of_roll: ndarray, impedance: float, exposure: ndarray, peak: ndarray)[source]

One segment’s contribution at each receiver, with the terms that make it up (arrays, one value a receiver): the distances (m), angles (degrees) and levels (dB) Volume 3 lists for its reference cases.

peak: ndarray

The segment’s maximum level at each receiver (dB(A)), eq. 4-8a.

class acoustic_spaces.doc29.SpectralClass(name: str, mode: str, description: str, levels: tuple[float, ...])[source]

A spectral class (Volume 2 Appendix D, G): the spectrum, in third octaves of SPECTRAL_BANDS_HZ, of an aircraft’s sound 1000 ft (305 m) under it, its level 70 dB at 1 kHz.

class acoustic_spaces.doc29.Track(points: tuple[tuple[float, float], ...], start_m: float = 0.0)[source]

A ground track: its points (x, y in m) in the direction of flight, and the distance along it of its first point (m). Doc 29 measures a departure’s track from the start of roll and an arrival’s from the landing threshold (section 3.3.2).

classmethod through(points: Sequence[tuple[float, float]], origin: tuple[float, float]) → Track[source]

The track through points measured from origin, a point on it (the start of roll or the landing threshold); a point within SAME_PLAN_POINT_M of the one before it is left out.

property node_distances: ndarray

The distance along the track of each of its points (m).

extended(first_m: float, last_m: float) → Track[source]

The track reaching back to first_m and on to last_m at least, its first and last legs made longer if they must be (section 3.6.6), the way the first and last that have a length go.

at(s: float) → tuple[float, float][source]

The point of the track s along it (m), on the leg that holds it, or on from the first or last leg that has a length before or after the track.

acoustic_spaces.doc29.event(aircraft: Aircraft, exposure: NpdCurves, maximum: NpdCurves, segments: Sequence[Segment], receivers: ndarray, impedance: float = 0.0) → Event[source]

The sound exposure level (eq. 4-11) and the maximum level (eq. 4-10) of the flight segments of aircraft at receivers. A segment whose NPD level at its power departs more than NPD_ENVELOPE_DB from the level at the nearest power of the curves gives an NpdExtrapolationWarning (section 4.2).

impedance is Doc 29’s impedance adjustment (dB, eq. 4-6 and 4-7) added to every segment’s levels: impedance_db() of the aerodrome’s temperature and pressure. Its default, 0, is the NPD curves’ reference day (25 °C, 101.325 kPa), not the standard atmosphere at sea level, for which the adjustment is 0.074 dB.

acoustic_spaces.doc29.flight_path(profile: Sequence[ProfilePoint], track: Track, departure: bool, threshold_m: float = 0.0) → list[Segment][source]

The segments of the flight of profile along track, a departure or an arrival. An arrival’s profile measures its distances to touchdown and its track from the landing threshold: threshold_m is the profile’s distance at the threshold (negative, before touchdown). The profile is carried on, at its last speed and power and its last slope, to the end of the track, or back to its start on arrival, and the track on to the end of the profile (section 3.6.6).

acoustic_spaces.doc29.impedance_db(temperature_c: float = 15.0, pressure_kpa: float = 101.325) → float[source]

The impedance adjustment of the NPD levels to the air at the aerodrome (dB), eq. 4-6 and 4-7.

acoustic_spaces.doc29.read_aircraft(path: str | Path) → dict[str, Aircraft][source]

The aircraft of the aircraft table path, by identifier, each its lateral directivity the installation of INSTALLATIONS it names.

acoustic_spaces.doc29.read_fixed_point_profiles(path: str | Path) → dict[tuple[str, str, str, str], tuple[ProfilePoint, ...]][source]

The fixed-point profiles of the table path, by (aircraft, operation mode “A” or “D”, profile identifier, stage length), each its points in order.

acoustic_spaces.doc29.read_npd(path: str | Path) → dict[tuple[str, str, str], NpdCurves][source]

The NPD curves of the NPD table path, by (NPD identifier, noise descriptor, operation mode): (“JETF”, “SEL”, “D”) for instance, the descriptor “SEL” or “LAmax” and the mode “A” (arrival) or “D” (departure).

acoustic_spaces.doc29.read_spectral_classes(path: str | Path) → dict[str, SpectralClass][source]

The spectral classes of the table path, by identifier.

acoustic_spaces.doc29.segment_levels(aircraft: Aircraft, exposure: NpdCurves, maximum: NpdCurves, segment: Segment, receivers: ndarray, impedance: float = 0.0) → SegmentLevels[source]

The contribution of segment of a flight of aircraft at receivers (an array of x, y, z in m, one a row), its exposure from the SEL curves exposure and its maximum level from the LAmax curves maximum.

impedance is Doc 29’s impedance adjustment (dB, eq. 4-6 and 4-7), added to both levels: impedance_db() of the aerodrome’s temperature and pressure. Its default, 0, is the NPD curves’ reference day (25 °C, 101.325 kPa), not the standard atmosphere at sea level, for which the adjustment is 0.074 dB.

Doc 29’s aircraft data read from tables laid out as the ANP database’s (Doc 29 Volume 2 Appendix G, as Volume 3’s workbook lays out its reference aircraft): the aircraft, their NPD curves, their spectral classes and their fixed-point profiles.

A table is a CSV file with a header row; its separator may be a comma or a semicolon. Columns are found by their names, whatever their case, spaces and punctuation, and a length or a speed is read in the unit its column’s name gives in round or square brackets, as Appendix G’s “Distance (ft)” and Volume 3’s “Distance (m)”: m, ft or feet for a length, m/s, kt, kts or knots for a speed. A column that names another unit, or none, is an error.

acoustic_spaces.doc29.tables.FOOT_M = 0.3048

A foot (m), a knot (m/s) and a nautical mile (m).

acoustic_spaces.doc29.tables.LENGTH_UNITS = {'feet': 0.3048, 'ft': 0.3048, 'm': 1.0}

The units a column of lengths (m) or of speeds (m/s) may give in brackets, its case and spaces aside.

acoustic_spaces.doc29.tables.INSTALLATIONS = ('Fuselage', 'Wing', 'Prop')

The engine installations a lateral directivity identifier names by its start, its case and punctuation aside (Volume 2 Appendix G2: “Fuselage-mounted”, “Wing-mounted” or “Prop”).

acoustic_spaces.doc29.tables.NPD_FEET = (200.0, 400.0, 630.0, 1000.0, 2000.0, 4000.0, 6300.0, 10000.0, 16000.0, 25000.0)

The distances of the NPD tables (ft), 200 to 25000 ft (Volume 2 Appendix G).

acoustic_spaces.doc29.tables.SPECTRAL_BANDS_HZ = (50, 63, 80, 100, 125, 160, 200, 250, 315, 400, 500, 630, 800, 1000, 1250, 1600, 2000, 2500, 3150, 4000, 5000, 6300, 8000, 10000)

The third-octave bands of a spectral class (Hz), 50 Hz to 10 kHz.

acoustic_spaces.doc29.tables.read_rows(path: str | Path) → list[dict[str, str]][source]

The rows of the CSV table path, each a dict from its column’s name to its cell (stripped).

acoustic_spaces.doc29.tables.installation_of(label: str) → str[source]

The engine installation, one of INSTALLATIONS, that the lateral directivity identifier label names by its start (“Wing-mounted” names “Wing”).

class acoustic_spaces.doc29.tables.Aircraft(name: str, description: str, engine_type: str, engines: int, npd: str, power_parameter: str, approach_spectrum: str, departure_spectrum: str, installation: str)[source]

An aircraft of the ANP database’s aircraft table (Volume 2 Appendix G2): what the noise calculation needs of it.

name: str

Its identifier, its description, its engines (“Jet”, “Turboprop” or “Piston”) and how many it has.

npd: str

The identifier of its NPD curves, and the power parameter they are given against.

approach_spectrum: str

The identifiers of its spectral classes on approach and on departure.

installation: str

Its lateral directivity, “Fuselage”, “Wing” or “Prop” (INSTALLATIONS): the engine installation correction of Volume 2 section 4.5.3.

property jet: bool

Whether its engines are jets (the start-of-roll directivity of jets).

property power_in_lb: bool

Whether its NPD curves’ power parameter is in pounds, as “Corrected Net Thrust (lb)” (a percentage of one is not): the corrected net thrust per engine that Appendix B’s procedural steps give.

acoustic_spaces.doc29.tables.read_aircraft(path: str | Path) → dict[str, Aircraft][source]

The aircraft of the aircraft table path, by identifier, each its lateral directivity the installation of INSTALLATIONS it names.

class acoustic_spaces.doc29.tables.NpdCurves(powers: tuple[float, ...], levels: tuple[tuple[float, ...], ...])[source]

One set of NPD curves (noise-power-distance, Volume 2 section 4.2): a level (dB) at each of NPD_FEET for each power, interpolated linearly in power (eq. 4-3) and in the logarithm of the distance (eq. 4-4), and extrapolated from the last two curves or distances beyond them (eq. 4-5).

levels: tuple[tuple[float, ...], ...]

The levels, a row for each power (as many as powers), a column for each distance.

level(power: ndarray | float, distance_m: ndarray | float) → ndarray[source]

The level at power and distance_m (m), each an array or a number.

acoustic_spaces.doc29.tables.read_npd(path: str | Path) → dict[tuple[str, str, str], NpdCurves][source]

The NPD curves of the NPD table path, by (NPD identifier, noise descriptor, operation mode): (“JETF”, “SEL”, “D”) for instance, the descriptor “SEL” or “LAmax” and the mode “A” (arrival) or “D” (departure).

class acoustic_spaces.doc29.tables.SpectralClass(name: str, mode: str, description: str, levels: tuple[float, ...])[source]

A spectral class (Volume 2 Appendix D, G): the spectrum, in third octaves of SPECTRAL_BANDS_HZ, of an aircraft’s sound 1000 ft (305 m) under it, its level 70 dB at 1 kHz.

acoustic_spaces.doc29.tables.read_spectral_classes(path: str | Path) → dict[str, SpectralClass][source]

The spectral classes of the table path, by identifier.

class acoustic_spaces.doc29.tables.ProfilePoint(distance_m: float, height_m: float, speed_m_s: float, power: float)[source]

A point of a fixed-point profile: the distance along the ground track (m; from the start of roll on departure, to touchdown on approach, negative before it), the height above the runway (m), the true airspeed (m/s) and the power (the NPD curves’ parameter, per engine).

acoustic_spaces.doc29.tables.read_fixed_point_profiles(path: str | Path) → dict[tuple[str, str, str, str], tuple[ProfilePoint, ...]][source]

The fixed-point profiles of the table path, by (aircraft, operation mode “A” or “D”, profile identifier, stage length), each its points in order.

acoustic_spaces.doc29.tables.points_m(rows: Sequence[dict[str, str]], x: str, y: str) → list[tuple[float, float]][source]

The points (m) of the columns x and y of rows, in the unit of their names.

A flight path built of straight segments, as Doc 29 builds it (Volume 2 section 3.6): a profile of heights, speeds and powers along a ground track, the take-off and landing rolls cut into segments by speed, the initial climb and the final approach by height, airborne segments that change speed much by speed, and the profile merged with the track’s nodes.

acoustic_spaces.doc29.path.CLIMB_HEIGHTS_M = (18.8976, 41.4528, 68.2752, 102.108, 147.5232, 214.88400000000001, 334.97520000000003, 609.6, 1289.6088)

The heights (m) that cut the initial climb and the final approach below 4231 ft (1289.6 m), for at most 1.5 dB of change of the lateral attenuation along a segment (Volume 2 section 3.6.4): its heights in feet, which Volume 3’s reference cases use (its heights in metres are these rounded).

acoustic_spaces.doc29.path.SPEED_CHANGE_M_S = 10.28888888888889

How much an airborne segment’s speed may change before it is cut (m/s), 20 kt, and the step of speed it is cut into, and a roll on the runway is, 10 m/s (section 3.6).

acoustic_spaces.doc29.path.NEAREST_POINTS_M = 10.0

How near two points of the same speed and power may be before one goes (m), section 3.6.7, and how low a source may be over the runway (m), section 3.5.

acoustic_spaces.doc29.path.SAME_PLAN_POINT_M = 1e-06

How near two consecutive points of a ground track may be before the later one goes (m): a walk’s places one above the other have one point in plan.

class acoustic_spaces.doc29.path.Node(s: float, height: float, speed: float, power: float, bank: float = 0.0, ground: bool = False)[source]

A point of a flight path: where it is (m), its speed (m/s), its power, its bank angle (degrees, positive in a left turn), and whether it is on the runway.

class acoustic_spaces.doc29.path.Segment(start: tuple[float, float, float], end: tuple[float, float, float], speeds: tuple[float, float], powers: tuple[float, float], banks: tuple[float, float] = (0.0, 0.0), roll: str = '')[source]

A straight segment of a flight path, from start to end (x, y, z in m), with the speed, power and bank angle at each end, and whether it is part of the take-off roll or the landing roll.

class acoustic_spaces.doc29.path.Track(points: tuple[tuple[float, float], ...], start_m: float = 0.0)[source]

A ground track: its points (x, y in m) in the direction of flight, and the distance along it of its first point (m). Doc 29 measures a departure’s track from the start of roll and an arrival’s from the landing threshold (section 3.3.2).

classmethod through(points: Sequence[tuple[float, float]], origin: tuple[float, float]) → Track[source]

The track through points measured from origin, a point on it (the start of roll or the landing threshold); a point within SAME_PLAN_POINT_M of the one before it is left out.

property node_distances: ndarray

The distance along the track of each of its points (m).

extended(first_m: float, last_m: float) → Track[source]

The track reaching back to first_m and on to last_m at least, its first and last legs made longer if they must be (section 3.6.6), the way the first and last that have a length go.

at(s: float) → tuple[float, float][source]

The point of the track s along it (m), on the leg that holds it, or on from the first or last leg that has a length before or after the track.

acoustic_spaces.doc29.path.speed_between(v1, v2, f)[source]

The speed f of the distance from v1 to v2 (m/s), its square linear in the distance, so that the speed is linear in time (eq. 3-2); f a number or an array of them.

acoustic_spaces.doc29.path.interpolate(a: Node, b: Node, s: float) → Node[source]

The node s along the way from a to b: the height and the bank angle linear in the distance, the speed and the power in its square, linear in time (eq. 3-2).

acoustic_spaces.doc29.path.power_between(p1: float, p2: float, f: float) → float[source]
acoustic_spaces.doc29.path.power_between(p1: float, p2: float, f: ndarray) → ndarray

The power f of the way from p1 to p2 (eq. 3-2d to 3-2g), f a number or an array of them.

acoustic_spaces.doc29.path.lowest_approach_node(profile: Sequence[ProfilePoint]) → float[source]

The distance (m, to touchdown) of the lowest node of an approach above the runway: its last profile point in the air, or the lowest height that cuts its last segment to touchdown (section 3.6.4) if one does. Volume 3’s reference cases put the landing threshold there (the jets’ point at 15.2 m, 290.2 m before touchdown, and the propeller aircraft’s cut at 17.2 m, 328.1 m before it).

acoustic_spaces.doc29.path.flight_path(profile: Sequence[ProfilePoint], track: Track, departure: bool, threshold_m: float = 0.0) → list[Segment][source]

The segments of the flight of profile along track, a departure or an arrival. An arrival’s profile measures its distances to touchdown and its track from the landing threshold: threshold_m is the profile’s distance at the threshold (negative, before touchdown). The profile is carried on, at its last speed and power and its last slope, to the end of the track, or back to its start on arrival, and the track on to the end of the profile (section 3.6.6).

The noise of one aircraft movement at receivers by Doc 29 (Volume 2 chapter 4): each segment’s level from the NPD curves at its power and distance, corrected for the speed, the engines’ installation, the lateral attenuation, the segment’s finite length and, behind a take-off roll, the start-of-roll directivity; summed over the segments to the event’s sound exposure level, or its maximum level taken.

acoustic_spaces.doc29.noise.NPD_ENVELOPE_DB = 5.0

How far an NPD level extrapolated in power (eq. 4-3) may depart from the level at the nearest power of the curves before event() warns (dB), section 4.2.

class acoustic_spaces.doc29.noise.Event(sel: ndarray, lamax: ndarray, segments: tuple[SegmentLevels, ...])[source]

One movement’s levels at the receivers (dB(A)), and each segment’s part.

exception acoustic_spaces.doc29.noise.NpdExtrapolationWarning[source]

A flight’s power lies so far outside its NPD curves’ powers that their levels, extrapolated in power (eq. 4-3), depart more than NPD_ENVELOPE_DB from the levels at the nearest power of the curves (Volume 2 section 4.2).

class acoustic_spaces.doc29.noise.SegmentLevels(q: ndarray, slant: ndarray, d1: ndarray, d2: ndarray, lateral: ndarray, npd_distance: ndarray, power: ndarray, elevation: ndarray, climb: float, depression: ndarray, installation: ndarray, lateral_attenuation: ndarray, baseline: ndarray, duration: ndarray, maximum: ndarray, fraction: ndarray, start_of_roll: ndarray, impedance: float, exposure: ndarray, peak: ndarray)[source]

One segment’s contribution at each receiver, with the terms that make it up (arrays, one value a receiver): the distances (m), angles (degrees) and levels (dB) Volume 3 lists for its reference cases.

peak: ndarray

The segment’s maximum level at each receiver (dB(A)), eq. 4-8a.

acoustic_spaces.doc29.noise.event(aircraft: Aircraft, exposure: NpdCurves, maximum: NpdCurves, segments: Sequence[Segment], receivers: ndarray, impedance: float = 0.0) → Event[source]

The sound exposure level (eq. 4-11) and the maximum level (eq. 4-10) of the flight segments of aircraft at receivers. A segment whose NPD level at its power departs more than NPD_ENVELOPE_DB from the level at the nearest power of the curves gives an NpdExtrapolationWarning (section 4.2).

impedance is Doc 29’s impedance adjustment (dB, eq. 4-6 and 4-7) added to every segment’s levels: impedance_db() of the aerodrome’s temperature and pressure. Its default, 0, is the NPD curves’ reference day (25 °C, 101.325 kPa), not the standard atmosphere at sea level, for which the adjustment is 0.074 dB.

acoustic_spaces.doc29.noise.fraction_db(alpha1: ndarray, alpha2: ndarray) → ndarray[source]

The finite segment correction (dB) of eq. 4-20 for the ends alpha1 and alpha2 of the segment in scaled distances.

acoustic_spaces.doc29.noise.impedance_db(temperature_c: float = 15.0, pressure_kpa: float = 101.325) → float[source]

The impedance adjustment of the NPD levels to the air at the aerodrome (dB), eq. 4-6 and 4-7.

acoustic_spaces.doc29.noise.installation_db(installation: str, depression_deg: ndarray) → ndarray[source]

The engine installation correction (dB) at the depression angle (degrees) under the wing plane, eq. 4-15, of the installation the lateral directivity installation names (installation_of()); nought for propellers, and at negative angles that at nought.

acoustic_spaces.doc29.noise.lateral_attenuation_db(elevation_deg: ndarray, lateral_m: ndarray) → ndarray[source]

The lateral attenuation (dB) at an elevation angle (degrees) and a lateral displacement from the ground track (m), eq. 4-18 and 4-19.

acoustic_spaces.doc29.noise.segment_levels(aircraft: Aircraft, exposure: NpdCurves, maximum: NpdCurves, segment: Segment, receivers: ndarray, impedance: float = 0.0) → SegmentLevels[source]

The contribution of segment of a flight of aircraft at receivers (an array of x, y, z in m, one a row), its exposure from the SEL curves exposure and its maximum level from the LAmax curves maximum.

impedance is Doc 29’s impedance adjustment (dB, eq. 4-6 and 4-7), added to both levels: impedance_db() of the aerodrome’s temperature and pressure. Its default, 0, is the NPD curves’ reference day (25 °C, 101.325 kPa), not the standard atmosphere at sea level, for which the adjustment is 0.074 dB.

acoustic_spaces.doc29.noise.start_of_roll_db(jet: bool, azimuth_deg: ndarray, distance_m: ndarray) → ndarray[source]

The start-of-roll directivity (dB) behind a take-off roll at the azimuth from the aircraft’s heading (90 to 180 degrees) and the distance (m), eq. 4-22 to 4-25.

Flight performance by Doc 29 Volume 2 Appendix B: an aircraft’s fixed-point profile (its height, true airspeed and corrected net thrust along the ground track) from its procedural steps, its engine and aerodynamic coefficients and its weight, at an aerodrome’s elevation, temperature and pressure and into a headwind.

As Appendix B does, the calculation runs in feet, knots and pounds, and its profile points (Point) are in those units: as_profile() gives them in the metres of ProfilePoint, ready for flight_path().

The aircraft’s coefficients are read from tables laid out as the ANP database’s (Volume 2 Appendix G3): read_performance() reads its aircraft, jet engine, propeller engine, aerodynamic coefficients and default weights tables, and read_departure_steps() and read_approach_steps() its procedural steps.

The aircraft flies straight: the bank angles of turns (Appendix B5) are not part of the calculation.

acoustic_spaces.doc29.performance.G_FT_S2 = 32.174

The standard gravitational acceleration (ft/s²) and a knot (ft/s), Appendix B2.

acoustic_spaces.doc29.performance.SEA_LEVEL_INHG = 29.92

The standard sea-level pressure (inHg) Appendix B3 keeps, and the lapse rate of the temperature (°F/ft), the standard sea-level temperature (°R) and the exponent of its pressure ratio.

acoustic_spaces.doc29.performance.KPA_PER_INHG = 3.38653131

An inch of mercury (kPa) as Appendix B2.2 converts it: less precise than 3.386389 on purpose, so that 29.92 inHg is the standard 101.325 kPa (its note 31).

acoustic_spaces.doc29.performance.BREAKPOINT_C = 30.0

The breakpoint temperature (°C) of eq. B-11, when the high-temperature jet coefficients are not given.

acoustic_spaces.doc29.performance.ENGINE_OUT_GRADIENT = {2: 1.2, 3: 1.5, 4: 1.7}

The engine-out climb gradients (%) of eq. B-13, by number of engines.

acoustic_spaces.doc29.performance.TRANSITION_FT = 1000.0

The longest transition segment (ft) where the thrust changes (B6.1.6, B7).

acoustic_spaces.doc29.performance.REFERENCE_HEADWIND_KT = 8.0

The headwind (kt) the coefficients are given for (Appendix G3.1).

class acoustic_spaces.doc29.performance.Aerodrome(elevation_ft: float = 0.0, temperature_c: float = 15.0, pressure_inhg: float = 29.92, headwind_kt: float = 8.0)[source]

Where and in what air the aircraft flies (Appendix B3): the aerodrome’s elevation (ft above mean sea level), its temperature (°C), its pressure reduced to sea level (QNH, inHg) and the headwind (kt). The defaults are the conditions of the ANP data (Appendix G3.1): a sea-level aerodrome in the standard atmosphere, into an 8 kt headwind.

theta(altitude_ft: float) → float[source]

The temperature ratio at altitude_ft (ft above mean sea level; eq. B-3).

delta(altitude_ft: float) → float[source]

The pressure ratio at altitude_ft (eq. B-4).

sigma(altitude_ft: float) → float[source]

The density ratio at altitude_ft (eq. B-5).

pressure_altitude(altitude_ft: float) → float[source]

The pressure altitude (ft) at altitude_ft (eq. B-6).

temperature(altitude_ft: float) → float[source]

The air’s temperature (°C) at altitude_ft (eq. B-1, B-2).

acoustic_spaces.doc29.performance.STANDARD = Aerodrome(elevation_ft=0.0, temperature_c=15.0, pressure_inhg=29.92, headwind_kt=8.0)

The conditions the approach procedures’ idle steps are given for (Appendix B7.1.2, B7.1.4): the standard atmosphere at a sea-level aerodrome.

class acoustic_spaces.doc29.performance.JetCoefficients(e: float, f: float, ga: float, gb: float, h: float)[source]

A thrust rating’s jet engine coefficients (Appendix G3.2): E (lb), F (lb/kt), GA (lb/ft), GB (lb/ft²) and H (lb/°C) of eq. B-9.

thrust(calibrated_kt: float, pressure_altitude_ft: float, temperature_c: float) → float[source]

The corrected net thrust per engine (lb; eq. B-9, B-10).

class acoustic_spaces.doc29.performance.PropellerCoefficients(efficiency: float, power_hp: float)[source]

A thrust rating’s propeller coefficients (Appendix G3.3): the propeller’s efficiency and the installed net propulsive power (hp).

class acoustic_spaces.doc29.performance.Flaps(b: float | None, speed: float | None, r: float)[source]

A flap setting’s aerodynamic coefficients (Appendix G3.4): B (ft/lb), the take-off ground roll’s; C or D (kt/√lb), the take-off’s or the landing’s speed; and R, the ratio of drag to lift. B, C and D are given only for the flaps of take-off and landing (None for the others).

class acoustic_spaces.doc29.performance.Performance(name: str, engine_type: str, engines: int, max_landing_weight_lb: float, max_static_thrust_lb: float, jet: dict[str, ~acoustic_spaces.doc29.performance.JetCoefficients] = <factory>, propeller: dict[str, ~acoustic_spaces.doc29.performance.PropellerCoefficients] = <factory>, flaps: dict[tuple[str, str], ~acoustic_spaces.doc29.performance.Flaps] = <factory>, weights: dict[tuple[str, str], float] = <factory>)[source]

What the performance calculation needs of an aircraft (Appendix G2 to G3.5).

max_landing_weight_lb: float

Its greatest landing weight and its engines’ greatest static thrust at sea level, each (lb).

jet: dict[str, JetCoefficients]

Its jet engine coefficients and its propeller coefficients, by the key of the thrust rating (rating_key()): “maxtakeoff”, “maxclimb”, “idleapproach”, and those with the suffix “hitemp”, above the breakpoint temperature.

flaps: dict[tuple[str, str], Flaps]

Its flaps’ coefficients, by (operation “A” or “D”, flap identifier).

weights: dict[tuple[str, str], float]

Its default weights (lb), by (operation “A” or “D”, stage length).

flap(operation: str, name: str) → Flaps[source]

The coefficients of the flap setting name on arrival (“A”) or departure (“D”).

acoustic_spaces.doc29.performance.rating_key(name: str) → str[source]

The key of the thrust rating name: its letters and digits in lower case, so that “MaxTakeoff”, “MaxTakeOff” and “MaxTake-off” are one, with “HighTemp” written “hitemp”.

class acoustic_spaces.doc29.performance.Point(distance_ft: float, height_ft: float, speed_kt: float, thrust_lb: float)[source]

A point of a fixed-point profile as Appendix B gives it: the distance along the ground track (ft; from the start of roll on departure, to touchdown on approach, negative before it), the height above the aerodrome (ft), the true airspeed (kt) and the corrected net thrust per engine (lb).

acoustic_spaces.doc29.performance.as_profile(points: Sequence[Point]) → tuple[ProfilePoint, ...][source]

points as the profile points (m, m/s) of a flight path.

class acoustic_spaces.doc29.performance.DepartureStep(kind: str, thrust: str, flap: str, altitude_ft: float | None = None, climb_rate_ft_min: float | None = None, speed_kt: float | None = None, accelerating_percent: float | None = None, distance_ft: float | None = None)[source]

A step of a departure procedure (Appendix G3.6): its type (“Takeoff”, “Climb”, “Accelerate”, “Level” or “Level-Accelerate”), its thrust rating, its flaps, the height it climbs to (ft above the aerodrome; a climb’s), its rate of climb (ft/min) or its share of the thrust that accelerates (%, its accel percentage) and the calibrated airspeed it accelerates to (kt; an acceleration’s), and its length (ft; a level step’s).

class acoustic_spaces.doc29.performance.ApproachStep(kind: str, flap: str, altitude_ft: float | None = None, speed_kt: float | None = None, angle_deg: float | None = None, touchdown_roll_ft: float | None = None, distance_ft: float | None = None, thrust_percent: float | None = None)[source]

A step of an approach procedure (Appendix G3.7): its type (“Descend”, “Descend-Decel”, “Descend-Idle”, “Level”, “Level-Decel”, “Level-Idle”, “Land” or “Decelerate”), its flaps, the height (ft above the aerodrome) and calibrated airspeed (kt) it starts at, its descent angle (°), the touchdown roll (ft; a landing’s), its length (ft) and the thrust it starts with (% of the greatest static thrust; a deceleration’s on the runway).

acoustic_spaces.doc29.performance.read_performance(aircraft: str | Path, jet: str | Path | None = None, propeller: str | Path | None = None, aerodynamic: str | Path | None = None, weights: str | Path | None = None) → dict[str, Performance][source]

The aircraft of the aircraft table aircraft with their coefficients from the jet engine coefficients table jet, the propeller engine coefficients table propeller, the aerodynamic coefficients table aerodynamic and the default weights table weights (each optional), by identifier.

acoustic_spaces.doc29.performance.read_departure_steps(path: str | Path) → dict[tuple[str, str, str], tuple[DepartureStep, ...]][source]

The departure procedures of the departure procedural steps table path, by (aircraft, profile identifier, stage length), each its steps in order.

acoustic_spaces.doc29.performance.read_approach_steps(path: str | Path) → dict[tuple[str, str], tuple[ApproachStep, ...]][source]

The approach procedures of the approach procedural steps table path, by (aircraft, profile identifier), each its steps in order.

acoustic_spaces.doc29.performance.departure(aircraft: Performance, steps: Sequence[DepartureStep], weight_lb: float, aerodrome: Aerodrome = Aerodrome(elevation_ft=0.0, temperature_c=15.0, pressure_inhg=29.92, headwind_kt=8.0), runway_gradient: float = 0.0) → list[Point][source]

The fixed-point profile (Appendix B6) of a departure of aircraft at weight_lb (lb) by the procedure steps from aerodrome, its runway’s gradient runway_gradient (positive uphill).

acoustic_spaces.doc29.performance.arrival(aircraft: Performance, steps: Sequence[ApproachStep], weight_lb: float | None = None, aerodrome: Aerodrome = Aerodrome(elevation_ft=0.0, temperature_c=15.0, pressure_inhg=29.92, headwind_kt=8.0)) → list[Point][source]

The fixed-point profile (Appendix B7) of an arrival of aircraft at weight_lb (lb; by default 90 % of its greatest landing weight, as Appendix B7 takes) by the procedure steps at aerodrome.

The reference cases of Doc 29 Volume 3 (5th edition, 2026), of three hypothetical aircraft that rely on no ANP data: a rear-engined jet (JETF), a wing-engined jet (JETW) and a propeller aircraft (PROP).

  • Part 1, the noise: each aircraft arriving and departing on a straight and a curved route at a hypothetical aerodrome (CASES), and the sound exposure levels Volume 3 gives at its receptors (its Appendix A and B, tables A-1 and A-6 to A-12 and B-1, as its workbook gives them).

  • Part 2, the flight performance: JETW flying departure and approach procedures and PROP departure procedures (Volume 3 gives no arrivals of PROP) at aerodromes of other elevations, temperatures, pressures and headwinds (profile_cases()), and the fixed-point profiles Volume 3 gives for them (its Appendix C and D, tables C-1 to C-8 and D-1 and D-2). The approach procedures are as its table C-6.2 prints them, to 0.1 ft, kt and degree, which its profiles are computed from (its workbook has more digits); the lengths of its Level-Idle steps, which the table gives in the column of the descent angle, are their distances.

The tables are read as the ANP database’s are.

acoustic_spaces.doc29.volume3.DATA = PosixPath('/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/acoustic_spaces/doc29/volume3')

Where the tables are.

acoustic_spaces.doc29.volume3.aircraft() → dict[str, Aircraft][source]

The three reference aircraft (table A-1), by identifier.

acoustic_spaces.doc29.volume3.npd() → dict[tuple[str, str, str], NpdCurves][source]

Their NPD curves (table A-7), by (aircraft, “SEL” or “LAmax”, “A” or “D”).

acoustic_spaces.doc29.volume3.spectral_classes() → dict[str, SpectralClass][source]

Their spectral classes (table A-8), by identifier.

acoustic_spaces.doc29.volume3.profiles() → dict[tuple[str, str], tuple[ProfilePoint, ...]][source]

Their fixed-point profiles (table A-6), by (aircraft, “A” or “D”).

acoustic_spaces.doc29.volume3.routes() → dict[str, tuple[tuple[float, float], ...]][source]

The four routes’ ground tracks (table A-11; m), by identifier: “AC” and “AS” the curved and straight arrivals, “DC” and “DS” the departures.

acoustic_spaces.doc29.volume3.runway() → tuple[tuple[float, float], tuple[float, float]][source]

The runway’s start of roll and end (table A-10; m).

acoustic_spaces.doc29.volume3.receptors() → dict[str, tuple[float, float, float]][source]

The 18 receptors (table A-12; m), by identifier.

acoustic_spaces.doc29.volume3.sel_results() → dict[tuple[str, str], float][source]

Volume 3’s sound exposure levels (table B-1; dB(A)), by (case, receptor).

acoustic_spaces.doc29.volume3.impedance() → float[source]

The impedance adjustment at the aerodrome’s temperature and pressure (dB; table A-9, the standard atmosphere’s: 0.074 dB).

class acoustic_spaces.doc29.volume3.Case(aircraft: str, operation: str, route: str)[source]

A reference case: an aircraft, an arrival (“A”) or a departure (“D”), and a route, curved (“C”) or straight (“S”); its identifier is Volume 3’s, “JETFDC” for instance.

classmethod named(name: str) → Case[source]

The case of Volume 3’s identifier name.

track() → Track[source]

Its ground track: a departure’s from the start of roll, an arrival’s from the landing threshold, the runway’s start (where the arrivals land, as the departures leave).

segments() → list[Segment][source]

Its flight path’s segments.

event(points: ndarray) → Event[source]

Its levels at points (x, y, z in m, one a row).

acoustic_spaces.doc29.volume3.CASES = (Case(aircraft='JETF', operation='A', route='C'), Case(aircraft='JETF', operation='A', route='S'), Case(aircraft='JETF', operation='D', route='C'), Case(aircraft='JETF', operation='D', route='S'), Case(aircraft='JETW', operation='A', route='C'), Case(aircraft='JETW', operation='A', route='S'), Case(aircraft='JETW', operation='D', route='C'), Case(aircraft='JETW', operation='D', route='S'), Case(aircraft='PROP', operation='A', route='C'), Case(aircraft='PROP', operation='A', route='S'), Case(aircraft='PROP', operation='D', route='C'), Case(aircraft='PROP', operation='D', route='S'))

The twelve cases, as Volume 3’s table 3-1 lists them.

acoustic_spaces.doc29.volume3.performance() → dict[str, Performance][source]

Part 2’s two aircraft, JETW and PROP, with their engine and aerodynamic coefficients and their default weights (tables C-1 to C-5), by identifier.

acoustic_spaces.doc29.volume3.departure_procedures() → dict[tuple[str, str], tuple[DepartureStep, ...]][source]

Part 2’s departure procedures (table C-6.1), by (aircraft, procedure).

acoustic_spaces.doc29.volume3.approach_procedures() → dict[tuple[str, str], tuple[ApproachStep, ...]][source]

Part 2’s approach procedures (table C-6.2), by (aircraft, procedure).

class acoustic_spaces.doc29.volume3.ProfileCase(number: str, operation: str, aircraft: str, procedure: str, aerodrome: Aerodrome)[source]

A reference case of Part 2 (tables C-7 and C-8): an aircraft flying a departure (“D”) or approach (“A”) procedure from an aerodrome; its number is Volume 3’s, “2A” or “54” for instance.

points() → list[Point][source]

Its fixed-point profile: a departure at the aircraft’s default take-off weight (table C-5), an arrival at 90 % of its greatest landing weight.

acoustic_spaces.doc29.volume3.profile_cases() → tuple[ProfileCase, ...][source]

Part 2’s 26 cases: nine arrivals (table C-7) and seventeen departures (C-8).

acoustic_spaces.doc29.volume3.reference_profiles() → dict[str, tuple[Point, ...]][source]

Volume 3’s fixed-point profiles of Part 2’s cases (tables D-1 and D-2, to 0.1 ft, kt and lb), by case number.

Doc 29 with the aircraft of a copy of the ANP database (Volume 2 Appendix G), the international Aircraft Noise and Performance database, that the user has downloaded from EASA under its terms.

This package ships no ANP data: the database’s terms (EASA’s ANP Database Terms and Conditions, issue 3, 2024) allow its use only for noise contours of an average fleet and traffic and forbid passing it on, so each user downloads their own copy and accepts those terms. read_database() reads the copy’s tables from a folder, by the names of their files: “Aircraft”, “NPD”, “Spectral classes”, “Fixed point profiles”, “Jet engine coefficients”, “Propeller engine coefficients”, “Aerodynamic coefficients”, “Default weights”, “Departure procedural steps” and “Approach procedural steps”, in any case, with spaces or underscores, as CSV or text files separated by commas or semicolons.

The readers take the fields Volume 2 Appendix G lists, as Volume 3’s workbook lays them out for its hypothetical aircraft; they have not been tried on a download of the database.

acoustic_spaces.doc29.anp.TABLES = {'aerodynamic': ('aerodynamic',), 'aircraft': ('aircraft',), 'approach_steps': ('approachprocedur', 'approachstep'), 'departure_steps': ('departureprocedur', 'departurestep'), 'fixed_point_profiles': ('fixedpoint',), 'jet': ('jetengine', 'jetcoef'), 'npd': ('npd',), 'propeller': ('propeller',), 'spectral_classes': ('spectral',), 'weights': ('weight',)}

The tables, each with the words its file’s name holds (its case, spaces and punctuation aside), the first that matches taken.

acoustic_spaces.doc29.anp.find_tables(folder: str | Path) → dict[str, Path][source]

The files of the ANP tables in folder and its subfolders, by the keys of TABLES; a table without its file is left out.

class acoustic_spaces.doc29.anp.Database(aircraft: dict[str, Aircraft], npd: dict[tuple[str, str, str], NpdCurves], spectral_classes: dict[str, SpectralClass], fixed_point_profiles: dict[tuple[str, str, str, str], tuple[ProfilePoint, ...]], performance: dict[str, Performance], departure_procedures: dict[tuple[str, str, str], tuple[DepartureStep, ...]], approach_procedures: dict[tuple[str, str], tuple[ApproachStep, ...]])[source]

The tables of an ANP database (Volume 2 Appendix G), as the readers of tables and performance give them.

curves(aircraft: str, operation: str) → tuple[NpdCurves, NpdCurves][source]

The SEL and LAmax curves of aircraft on arrival (“A”) or departure (“D”).

profile(aircraft: str, operation: str, profile: str, stage: str = '1', aerodrome: Aerodrome = Aerodrome(elevation_ft=0.0, temperature_c=15.0, pressure_inhg=29.92, headwind_kt=8.0)) → tuple[ProfilePoint, ...][source]

The profile profile of aircraft on arrival (“A”) or departure (“D”), in metres: from its procedural steps where the database has them and the aircraft’s coefficients (a departure at the default weight of its stage length stage), else its fixed-point profile. Procedural steps give the corrected net thrust in lb (Appendix B): for an aircraft whose NPD curves’ power parameter is not in lb (Aircraft.power_in_lb) they are a ValueError.

acoustic_spaces.doc29.anp.read_database(folder: str | Path) → Database[source]

The ANP database whose tables are the files in folder (find_tables()); the aircraft table is needed, the others are empty when their files are missing.

An aircraft’s NPD curves adjusted to the air at the aerodrome (Doc 29 Volume 2 Appendix D).

The NPD curves and the spectral classes of the ANP database are normalised to the “AIR-1845 atmosphere”: the average attenuation rates of SAE AIR-1845, per third octave (AIR_1845_DB_PER_M, Volume 2 table D-1), a notional atmosphere of no one temperature and humidity. Appendix D adjusts the curves to another one in three steps:

  1. the aircraft’s spectral class (its spectrum 1000 ft under it at the time of the maximum level) is taken back to the source, the AIR-1845 attenuation over 1000 ft added back (eq. D-1);

  2. it is taken out to each of the ten NPD distances by spherical spreading and the attenuation of each atmosphere, AIR-1845’s and the aerodrome’s (eq. D-2, D-3);

  3. at each distance, both spectra are A-weighted and summed, and the difference between them, increments_db() (eq. D-4), is added to the NPD curves’ levels (adjusted()), the maximum levels’ and the sound exposure levels’ alike.

The aerodrome’s attenuation is ISO 9613-1’s (acoustic_spaces.air.absorption_db_per_m()), the absorption of SAE ARP-5534, the method Appendix D recommends, averaged over each third octave as a sound of flat spectrum through it loses it (band_attenuation_db()): over a long path a band’s upper frequencies are lost first, so its attenuation per metre falls as the path grows longer, as ARP-5534’s does. It gives Volume 2’s worked example (JETW’s spectral classes at 10 °C, 80 % relative humidity and 101.325 kPa, its tables D-3c and D-4) within 0.1 dB, the tables’ rounding.

acoustic_spaces.doc29.atmosphere.AIR_1845_DB_PER_M: tuple[float, ...] = (0.00033, 0.00033, 0.00033, 0.00066, 0.00066, 0.00098, 0.00131, 0.00131, 0.00197, 0.0023, 0.00295, 0.00361, 0.00459, 0.0059, 0.00754, 0.00983, 0.01311, 0.01705, 0.022949999999999998, 0.03115, 0.036070000000000005, 0.05246000000000001, 0.07213, 0.09836)

The AIR-1845 atmosphere’s attenuation rates (dB/m) per third octave of the spectral classes, 50 Hz to 10 kHz (Volume 2 table D-1, there in dB/100 m).

acoustic_spaces.doc29.atmosphere.A_WEIGHTING_DB: tuple[float, ...] = (-30.2, -26.2, -22.5, -19.1, -16.1, -13.4, -10.9, -8.6, -6.6, -4.8, -3.2, -1.9, -0.8, 0.0, 0.6, 1.0, 1.2, 1.3, 1.2, 1.0, 0.5, -0.1, -1.1, -2.5)

The A-weighting (dB) of the third octaves 50 Hz to 10 kHz (IEC 61672-1).

acoustic_spaces.doc29.atmosphere.REFERENCE_M = 304.8

The spectral classes’ distance (m), 1000 ft.

acoustic_spaces.doc29.atmosphere.adjusted(curves: NpdCurves, spectral_class: SpectralClass, temperature_c: float = 15.0, humidity_percent: float = 70.0, pressure_kpa: float = 101.325) → NpdCurves[source]

curves (an aircraft’s NPD curves of one descriptor and operation) in the air at temperature_c, humidity_percent and pressure_kpa: each level plus increments_db() of its distance, for spectral_class, the aircraft’s of that operation.

acoustic_spaces.doc29.atmosphere.band_attenuation_db(distance_m: float, temperature_c: float = 15.0, humidity_percent: float = 70.0, pressure_kpa: float = 101.325) → ndarray[source]

The attenuation (dB) of each third octave, 50 Hz to 10 kHz, over distance_m of air at temperature_c, humidity_percent and pressure_kpa: ISO 9613-1’s absorption at each frequency through the band (its edges a tenth of a decade apart), the band’s energy of a flat spectrum averaged.

acoustic_spaces.doc29.atmosphere.increments_db(spectral_class: SpectralClass, temperature_c: float = 15.0, humidity_percent: float = 70.0, pressure_kpa: float = 101.325) → ndarray[source]

What the air at temperature_c, humidity_percent and pressure_kpa adds to the NPD levels at each of NPD_FEET against the AIR-1845 atmosphere’s (dB, eq. D-1 to D-4), for an aircraft of spectral_class.

An aircraft of Doc 29 as a source of a scene: the sound power and the directivity that give its NPD curves’ levels in the engine, and its flight as a walk’s keyframes.

Doc 29 gives an aircraft’s sound as levels at receivers: its NPD curves (the maximum level and the sound exposure level at distances from 200 to 25,000 ft, at each power, in the AIR-1845 atmosphere, at 160 kt) and its spectral class (the spectrum 1000 ft under it at the time of its maximum level). The NPD curves are measured 1.2 m above flat soft ground (Volume 2 sections 2.5 and 4.5.4), so they hold that ground’s reflection. A point source of the scene that sends the same sound gets:

  • its spectrum from the spectral class, scaled to the NPD curves’ maximum level 1000 ft under the aircraft at its power, raised by what a sound level meter’s slow time weighting takes off it (sound_power_db()): Doc 29 reads its levels through that weighting (Volume 2’s glossary; IEC 61672-1’s S, a time constant of 1 s), which lags behind the passing aircraft, where the scene’s source sends its sound with none. On the NPD curves’ own pass (slow_drop_db()) it takes 0.29 dB off JETW’s loudest moment, at 160 kt in air at 15 °C and 70 % humidity;

  • its level back at the source: the AIR-1845 atmosphere’s attenuation over the 1000 ft added back (Appendix D eq. D-1), and the soft ground’s reflection taken out (ground_gain_db()): grass (Nord2000’s class D, 200 kPa s/m², Miki’s impedance) at normal incidence, its reflection’s energy added to the direct sound’s, as no coherent dip shows in the spectral classes (the first would be near 70 Hz);

  • its directivity from the engines’ installation (eq. 4-15, installation_db()), the depression angle under the wing plane measured across the flight path, the same in every band (directivity()); nought straight down, where the NPD curves are measured, so the scene’s sound power is the power below that much over (below_offset_db()).

Doc 29 gives the NPD curves no directivity along the flight path but behind a take-off roll (eq. 4-22), which the scene’s source does not hold, nor the impedance adjustment (eq. 4-6): 0.074 dB at sea level in the standard atmosphere, -0.24 dB 2000 ft up at 15 °C and -0.83 dB 5000 ft up at 30 °C. The NPD curves at the powers of a flight differ by nearly the same at every distance: the aircraft’s sound power changes with its power as the NPD curves’ maximum level 1000 ft away does (power_change_db()), its spectrum kept.

flight() turns a flight path’s segments (flight_path()) into keyframes, when the aircraft is where: along a segment its speed’s square changes evenly with the distance (a constant acceleration, as Doc 29 interpolates it), cut into legs whose speeds differ by at most LEG_SPEED_STEP_M_S, each leg timed for that acceleration. The aircraft faces the way it flies, along each segment’s heading and climb, and turns to the next one’s over its first TURN_S.

acoustic_spaces.doc29.source.LEG_SPEED_STEP_M_S = 5.0

How much the speed may change along one leg of a flight’s keyframes (m/s).

acoustic_spaces.doc29.source.MICROPHONE_M = 1.2

How high the NPD curves’ microphone is over the ground (m), Volume 2 sections 2.5 and 4.5.4, and the flow resistivity of its soft ground (kPa s/m²), taken to be grass (Nord2000’s class D, acoustic_spaces.materials.ground.PRESETS).

acoustic_spaces.doc29.source.SHORTEST_M = 0.001

A segment shorter than this (m) is passed over: where the track’s nodes and the profile’s points nearly meet (the walk’s own keyframes as a track), the flight path has segments a few micrometres long, flown in microseconds.

acoustic_spaces.doc29.source.TURN_S = 1.0

How long the aircraft takes to turn to a segment’s heading and climb (s).

class acoustic_spaces.doc29.source.Flight(times: tuple[float, ...], positions: tuple[tuple[float, float, float], ...], orientations: tuple[tuple[float, float, float], ...], speeds: tuple[float, ...], powers: tuple[float, ...])[source]

A flight as a walk’s keyframes: when (s from its start) the aircraft is where (x, y, z in m), how it faces there (yaw, pitch and roll in degrees, as a scene’s orientation), and its speed (m/s) and power there. It flies at one speed along each leg, from one keyframe to the next, and its power changes along the leg as Doc 29’s does along a segment (eq. 3-2).

power_at(times) → ndarray[source]

The power at times (s), each in its leg (eq. 3-2, the share of the leg’s length the share of its time, at one speed); the first’s before the start, the last’s after the end.

keyframes(digits: int = 4) → list[dict][source]

The keyframes after the first, as a scene’s walk takes them (the first is the source’s own position and orientation), rounded to digits.

acoustic_spaces.doc29.source.below_offset_db(installation: str) → float[source]

How far the sound power of a source with the installation’s directivity() is over the power of one that sends each way what it sends straight down (dB), where the installation correction is nought: 10 lg of its energy’s mean over the sphere, as the balloon is scaled to average 1.

acoustic_spaces.doc29.source.depression_deg(directions) → ndarray[source]

(n,) the depression angle (degrees) under the wing plane of directions (n, 3) in the aircraft’s frame (x forward, y left, z up), measured across the flight path: atan2(-z, |y|), negative above the wing plane; nought straight ahead and behind.

acoustic_spaces.doc29.source.directivity(installation: str, name: str = '')[source]

The directivity (a Balloon of octave bands) of the engines’ installation (“Wing”, “Fuselage” or a propeller’s, which has none): the installation correction each way (eq. 4-15) at its depression angle (depression_deg()), the same in every band, over its mean on the sphere.

acoustic_spaces.doc29.source.flight(segments: Sequence[Segment], step_m_s: float = 5.0) → Flight[source]

The keyframes of a flight along segments, in order, from the first’s start at 0 s (see the module): each segment at a constant acceleration, its speed’s square changing evenly with its length, cut into legs whose speeds differ by at most step_m_s; each leg’s time is its length over the mean of its ends’ speeds.

acoustic_spaces.doc29.source.ground_gain_db(temperature_c: float = 15.0) → ndarray[source]

(24,) what the soft ground under the NPD curves’ microphone adds to the sound of an aircraft 1000 ft from it straight above, per third octave of the spectral classes, 50 Hz to 10 kHz (dB): the reflection’s energy added to the direct sound’s, 1 + |Q|² (r1 / r2)², averaged over the band, Q the reflection factor of a point source’s sound off grass at normal incidence (spherical_reflection()), r1 the 1000 ft and r2 the image’s path, 2.4 m longer, in air at temperature_c.

acoustic_spaces.doc29.source.power_change_db(maximum: NpdCurves, power, reference: float) → ndarray[source]

How much louder the aircraft is at power (a number or an array) than at reference (dB): the maximum levels of its NPD curves maximum 1000 ft away.

acoustic_spaces.doc29.source.profile_between(profile: Sequence[ProfilePoint], first_m: float, last_m: float) → tuple[ProfilePoint, ...][source]

The part of profile from first_m to last_m along its ground track (m, as its distances go), its ends interpolated as Doc 29 does between two points (the height linear in the distance, the speed and the power in its square, eq. 3-2); a profile shorter than that is kept to its own ends.

acoustic_spaces.doc29.source.slow_drop_db(spectral_class: SpectralClass, temperature_c: float = 15.0, humidity_percent: float = 70.0, pressure_kpa: float = 101.325) → float[source]

How far (dB) a sound level meter’s slow time weighting lowers the loudest moment of the NPD curves’ own pass, which their maximum level is read with (Volume 2’s glossary: L_A(t) and L_Amax are measured with slow time weighting): a point source with the spectrum of spectral_class flying straight and level at 160 kt (REFERENCE_SPEED_M_S) 1000 ft right over the microphone, in a free field of air at temperature_c, humidity_percent and pressure_kpa, each third octave spreading spherically and losing the air’s attenuation over its path beyond the 1000 ft (band_attenuation_db() over 1000 ft, per metre), heard when its sound arrives; its A-weighted level as it passes over, with no time weighting, less the highest through IEC 61672-1’s slow time weighting (acoustic_spaces.parameters.time_weighted()).

acoustic_spaces.doc29.source.sound_power_db(maximum: NpdCurves, spectral_class: SpectralClass, power: float, temperature_c: float = 15.0, humidity_percent: float = 70.0, pressure_kpa: float = 101.325) → ndarray[source]

(24,) the sound power (dB re 1 pW) per third octave, 50 Hz to 10 kHz, of a point source that sends each way what the aircraft sends straight down at power: in a free field of the AIR-1845 atmosphere, 1000 ft from it, the spectrum of spectral_class at the maximum level of its NPD curves maximum there, raised by how far the slow time weighting the curves are read with lowers it (slow_drop_db(), in the scene’s air at temperature_c, humidity_percent and pressure_kpa), less the NPD’s soft ground (ground_gain_db()).

Ground-borne vibration

Ground-borne vibration from trains, trams and construction plant, and the rumble it makes in a building, by the US Federal Transit Administration’s general method.

FTA, Transit Noise and Vibration Impact Assessment Manual, FTA Report No. 0123 (September 2018): the General Vibration Assessment of its section 6.4 for trains and trams (ground_level(), indoor_db(), NOISE_DB), the construction vibration of its section 7.2 for plant (plant_ppv(), plant_level()), and the criteria of its tables 6-2 to 6-4 and 7-5.

A vibration level here is the manual’s: the rms vibration velocity in VdB, decibels re 1 micro-inch per second (25.4 nm/s). Distances are in metres, the manual’s feet converted, and speeds in km/h. The method gives the overall level at a building and the A-weighted level of the sound its room surfaces radiate, not their spectra. The manual reads its base curves as “the upper range of vibration levels from well-maintained systems”, which ground-borne vibration rarely exceeds “by more than 1 or 2 dB unless there are extenuating circumstances such as wheel- or running-surface defects” (section 6.4, step 3).

acoustic_spaces.vibration.BUILDINGS: dict[str, str] = {'large': 'a large building, its structure not known', 'large_masonry_footings': 'a large masonry building on spread footings', 'large_masonry_piles': 'a large masonry building on piles', 'light_wood_frame': 'a light wood-frame house, its structure not known', 'masonry_1_2': 'a masonry building of one or two storeys', 'masonry_3_4': 'a masonry building of three or four storeys', 'on_rock': 'a building founded on rock', 'small_masonry': 'a small masonry building, its structure not known', 'wood_frame': 'a wood-frame house'}

What each building of COUPLINGS and GENERIC is, in words.

acoustic_spaces.vibration.COUPLINGS: dict[str, float] = {'large_masonry_footings': -13.0, 'large_masonry_piles': -10.0, 'masonry_1_2': -7.0, 'masonry_3_4': -10.0, 'on_rock': 0.0, 'wood_frame': -5.0}

Table 6-12, the coupling loss of a building’s foundation to the ground (dB).

acoustic_spaces.vibration.CRITERIA: dict[int, dict[str, Criterion]] = {1: {'frequent': Criterion(vibration_vdb=65.0, noise_dba=None), 'infrequent': Criterion(vibration_vdb=65.0, noise_dba=None), 'occasional': Criterion(vibration_vdb=65.0, noise_dba=None)}, 2: {'frequent': Criterion(vibration_vdb=72.0, noise_dba=35.0), 'infrequent': Criterion(vibration_vdb=80.0, noise_dba=43.0), 'occasional': Criterion(vibration_vdb=75.0, noise_dba=38.0)}, 3: {'frequent': Criterion(vibration_vdb=75.0, noise_dba=40.0), 'infrequent': Criterion(vibration_vdb=83.0, noise_dba=48.0), 'occasional': Criterion(vibration_vdb=78.0, noise_dba=43.0)}}

Table 6-3, by land use: 1 buildings where vibration would interfere with what is done inside (moderately sensitive equipment such as optical microscopes), 2 residences and buildings where people normally sleep, 3 institutions used mostly by day; and by events (EVENT_KINDS).

acoustic_spaces.vibration.CURVES: dict[str, Curve] = {'locomotive': Curve(what='locomotive-powered passenger or freight trains', coefficients=(92.28, 14.81, -14.17, 1.65), reference_kmh=80.4672), 'rapid_transit': Curve(what='rapid transit or light rail vehicles', coefficients=(85.88, -1.06, -2.32, -0.87), reference_kmh=80.4672), 'rubber_tyred': Curve(what='rubber-tyred vehicles', coefficients=(66.08, 34.28, -30.25, 5.4), reference_kmh=48.28032)}

Table 6-9 and 6-10: the three base curves. The locomotive-powered curve is for trains hauled by diesel or electric locomotives (intercity, commuter and freight trains), the rapid transit curve for heavy and light rail vehicles, electric multiple units and streetcars, the rubber-tyred curve for a bus on a smooth road.

acoustic_spaces.vibration.DAMAGE: dict[str, Damage] = {'I': Damage(what='reinforced-concrete, steel or timber (no plaster)', ppv_in_s=0.5, level_vdb=102.0), 'II': Damage(what='engineered concrete and masonry (no plaster)', ppv_in_s=0.3, level_vdb=98.0), 'III': Damage(what='non-engineered timber and masonry buildings', ppv_in_s=0.2, level_vdb=94.0), 'IV': Damage(what='buildings extremely susceptible to vibration damage', ppv_in_s=0.12, level_vdb=90.0)}

Table 7-5: construction vibration damage criteria.

acoustic_spaces.vibration.EVENT_KINDS = ('frequent', 'occasional', 'infrequent')

Table 6-2’s kinds of events (events()).

acoustic_spaces.vibration.FARTHEST_M = 91.44

How near and how far from the track the manual draws its base curves (figure 6-4): 10 to 300 ft from the track’s centreline (m), the diagonal distance for a subway.

acoustic_spaces.vibration.FREIGHT_WAGONS_DB = -3.0

Section 6.2, step 3c: a freight train’s locomotives count as infrequent events and its wagons, which pass for minutes, as frequent ones, the locomotives “often” 3 to 8 dB higher; the wagons are taken FREIGHT_WAGONS_DB under the curve, the least of that.

acoustic_spaces.vibration.GENERIC: dict[str, float] = {'large': 0.0, 'light_wood_frame': 3.0, 'small_masonry': 3.0}

Section 6.4, step 2c: where a building’s structure is not known, the manual’s conservative change from the vibration outdoors to indoors (dB), instead of its coupling loss, floors and amplification: a light wood-frame house’s on its first floor and on its second and third, a small masonry building’s and a large building’s.

acoustic_spaces.vibration.NEAREST_M = 3.048

How near and how far from the track the manual draws its base curves (figure 6-4): 10 to 300 ft from the track’s centreline (m), the diagonal distance for a subway.

acoustic_spaces.vibration.NOISE_DB: dict[str, float] = {'high': -20.0, 'low': -50.0, 'mid': -35.0}

Table 6-14: the A-weighted sound level radiated by a room’s surfaces (dB(A)) against their vibration level, by the frequency where the ground’s vibration peaks: below 30 Hz (most surface track, subways in sandy soil, track on vibration isolation), 30 to 60 Hz (most subways, surface track on very stiff clayey soil) or above 60 Hz (subways founded in rock or very stiff clayey soil).

acoustic_spaces.vibration.PERCEPTION_VDB = 65.0

Section 5.2: “the threshold of perception for humans is approximately 65 VdB”.

acoustic_spaces.vibration.PLANT: dict[str, Plant] = {'caisson_drilling': Plant(what='caisson drilling', ppv_in_s=0.089, level_vdb=87.0), 'clam_shovel': Plant(what='a clam shovel drop (slurry wall)', ppv_in_s=0.202, level_vdb=94.0), 'hoe_ram': Plant(what='a hoe ram (a breaker on an excavator)', ppv_in_s=0.089, level_vdb=87.0), 'hydromill_rock': Plant(what='a hydromill (slurry wall) in rock', ppv_in_s=0.017, level_vdb=75.0), 'hydromill_soil': Plant(what='a hydromill (slurry wall) in soil', ppv_in_s=0.008, level_vdb=66.0), 'jackhammer': Plant(what='a jackhammer', ppv_in_s=0.035, level_vdb=79.0), 'large_bulldozer': Plant(what='a large bulldozer', ppv_in_s=0.089, level_vdb=87.0), 'loaded_trucks': Plant(what='loaded trucks', ppv_in_s=0.076, level_vdb=86.0), 'pile_driver_impact': Plant(what='an impact pile driver, typical', ppv_in_s=0.644, level_vdb=104.0), 'pile_driver_impact_upper': Plant(what='an impact pile driver, upper range', ppv_in_s=1.518, level_vdb=112.0), 'pile_driver_sonic': Plant(what='a sonic pile driver, typical', ppv_in_s=0.17, level_vdb=93.0), 'pile_driver_sonic_upper': Plant(what='a sonic pile driver, upper range', ppv_in_s=0.734, level_vdb=105.0), 'small_bulldozer': Plant(what='a small bulldozer', ppv_in_s=0.003, level_vdb=58.0), 'vibratory_roller': Plant(what='a vibratory roller', ppv_in_s=0.21, level_vdb=94.0)}

Table 7-4: averages over many sites and soils.

acoustic_spaces.vibration.RUMBLE_HZ: dict[str, float] = {'high': 125.0, 'low': 25.0, 'mid': 50.0}

Where each peak of NOISE_DB puts the rumble (Hz): the third octave whose A-weighting is the table’s adjustment less UNWEIGHTED_DB to within 1.1 dB (25 Hz -44.7 dB, 50 Hz -30.2, 125 Hz -16.1), as the manual’s note to its table 5-5 says the A-weighted level comes from A-weighting the vibration’s spectrum and taking off 5 dB for the room.

acoustic_spaces.vibration.SPECIAL_BUILDINGS: dict[str, tuple[Criterion, Criterion]] = {'auditorium': (Criterion(vibration_vdb=72.0, noise_dba=30.0), Criterion(vibration_vdb=80.0, noise_dba=38.0)), 'concert_hall': (Criterion(vibration_vdb=65.0, noise_dba=25.0), Criterion(vibration_vdb=65.0, noise_dba=25.0)), 'recording_studio': (Criterion(vibration_vdb=65.0, noise_dba=25.0), Criterion(vibration_vdb=65.0, noise_dba=25.0)), 'theatre': (Criterion(vibration_vdb=72.0, noise_dba=35.0), Criterion(vibration_vdb=80.0, noise_dba=43.0)), 'tv_studio': (Criterion(vibration_vdb=65.0, noise_dba=25.0), Criterion(vibration_vdb=65.0, noise_dba=25.0))}

Table 6-4, special buildings: frequent events, then occasional or infrequent ones.

acoustic_spaces.vibration.UNWEIGHTED_DB = -5.0

The manual’s unweighted sound pressure level of the rumble against the room surfaces’ vibration level (dB): “approximately 5 dB” less (section 6.4, step 2d).

class acoustic_spaces.vibration.Criterion(vibration_vdb: float, noise_dba: float | None)[source]

An impact criterion: the indoor vibration (VdB) and ground-borne noise (dB(A), or None where the manual gives none) above which there is impact.

class acoustic_spaces.vibration.Curve(what: str, coefficients: tuple[float, float, float, float], reference_kmh: float)[source]

A base curve of the ground’s vibration (table 6-10): the overall rms vibration level at the ground’s surface D feet from the track, a0 + a1 x + a2 x^2 + a3 x^3 with x = log10(D), for vehicles in good condition at reference_kmh on welded track at grade, with normal propagation through soil; drawn from 10 to 300 ft (NEAREST_M, FARTHEST_M), and fitted with these equations only there.

level(distance_m: float, speed_kmh: float | None = None, extend: bool = False) → float[source]

The level (VdB) distance_m from the track, at speed_kmh (eq. 6-4) or at the curve’s own speed; a ValueError nearer or farther than the manual draws the curve, unless extend: then nearer it holds its value at NEAREST_M, and farther it goes on falling as it falls at FARTHEST_M (straight on in log10 of the distance; the cubics themselves turn back up there).

levels(distances_m, speed_kmh: float | None = None) → ndarray[source]

level() at each of distances_m (m), extended as extend does.

class acoustic_spaces.vibration.Damage(what: str, ppv_in_s: float, level_vdb: float)[source]

A category of building and the peak particle velocity (in/s) from which plant may damage it (table 7-5), with the rms level the manual gives for it (VdB).

class acoustic_spaces.vibration.Line(vehicles: str = 'good', track: str = 'good', special_trackwork_m: float | None = None, treatment: str = 'none', structure: str = 'at_grade', ground: str = 'normal')[source]

What the manual adjusts its base curve for, at the source and along the path (tables 6-11 and 6-12): the vehicles, the track, its treatment and structure, and the ground.

special_trackwork_m: float | None = None

The distance from the nearest turnout or crossover (m), or None for none near.

source_db() → float[source]

Table 6-11’s adjustment for the vehicles, the track and its treatment (dB): the vehicles’ and the track’s added, but only the greater of the two when the track is worn or corrugated, as the manual says.

path_db(distance_m: float) → float[source]
path_db(distance_m: ndarray) → ndarray

Table 6-12’s adjustment for the structure and the ground, distance_m from the track (dB), a number or an array of them.

class acoustic_spaces.vibration.Plant(what: str, ppv_in_s: float, level_vdb: float)[source]

A piece of construction plant’s vibration 25 ft away (table 7-4): its peak particle velocity (in/s) and its rms vibration level (VdB), which the manual takes 12 dB under the peak (a crest factor of 4).

acoustic_spaces.vibration.criterion(use: int | str, kind: str) → Criterion[source]

The criterion for the land use use (1, 2 or 3, CRITERIA, or a special building, SPECIAL_BUILDINGS) and events of kind (one of EVENT_KINDS).

acoustic_spaces.vibration.distance_for(level: Callable[[float], float], limit: float, near_m: float, far_m: float) → float | None[source]

The distance (m) between near_m and far_m beyond which level (of the distance, falling with it) stays at or under limit: near_m when it is under all along, None when it is over all along.

acoustic_spaces.vibration.events(per_day: float) → str[source]

Table 6-2: per_day events are frequent above 70 a day, occasional from 30 to 70, infrequent under 30.

acoustic_spaces.vibration.floors_db(floor: int) → float[source]

Table 6-13’s attenuation (dB) up to floor, counted from 1 above the basement, as the manual’s first floor assumes one: 2 dB a floor up to the fifth, 1 dB a floor from there up to the tenth.

acoustic_spaces.vibration.ground_level(curve: str, distance_m: float, speed_kmh: float, line: Line | None = None) → float[source]

The overall vibration level (VdB) at the ground’s surface distance_m from the track, of vehicles on the base curve curve (CURVES) at speed_kmh, with the adjustments of line (none by default): what reaches a building’s foundation.

acoustic_spaces.vibration.horizontal_distance(point: Sequence[float], path: Sequence[Sequence[float]], closed: bool = False) → float[source]

The distance (m) in plan from point (x, y[, z]) to the nearest point of path, a line through (x, y[, z]) points, or the outline of a footprint when closed.

acoustic_spaces.vibration.horizontal_distances(points, path, closed: bool = False) → ndarray[source]

(n,) horizontal_distance() of each of points (n, 2 or 3).

acoustic_spaces.vibration.indoor_db(building: str, floor: int = 1) → float[source]

The change in vibration level (dB) from the ground outside building to its floor. For one of COUPLINGS, its foundation’s coupling loss, the attenuation up to the floor and the floors’ amplification (tables 6-12 and 6-13): the first floor of a wood-frame house gives -5 - 2 + 6 = -1 dB, as the manual’s own example says. For one of GENERIC, the manual’s conservative change where the structure is not known; a light wood-frame house’s is given for its first three floors only.

acoustic_spaces.vibration.level_of(ppv_in_s: float, crest_db: float = 12.0) → float[source]

The rms vibration level (VdB) of a peak particle velocity (in/s), crest_db under it: the manual’s tables 7-4 and 7-5 take a crest factor of 4 (12 dB).

acoustic_spaces.vibration.mm_s(in_s: float) → float[source]

A velocity in inches a second, in millimetres a second.

acoustic_spaces.vibration.nearest_points(points, path, closed: bool = False) → ndarray[source]

(n, 2) the point of path (as horizontal_distance() takes it) nearest each of points (n, 2 or 3), in plan.

acoustic_spaces.vibration.noise_level(vibration_vdb: float, peak: str = 'low') → float[source]

The ground-borne noise (dB(A)) of a room whose surfaces vibrate at vibration_vdb, the ground’s vibration peaking at peak (NOISE_DB).

acoustic_spaces.vibration.plant_level(plant: str, distance_m: float) → float[source]

Eq. 7-3: the rms vibration level (VdB) distance_m from plant, Lv - 30 log10(D / 25 ft).

acoustic_spaces.vibration.plant_ppv(plant: str, distance_m: float) → float[source]

Eq. 7-2: the peak particle velocity (in/s) distance_m from plant (PLANT), PPV (25 ft / D)^1.5, a point source with normal propagation.

acoustic_spaces.vibration.speed_db(speed_kmh: float, reference_kmh: float) → float[source]

Eq. 6-4: the change in vibration level with speed, 20 log10(speed / reference).

Sound through a façade

The sound outdoors heard in a room behind a closed window: a façade’s level difference by EN ISO 12354-3, for the pass-by demos’ houses.

EN ISO 12354-3:2017 gives a façade’s standardized level difference, from the level 2 m in front of it to the room behind it at the reference reverberation time T0 = 0.5 s, per band as

D_2m,nT = R’ + ΔL_fs + 10 lg(V / (6 T0 S)),

R’ the façade’s apparent sound reduction index, S its area as the room sees it, V the room’s volume, ΔL_fs what the façade’s shape adds (none for a flat one). The level 2 m in front of the façade, L_2m, holds the façade’s own reflection. The pass-by demos and the road works demo simulate it there, the house standing in the scene: at a listener that stands 2 m in front of the wall, or else at one more listener at the point 2 m in front of it, square to it, at the listener’s height (acoustic_spaces.demos.indoors.with_fronts()). The room’s level is

L_room = L_2m - D_2m,nT.

Here the closed window is the façade’s only path: R’ S is the window’s R over its own area (the area cancels), so the room hears L_2m - R - 10 lg(V / (6 T0 S_window)). The wall round it, a masonry one, lets through far less, and is left out; so are the window’s frame and seals and any vent, so the room is as quiet as the glazing lets it be.

acoustic_spaces.facade.GLAZING_R_DB = (20.5, 16.8, 25.7, 36.4, 41.4, 36.5)

AGC Glass Europe’s THERMOBEL 4-16-4, double glazing of two 4 mm panes 16 mm apart: its sound reduction index per octave band from 125 Hz to 4 kHz (dB), measured by EN ISO 10140 on a pane of 1.23 by 1.48 m, Rw (C; Ctr) = 30 (-1; -4) dB, “not better than +/- 1 dB” (AGC, Performances: Planibel, Stratobel, Stratophone, Thermobel, 9000625 EN, 05/18).

acoustic_spaces.facade.HOUSE = Facade(what='a living room of 50 m³ behind a closed window of 4-16-4 double glazing, 1.82 m²', reduction_db=(14.55, 20.5, 16.8, 25.7, 36.4, 41.4, 36.5, 36.5), window_m2=1.8204, volume_m3=50.0)

The pass-by demos’ house: a living room of 50 m³ (5 by 4 m, 2.5 m high) behind a masonry wall with one window of the double glazing AGC measured, as large as its pane (1.82 m²), closed.

acoustic_spaces.facade.PANE_M = (1.23, 1.48)

The pane AGC measured (m): its width and height.

acoustic_spaces.facade.REFERENCE_DB = (36.0, 45.0, 52.0, 55.0, 56.0)

ISO 717-1’s reference values for airborne sound insulation in octave bands, 125 Hz to 2 kHz (dB), and its spectra No. 1 (pink noise, C) and No. 2 (urban traffic, Ctr), A- weighted and normalised to 0 dB overall.

acoustic_spaces.facade.T0_S = 0.5

EN ISO 12354-3’s reference reverberation time of a room (s): a furnished dwelling’s.

class acoustic_spaces.facade.Facade(what: str, reduction_db: tuple[float, ...], window_m2: float, volume_m3: float)[source]

A room behind a façade whose closed window is its only way in: the window’s sound reduction index per octave band (reduction_db, 8 bands from 63 Hz), its area and the room’s volume, at the reference reverberation time T0_S.

property room_term_db: float

EN ISO 12354-3’s 10 lg(V / (6 T0 S)) of the room and the window (dB).

level_difference() → ndarray[source]

(8,) the standardized level difference D_2m,nT per octave band (dB).

indoor_db() → ndarray[source]

(8,) the room’s level less the level 2 m in front of the façade, its reflection included, per octave band (dB): -D_2m,nT.

gains() → ndarray[source]

(8,) the amplitude gain per octave band from 2 m in front of the façade to the room.

acoustic_spaces.facade.glazing_r_db() → ndarray[source]

(8,) the double glazing’s sound reduction index in the 8 octave bands, 63 Hz to 8 kHz (dB): AGC’s measured values (GLAZING_R_DB); at 63 Hz the 125 Hz value less the mass law’s 6 dB an octave, as below the panes’ resonance on the air between them (some 210 Hz for this unit) they move as one; at 8 kHz the 4 kHz value, where the panes’ coincidence dip is (near 3 kHz for 4 mm glass), above which the index rises again.

acoustic_spaces.facade.weighted(reduction_db) → tuple[int, int, int][source]

ISO 717-1’s single numbers of a sound reduction index in the five octave bands 125 Hz to 2 kHz: (Rw, C, Ctr), the reference curve shifted in 1 dB steps as high as it goes with its unfavourable deviations summing to 10 dB at most, Rw its value at 500 Hz, and the adaptation terms against the two spectra, rounded to whole dB.

Head tracking

Head tracking: binaural playback of an Ambisonics response that turns with the listener’s head, so the sources stay where they are in the room.

A simulated AmbiX response holds the sound field at the listener, arriving from every direction. HeadTrackedBinaural runs a dry signal through it in real time, turns the field against the head’s latest orientation once per block (crossfading from the previous orientation over the block, so turning does not click) and decodes it to the two ears with binaural_decoder().

The orientation lives in a HeadOrientation, which anything may set: the editor’s controls, a script, or a head tracker sending OSC over UDP to an OscReceiver. The receiver reads the messages head trackers commonly send, whatever comes before the last part of the address (/ypr and /SceneRotator/ypr alike):

  • .../ypr: yaw, pitch and roll in degrees;

  • .../quaternion, .../quaternions or .../quat: w, x, y and z;

  • .../yaw, .../pitch or .../roll: one angle in degrees.

Angles follow the scene’s convention: yaw turns left, pitch looks up and roll tilts the head to the right. A tracker that counts an axis the other way round needs that axis in invert.

acoustic_spaces.headtracking.AXES = ('yaw', 'pitch', 'roll')

The axes of a head orientation, as invert names them.

acoustic_spaces.headtracking.DEFAULT_OSC_PORT = 9000

UDP port OscReceiver listens on unless told otherwise.

acoustic_spaces.headtracking.QUATERNION_ADDRESSES = ('quaternion', 'quaternions', 'quat')

Last parts of OSC addresses that carry a quaternion.

class acoustic_spaces.headtracking.HeadOrientation(invert: Iterable[str] = ())[source]

The listener’s head orientation, set from one thread and read from another.

invert names the axes ("yaw", "pitch", "roll") whose incoming angles count the other way round. centre() takes the current orientation as straight ahead; rotation() and angles() are relative to it.

set_angles(yaw: float | None = None, pitch: float | None = None, roll: float | None = None) → None[source]

Yaw, pitch and roll in degrees; an angle left out keeps its last value. Angles that are not finite numbers are ignored.

set_quaternion(w: float, x: float, y: float, z: float) → None[source]

The orientation as a quaternion (normalised first) in the scene’s axes: x forward, y left, z up.

look(yaw: float = 0.0, pitch: float = 0.0, roll: float = 0.0) → None[source]

Turn the head to yaw, pitch and roll in degrees relative to the centre, as angles() gives them back (invert does not apply).

centre() → None[source]

Take the current orientation as straight ahead.

rotation() → tuple[int, ndarray][source]

(version, rotation (3, 3)) of the head relative to the centre. The version counts the changes, so a reader can tell when to look again.

angles() → tuple[float, float, float][source]

Yaw, pitch and roll in degrees relative to the centre.

class acoustic_spaces.headtracking.HeadTrackedBinaural(ir: ndarray, sample_rate: float, *, hrtf: HRTF | None = None, orientation: HeadOrientation | None = None, block: int = 256, decoder: str = 'magls')[source]

A dry signal through an Ambisonics response, turned against the head and decoded to the two ears, one block at a time.

ir is (taps, channels) AmbiX (ACN / SN3D) of order 1 to 7, at sample_rate, as the simulator renders it for a listener: directions relative to the listener’s orientation in the scene, which head tracking then turns from. hrtf defaults to the spherical head model and is resampled to sample_rate; decoder is "magls" or "ls" (see binaural_decoder()). orientation (a new HeadOrientation by default) is read once per block. It works with acoustic_spaces.render.play() as a Convolver does, with one input and two outputs, and the only latency is the block.

process(block: ndarray, out: ndarray | None = None) → ndarray[source]

One block (block,) of the dry signal to (block, 2) float32, into out when given, as Convolver.process takes it. The buffers the size of a block are kept from block to block.

run(signal: ndarray, head: Callable[[float], tuple[float, float, float]] | None = None) → ndarray[source]

A whole signal (samples,) through the renderer: (samples + taps - 1, 2).

head gives the yaw, pitch and roll in degrees at a time in seconds, relative to the centre as HeadOrientation.look() takes them (invert does not apply); it is asked at the start of every block. Without it, the orientation stays as it is.

reset() → None[source]

Forget all past input.

class acoustic_spaces.headtracking.OscReceiver(orientation: HeadOrientation, port: int = 9000, host: str = '127.0.0.1')[source]

Sets orientation from the OSC messages arriving on UDP port of host (0 picks a free port; port says which), in a background thread.

The default host takes messages from this computer only; "0.0.0.0" takes them from the network too, as from a phone. Use the receiver as a context manager, or call start() and stop().

received

Messages that set the orientation.

rejected

Packets that were not OSC.

stop() → None[source]

Stop listening and free the port.

acoustic_spaces.headtracking.apply_osc(orientation: HeadOrientation, address: str, arguments: list) → bool[source]

Set orientation from one OSC message (see the module’s description); False when the message is not about the head’s orientation.

acoustic_spaces.headtracking.parse_osc(packet: bytes, _depth: int = 0) → list[tuple[str, list]][source]

The messages (address, arguments) of an OSC packet, with bundles unpacked.

Reads 32-bit floats and integers, doubles, 64-bit integers, strings and the argument-less types (true, false, nil, infinity); anything else, or a malformed packet, raises ValueError.

Measurement

Measuring impulse responses with exponential sine sweeps.

The usual chain is: generate an excitation (Sweep), play it through a loudspeaker while recording one or more microphones, deconvolve the recording into an impulse response, then analyse it with acoustic_spaces.parameters, the same code that analyses simulated responses.

  • Sweep is a synchronized exponential sweep (Novak et al., 2015): its harmonic distortion lands in separate impulse responses before the linear one, so deconvolution leaves the linear response clean. The excitation repeats the sweep with silence after each one, long enough for the room to decay.

  • deconvolve() divides spectra with Kirkeby regularisation outside the swept band, then averages the repeats, which lowers background noise by 3 dB per doubling.

  • measure() plays and records through sounddevice (the measure extra) and returns the deconvolved responses. A loopback channel (an output wired straight back to an input) removes the latency of the audio interface.

Rules of thumb: make the silence after each sweep longer than the reverberation time, and the sweep itself about ten times longer than the reverberation time if distortion products must not overlap the linear response at all.

class acoustic_spaces.measurement.Measurement(impulse_responses: ndarray, sample_rate: int, recording: ndarray, sweep: Sweep, latency_s: float | None = None)[source]

Measured impulse responses, one column per microphone.

latency_s: float | None = None

Round-trip latency removed using the loopback channel (s), or None.

class acoustic_spaces.measurement.Sweep(sample_rate: int = 48000, duration_s: float = 6.0, f_start: float = 20.0, f_stop: float = 20000.0, level_db: float = -6.0, silence_s: float = 3.0, repeats: int = 1, fade_in_s: float = 0.05, fade_out_s: float = 0.005)[source]

An exponential sine sweep excitation, repeated with silence after each sweep.

property rate: float

L of x(t) = sin(2 pi f_start L exp(t / L)), rounded so that harmonics stay in phase with the fundamental (the synchronized sweep).

property sweep_length: int

Samples in one sweep (the duration after synchronization).

property period: int

Samples from one sweep’s start to the next.

harmonic_delay_s(order: int) → float[source]

How far before the linear response the order-th harmonic’s response lands.

sweep() → ndarray[source]

One sweep, faded in and out.

signal() → ndarray[source]

The whole excitation: every repeat, each followed by its silence.

save(path: str | Path) → None[source]

Write the excitation as a float WAV and its settings next to it as JSON.

classmethod load(path: str | Path) → Sweep[source]

Read the settings of a saved excitation (its .json, or the .wav next to it).

acoustic_spaces.measurement.deconvolve(recording: ndarray, sweep: Sweep, length_s: float | None = None, reference: ndarray | None = None) → ndarray[source]

Impulse responses (samples, channels) from a recording of sweep.signal().

recording is (samples,) or (samples, channels), starting when playback started. Each repeat is deconvolved and the repeats are averaged. length_s defaults to the silence after each sweep, and a longer one is cut. With repeats, it is cut to the silence: the next sweep’s harmonic distortion lands right after it. With one sweep, it is cut to the recording’s length less the sweep’s, beyond which the recording lacks the response’s high frequencies; for a recording as long as the excitation, that is the silence too. reference replaces the generated sweep, for instance with a loopback recording of one sweep: (samples,) or (samples, 1), as read_wav() gives a mono file.

acoustic_spaces.measurement.list_devices() → str[source]

The audio devices sounddevice sees, as text.

acoustic_spaces.measurement.measure(sweep: Sweep, *, inputs: Sequence[int] = (1,), output: int = 1, loopback: int | None = None, device: object = None, length_s: float | None = None, play_record: Callable[[ndarray, int, Sequence[int], Sequence[int], object], ndarray] | None = None) → Measurement[source]

Play sweep on one output, record inputs and deconvolve them.

Channels are 1-based. With loopback (an input wired to the output), the latency of the audio interface is measured on it and removed from every response. play_record replaces the audio device, for tests or other audio back ends.

acoustic_spaces.measurement.play_and_record(signal: ndarray, sample_rate: int, outputs: Sequence[int], inputs: Sequence[int], device: object = None) → ndarray[source]

Play signal on the output channels and record the inputs (1-based channels).

Returns (samples, len(inputs)), as long as the signal.

acoustic_spaces.measurement.remove_latency(responses: ndarray, loopback: int) → tuple[ndarray, int][source]

Move responses (samples, channels) earlier by the delay of a loopback channel.

loopback is the 0-based column of the loopback response, which is dropped. Returns the other columns, padded with zeros at the end, and the delay in samples.

Comparing with measurements

Comparing a simulated response with a measured one, by the parameters of ISO 3382-1.

A model is checked against the room it stands for by comparing its parameters with those measured there, octave band by octave band, in just noticeable differences (JNDs, ISO 3382-1:2009, annex A, table A.1, and annex B for IACC; by analogy for T20, T30 and C50, see JND): a difference of less than one JND is too small to be heard.

Both give a Comparison: per parameter and band the simulated and the measured value, their difference and that difference in JNDs; and per parameter, how many bands are within one JND and the mean absolute difference in JNDs from 125 Hz to 4 kHz. A band where either side has no value is missing, with the reason, never zero: a response that decays by less than 20 dB, a decay time whose range does not clear the background noise, G without a reference on both sides, or a band above half a response’s sample rate.

acoustic_spaces.compare.CONVERGED_JND = 0.5

The standard error, in JNDs, past which more rays would be worth tracing: the parameter would change by about a JND or more between runs with other seeds.

acoustic_spaces.compare.JND: dict[str, tuple[float, bool]] = {'c50': (1.0, False), 'c80': (1.0, False), 'd50': (0.05, False), 'edt': (0.05, True), 'g': (1.0, False), 'iacc_e': (0.075, False), 'iacc_l': (0.075, False), 'lf': (0.05, False), 'lfc': (0.05, False), 't20': (0.05, True), 't30': (0.05, True), 't30_x': (0.05, True), 't30_y': (0.05, True), 't30_z': (0.05, True), 'ts': (0.01, False)}

Just noticeable differences per parameter: the JND, and whether it is a fraction of the measured value (the decay times) rather than a step in the parameter’s own unit (dB, s, or none for D50, LF, LFC and IACC). ISO 3382-1:2009 gives those of EDT, C80, D50, Ts, G and LF (annex A, table A.1) and of IACC (annex B); T20 and T30 take EDT’s and C50 takes C80’s by analogy, and the directional decay times take that of T30. The standard gives none for LJ and stage support, which are not compared.

acoustic_spaces.compare.SUMMARY_BANDS_HZ: tuple[int, ...] = (125, 250, 500, 1000, 2000, 4000)

The octave bands the mean difference of each parameter is taken over (Hz).

class acoustic_spaces.compare.Comparison(simulated: RoomParameters, measured: RoomParameters, parameters: dict[str, ParameterComparison])[source]

A simulated and a measured response compared parameter by parameter.

simulated and measured are the parameters of each side, and parameters a ParameterComparison for each name of PARAMETERS, and of those further ones with a JND that both sides give, which indexing gives as well: comparison["t30"].difference_jnd.

as_dict() → dict[source]

Plain lists and numbers, with None for missing values (JSON friendly).

table() → str[source]

A text table: per parameter, the simulated and the measured value in each band and their difference in JNDs, marked * where it is more than one; then why the bands shown as - cannot be compared.

summary() → str[source]

A text table: per parameter, how many of the compared bands are within one JND, and the mean absolute difference in JNDs from 125 Hz to 4 kHz.

class acoustic_spaces.compare.ParameterComparison(name: str, simulated: ndarray, measured: ndarray, jnd: ndarray, difference: ndarray, difference_jnd: ndarray, missing: list[str | None])[source]

One parameter of a simulated and a measured response, one value per octave band.

difference is the simulated value minus the measured one, and difference_jnd the same in JNDs, so both are positive where the simulation reads higher. They are NaN in the bands that cannot be compared; missing holds the reason for each of those, and None for the bands that are compared.

jnd: ndarray

The JND in each band, in the parameter’s unit (NaN for a relative JND where there is no measured value to take it of).

property compared: int

How many bands have a value on both sides.

property within_jnd: int

How many of the compared bands are at most one JND apart.

property mean_abs_jnd: float

Mean absolute difference in JNDs over the compared bands from 125 Hz to 4 kHz (SUMMARY_BANDS_HZ); NaN when none of them is compared.

acoustic_spaces.compare.compare_impulse_responses(simulated: ndarray, simulated_rate: float, measured: ndarray, measured_rate: float, *, simulated_reference: float | Sequence[float] | None = None, measured_reference: float | Sequence[float] | None = None, filters: str = 'iec', noise: bool = True) → Comparison[source]

Compare a simulated and a measured impulse response, each at its own sample rate.

Each is mono, (samples,) or (samples, 1), and analysed as by from_impulse_response() with the same filters and noise settings. The references are those of its reference_energy: the energy of the same source at 10 m in free field, per band or of a broadband impulse (0.01 for responses made by this package, 0.01 * ir_gain**2 for those written with normalize). G is compared only where both sides have one; without, it is missing in every band. A band at or above half a response’s sample rate is missing (see from_impulse_response()).

acoustic_spaces.compare.compare_parameters(simulated: RoomParameters, measured: RoomParameters, *, simulated_rate: float | None = None, measured_rate: float | None = None) → Comparison[source]

Compare two sets of parameters, one value per octave band of OCTAVE_BANDS_HZ.

NaN values are missing bands, whose reason is read from the parameters themselves: a band with no parameter at all lies above half the sample rate of its response (when simulated_rate or measured_rate, in Hz, gives it) or else decays by less than 20 dB, G alone is NaN without a reference, and a decay time alone when the decay does not reach the bottom of its fit range (compare_impulse_responses() also tells when the noise is in the way). LF, LFC, IACC and the directional decay times are compared where both sides give them.

acoustic_spaces.compare.in_jnds(values: RoomParameters, errors: RoomParameters) → dict[str, ndarray][source]

errors of values (such as their standard errors, standard_errors()) in JNDs, for each parameter with a JND, per octave band; a relative JND is taken of the value itself. NaN where either is undefined.

Fitting materials to measurements

Material calibration: absorption fitted to the parameters measured in a room.

A model of an existing room starts from absorption coefficients out of tables, which seldom match the room as built. calibrate() adjusts the absorption of the materials named, octave band by octave band, until the simulated parameters (T30, EDT and C80 by default) at each measured source and listener pair come as close as they can to those measured, in just noticeable differences (ISO 3382-1, annex A, and by analogy for T30; see JND).

It does not trace the room again for every trial. Each round traces it once, keeping the reflections each ray had off each material (reweight); the responses for other absorption then come from re-weighting those rays, so a least-squares fit per band (scipy.optimize.least_squares()) costs little more than computing the parameters. The next round traces again at the absorption found, until it moves by less than tolerance; a last trace gives the parameters reported after the fit.

Measurements seldom pin down every material: what they fix best is the total absorption, and two surfaces that the sound meets in much the same way (a ceiling and a floor of a flat room, say) trade absorption freely. So the materials keep their proportions unless the measurements ask otherwise: the fit is free to scale every material’s absorption by a common factor, but a material that moves by a factor more than the others costs as much as missing a parameter, one JND for each factor of PRIOR_FACTOR. Without measurements that tell the materials apart this is the fit of a single factor per band, as fitting a diffuse-field formula to the reverberation time does. Calibration.uncertainty says, per material and band, how far its absorption could move, the other materials following it, before the sum of the squared misses grows by one JND squared (its standard error): what the measurements leave open.

acoustic_spaces.calibration.DEFAULT_PARAMETERS: tuple[str, ...] = ('t30', 'edt', 'c80')

The parameters fitted unless others are named.

acoustic_spaces.calibration.PRIOR_FACTOR = 2.0

A material whose absorption moves by this factor more than the others’ does costs as much as missing one parameter by one JND.

class acoustic_spaces.calibration.Calibration(scene: ~acoustic_spaces.scene.model.Scene, materials: list[str], parameters: tuple[str, ...], initial: ~numpy.ndarray, absorption: ~numpy.ndarray, uncertainty: ~numpy.ndarray, measured: dict[tuple[str, str], ~acoustic_spaces.parameters.RoomParameters], before: dict[tuple[str, str], ~acoustic_spaces.parameters.RoomParameters], after: dict[tuple[str, str], ~acoustic_spaces.parameters.RoomParameters], rounds: int, bands_hz: tuple[int, ...] = (63, 125, 250, 500, 1000, 2000, 4000, 8000), details: dict[str, float] = <factory>)[source]

What calibrate() found: the absorption per material and octave band, and the parameters before and after, against those measured.

uncertainty: ndarray

(materials, bands) the standard error of each material’s absorption, for misses of one JND: how far it can move, the others following it, before the sum of the squared misses grows by one JND squared. It is what the measurements leave open. Above 0.1 or so they hardly constrain it.

fitted_scene() → Scene[source]

A copy of the scene with the fitted absorption.

errors(which: str = 'after') → dict[str, ndarray][source]

Per fitted parameter, the mean absolute difference from the measurements in JNDs per band over the pairs (NaN where no pair has both values); which is “before” or “after”.

table() → str[source]

The fitted absorption, what it started from, its uncertainty and the errors before and after, as text.

acoustic_spaces.calibration.calibrate(room: Room | Scene | str | Path, measured: Mapping[tuple[str, str], RoomParameters], materials: Sequence[str] | None = None, *, parameters: Sequence[str] = ('t30', 'edt', 'c80'), rounds: int = 4, bounds: tuple[float, float] = (0.01, 0.99), tolerance: float = 0.01, threads: int | None = None, progress: Callable[[str], None] | None = None) → Calibration[source]

Fit the absorption of materials (default: every material on a surface but openings, at most 16) so that the simulated parameters (edt, t20, t30, c50, c80, d50, ts and g) match those measured at each (source, listener) pair of the scene, band by band, in JNDs.

The scene’s simulation settings (rays, response length, seed, and threads unless threads is given) are used, with stochastic ray tracing in octave bands and no wave solver. At most rounds traces at new absorption are made; it stops sooner once no value moves by more than tolerance. Absorption stays within bounds (the lower one above 0, as the prior takes the logarithm of the absorption), and above what a material lets through.

acoustic_spaces.calibration.with_absorption(scene: Scene, materials: Sequence[str], absorption: ndarray) → Scene[source]

A copy of scene whose materials take absorption (materials, octave bands), as calibrated to measurements (with_absorption()).

Re-weighting a traced response for new absorption, without tracing it again.

The energy of every arrival is what left the source that way times, at each reflection, the share the surface reflects, 1 - a, and factors that do not depend on the absorption (scattering, air, the source’s directivity, what a partition lets through). With other absorption a’, the same paths bring each arrival times the product over its reflections of (1 - a’) / (1 - a). The paths themselves need not be traced again: where a ray goes depends on the scattering, not on the absorption. (Russian roulette and splitting chose rays by their energies, but those choices only weight the estimate; it stays unbiased.) An early reflection off a ground with an impedance is not of this kind: it takes the impedance’s reflection factor in place of 1 - a, and that impedance cannot change without tracing again (reweighted_result()). Nor quite one off a ground with zones, which takes the factors of the grounds its Fresnel zone covers and is re-weighted as off the ground it meets alone. With source and listener 0.5 and 1.5 m high and 30 m apart, and a zone without an impedance taken from an absorption of 0.1 to 0.2, a reflection half a metre inside the zone’s edge falls by 0.5 dB re-weighted and by 0.13 to 0.20 dB traced again; half a metre outside it, by none and by 0.11 to 0.16 dB. Nor is the path of the solver for whole rows (row_paths): it reflects off no face, and its sound depends on the absorption of a ground without an impedance through the admittance fitted to it. A result with such a path is not re-weighted for another absorption of such a ground (reweighted_result()); a spread’s draws and a calibration’s fits, which re-weight response by response, leave that path as it was traced.

The other early paths carry the faces they reflect off, so their energies re-weight exactly. Where they add in pressure (coherent), a reflection also shifts the phase, by that of its reflection factor, which comes from the admittance fitted to its face’s absorption and the angle it meets the face at; the paths keep those angles (cosines), so their phases turn to the new absorption’s exactly too (turned_paths()). Of a diffracted path only the reflections on its way count, not the faces of the edge it bends round, nor how it interferes with the reflection it shades. The late part’s arrivals are far too many to keep, so the tracer sums, per listener and slot of MOMENT_STEP, the energy times the reflections each ray has had off each group of faces and their products (stochastic_energy() with groups): the energy-weighted mean mu and covariance C of the counts n in the slot. With l_i = ln((1 - a’_i) / (1 - a_i)) for group i, a slot’s energy becomes E exp(K), K = ln of the mean of exp(n . l) over its arrivals, which mu and C give to second order in l as mu . l + 1/2 l’ C l. That form alone holds near the traced absorption only: for much more absorption its square term outgrows the first and the energy rises again, without bound. moment_exponent() takes instead the form the counts of a diffuse field lead to. There a ray’s N reflections fall on the groups by chance (a multinomial), and with u_i = exp(l_i) - 1, the change of what group i reflects,

K = N ln(1 + sum_i mu_i u_i / N),

which is Eyring’s decay for the new absorption over that for the old. N comes from the covariance: 1 / N = -mu’ F mu / (mu . mu)^2 with F = C - diag(mu), which is -mu mu’ / N for a multinomial. It is held within plus and minus one over the sum of mu: a ray has had at least the reflections the groups count, and counts that spread wider than by chance make it negative. What of the covariance it leaves, R = F + mu mu’ / N, adds 1/2 w’ R w, with w_i = u_i for more absorption and l_i for less. K is then the same to second order in l as the form above, exact for the same absorption and for counts that fall by chance, and held to what holds for any counts: at least mu . l (Jensen’s inequality), and no gain where no group reflects more. Further from the traced absorption it stays an estimate from two moments. In a box of 8 by 6 by 3.5 m traced with a ceiling that absorbs 0.5 (20 000 rays, at 1 kHz), the late part’s decay time for a ceiling of 0.9 is within 1 % of tracing again, for 0.99 within 5 %, and for 0.1 it is 6 % too short; with a ceiling of 0.85 taken to 0.2, 16 % too short. So calibrate() traces again at the absorption it arrives at. Its fit within a round keeps the early paths’ phases as traced, which that next trace turns.

class acoustic_spaces.engine.reweight.Redraws(paths: EarlyReflections, face_group: ndarray, groups: int, old: ndarray, admittance_of=None)[source]

What re-weighting the early paths paths of one traced response (reweighted()) for draw after draw of the absorption of groups groups of faces (face_group) takes that does not depend on the draw: how often each path reflects off each group (path_counts()); for each set of groups a draw changes, the reflections turned_paths() turns and the phases of the absorption old as traced that it turns them from, with admittance_of; and what the coherent bands’ echograms of the draws share (delays, a SameDelays). A draw comes out the same with it as without it: for other paths, groups, traced absorption or admittances than its own, each is worked out as without it. Made from its arguments alone, for one response’s draws, and dropped after them.

counts(paths: EarlyReflections, face_group: ndarray, groups: int) → ndarray[source]

path_counts() of these arguments (read-only).

turned(paths: EarlyReflections, face_group: ndarray, old: ndarray, new: ndarray, admittance_of=None) → EarlyReflections[source]

turned_paths() of these arguments, for paths that are this one’s re-weighted (reweighted_paths()).

acoustic_spaces.engine.reweight.cannot_reweight(room, settings=None) → str | None[source]

Why a run of room with settings (default the scene’s) cannot be re-weighted for other absorption, in words that follow “it needs”, or None when it can: another late method, third-octave bands, the wave solver, or more than MAX_GROUPS materials on its surfaces.

acoustic_spaces.engine.reweight.face_groups(room, materials: Sequence[str]) → ndarray[source]

(faces,) the index in materials of each face’s material, or -1 for faces of other materials.

acoustic_spaces.engine.reweight.groups_of(room, settings=None) → tuple[ndarray, list[str]] | None[source]

Face groups to trace room with so that its absorption can change afterwards (reweighted_result()): the group of each face and the materials, those on surfaces that absorb less than everything in some band (a band in which one absorbs everything keeps that: no energy is left there to re-weight). None when its simulation settings (settings, default the scene’s) do not keep what re-weighting needs (cannot_reweight()) or no material is left.

acoustic_spaces.engine.reweight.log_ratio(old: ndarray, new: ndarray) → ndarray[source]

(groups, bands) ln((1 - new) / (1 - old)): the change in level per reflection; 0 where both absorb everything, which leaves no energy to change.

acoustic_spaces.engine.reweight.moment_exponent(moments: ndarray, ratio: ndarray) → ndarray[source]

(bands, slots) the exponent by which each slot of late energy changes, from the moments of the counts (terms, bands, slots) and log_ratio (groups, bands): the multinomial’s form with the rest of the covariance to second order, within the bounds that hold for any counts (see the module’s text).

acoustic_spaces.engine.reweight.path_counts(paths: EarlyReflections, face_group: ndarray, groups: int) → ndarray[source]

(paths, groups) how often each early path reflects off each group of faces.

acoustic_spaces.engine.reweight.reweighted_paths(paths: EarlyReflections, counts: ndarray, ratio: ndarray)[source]

paths with their energies for the new absorption (counts from path_counts(), ratio from log_ratio()).

acoustic_spaces.engine.reweight.reweighted_materials(room) → list[str][source]

The materials on room’s surfaces that absorb less than everything in some band: those whose absorption a re-weighting can change.

acoustic_spaces.engine.reweight.reweighted_result(result, traced, face_group: ndarray, materials: Sequence[str], scene)[source]

result, simulated from the scene traced with face_group for materials (groups_of()), for the absorption of scene: re-weighted, without tracing again. None when scene differs from traced in more than the absorption of its materials, a material changed that re-weighting does not cover, or one did that the solver for whole rows took for a response (solver_grounds()).

acoustic_spaces.engine.reweight.solver_grounds(result) → list[str][source]

The materials without an impedance on the ground of result’s scene, where some response of it has the path of the solver for whole rows (row_paths) among its early paths; none otherwise. That path’s sound depends on those grounds’ absorption, through the admittance fitted to it, and reflects off no face that a re-weighting counts.

acoustic_spaces.engine.reweight.slot_factor(exponent: ndarray, slots: int, time_step: float, moment_step: float)[source]

(bands, slots) the factor on each of slots slots of time_step, taking that of the moment slot it lies in.

acoustic_spaces.engine.reweight.turned_paths(paths: EarlyReflections, face_group: ndarray, old: ndarray, new: ndarray, admittance_of=None) → EarlyReflections[source]

paths with the phase of each reflection off a group of faces (face_group) turned, in the bands where they add in pressure, from that of the group’s absorption old (groups, bands) to that of new: from the angle each meets its face at (cosines). Reflections whose phase their face’s absorption does not give keep theirs. admittance_of gives the admittance of an absorption row ( absorption_phases(); by default the one fitted to it).

Audio files and results

WAV files: 32-bit float output, and input in the common PCM and float formats.

acoustic_spaces.audio.channel_mask(path: str | Path) → int | None[source]

The speaker positions (WAVE_FORMAT_EXTENSIBLE channel mask) of a WAV file, or None for a file in the plain format.

acoustic_spaces.audio.read_wav(path: str | Path) → tuple[ndarray, int][source]

Read a WAV file as float64 (frames, channels) and its sample rate.

PCM 16, 24 and 32 bit are scaled to [-1, 1); float 32 and 64 bit are kept as they are. RF64 and BW64 files (WAV with 64-bit sizes, for files over 4 GiB) are read too. The samples come in a few MiB at a time, so the file takes no copy of itself in memory.

acoustic_spaces.audio.write_wav(path: str | Path, data: ndarray, sample_rate: int, channel_mask: int | None = None) → None[source]

Write samples (frames,) or (frames, channels) as 32-bit float WAV.

Float WAV keeps levels above full scale, so relative levels between files survive. Files with more than two channels, or a channel_mask (WAVE_FORMAT_EXTENSIBLE speaker positions; 0 for none, as in AmbiX), use the extensible format. A file of more than 4 GiB is written as RF64 (EBU Tech 3306), the WAV format whose sizes take 64 bits. The samples go out a few MiB at a time, so a long file takes no copy of itself in memory.

Write a simulation’s responses to a folder: the files acoustic-spaces simulate and the editor’s Export produce.

For every (source, listener) pair, one WAV file per output format (<source>__<listener>.wav for mono, <source>__<listener>.<format>.wav for the others, with -2, -3… after the names or the format where two files would otherwise be the same), and for the whole run parameters.json: the settings, run details and the ISO 3382-1 parameters of every response (with IACC when a binaural response is written, from the first if there are several), its STI, STIPA and U50, and its echo criteria. Outdoors also its level relative to free field, and the insertion loss of the buildings, barriers or vegetation the run was also made without (simulation.insertion_loss_of). acoustic-spaces auralize reads that folder.

acoustic_spaces.results.file_name(text: str) → str[source]

text with anything but letters, digits, dots, dashes and underscores replaced.

acoustic_spaces.results.results_folder(out: str | Path) → Path[source]

The folder out ready for results: made where it is missing, and found to take files. Otherwise an OSError says why not: out is a file, or the folder cannot be made or written in. acoustic-spaces simulate asks before its run, so that a run is not lost at its end.

acoustic_spaces.results.unique_stems(stems: Sequence[str], suffixes: Sequence[str] = ('',)) → list[str][source]

stems, each that would name the same file as one before it with any of suffixes given -2, -3… in turn, also where the names differ only in case (the file systems of Windows and macOS ignore it): file_name() turns A/B and A_B into the same name, and names in other scripts into unnamed.

acoustic_spaces.results.write_results(result: SimulationResult, out: str | Path, formats: Sequence[Format] | None = None, *, sample_rate: int | None = None, normalize: bool = False, plots: bool = False, progress: Callable[[str], None] | None = None) → dict[source]

Write every response of result into the folder out and return the report saved as parameters.json.

formats are formats of acoustic_spaces.spatial (default: the scene’s outputs); sample_rate defaults to the simulation’s. normalize scales all files together so the loudest sample is at -1 dBFS; otherwise they keep the simulation’s levels, which exceed full scale when a listener is closer than 1 m to a source (the report’s peak says by how much). plots adds the echogram and direction plots of acoustic_spaces.viz when matplotlib is installed. Each response’s spread from its materials’ absorption uncertainty, where the result has it (spreads), goes into the report too.

The files are written into a hidden folder in out first and moved into place once all of them are, the report last, so that a run that fails or is cancelled while writing (a full disk, say) leaves out as it was. Each response is rendered and written in turn (on the run’s threads, one each), so memory holds a response’s files at a time, not the whole run’s, and its late part while its formats are rendered; threads the responses leave free render the channels of each side by side, a channel’s band signals in memory for each, the channels in progress held to a quarter of the computer’s memory. With normalize the files are scaled once all are written, by one rounding to single precision more.

Example scenes

Example scenes that come with the package.

They are the scenes in the repository’s examples folder, which wheels carry as acoustic_spaces/example_scenes:

from acoustic_spaces import Room
from acoustic_spaces.examples import example_path, list_examples

for example in list_examples():
    print(example.name, example.title)
room = Room.from_yaml(example_path("concert_hall"))

acoustic-spaces examples lists them, and --copy DIR copies them to a folder you can edit; the editor opens them from its File menu, in the groups of GROUPS.

acoustic_spaces.examples.GROUPS: tuple[tuple[str, tuple[str, ...]], ...] = (('Rooms', ('shoebox', 'room_modes', 'studio', 'listening_room', 'apartment', 'archway', 'workshop')), ('Halls and churches', ('lecture_hall', 'concert_hall', 'orchestra', 'church', 'gallery')), ('Sound systems', ('town_hall_pa', 'concert_stage', 'stadium_concert')), ('Outdoors', ('street', 'roadside', 'railway', 'tree_belt', 'hillside', 'open_air_stage', 'lakeside_concert', 'helicopter_flyover', 'airport')), ('Models from CAD and BIM files', ('rehearsal_room', 'bim_office', 'leaky_classroom')), ('Measurements and material libraries', ('fitting', 'material_libraries')))

The groups the examples are shown in, in order, each with its examples (folder names) from the simplest. The titles are English; the editor translates them.

acoustic_spaces.examples.OTHER_GROUP = 'Other examples'

The group of an example that GROUPS leaves out.

class acoustic_spaces.examples.Example(name: 'str', title: 'str', description: 'str', path: 'Path', model: 'Path | None' = None, group: 'str' = 'Other examples')[source]
name: str

Folder name, used to pick the example.

title: str

The scene’s name.

description: str

The comment at the top of the scene file.

path: Path

The scene file.

model: Path | None = None

Its model file, or None for a room built from dimensions.

group: str = 'Other examples'

The group it is shown in (English: see GROUPS).

property extra: str | None

The extra its model is read with (ifc for an IFC file), or None.

property missing_extra: str | None

The extra its model needs when that is not installed, or None.

acoustic_spaces.examples.copy_examples(destination: str | Path, names: list[str] | None = None) → list[Path][source]

Copy examples (all, or names) into destination, one folder each, and return their scene files. Raises FileExistsError rather than overwrite a folder.

acoustic_spaces.examples.example_groups(examples: list[Example] | None = None) → list[tuple[str, list[Example]]][source]

The examples (default: all) by group, in the order of GROUPS and within a group from the simplest; those it leaves out last, in OTHER_GROUP. Groups with no example are left out.

acoustic_spaces.examples.example_of(scene_file: str | Path) → str | None[source]

The example the scene file scene_file is, or is a copy of: its folder’s name when that names an example, else the example whose scene has the same name, so that a copy saved anywhere keeps its example; None for any other scene, or one that cannot be read.

acoustic_spaces.examples.example_path(name: str) → Path[source]

The scene file of the example name (a folder name from list_examples()).

acoustic_spaces.examples.examples_dir() → Path[source]

The folder that holds one sub-folder per example.

Installed packages carry it as acoustic_spaces/example_scenes; a source checkout (an editable install) uses the repository’s examples folder.

acoustic_spaces.examples.is_installed_example(path: str | Path) → bool[source]

Whether path lies among the examples of an installed package, which an upgrade or an uninstall replaces or removes: nothing is to be written there, even where the folder can be written (a virtual environment). A source checkout’s examples folder is not.

acoustic_spaces.examples.list_examples() → list[Example][source]

Every example scene, sorted by folder name.

3D view and plots

Pictures of rooms and responses.

  • 3D view (PyVista): surfaces coloured by material, sources with their directivity balloons, listeners, and early reflection paths coloured by order (paths diffracted at an edge in a colour of their own); outdoors the vegetation, and the wind: arrows over the ground, the weather zones, and masts with the wind’s profile up them.

  • Leaks (PyVista): the open edges of a model that is not closed, and the rays of the leak finder that escape through its gaps.

  • Animation (PyVista): sound particles spreading from a source and reflecting around the room, in a window with a time slider or saved as a GIF or MP4 video; a walker going along its walk, as a video to go with its sound.

  • Response plots (matplotlib): echogram with the early paths, decay curves per band, and arrival directions as the listener faces; the decays of a simulated and a measured response band by band; polar patterns of a source directivity; the wind, temperature and speed of sound over the ground outdoors.

  • Coverage maps: a parameter over the audience area, from above (matplotlib) or as coloured tiles in the 3D view.

Needs the viz extra (pip install "acoustic-spaces[viz]", or uv sync --extra viz in a source checkout). The 3D view works in a desktop window, in Jupyter, and off screen for screenshots.

acoustic_spaces.viz.MATERIAL_COLOURS = ('#8dd3c7', '#ffffb3', '#bebada', '#fb8072', '#80b1d3', '#fdb462', '#b3de69', '#fccde5', '#d9d9d9', '#bc80bd', '#ccebc5', '#ffed6f')

ColorBrewer Set3: light colours, so the saturated source and listener markers stand out.

acoustic_spaces.viz.ORDER_COLOURS = ('#ffffff', '#ffd166', '#f78c6b', '#ef476f', '#b5179e', '#7209b7', '#4361ee')

Reflection paths by order, direct sound first; orders past the end reuse the last.

acoustic_spaces.viz.DIFFRACTED_COLOUR = '#06d6a0'

Paths that bend over an edge.

acoustic_spaces.viz.BAND_COLOURS = ('#5e4fa2', '#3288bd', '#66c2a5', '#abdda4', '#e6f598', '#fdae61', '#f46d43', '#d53e4f')

Octave band colours for decay curves, low to high.

acoustic_spaces.viz.LEAK_COLOUR = '#ff4d4d'

Open edges and the rays that escape through them.

acoustic_spaces.viz.MAX_ESCAPES_DRAWN = 400

Escaping rays drawn at most, so a big hole does not hide the room.

acoustic_spaces.viz.COMPARISON_COLOURS = ('#4da3ff', '#ffd166')

A simulated and a measured response drawn together.

acoustic_spaces.viz.VEGETATION_COLOUR = '#5cb85c'

Trees, hedges and belts of trees outdoors.

acoustic_spaces.viz.WIND_COLOUR = '#4cc9f0'

The wind and the weather zones outdoors.

acoustic_spaces.viz.WIND_ARROWS = 40

Arrows of the wind over the ground in the 3D view, about this many.

acoustic_spaces.viz.WIND_REACH = 0.8

The longest arrow of the wind, the strongest’s, as a share of the space between them.

acoustic_spaces.viz.PROFILE_ARROWS = 5

Arrows up each mast of the wind’s profile.

acoustic_spaces.viz.room_polydata(room: Room, faces: np.ndarray | None = None) → pyvista.PolyData[source]

Room surfaces (all, or the given face indices) as PyVista PolyData.

The material cell array holds the index into room.material_names.

acoustic_spaces.viz.paths_polydata(paths: EarlyReflections, order: int | None = None, *, mask: np.ndarray | None = None) → pyvista.PolyData[source]

The specular paths of one reflection order, or the paths mask picks, as polylines.

class acoustic_spaces.viz.PathGroup(label: str, colour: str, mask: np.ndarray, order: int | None)[source]

Paths drawn together: specular paths of one order, or (order None) those diffracted at an edge.

label: str

Alias for field number 0

colour: str

Alias for field number 1

mask: ndarray

Alias for field number 2

order: int | None

Alias for field number 3

acoustic_spaces.viz.path_groups(paths: EarlyReflections, max_order: int | None = None) → list[PathGroup][source]

The specular paths by order, then those diffracted at an edge (with up to max_order reflections).

acoustic_spaces.viz.plot_paths(paths: EarlyReflections, plotter: pyvista.Plotter, *, max_order: int | None = None, line_width: float = 2.0) → list[list[str]][source]

Draw specular paths coloured by order and diffracted paths in their own colour; returns their legend entries.

acoustic_spaces.viz.plot_leaks(leaks: Leaks, room: Room, plotter: pyvista.Plotter, *, render: bool = True) → list[list[str]][source]

Draw the open edges of room, the rays of leaks (from acoustic_spaces.engine.leaks.find_leaks()) that escape, from their last reflection to a little past where they leave, and a numbered marker on each gap; returns their legend entries.

acoustic_spaces.viz.balloon_polydata(directivity: Directivity, center, rotation=None, *, band: int = 4, size: float = 1.0, db_range: float = 30.0) → pyvista.PolyData[source]

A directivity balloon around center in one octave band (band indexes OCTAVE_BANDS_HZ; 4 is 1 kHz): its radius grows from 0 at db_range dB below the loudest direction to size there. rotation has the source’s forward, left and up axes as columns (Orientation.rotation()). The point data level holds the level in dB re the loudest direction.

acoustic_spaces.viz.extent_polydata(source, radius: float) → pyvista.PolyData | None[source]

A line source as a tube of radius (m), a surface source as its rectangle, or None for a point source.

acoustic_spaces.viz.nearest_spacing(points) → ndarray[source]

The distance from each of points (rows of coordinates) to the nearest other one: infinite for a point alone.

acoustic_spaces.viz.clear_lengths(points, directions, radius, length) → ndarray[source]

The length of the arrow from each of points along its unit row of directions (zeros for none): length, cut short where the arrow would run into the marker (of radius) of another point ahead of it, but no shorter than twice its own marker’s radius.

acoustic_spaces.viz.marker_radius(positions, size: float) → float[source]

The radius of the markers of sources and listeners at positions where they do not crowd, in a model size metres across: a fifth of their usual spacing (the median distance to the nearest one), from 1.2 % to 2.5 % of the model’s size.

acoustic_spaces.viz.common_radius(nearest, full: float, lowest: float = 0.2) → float[source]

One radius for every marker, so that markers of one kind look alike: full where no two of them would touch, else as small as the closest two need (0.45 of their distance, nearest holding each one’s distance to its nearest), down to lowest times full to stay clearly visible.

acoustic_spaces.viz.marker_sizes(positions, size: float, directions=None, *, apart=None) → tuple[ndarray, ndarray][source]

The radius of the marker of each source or listener at positions and the length of its arrow along its unit row of directions, in a model size metres across, from how far apart the points are: a fifth of their usual spacing (the median distance to the nearest one), from 1.2 % to 2.5 % of the model’s size, and an arrow six times that. Where points crowd, every marker shrinks alike so that the closest two do not overlap (common_radius()), down to a fifth, and an arrow stops short of a marker ahead of it. apart (a boolean per point, default all) picks the points that are not to overlap: those in use, say, where the others are drawn faded.

acoustic_spaces.viz.vegetation_polydata(shape) → pyvista.PolyData[source]

The volume of a tree, a hedge or a belt of trees (PlantShape) as a closed surface: a lone tree’s crown, or an outline raised from its bottom to its top.

acoustic_spaces.viz.plot_vegetation(room: Room, plotter: pyvista.Plotter, *, render: bool = True) → list[source]

Add an outdoor room’s trees, hedges and belts of trees to plotter, as see-through green volumes; returns their legend entries.

class acoustic_spaces.viz.WindMap(room: Room)[source]

The weather over an outdoor room’s ground as the views draw it: the scene’s own (index 0) and each weather zone’s (1 on), where each holds, and each one’s wind at one height above the ground, the height the scene gives its wind’s speed at, so that the zones’ winds compare with the scene’s. Zones are polygons in metres, cut to the ground; one that cannot be (its sides cross) or that lies off the ground is None and holds nowhere.

classmethod of(room: Room) → WindMap | None[source]

The map of room, or None indoors and outdoors without an atmosphere.

property windy: bool

Whether the wind blows anywhere at the map’s height.

weather_at(points) → ndarray[source]

(n,) which weather holds at each point (n, 2 or 3): 0 for the scene’s own, k for its zone k (the first where zones overlap).

centre(k: int) → ndarray | None[source]

(2,) a point inside weather zone k: its centroid, or another inside if the centroid is not (an L-shaped zone); None for a zone that holds nowhere.

label(k: int) → str[source]

What weather zone k holds, in words: its name, its wind’s speed (if the wind blows anywhere) and its ground temperature (if it has one of its own).

arrows(spacing: float | None = None, clear=None, within=None) → WindArrows[source]

The arrows of the wind over the ground, one in the middle of each cell of a grid no more than spacing metres apart (by default about WIND_ARROWS cells), each the wind of the weather there: the strongest WIND_REACH of a cell long, the others in proportion, none where the air is still. Arrows that would pass near one of clear (m, 2), where sources and listeners stand, are left out, and a weather zone the grid misses gets one inside it. within (x_min, y_min, x_max, y_max) keeps only the cells it overlaps.

class acoustic_spaces.viz.WindArrows(middles: np.ndarray, vectors: np.ndarray, weather: np.ndarray, reach: float, cell: float)[source]

The arrows of the wind over the ground (see WindMap.arrows()).

middles: ndarray

(n, 2) the middle of each arrow (m).

vectors: ndarray

(n, 3) each arrow, horizontal, from its tail to its tip (m).

weather: ndarray

(n,) the weather each arrow shows: 0 the scene’s own, k its zone k.

reach: float

How long an arrow is per m/s of wind (m).

cell: float

The size of the grid’s cells (m).

acoustic_spaces.viz.plot_wind(room: Room, plotter: pyvista.Plotter, *, field: bool = True, profile: bool = False, render: bool = True) → list[source]

Add the wind over an outdoor room’s ground to plotter. field: sky blue arrows the way it blows, as long as it is strong, at the height the scene gives the wind’s speed at above the ground, and each weather zone as see-through walls up to that height with its name and wind. profile: a mast in each weather where the wind blows, with arrows at heights up it and a curve through the wind at every height, how the wind grows with height over the ground. Nothing indoors or in still air. Returns the legend entry of the wind.

acoustic_spaces.viz.plot_room(room: Room, plotter: pyvista.Plotter | None = None, *, opacity: float = 0.45, show_labels: bool = True, paths: EarlyReflections | None = None, max_order: int | None = None, coverage: CoverageMap | None = None, parameter: str = 'g', band: int = 4, part: str = 'value', leaks: Leaks | None = None, wind: bool = True) → pyvista.Plotter[source]

Add the room to plotter (a new one if None) and return it.

paths adds early reflection paths (from acoustic_spaces.engine.early_paths() or a response’s early), coloured by order up to max_order. coverage adds a coverage map of one parameter and band, or of a part of its spread (see plot_coverage()). leaks adds the open edges and the rays that escape through them (see plot_leaks()). Outdoors, wind adds the wind and the weather zones (see plot_wind()).

acoustic_spaces.viz.show_room(room: Room, screenshot: str | Path | None = None, window_size: tuple[int, int] = (1280, 800), **kwargs) → None[source]

Open the room in a window, or save a PNG to screenshot without one.

Keyword arguments go to plot_room() (for example paths).

acoustic_spaces.viz.animate_particles(room: Room, particles: Particles, path: str | Path | None = None, *, fps: int = 25, color: str = 'energy', db_range: float = 40.0, window_size: tuple[int, int] = (1024, 640)) → None[source]

Show sound particles (from acoustic_spaces.engine.trace_particles()) moving through the room: in a window with a time slider, or saved to path as an animated GIF or an MP4 video.

color is "energy" (level in dB relative to a particle’s share at emission, down to -db_range) or "order" (reflections so far).

acoustic_spaces.viz.check_video(path: str | Path) → None[source]

Raise what saving an animation to path would, before the work of making it: ValueError unless it is a .gif or .mp4, ImportError without PyVista or, for an MP4, without imageio and imageio-ffmpeg.

acoustic_spaces.viz.animate_walk(room: Room, walk: WalkResponses, path: str | Path, *, fps: int = 25, window_size: tuple[int, int] = (1024, 640), sound: str | Path | None = None) → None[source]

Save a walk (from acoustic_spaces.walkthrough.simulate_walk()) as an animated GIF or an MP4 video: the room, the path and the walker going along it, in time with the sound of render_walk(). room is the scene’s room. sound, a WAV file of that sound in one or two channels, becomes an MP4’s sound track, and the video then lasts as long as the sound (a GIF has none).

acoustic_spaces.viz.animate_movement(room: Room, movement: Movement, path: str | Path, *, fps: int = 25, window_size: tuple[int, int] = (1024, 640), sound: str | Path | None = None) → None[source]

Save a movement (from acoustic_spaces.walkthrough.simulate_movement()) as an animated GIF or an MP4 video: the room, every mover’s path and the movers going along them on one clock, each with an arrow the way it faces, the still sources and listeners where they stand. sound, a WAV file of one listener’s sound in one or two channels, becomes an MP4’s sound track, and the video then lasts as long as the sound (a GIF has none).

acoustic_spaces.viz.plot_response(response: Response, path: str | Path | None = None, *, band: int = 4)[source]

Echogram and decay curves of one response; saved to path if given.

The echogram shows the energy per millisecond in one octave band (band indexes OCTAVE_BANDS_HZ; 4 is 1 kHz) with the early specular paths as stems coloured by order. The decay panel shows the backward-integrated curve of every band. A response in third-octave bands shows them averaged into octave bands. Returns the matplotlib figure.

acoustic_spaces.viz.plot_directions(response: Response, path: str | Path | None = None, *, band: int = 4)[source]

Where the sound comes from, as the listener faces: early reflections (dots sized by level and coloured by delay) and the late energy per arrival direction, in one octave band (band indexes OCTAVE_BANDS_HZ; 4 is 1 kHz). Azimuth runs from the left to the right of the listener. A response in third-octave bands shows them averaged into octave bands. Returns the matplotlib figure.

acoustic_spaces.viz.plot_directivity(directivity: Directivity, path: str | Path | None = None, *, db_range: float = 30.0)[source]

Polar patterns of a source directivity in every octave band, in dB re the loudest direction of each band: the horizontal plane (seen from above, front at the top and the source’s left on the left) and the vertical plane through the front (seen from the side, front on the right and up at the top). Returns the matplotlib figure.

acoustic_spaces.viz.plot_atmosphere(atmosphere: Atmosphere, ground_c: float, path: str | Path | None = None, *, top: float = 100.0)[source]

An outdoor atmosphere from the ground to top metres up: the temperature and the wind’s speed (left), and the speed of sound (right) in still air and, with a wind, as sound going with it and against it, the speed that bends sound: towards where it is lower. ground_c is the temperature at the ground (the scene’s air temperature). Returns the matplotlib figure.

acoustic_spaces.viz.plot_impulse_response(ir: ndarray, sample_rate: float, path: str | Path | None = None, *, title: str | None = None, filters: str = 'iec', noise: bool = True)[source]

Level and decay curves of a measured (or any) impulse response.

The top panel shows the squared response in dB over 1 ms windows and, per octave band with noise, the background noise level found for it. The bottom panel shows each band’s backward-integrated decay up to where it sinks into the noise, with the noise taken off and the missing tail added, as the parameters are computed. Returns the matplotlib figure; it is saved to path if given.

acoustic_spaces.viz.plot_comparison(simulated: ndarray, simulated_rate: float, measured: ndarray, measured_rate: float, path: str | Path | None = None, *, title: str | None = None, labels: tuple[str, str] = ('simulated', 'measured'), filters: str = 'iec', noise: bool = True)[source]

Decay curves of a simulated and a measured impulse response, one panel per octave band.

Each panel overlays the backward-integrated (Schroeder) decays of the two, each from its own direct sound on, as plot_impulse_response() draws them: up to where the band sinks into its noise, with the noise taken off and the missing tail added. labels name the two responses in the legend. Returns the matplotlib figure; it is saved to path if given.

acoustic_spaces.viz.MAP_COLOURS = 'turbo'

Colour map of coverage maps.

acoustic_spaces.viz.MAP_OPACITY = 0.7

Opacity of a coverage map in 3D: see-through, so the sources and listeners at listening height, half under its tiles, stay in sight.

acoustic_spaces.viz.MAP_PARTS = {'at_least': 'at least', 'at_most': 'at most', 'high': 'upper end of the interval', 'low': 'lower end of the interval', 'standard': 'standard uncertainty', 'value': 'value'}

What a map shows of a parameter: its value, or a part of its spread (spread_of()), each with the name it has in a title.

acoustic_spaces.viz.map_values(coverage: CoverageMap, parameter: str = 'g', band: int = 4, part: str = 'value')[source]

The values a map shows of parameter (in band when it has bands, as an index into OCTAVE_BANDS_HZ), in the units of its label, and its title. part (a key of MAP_PARTS) takes, in place of the value, a part of its spread on a map run with one: its standard uncertainty, an end of its interval, or the value it is at least or at most, the last four with their probability in the title.

acoustic_spaces.viz.map_polydata(coverage: CoverageMap, parameter: str = 'g', band: int = 4, part: str = 'value') → pyvista.PolyData[source]

The map’s columns as tiles at listening height, over the audience surfaces (tiles()); the cell data value holds the parameter as map_values() gives it (NaN where undefined) and point the map point of each tile.

acoustic_spaces.viz.plot_coverage(coverage: CoverageMap, plotter: pyvista.Plotter, *, parameter: str = 'g', band: int = 4, render: bool = True, part: str = 'value')[source]

Add a coverage map to a 3D view: coloured tiles at listening height over the audience area, with a colour bar (parameter, band and part as map_values() takes them). Returns the actor of the tiles.

acoustic_spaces.viz.plot_map(coverage: CoverageMap, path: str | Path | None = None, *, parameter: str = 'g', band: int = 4, room: Room | None = None, part: str = 'value')[source]

A coverage map seen from above: one panel per level (stalls, balcony, …), columns coloured by parameter in band (an index into OCTAVE_BANDS_HZ; 4 is 1 kHz) and labelled with their values when there is room; with part, by that part of its spread (map_values()). With room the walls and sources are drawn too. Returns the matplotlib figure; it is saved to path if given.

Export to Blender (glTF)

Scenes as glTF 2.0 binary files (.glb) for Blender and other 3D tools.

The file holds the room, one object per surface name with a see-through material per scene material (its absorption and scattering per octave band as extras, which Blender shows as custom properties), an outdoor scene’s trees, hedges and belts of trees as see-through green volumes, and the sources and listeners turned the way they face, with an arrow along the aim. It can also hold early reflection paths as lines, one object per order, and sound particles as an animation in slow motion: by default 100 ms of sound play over 4 s. Blender opens it with File > Import > glTF 2.0.

Scenes are Z-up and glTF is Y-up: a point (x, y, z) is written as (x, z, -y), which the importer turns back.

acoustic_spaces.gltf.PARTICLE_COUNT = 1000

Particles the command line and the editor export: about 3 MB at 100 frames.

acoustic_spaces.gltf.SLOW_MOTION = 40.0

Seconds of animation per second of sound.

acoustic_spaces.gltf.export_gltf(room: Room, path: str | Path, *, paths: EarlyReflections | None = None, particles: Particles | None = None, slow_motion: float = 40.0, db_range: float = 60.0) → None[source]

Write room with its sources and listeners to path as glTF 2.0 (.glb).

paths (from acoustic_spaces.engine.early_paths() or a response’s early) adds the early reflection paths, coloured by order as in the 3D view. particles (from acoustic_spaces.engine.trace_particles()) adds an animation with a small sphere per particle that moves with it and shrinks with its level: full size at its share of the emitted energy, gone db_range dB below. The animation runs slow_motion times slower than the sound, with a keyframe at each of the particles’ frames.