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 |
None
|
data_origin
|
str
|
Default |
None
|
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 ( |
0
|
y
|
float
|
The geometry's reference point ( |
0
|
z
|
float
|
The geometry's reference point ( |
0
|
name
|
str
|
Default: the class name. |
None
|
role
|
str
|
|
'boundary'
|
group
|
str
|
The OBJ group the object was read from, for |
None
|
Methods:¶
assign_materials_by_group
staticmethod
¶
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
|
|
required |
Returns:
| Type | Description |
|---|---|
list of [`AcousticObject`][compas_acoustics.acoustic_object.AcousticObject]
|
|
assign_roles_by_group
staticmethod
¶
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
|
|
required |
Returns:
| Type | Description |
|---|---|
list of [`AcousticObject`][compas_acoustics.acoustic_object.AcousticObject]
|
|
from_obj
classmethod
¶
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 ( |
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 ( |
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, |
AirConditions
dataclass
¶
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.
Analyser
¶
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
|
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
|
|
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
|
|
plot_frequency_response
¶
Plot the magnitude response, with a 1/smooth octave smoothed one over it unless smooth is None.
print_table
¶
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 ( |
None
|
strength
|
dict
|
|
None
|
Returns:
| Type | Description |
|---|---|
dict
|
|
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
|
None
|
Returns:
| Type | Description |
|---|---|
dict
|
|
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
|
|
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
|
|
AudioPlayer
¶
Plays a sound file or an array, on Windows and macOS.
Attributes:
| Name | Type | Description |
|---|---|---|
system |
str
|
|
sound_type |
str
|
|
Attributes¶
duration
property
¶
The length of the array last played, in seconds; 0 for a file or nothing.
position
property
¶
Where the array's playback is, in seconds: it runs with the clock while playing, and holds when paused.
Methods:¶
play
¶
Play a file path, whole at its level, or an array with the arguments of play_array.
play_array
¶
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 |
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
|
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
|
|
required |
anechoic_sounds
|
dict or list
|
File paths, or a dict of ids to dicts with |
None
|
sampling_rate
|
int
|
Responses and sounds are resampled to it; default that of the first response. |
None
|
level
|
str
|
Default |
'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
¶
str : 'mono', 'binaural' or 'ambisonic', of the impulse responses and of the signal.
impulse_responses
property
writable
¶
dict : The impulse responses, (samples, channels) arrays at sampling_rate, ambisonic in ACN/SN3D.
output_channels
property
¶
int : Number of channels of the auralised signal: 1, 2, or (order + 1)**2 for ambisonics.
Methods:¶
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, |
export_convolved_sound
¶
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: |
None
|
gain
|
float
|
E.g. from |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The written signal, shaped (samples, channels), as float32. |
import_anechoic_sound
¶
An audio file as a mono (samples,) array at sampling_rate, multichannel files mixed down.
peak_dbfs
staticmethod
¶
Peak absolute value of a signal in dBFS (-inf for silence).
render_gains
staticmethod
¶
Defaults
¶
EnergyMap
¶
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 |
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 |
None
|
n_rays
|
int
|
Per source; default |
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 |
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
¶
The sound pressure level per point and band, (n, b), in dB; NaN outside the room.
spl_a
¶
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 |
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
|
|
None
|
channel_order
|
str
|
|
None
|
Attributes¶
format
property
¶
str : 'mono', 'binaural' (two channels, no ambisonic order) or 'ambisonic'.
ir
property
writable
¶
np.ndarray : Peak-normalized when normalized; setting it sets the raw response.
metadata
property
¶
dict : The response and how it was generated, as written next to it on export.
normalization_factor
property
¶
float : Peak absolute value of the raw impulse response across all channels.
Methods:¶
denormalize_group
staticmethod
¶
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
|
|
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
¶
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
|
As in |
True
|
Returns:
| Type | Description |
|---|---|
ImpulseResponse
|
|
to_wav
¶
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 |
None
|
Returns:
| Type | Description |
|---|---|
tuple of Path
|
The WAV and JSON files. |
MaterialCategory
¶
MaterialsLibrary
¶
MaterialsLibrary(library_path: str = None)
The materials of a folder of JSON files, one per material, looked up by name.
Attributes¶
materials_by_category
property
¶
materials_by_category: dict
dict : Sorted material names per MaterialCategory that has any, in the categories' order.
Methods:¶
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 |
3
|
ray_tracing
|
bool
|
Materials without scattering coefficients scatter 0.05 in every band. Without it, the settings |
True
|
air_absorption
|
bool
|
|
True
|
n_rays
|
int
|
Per source; default |
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: |
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
( |
True
|
normalize
|
bool
|
Whether the responses are peak-normalized views. |
True
|
air
|
AirConditions
|
Its speed of sound and, with |
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 |
0.0
|
name
|
str
|
|
None
|
Attributes¶
cumulative_distances
property
¶
The travelled distance from the ray origin at each vertex, including distance_offset.
total_distance
property
¶
total_distance: float
The total distance travelled by the ray, including distance_offset.
Methods:¶
up_to_distance
¶
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
¶
A copy of the ray with its first order segments; None: all.
RayField
¶
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 |
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
¶
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; |
None
|
include_scattering
|
bool
|
|
False
|
scatter_density
|
int
|
Scattered rays per hit at |
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
|
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 |
None
|
Attributes¶
frame
property
writable
¶
compas.geometry.Frame : The position and the axes of rotation; setting it sets
direction and up.
rotation
property
¶
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:¶
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
¶
(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
¶
The unit normal of every exposed face times its area, (n_exposed, 3); the boundary faces come first.
faces_with_materials
¶
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
|
{}
|
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: |
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 |
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 |
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 |
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 |
required |
polar_source_indices
|
list of int
|
The sources whose polar levels the result holds, as indices into the source arrays ( |
None
|
unconverged_octaves
|
list of int
|
The simulated octaves holding a frequency at which the solver did not converge (BEM; see
|
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 |
None
|
d_bands
|
list of float
|
Its random-incidence value per band (the Paris weights of |
None
|
d_octaves
|
list of float
|
Its mean per simulated octave, like |
None
|
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 |
None
|
reference_kind
|
(flat, proxy)
|
Whether the reference is the flat footprint or a user-given proxy mesh. |
"flat"
|
Methods:¶
as_drawn
classmethod
¶
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 |
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
¶
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¶
scene_materials
property
¶
The unique acoustic materials used in the scene, keyed by material name.
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
¶
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. |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, ImpulseResponse]
|
One per source-receiver pair inside the room, keyed |
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).
SpecularPath
¶
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 |
required |
image
|
[`compas.geometry.Point`][compas.geometry.Point] or list
|
|
required |
receiver_index
|
int
|
The receiver's index in the scene. |
required |
**kwargs
|
{}
|
SpecularReflections
¶
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¶
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.