Skip to content

Every public class and function is importable from compas_acoustics.

compas_acoustics

Classes

AcousticMaterial

AcousticMaterial(name: str, absorption_coefficients, scattering_coefficients: list = None, transmission_coefficients: list = None, description: str = None, category=None, data_origin: str = None)

Bases: _PackageDtype, Data

Absorption, scattering and transmission coefficients per octave band, 125 Hz to 8 kHz.

Parameters:

Name Type Description Default
name str
required
absorption_coefficients float or list of float

One for every band, or one per band; so are the other coefficients.

required
scattering_coefficients float or list of float
None
transmission_coefficients float or list of float

Stored and serialised only: the simulation methods do not use them.

None
description str
None
category [`MaterialCategory`][compas_acoustics.materials.MaterialCategory] or str

Default MaterialCategory.OTHER.

None
data_origin str

Default "custom".

None

Attributes

slug property
slug

The name as the library's file name.

AcousticObject

AcousticObject(acoustic_geometry: Mesh, material: AcousticMaterial, x: float = 0, y: float = 0, z: float = 0, name: str = None, role: str = 'boundary', group: str = None)

Bases: _PackageDtype, Data

A surface of the scene with its material.

Parameters:

Name Type Description Default
acoustic_geometry [`compas.datastructures.Mesh`][compas.datastructures.Mesh]
required
material [`compas_acoustics.AcousticMaterial`][compas_acoustics.materials.AcousticMaterial]
required
x float

The geometry's reference point (position). Stored and serialised only: the simulation methods do not use it.

0
y float

The geometry's reference point (position). Stored and serialised only: the simulation methods do not use it.

0
z float

The geometry's reference point (position). Stored and serialised only: the simulation methods do not use it.

0
name str

Default: the class name.

None
role str

'boundary' (part of the closed room, the default) or 'obstacle' (free-standing inside it).

'boundary'
group str

The OBJ group the object was read from, for assign_roles_by_group and assign_materials_by_group. Not serialised.

None

Methods:

assign_materials_by_group staticmethod
assign_materials_by_group(objects, materials)

Set the material of the objects of from_obj by group name; an unknown name raises ValueError.

Parameters:

Name Type Description Default
objects list of [`AcousticObject`][compas_acoustics.acoustic_object.AcousticObject]
required
materials dict

AcousticMaterial by group name; other groups keep theirs.

required

Returns:

Type Description
list of [`AcousticObject`][compas_acoustics.acoustic_object.AcousticObject]

objects.

assign_roles_by_group staticmethod
assign_roles_by_group(objects, roles)

Set the role of the objects of from_obj by group name; an unknown name raises ValueError.

Parameters:

Name Type Description Default
objects list of [`AcousticObject`][compas_acoustics.acoustic_object.AcousticObject]
required
roles dict

'boundary' or 'obstacle' by group name.

required

Returns:

Type Description
list of [`AcousticObject`][compas_acoustics.acoustic_object.AcousticObject]

objects.

from_obj classmethod
from_obj(filepath, materials=None, name=None)

One acoustic object per g group of a Wavefront OBJ file, named '<name>_<group>'.

Faces before any g line are in 'default'; a file without g lines is grouped by its o lines; a group that recurs is merged. Coordinates are metres. Faces with fewer than three distinct vertices are dropped. Every object is a boundary; see assign_roles_by_group.

Parameters:

Name Type Description Default
filepath str
required
materials [`AcousticMaterial`][compas_acoustics.materials.AcousticMaterial] or dict

One material for every group, or one per group name (assign_materials_by_group).

None
name str

The prefix of the objects' names; default the file name.

None

Returns:

Type Description
list of [`AcousticObject`][compas_acoustics.acoustic_object.AcousticObject]

AcousticObjectsLibrary

Factories of commonly used acoustic objects.

Methods:

shoebox_room classmethod
shoebox_room(length: float, width: float, height: float, materials=None, sources: list = None, name: str = None)

A shoebox room as six surfaces, each its own AcousticObject.

Parameters:

Name Type Description Default
length float
required
width float
required
height float
required
materials dict or [`AcousticMaterial`][compas_acoustics.materials.AcousticMaterial]

One material for every surface, or one per surface name ('floor', 'left_wall', 'front_wall', 'right_wall', 'back_wall', 'ceiling'). Missing ones: absorption and scattering 0.1.

None
sources list

Sources attached to the floor.

None
name str

The prefix of the surfaces' names; default from the dimensions.

None

Returns:

Type Description
list of [`AcousticObject`][compas_acoustics.acoustic_object.AcousticObject]

Floor, right, front, left and back wall, ceiling. Facing +x from the centre, 'left_wall' is at y = width, 'right_wall' at y = 0 and 'front_wall' at x = length.

AirConditions dataclass

AirConditions(temperature: float = 20.0, humidity: float = 50.0, pressure: float = 101325.0)

Air at a temperature (deg C), relative humidity (%) and static pressure (Pa).

Within Cramer's range, 0 to 30 deg C and 75 to 102 kPa.

Attributes

speed_of_sound property
speed_of_sound: float

Speed of sound in m/s, after Cramer (1993).

Methods:

air_attenuation
air_attenuation(frequencies) -> ndarray

Energy attenuation coefficient m per metre at frequencies in Hz (above 50 Hz), after ISO 9613-1.

The coefficient is ISO 9613-1's pure-tone one; the package takes it at each band's centre frequency and applies it to the whole band.

Analyser

Analyser(ir)

Room acoustic parameters of an impulse response (analyse).

Every window starts at onset, the direct sound of channel 0 as pyfar.dsp.find_impulse_response_start finds it with the 20 dB criterion of ISO 3382-1:2009, p. 22.

Parameters:

Name Type Description Default
ir (list, ndarray or ImpulseResponse)

(samples,) or (samples, channels). LF and LFC take the first-order channels of an ambisonic ImpulseResponse, every other parameter channel 0 (the omnidirectional component, or the left ear). An ImpulseResponse is analysed at its raw level and sets sampling_rate.

required

Examples:

>>> import compas_acoustics as ca
>>> scene = ca.Scene("office")
>>> room = ca.AcousticObjectsLibrary.shoebox_room(6, 5, 3, materials=ca.AcousticMaterial("wall", 0.2, 0.1))
>>> scene.add_acoustic_objects(room)
>>> scene.add_source(ca.Source("talker", 1.5, 1.5, 1.6))
>>> scene.add_receiver(ca.Receiver("listener", 4.0, 3.0, 1.2))
>>> responses = scene.simulate(ca.Mono(ray_tracing=True, n_rays=2000, duration=0.5))
>>> analyser = ca.Analyser(next(iter(responses.values())))
>>> results = analyser.analyse()
>>> results["freqs"]
[125, 250, 500, 1000, 2000, 4000, 8000]
>>> results["T30_overall"] > 0
True

Methods:

analyse
analyse() -> dict

Every parameter of _PARAM_NAMES per band and as '<name>_overall'.

The overall values of EDT, T20, T30, C50, C80, D50 and Ts average 500 and 1000 Hz, after the single-number averages of ISO 3382-1:2009 Table A.1; the same average for all seven is the package's choice. The others have their own. The per-band 'STI' values are the modulation transfer indices, 'STI_overall' the STI.

center_time
center_time() -> dict

Centre time Ts of the zero-phase bands, in seconds from the broadband direct sound (ISO 3382-1:2009).

clarity_definition
clarity_definition() -> dict

C50, C80 and D50 per band (ISO 3382-1:2009).

Early and late parts are cut from the broadband response before causal band filtering, so filter delay and ringing stay with the part they belong to, the package's choice.

direct_to_reverberant_ratio
direct_to_reverberant_ratio() -> dict

Direct-to-reverberant ratio per band and for 700-4000 Hz, in dB.

The energy from 1 ms before to 5 ms after the direct sound over the energy after it. The window and the 700-4000 Hz band of 'DRR_overall' (a fourth-order Butterworth band-pass, butter(2, ..., "bandpass")) are the package's choice. Per band the two parts are cut before filtering; for 'DRR_overall' the response is filtered first.

Returns:

Type Description
dict

'DRR' per band in frequency_bands, and 'DRR_overall'.

export_csv
export_csv(filepath: str, parameters=None)

Write the results of analyse to a CSV file.

Parameters:

Name Type Description Default
filepath str
required
parameters str or list of str

Default: all.

None
lateral_fraction
lateral_fraction() -> dict

Early lateral energy fractions J_LF and J_LFC per band (ISO 3382-1:2009 Annex A).

J_LF is the figure-of-eight energy 5-80 ms after the direct sound over the omnidirectional energy 0-80 ms; J_LFC takes |p_L p| for p_L^2 (Kleiner 1989; Bradley 1994). The figure-of-eight is the first-order dipole of the response, horizontal in the receiver's frame and perpendicular to the source direction (the receiver's y axis for a source straight above or below). Windows are cut before band filtering, the package's choice.

Returns:

Type Description
dict

'freqs', 'LF' and 'LFC' per band, and 'LF_overall' and 'LFC_overall', the mean of 125-1000 Hz. NaN for a response that is not an ambisonic ImpulseResponse (ACN, SN3D or N3D).

plot
plot(parameters=None)

Plot the results of analyse against frequency, one figure per parameter (default: all).

plot_frequency_response
plot_frequency_response(smooth=3, raw_alpha=0.3)

Plot the magnitude response, with a 1/smooth octave smoothed one over it unless smooth is None.

plot_rir
plot_rir()

Plot the impulse response against time.

print_table
print_table(parameters=None, show_bands=True, show_overall=False)

Print the results of analyse.

Parameters:

Name Type Description Default
parameters str or list of str

Default: all.

None
show_bands bool

Per-band values.

True
show_overall bool

Overall values.

False
reverberation_times
reverberation_times() -> dict

EDT, T20 and T30 per band (ISO 3382-1:2009).

Schroeder (1965, J. Acoust. Soc. Am. 37(3)) backward integration of the zero-phase band (_band_from_onset) from the direct sound to the last non-zero sample, normalized to 0 dB at its start, then linear regression. No noise compensation: truncate a measured response at its noise floor first.

sound_pressure_level
sound_pressure_level(source_spl=None, strength=None) -> dict

Sound pressure level per band, Lp = spl + G - 20 dB: G's reference at 10 m is 20 dB below 1 m.

Parameters:

Name Type Description Default
source_spl float or list of float

The source's on-axis level at 1 m (compas_acoustics.Source.spl), one or one per band. Default: that of the response's source.

None
strength dict

sound_strength, when already computed.

None

Returns:

Type Description
dict

'freqs', 'SPL' per band, 'SPL_overall' the A-weighted total in dB(A) and 'SPL_total' the unweighted one. NaN, with a warning, without a level or off the package scale.

sound_strength
sound_strength(reference_ir=None) -> dict

Strength G per band (ISO 3382-1:2009): the energy over that of the free field at 10 m.

Both at their raw level. The single number averages 500 and 1000 Hz.

Parameters:

Name Type Description Default
reference_ir ImpulseResponse or ndarray

The source's free-field response at 10 m, at the same sample rate. Default: the package-scale free field 1 / (4 pi 10), for a package-scale response.

None

Returns:

Type Description
dict

'freqs', 'G' per band in frequency_bands, and 'G_overall'.

speech_transmission_index
speech_transmission_index(snr=inf) -> dict

STI and the modulation transfer index per octave band (IEC 60268-16:2020, indirect method).

Responses shorter than the 1.6 s of Section 6.2 are zero-padded, which assumes a full decay. snr is the signal-to-noise ratio in dB, one value or one per octave band 125-8000 Hz.

Returns:

Type Description
dict

'mti' per octave band 125-8000 Hz and 'sti'; NaN where pyrato cannot compute them.

stage_support
stage_support() -> dict

ST_early and ST_late per band (Gade; ISO 3382-1:2009 Annex C), for source and receiver 1 m apart.

The energy 20-100 ms (ST_early) or 100-1000 ms (ST_late) after the direct sound over the energy of the first 10 ms, in dB; the windows are cut before band filtering. Single numbers average 250-2000 Hz.

Returns:

Type Description
dict

'freqs', 'ST_early' and 'ST_late' per band in frequency_bands, and 'ST_early_overall' and 'ST_late_overall'.

AudioPlayer

AudioPlayer()

Plays a sound file or an array, on Windows and macOS.

Attributes:

Name Type Description
system str

"Windows" or "Darwin".

sound_type str

'file', 'array' or None.

Attributes

duration property
duration

The length of the array last played, in seconds; 0 for a file or nothing.

playing property
playing

Whether a sound is playing now.

position property
position

Where the array's playback is, in seconds: it runs with the clock while playing, and holds when paused.

Methods:

pause
pause()

Stop an array's playback and keep its position; resume plays on from it. A file stops.

play
play(sound, sampling_rate=None, normalize=True, gain_db=0.0, start=0.0)

Play a file path, whole at its level, or an array with the arguments of play_array.

play_array
play_array(array, sampling_rate, normalize=True, gain_db=0.0, start=0.0)

Play an array.

Parameters:

Name Type Description Default
array ndarray

(samples,) or (samples, channels). A mono signal plays on both channels.

required
sampling_rate int or None

None for Defaults.SAMPLING_RATE.

required
normalize bool

Scale to a peak of 0.99; disable to play an auralisation at its rendered level.

True
gain_db float

Applied after the normalisation.

0.0
start float

In seconds from the beginning.

0.0
play_file
play_file(file_path)

Play a .wav file.

resume
resume()

Play on from where pause stopped.

stop
stop()

Stop the playback and return to the beginning.

Auraliser

Auraliser(impulse_responses, anechoic_sounds=None, sampling_rate: int = None, level: str = 'relative', headroom_db: float = -1.0)

Convolves impulse responses with their anechoic sounds and sums them.

The signal has the format of its responses (format): 'mono', 'binaural' or 'ambisonic' (ACN/SN3D at the highest order present; N3D is converted). Formats cannot be mixed: there is no decoding. Responses are used at their raw level; level sets the gain on export: 'relative' (one gain for a group of renders, the loudest peaking at headroom_db), 'individual' (each peaks at it) or 'none' (no gain; warns above 0 dBFS).

Parameters:

Name Type Description Default
impulse_responses dict or list

ImpulseResponse objects (ACN/SN3D when they state no convention), or a dict of ids to dicts with 'ir' ((samples,) or (samples, channels)), 'sampling_rate', 'ambisonic_order', 'channel_order' ('acn') and 'normalization' ('sn3d' or 'n3d').

required
anechoic_sounds dict or list

File paths, or a dict of ids to dicts with 'filepath': paired by id when both are dicts with the same ids, else by position. Default: the sound_file of each response's source.

None
sampling_rate int

Responses and sounds are resampled to it; default that of the first response.

None
level str

Default 'relative'.

'relative'
headroom_db float

In dBFS; default -1.

-1.0

Examples:

>>> import compas_acoustics as ca
>>> sound = ca.Defaults().ANECHOIC_SOUNDFILES_LIBRARY_PATH + "/female_speech.wav"
>>> scene = ca.Scene("office")
>>> room = ca.AcousticObjectsLibrary.shoebox_room(6, 5, 3, materials=ca.AcousticMaterial("wall", 0.2, 0.1))
>>> scene.add_acoustic_objects(room)
>>> scene.add_source(ca.Source("talker", 1.5, 1.5, 1.6, sound_file=sound))
>>> scene.add_receiver(ca.Receiver("listener", 4.0, 3.0, 1.2))
>>> responses = scene.simulate(ca.Mono(ray_tracing=True, n_rays=2000, duration=0.5))
>>> auraliser = ca.Auraliser(list(responses.values()))
>>> auraliser.format, auraliser.convolve().shape[1]
('mono', 1)

Attributes

format property
format

str : 'mono', 'binaural' or 'ambisonic', of the impulse responses and of the signal.

impulse_responses property writable
impulse_responses

dict : The impulse responses, (samples, channels) arrays at sampling_rate, ambisonic in ACN/SN3D.

output_channels property
output_channels

int : Number of channels of the auralised signal: 1, 2, or (order + 1)**2 for ambisonics.

Methods:

convolve
convolve()

Convolve each impulse response with its anechoic sound and sum, in format.

Responses that share a sound are summed first, so each sound is read and convolved once. Lower-order ambisonic responses are padded with zero channels to the highest order.

Returns:

Type Description
ndarray

The auralised signal, shaped (samples, output_channels).

export_convolved_sound
export_convolved_sound(filepath, convolved_sound=None, gain=None)

Write an auralised signal at its output level as a 32-bit float audio file.

Parameters:

Name Type Description Default
filepath str
required
convolved_sound ndarray

Default: convolve.

None
gain float

E.g. from render_gains for a group of renders. Default: from level and headroom_db for this signal alone.

None

Returns:

Type Description
ndarray

The written signal, shaped (samples, channels), as float32.

import_anechoic_sound
import_anechoic_sound(filepath)

An audio file as a mono (samples,) array at sampling_rate, multichannel files mixed down.

peak_dbfs staticmethod
peak_dbfs(signal)

Peak absolute value of a signal in dBFS (-inf for silence).

render_gains staticmethod
render_gains(signals, level='relative', headroom_db=-1.0)

One gain per signal of a group of convolve results, for level as level.

Parameters:

Name Type Description Default
signals list of np.ndarray
required
level str
'relative'
headroom_db float

The target peak in dBFS.

-1.0

Returns:

Type Description
list of float

Defaults

Attributes

DEFAULT_SPEED_OF_SOUND property
DEFAULT_SPEED_OF_SOUND

The speed of sound of AirConditions() (20 deg C, 50 %, 101325 Pa), in m/s.

EnergyMap

EnergyMap(points, inside, bands, bin_size, energy, name=None)

Bases: _PackageDtype, Data

The energy of a scene's sources at many points, per octave band and time bin.

Scaled so that 10 log10 of the sum over the bins is the level in dB re 20 uPa of sources radiating compas_acoustics.Source.spl (spl).

Parameters:

Name Type Description Default
points array - like

The points, (n, 3).

required
inside array - like

Whether each point is in the air of the room, (n,); the others hold no energy and read NaN.

required
bands array - like

The octave bands' centres in Hz, (b,).

required
bin_size float

The length of a time bin in seconds; bin k starts k * bin_size after the emission.

required
energy array - like

(n, b, bins).

required
name str
None

Methods:

frames
frames(frame_s: float = 0.012)

The frames' start times (k,) in seconds and the broadband levels (n, k) in dB, per point in frames of frame_s rounded up to whole bins: -inf before any energy arrives, NaN outside the room.

from_scene classmethod
from_scene(scene, points, source_index=None, n_rays=None, image_source_order=1, duration=None, air_absorption=True, seed=True, ray_spacing=1.0) -> 'EnergyMap'

The energy map of scene's sources at points.

Points outside the room or inside a closed obstacle are left out with one UserWarning.

Parameters:

Name Type Description Default
scene [`compas_acoustics.Scene`][compas_acoustics.scene.Scene]
required
points iterable of xyz
required
source_index int

One source of scene.sources; default all, their energies added.

None
n_rays int

Per source; default map_rays.

None
image_source_order int

Image sources up to this order, the rays from it on. At least 1: at 0 the rays log the direct path too.

1
duration float

Seconds; default compas_acoustics.room.raytracing.default_duration, as the Mono method: 1.5 times the longest Eyring reverberation time within 0.5 s and 12 s, 10 s for a scene that closes no volume.

None
air_absorption bool
True
seed bool or int

True seeds the rays with 42, an int with that value, False not at all.

True
ray_spacing float or None

The rays are traced to one point per cell of this size in metres, the one nearest the cell's centre, and interpolated to the others from the four nearest by inverse squared distance; None traces them to every point. The image sources are computed at every point. The package's choice: a run costs rays times receivers.

1.0
spl
spl() -> ndarray

The sound pressure level per point and band, (n, b), in dB; NaN outside the room.

spl_a
spl_a() -> ndarray

The A-weighted total of the bands per point, (n,), in dB(A); IEC 61672-1:2013 weights at the band centres.

ImpulseResponse

ImpulseResponse(name: str, source: Source, receiver: Receiver, ir: ndarray, sampling_rate: int, normalized: bool = True, generation: dict = None, ambisonic_order: int = None, normalization: str = None, channel_order: str = None)

Bases: _PackageDtype, Data

An impulse response between a source and a receiver, stored at its raw level.

ir is peak-normalized by default (the peak of all channels, normalization_factor); denormalized gives the raw level, and denormalize_group scales a group so that its loudest response peaks at 1. Both keep the level differences between responses.

Parameters:

Name Type Description Default
name str
required
source Source
required
receiver Receiver
required
ir ndarray

The raw response, (samples,) or (samples, channels).

required
sampling_rate int
required
normalized bool

Whether ir is peak-normalized; default True.

True
generation dict

The method and its settings, written to the JSON metadata on export.

None
ambisonic_order int

None for a mono or binaural response.

None
normalization str

'sn3d' or 'n3d'.

None
channel_order str

'acn'.

None

Attributes

format property
format

str : 'mono', 'binaural' (two channels, no ambisonic order) or 'ambisonic'.

ir property writable
ir

np.ndarray : Peak-normalized when normalized; setting it sets the raw response.

level_db property
level_db

float : The normalization factor in dB (20 log10 of the raw peak).

metadata property
metadata

dict : The response and how it was generated, as written next to it on export.

n_channels property
n_channels

int : The number of channels.

normalization_factor property
normalization_factor

float : Peak absolute value of the raw impulse response across all channels.

Methods:

denormalize_group staticmethod
denormalize_group(impulse_responses)

The raw arrays of the responses, scaled together so that the loudest peaks at 1.

Parameters:

Name Type Description Default
impulse_responses list or dict of ImpulseResponse
required

Returns:

Type Description
list or dict of np.ndarray
denormalized
denormalized()

A copy of the raw impulse response.

direct_sound_index
direct_sound_index() -> int

Sample of the direct sound.

On the package scale the geometric one, distance / c, even when an early ray-traced bin is louder or an obstacle blocks it; otherwise the largest sample of the omnidirectional channel.

from_wav classmethod
from_wav(filepath, source: Source = None, receiver: Receiver = None, normalized: bool = True)

Read a WAV written by to_wav at the raw level of its JSON metadata; without metadata the WAV is raw.

Parameters:

Name Type Description Default
filepath str
required
source (Source, Receiver)

Used instead of those of the metadata.

None
receiver (Source, Receiver)

Used instead of those of the metadata.

None
normalized bool True

Returns:

Type Description
ImpulseResponse
to_wav
to_wav(filepath, gain=None)

Write the response as a 32-bit float WAV, and metadata with the factor back to the raw level as JSON beside it.

Parameters:

Name Type Description Default
filepath str
required
gain float

Applied to the raw response, e.g. from Auraliser.render_gains for a group of responses. Default: peak-normalized.

None

Returns:

Type Description
tuple of Path

The WAV and JSON files.

MaterialCategory

Bases: str, Enum

Broad groups of acoustic materials, as the library is organised.

Methods:

parse classmethod
parse(value)

Get a category from a member, its value ("Stone & Tiles") or its name ("STONE_AND_TILES").

MaterialsLibrary

MaterialsLibrary(library_path: str = None)

The materials of a folder of JSON files, one per material, looked up by name.

Attributes

index property
index: dict

Material names to JSON file paths, read on first access.

material_names property
material_names: list

list : The names of the library's materials.

materials_by_category property
materials_by_category: dict

dict : Sorted material names per MaterialCategory that has any, in the categories' order.

Methods:

path_from_material_name
path_from_material_name(material_name: str) -> str

The JSON file of a material, or where it would be stored when not in the library.

Mono

Mono(image_source_order: int = 3, ray_tracing: bool = True, air_absorption: bool = True, n_rays: Optional[int] = None, energy_thres: float = 1e-07, duration: Optional[float] = None, receiver_radius: float = 0.5, seed: Union[bool, int] = True, normalize: bool = True, air: Optional[AirConditions] = None)

Bases: SimulationMethod

Image sources up to image_source_order (pyroomacoustics: Scheibler et al. 2018, Sec. 3) and, if ray_tracing, pyroomacoustics' stochastic ray tracer.

Parameters:

Name Type Description Default
image_source_order int

Last image source order. With ray_tracing the rays also hold this order, the later ones and the scattered energy (compas_acoustics.room.raytracing). The search cost grows steeply with the order (image_source_search_seconds).

3
ray_tracing bool

Materials without scattering coefficients scatter 0.05 in every band. Without it, the settings n_rays to seed raise ValueError when changed.

True
air_absorption bool
True
n_rays int

Per source; default default_rays, from the room's volume (at least 20000).

None
energy_thres float

The product of its reflections in its least absorbed band at which a ray stops; the logged energy is that over the squared distance (Schroeder 2011, Eq. 5.54), so the tail has decayed much further.

1e-7
duration float

Of the ray-traced responses, in seconds. Default: default_duration, traced again longer while the responses end before 2/3 of their T30 (up to 12 s). A given duration is kept and warns when it cuts the decay. Without ray tracing the responses have their natural length.

None
receiver_radius float

In metres.

0.5
seed bool or int

True seeds with 42, an int with that value, False or None leaves the run unseeded (generation["seed"] = None).

True
normalize bool

Whether the responses are peak-normalized views.

True
air AirConditions

Its speed of sound and, with air_absorption, its ISO 9613-1 absorption; default AirConditions().

None

Examples:

>>> import compas_acoustics as ca
>>> scene = ca.Scene("office")
>>> wall = ca.AcousticMaterial("wall", 0.2, 0.1)
>>> scene.add_acoustic_objects(ca.AcousticObjectsLibrary.shoebox_room(6, 5, 3, materials=wall))
>>> scene.add_source(ca.Source("talker", 1.5, 1.5, 1.6))
>>> scene.add_receiver(ca.Receiver("listener", 4.0, 3.0, 1.2))
>>> responses = scene.simulate(ca.Mono(image_source_order=2, ray_tracing=False))
>>> ir = next(iter(responses.values()))
>>> ir.sampling_rate, ir.n_channels, ir.generation["method"]
(48000, 1, 'mono')

Ray tracing, on by default, adds the late reflections; the seed makes a run repeatable.

>>> responses = scene.simulate(ca.Mono(n_rays=2000, duration=0.5))
>>> ir = next(iter(responses.values()))
>>> ir.ir.shape, ir.generation["seed"]
((24000,), 42)

Ray

Ray(points, source=None, source_index: Optional[int] = None, ray_index: Optional[int] = None, direction=None, distance_offset: float = 0.0, name: Optional[str] = None)

Bases: _PackageDtype, Polyline

A ray traced through a scene, the polyline [source_position, hit_1, hit_2, ...].

Times are distances at Defaults().DEFAULT_SPEED_OF_SOUND.

Parameters:

Name Type Description Default
points list
required
source [`compas_acoustics.Source`][compas_acoustics.source.Source]
None
source_index int

The source's index in the scene.

None
ray_index int

The ray's index among those of its source.

None
direction [`compas.geometry.Vector`][compas.geometry.Vector] or list

The initial direction; default that of the first segment.

None
distance_offset float

The distance travelled before points[0]: non-zero for a scattered ray born at a hit.

0.0
name str
None

Attributes

cumulative_distances property
cumulative_distances: List[float]

The travelled distance from the ray origin at each vertex, including distance_offset.

reflection_order property
reflection_order: int

The number of segments (hops) of the ray.

segment_lengths property
segment_lengths: List[float]

The length of each segment of the ray.

total_distance property
total_distance: float

The total distance travelled by the ray, including distance_offset.

travel_time property
travel_time: float

The total travel time of the ray in milliseconds.

Methods:

up_to_distance
up_to_distance(distance: Optional[float]) -> Optional[Ray]

A copy of the ray cut at distance from the source (distance_offset included); None: all.

Returns None if the ray has not emerged yet at distance.

up_to_reflection_order
up_to_reflection_order(order: Optional[int]) -> Ray

A copy of the ray with its first order segments; None: all.

up_to_time
up_to_time(time_ms: Optional[float]) -> Optional[Ray]

A copy of the ray cut at time_ms milliseconds, as up_to_distance.

RayField

RayField(rays: Optional[List[Ray]] = None, name: Optional[str] = None)

Bases: _PackageDtype, Data

Traced rays, with filters and display.

Parameters:

Name Type Description Default
rays list of [`compas_acoustics.Ray`][compas_acoustics.rays.Ray]

The specular rays, each with its scattered rays in ray.scattered_reflections.

None
name str
None

Attributes

scattered_rays property
scattered_rays: List[ScatteredRay]

All scattered rays across every ray in the field.

Methods:

display_in_viewer
display_in_viewer(scene=None, reflection_order: Optional[int] = None, travel_time_ms: Optional[float] = None, show_specular: bool = True, show_scattered: bool = False, color=None, scattered_color=None, linewidth: float = 1.0, show: bool = True)

Display the rays, and the scene's geometry, sources and receivers when given, in a viewer.

reflection_order and travel_time_ms are those of truncated. With show=False the viewer is returned without being opened.

filter
filter(source=None, ray_index: Optional[Union[int, List[int]]] = None) -> RayField

A new field of the rays of source (object or index) and of ray_index (one or several).

from_scene classmethod
from_scene(scene, n_rays: int = 500, max_reflection_order: int = 10, direction=None, angle: Optional[float] = None, duration: Optional[float] = None, energy_thres: Optional[float] = None, sources=None, include_scattering: bool = False, scatter_density: int = 10, scatter_max_bounces: int = 1, scatter_band: Optional[int] = None, random_seed: Union[bool, int] = True)

Trace rays through the scene, for display.

Directions follow the energy of each source's first-order pattern, (p + (1 - p) cos(theta))^2, on a Fibonacci lattice; direction and angle put all n_rays into a cone. The scattered rays are the package's own illustration, not the scattering of the simulation methods: a hit with coefficient s spawns round(s * scatter_density) rays, cosine-weighted within 90 s degrees of the axis (1 - s) specular + s normal, sharing s of the ray's energy. Absorption and scattering are means over the octave grid of RoomGeometry.to_pra (from 62.5 Hz, nine bands at 48 kHz), not the seven material bands.

Parameters:

Name Type Description Default
scene [`compas_acoustics.Scene`][compas_acoustics.scene.Scene]
required
n_rays int

Per source.

500
max_reflection_order int
10
direction optional

The cone's axis and half angle in degrees; both or neither.

None
angle optional

The cone's axis and half angle in degrees; both or neither.

None
duration float

Seconds; a ray stops at the first reflection past it.

None
energy_thres float

A ray stops once the energy left to it falls below this.

None
sources list of [`compas_acoustics.Source`][compas_acoustics.source.Source]

Default: all of the scene's; source_index is the index in scene.sources.

None
include_scattering bool
False
scatter_density int

Scattered rays per hit at s = 1.

10
scatter_max_bounces int
1
scatter_band int

The band of that grid whose coefficient is used; default the mean of all.

None
random_seed bool or int

Seeds the scattered rays: True with 42, an int with that value, False or None not at all.

True
truncated
truncated(reflection_order: Optional[int] = None, travel_time_ms: Optional[float] = None) -> RayField

A new field of the rays cut to their first reflection_order segments and to travel_time_ms.

Receiver

Receiver(name: str, x: float, y: float, z: float, direction: Vector = None, radius=0.5, up: Vector = None)

Bases: _PackageDtype, Point

A receiver with an orientation, the frame of its ambisonic responses: x is direction, y its left, z up.

Parameters:

Name Type Description Default
name str

Lowercase, without spaces.

required
x float
required
y float
required
z float
required
direction [`compas.geometry.Vector`][compas.geometry.Vector]

Where it faces; default +x.

None
radius float

In metres; default 0.5. Stored and serialised only: the simulation methods do not use it.

0.5
up [`compas.geometry.Vector`][compas.geometry.Vector]

Default +z; only its component orthogonal to direction is used.

None

Attributes

frame property writable
frame

compas.geometry.Frame : The position and the axes of rotation; setting it sets direction and up.

rotation property
rotation

The orientation, a 3x3 proper rotation whose columns are the facing, left and up axes in world coordinates.

Its transpose takes a world vector to the receiver frame.

Methods:

from_frame classmethod
from_frame(name: str, frame, radius=0.5)

A receiver at frame.point, facing frame.xaxis with frame.zaxis up.

transform
transform(T)

Transform the receiver: its position and its orientation.

RoomGeometry dataclass

RoomGeometry(vertices: ndarray, faces: Tuple[Tuple[int, ...], ...], face_materials: Tuple[str, ...], face_names: Tuple[str, ...], face_roles: Tuple[str, ...], materials: Dict[str, SurfaceMaterial], is_closed: bool, open_edge: Optional[Tuple[Tuple[float, ...], Tuple[float, ...]]] = None, obstacle_faces: Tuple[Tuple[int, ...], ...] = (), obstacle_face_materials: Tuple[str, ...] = ())

Every surface of a scene as one room: welded, oriented, materials on SYNTHESIS_BANDS.

Faces are listed boundary first, then the front and then the back copy of every obstacle face. is_closed says whether the boundary faces close a volume; open_edge holds the end points of the first edge that prevents it.

Attributes

surface_area property
surface_area: float

Total area exposed to the air: the S of Sabine, Eyring and the mean free path 4 V / S.

surfaces property
surfaces: List[Tuple[float, SurfaceMaterial]]

(area, material) per material over the faces exposed to the air (see _exposed_faces).

volume cached property
volume: float

The air volume: the boundary's less the volume each closed obstacle encloses; a closed room only.

Methods:

area_normals
area_normals() -> ndarray

The unit normal of every exposed face times its area, (n_exposed, 3); the boundary faces come first.

faces_with_materials
faces_with_materials() -> List[Tuple[ndarray, str]]

Every face as (vertices (k, 3), material name), obstacle copies included.

from_mesh classmethod
from_mesh(vertices, faces, face_materials, materials, obstacles=(), merge_coplanar: bool = False) -> RoomGeometry

A room from shared vertices and faces, as from_scene; materials maps names to SurfaceMaterial, and the faces of the names in obstacles are obstacles.

from_scene classmethod
from_scene(scene, merge_coplanar: bool = True) -> RoomGeometry

Collect, weld, orient and validate every surface of scene.

Boundary faces that close a volume are wound outward; otherwise they are kept as drawn, with a UserWarning. Obstacle faces are stored twice, OBSTACLE_OFFSET either side and wound opposite, since a wall reflects off one side only. merge_coplanar joins coplanar faces of one object and material into larger walls (a triangulated CAD mesh); False keeps them and warns where it could. Vertices within 1 mm, a CAD model's usual absolute tolerance, are welded.

is_inside
is_inside(point) -> bool

Whether point is in the air: inside a closed boundary (anywhere in an open scene) and outside every closed obstacle, by generalised winding numbers over the drawn faces.

to_pra
to_pra(fs: int, max_order: int, ray_tracing: bool = False, air_absorption: bool = False, air: Optional[AirConditions] = None) -> Room

The pyroomacoustics room, one wall per face, materials resampled to its octave grid (nine bands at 48 kHz).

Bands above 8 kHz hold the 8 kHz value, where linear extrapolation could pass 1. A material without scattering scatters DEFAULT_SCATTERING. The room answers is_inside with is_inside. air (default AirConditions()) sets the speed of sound (Cramer 1993) and, with air_absorption, the ISO 9613-1 absorption, in place of pyroomacoustics' own 343 m/s and absorption table.

ScatteredRay

ScatteredRay(points, parent_ray_index: Optional[int] = None, energy: Optional[float] = None, origin_reflection_order: int = 0, **kwargs)

Bases: Ray

A scattered ray born at a reflection point of a specular ray.

Parameters:

Name Type Description Default
points list

From the reflection point it scattered from.

required
parent_ray_index int
None
energy float

The scattered energy it carries.

None
origin_reflection_order int

The parent's segments up to that reflection point.

0
**kwargs {}

Attributes

reflection_order property
reflection_order: int

The specular reflection order of the originating hit point.

ScatteringResult

ScatteringResult(method, bands, s_bands, octave_bands, s_octaves, filled_octaves, s_angle, source_colatitude, source_azimuth, source_weights, receiver_directions, polar_sample_db, polar_reference_db, polar_source_indices=None, unconverged_octaves=None, warnings=None, generation=None, name=None, d_angle=None, d_bands=None, d_octaves=None)

Bases: _PackageDtype, Data

Scattering and diffusion coefficients of a sample, measured by a free-field method (ISO 17497-2; Heimes & Vorländer eq. 3 and eq. 11).

Use compas_acoustics.lab.scattering.measure_scattering to make one.

Parameters:

Name Type Description Default
method str

The method: "geometric" (heuristic, see generation["heuristic"]), "kirchhoff" or "bem".

required
bands list of int

The nominal one-third-octave centres in Hz.

required
s_bands list of float

The random-incidence scattering coefficient per band (Paris weighting of s_angle).

required
octave_bands list of int

The simulated octaves in Hz: 125...4000 by default, 125...8000 with the extended range.

required
s_octaves list of float

The mean of the one-third-octave values inside each simulated octave (ISO 354 §8.3, ISO 11654).

required
filled_octaves list of int

The material octaves that were not simulated and take the nearest simulated octave's value.

required
s_angle ndarray

The directional scattering coefficient, shape (n_sources, n_bands): Heimes & Vorländer eq. 3 per frequency, averaged per band (eq. 11); for "geometric" the heuristic s_max·(1 − exp(−(k h)²)) at the bands' exact centres.

required
source_colatitude ndarray

The source directions in degrees, shape (n_sources,).

required
source_azimuth ndarray

The source directions in degrees, shape (n_sources,).

required
source_weights ndarray

Their Paris random-incidence weights, summing to 1.

required
receiver_directions ndarray

Unit vectors from the sample to the receivers, shape (n_receivers, 3).

required
polar_sample_db ndarray

The levels at the receivers per source direction and simulated octave, shape (n_preview, n_octaves, n_receivers), float32: the mean of |p|² over the simulation frequencies in the octave, in dB relative to the reference's maximum for the same source and octave (for "geometric": the cells' energy per steradian, the same at every octave). −300 dB where the level is 0. Stored rounded to 0.1 dB, the resolution ISO 17497-2 §8.5 presents polar responses at.

required
polar_reference_db ndarray

The levels at the receivers per source direction and simulated octave, shape (n_preview, n_octaves, n_receivers), float32: the mean of |p|² over the simulation frequencies in the octave, in dB relative to the reference's maximum for the same source and octave (for "geometric": the cells' energy per steradian, the same at every octave). −300 dB where the level is 0. Stored rounded to 0.1 dB, the resolution ISO 17497-2 §8.5 presents polar responses at.

required
polar_source_indices list of int

The sources whose polar levels the result holds, as indices into the source arrays (source_colatitude ...): every source of a result of compas_acoustics.lab.measure_scattering. By default the first n_preview sources.

None
unconverged_octaves list of int

The simulated octaves holding a frequency at which the solver did not converge (BEM; see generation["unconverged"]): their values are unreliable.

None
warnings list of str

Where the result falls outside the standards or the method's validity.

None
generation dict

How the result was made: method, preset, band range, speed of sound, grid sizes and the solver's own record.

None
d_angle ndarray

The normalised directional diffusion coefficient d_n = (d − d_ref)/(1 − d_ref) (ISO 17497-2 eq. 6 on the intensities at the receivers, weighted by their solid angles, for the sample and for the reference), shape (n_sources, n_bands), averaged per band like s_angle. It is negative where the sample's response is less uniform than the reference's. None in a result made before d existed.

None
d_bands list of float

Its random-incidence value per band (the Paris weights of s_bands).

None
d_octaves list of float

Its mean per simulated octave, like s_octaves.

None

Attributes

scattering_coefficients property
scattering_coefficients

The coefficients on the 7 material octaves 125...8000 Hz; an octave not simulated takes the nearest simulated one's value.

ScatteringSample

ScatteringSample(sample, reference, mode, diameter, period=None, structural_depth=0.0, feature_size=None, symmetry='none', baseplate=0.01, warnings=None, name=None, reference_kind='flat')

Bases: _PackageDtype, Data

A scattering sample and its flat reference, both closed and triangulated (Heimes & Vorländer §3.2).

Use disc or as_drawn to make one.

Parameters:

Name Type Description Default
sample [`compas.datastructures.Mesh`][compas.datastructures.Mesh]

The closed sample body and the flat reference body with the same footprint, outward-oriented triangles.

required
reference [`compas.datastructures.Mesh`][compas.datastructures.Mesh]

The closed sample body and the flat reference body with the same footprint, outward-oriented triangles.

required
mode (disc, as_drawn)
"disc"
diameter float

The footprint diameter in m: the disc's, or, as drawn, the largest xy distance between outline vertices.

required
period tuple of float

The tile period (x, y) in m, in disc mode.

None
structural_depth float

The relief's height h in m: its maximum z, its minimum being at z = 0.

0.0
feature_size float

The relief's characteristic feature size in m, if known.

None
symmetry (none, rotational)
"none"
baseplate float

The thickness in m of the plate below z = 0 that closes both bodies.

0.01
warnings list of str

Problems found: ISO 17497-1 §6.3.2's depth limit h ≤ d/16, or a size that suggests millimetres.

None
reference_kind (flat, proxy)

Whether the reference is the flat footprint or a user-given proxy mesh.

"flat"

Methods:

as_drawn classmethod
as_drawn(mesh, baseplate=0.01, symmetry='none', feature_size=None, reference=None)

A relief as drawn, closed on a baseplate unless it is closed already (Heimes & Vorländer §3.2).

An open relief is walled down to z = −baseplate and closed by a bottom, like disc. A closed mesh is used as it is, its lowest point moved to z = −baseplate (so its bottom baseplate lies below z = 0); its reference is the outline of its bottom, flat at z = 0.

Parameters:

Name Type Description Default
mesh [`compas.datastructures.Mesh`][compas.datastructures.Mesh]

The detailed relief.

required
baseplate float
0.01
symmetry (none, rotational)
"none"
feature_size float
None
reference [`compas.datastructures.Mesh`][compas.datastructures.Mesh]

A proxy to use as the reference instead of the flat footprint: the simplified mesh the room model will carry the scattering coefficient on. It must be open when mesh is open and closed when mesh is closed, share its outline, and is placed with the same z shift as mesh. s then measures the share of the relief's reflection that the proxy does not reproduce.

None

Raises:

Type Description
ValueError

If the relief has not exactly one closed outline, or a closed mesh has no flat bottom, or the proxy is open where the relief is closed (or the other way round) or has another outline.

disc classmethod
disc(tile, diameter, period=None, baseplate=0.01, segments=128, offset=(0.0, 0.0), symmetry='none', feature_size=None)

A tile repeated over the plane and cropped to a disc of diameter (ISO 17497-1 §6.3.2, Heimes & Vorländer §3.2).

Parameters:

Name Type Description Default
tile [`compas.datastructures.Mesh`][compas.datastructures.Mesh]

One period of the relief; quads, n-gons and unwelded seams are fine.

required
diameter float

The disc diameter d in m.

required
period tuple of float

The tile period (x, y) in m; by default the tile's xy bounding box.

None
baseplate float

The plate thickness in m below z = 0.

0.01
segments int

The sides of the regular polygon, inscribed in the circle of radius d/2, that stands for the disc.

128
offset tuple of float

The shift (x, y) in m of the tiling relative to the disc centre at the origin.

(0.0, 0.0)
symmetry (none, rotational)
"none"
feature_size float
None

Raises:

Type Description
ValueError

If the cropped relief has holes or parts, i.e. not exactly one closed outline.

Scene

Scene(name: str, description: str = '', sampling_rate: int = None)

Bases: _PackageDtype, Data

A room: its surfaces with their materials, sources, receivers, and the impulse responses simulated for them.

Parameters:

Name Type Description Default
name str
required
description str
''
sampling_rate int

Of every simulation; default 48000.

None

Examples:

>>> import compas_acoustics as ca
>>> scene = ca.Scene("office")
>>> room = ca.AcousticObjectsLibrary.shoebox_room(6, 5, 3, materials=ca.AcousticMaterial("wall", 0.2, 0.1))
>>> scene.add_acoustic_objects(room)
>>> scene.add_source(ca.Source("talker", 1.5, 1.5, 1.6))
>>> scene.add_receiver(ca.Receiver("listener", 4.0, 3.0, 1.2))
>>> len(scene.acoustic_objects), len(scene.sources), len(scene.receivers)
(6, 1, 1)
>>> scene.sampling_rate
48000

Attributes

sampling_rate property writable
sampling_rate: int

The sample rate simulate runs every method at.

scene_materials property
scene_materials

The unique acoustic materials used in the scene, keyed by material name.

sources property
sources

The scene's sources, then those attached to its acoustic objects.

Methods:

add_impulse_response
add_impulse_response(source: Source, receiver: Receiver, ir: ImpulseResponse, attribute: str = 'data') -> None

Store ir on the source-receiver edge under attribute: a method's name, or 'data', the latest mono response.

impulse_responses
impulse_responses(attribute: str = 'data') -> dict

Every response stored under attribute, keyed '<receiver guid>_<source guid>'.

populate_ir_graph
populate_ir_graph(impulse_responses: Union[dict, Iterable[ImpulseResponse]], attribute: str = 'data') -> None

Replace every response stored under attribute; other attributes are kept.

simulate
simulate(method) -> dict

Run a simulation method at sampling_rate and store its responses on the IR graph under its name.

A mono method's responses also go under 'data', the default of impulse_responses.

Parameters:

Name Type Description Default
method [`SimulationMethod`][compas_acoustics.simulation_methods.base.SimulationMethod]

E.g. Mono(ray_tracing=True), Binaural() or Ambisonics().

required

Returns:

Type Description
Dict[str, ImpulseResponse]

One per source-receiver pair inside the room, keyed '<receiver guid>_<source guid>'.

SimulationMethod

Bases: ABC

A way to compute impulse responses. See the module docstring for the output contract.

Methods:

compute abstractmethod
compute(context: SimulationContext) -> dict

One response per source-receiver pair, keyed '<receiver guid>_<source guid>'.

Source

Source(name: str, x: float, y: float, z: float, directivity: str = None, direction: Vector = None, sound_file: str = None)

Bases: _PackageDtype, Point

A sound source: position, directivity and facing, an optional sound file, and its level.

directivity is a first-order pattern p + (1 - p) cos(theta) about direction, one of 'omnidirectional' (the default), 'cardioid', 'supercardioid', 'hypercardioid' and 'bidirectional' (compas_acoustics.room.pra.CARDIOID_P); the name is checked when a method simulates the source.

spl is the free-field level on its axis at 1 m per octave band, 125 Hz to 8 kHz, in dB re 20 uPa, 120 dB in every band unless set (the package's choice). On the package scale the direct sound is 1 / (4 pi r) with gain 1 on axis, so Lp = spl + G - 20 dB (Analyser.sound_pressure_level).

Methods:

transform
transform(T)

Transform the source: its position and its direction.

SpecularPath

SpecularPath(points, order: int, walls: List[int], image, receiver_index: int, **kwargs)

Bases: Ray

An image-source path [source_position, hit_1, ..., hit_order, receiver_position].

Parameters:

Name Type Description Default
points list
required
order int

The number of reflections.

required
walls list of int

The wall of each reflection, in path order: indices into RoomGeometry.faces of RoomGeometry.from_scene(scene), obstacle copies included.

required
image [`compas.geometry.Point`][compas.geometry.Point] or list
required
receiver_index int

The receiver's index in the scene.

required
**kwargs {}

Attributes

reflection_order property
reflection_order: int

The number of walls the path is reflected by: its last segment ends at the receiver, not a wall.

SpecularReflections

SpecularReflections(rays: Optional[List[Ray]] = None, name: Optional[str] = None)

Bases: RayField

The image-source paths between sources and receivers: a RayField of SpecularPath.

Parameters:

Name Type Description Default
rays list of [`SpecularPath`][compas_acoustics.rays.SpecularPath]
None
name str
None

Attributes

orders property
orders: List[int]

The sorted distinct reflection orders present.

paths property

The reflection paths, the field's rays.

Methods:

filter
filter(source=None, ray_index: Optional[Union[int, List[int]]] = None, receiver_index: Optional[int] = None, order: Optional[Union[int, List[int]]] = None) -> SpecularReflections

As RayField.filter, and the paths to receiver_index of order (one or several).

from_scene classmethod
from_scene(scene, max_order: int = 3) -> SpecularReflections

The visible image-source paths of orders 0 to max_order, for every source and receiver inside the room.

The search records only the last wall of an image; _trace_back finds the others. An image found twice, through an edge, is kept once. Sources and receivers outside the room are left out with a UserWarning.

Functions:

regularized_fitness

regularized_fitness(values: list[float], target: float, k: float = 1.0) -> float

Mean absolute error to target plus k times the sample standard deviation; lower is better.

999 for no values, the package's choice.