Source code for acoustic_spaces.engine.simulate

"""Run the early and late stages for every source and listener of a room."""

from __future__ import annotations

import dataclasses
import math
import time
from collections.abc import Callable, Collection, Generator, Mapping, Sequence
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from typing import TYPE_CHECKING

import numpy as np

from acoustic_spaces import products
from acoustic_spaces.engine import early as early_stage
from acoustic_spaces.engine import late as late_stage
from acoustic_spaces.engine import run_size, tuning
from acoustic_spaces.engine import wave as wave_stage
from acoustic_spaces.engine.coherent import band_count
from acoustic_spaces.engine.crests import CrestDiffraction
from acoustic_spaces.engine.diffraction import EdgeDiffraction, Edges, find_edges
from acoustic_spaces.engine.edge_fade import EdgeFade
from acoustic_spaces.engine.grazing import apply_grazing
from acoustic_spaces.engine.model import TraceModel, free_field_energy
from acoustic_spaces.engine.refracted import direct_times, refraction_for, solve
from acoustic_spaces.engine.response import Deferred, Response
from acoustic_spaces.engine.row_paths import RowPaths
from acoustic_spaces.engine.turbulence import Eddies
from acoustic_spaces.geometry import distance_to_surface
from acoustic_spaces.parameters import RoomParameters
from acoustic_spaces.room import Room, every_left_out
from acoustic_spaces.scene import Scene
from acoustic_spaces.scene.model import FITTED_WALLS_OUTDOORS, FITTED_WALLS_STENCIL
from acoustic_spaces.scene.model import Simulation as SimulationSettings
from acoustic_spaces.spatial.directions import fibonacci_sphere

if TYPE_CHECKING:
    from acoustic_spaces.engine.long_term import LongTermLevels

#: Slot width of the late energy (s).
TIME_STEP = 1e-3


[docs] def mixing_time(volume_m3: float | np.ndarray | None) -> float | np.ndarray: """Time after the direct sound when the late field is diffuse (s): sqrt(V) ms, V the volume of the room the listener is in (one per listener in an array).""" if volume_m3 is None: return 0.02 return 1e-3 * np.sqrt(volume_m3)
[docs] @dataclass class SimulationResult: """Responses for every (source, listener) pair, plus run details.""" room: Room settings: SimulationSettings responses: dict[tuple[str, str], Response] #: Per source: rays, escaped rays, receiver radius, seed and timings. details: dict[str, dict[str, float]] = field(default_factory=dict) #: The buildings, barriers and vegetation of an outdoor scene that it was also run #: without (:func:`~acoustic_spaces.engine.insertion.simulate`), and their insertion #: loss per (source, listener) in each octave band (dB): the level without them less #: the level with them. Empty otherwise. removed: tuple[str, ...] = () insertion_loss: dict[tuple[str, str], np.ndarray] = field(default_factory=dict) #: The levels over a long term, when the scene has weather classes (``long_term``; #: :func:`~acoustic_spaces.engine.long_term.simulate`): the responses are the scene's #: own weather's, this holds each class's run and the levels combined. None otherwise. long_term: LongTermLevels | None = None #: The spread of each response's parameters from its materials' absorption #: uncertainty, by (source, listener) #: (:func:`~acoustic_spaces.engine.uncertainty.material_spread`), where it was drawn. #: Empty otherwise. spreads: dict = field(default_factory=dict)
[docs] def parameters(self) -> dict[tuple[str, str], RoomParameters]: """ISO 3382-1 parameters of every response.""" return {key: r.parameters() for key, r in self.responses.items()}
def __getitem__(self, key: tuple[str, str]) -> Response: return self.responses[key] def __iter__(self): return iter(self.responses.values()) def __len__(self) -> int: return len(self.responses)
def _towards(source: np.ndarray, listener: np.ndarray) -> np.ndarray | None: """Unit vector from the listener towards the source, or None where they meet.""" d = np.asarray(source, dtype=float) - np.asarray(listener, dtype=float) length = float(np.linalg.norm(d)) return d / length if length > 0 else None def response_length(room: Room, length_s: float, starts, ends) -> float: """How long responses last (s): ``length_s`` (``simulation.ir_length_s``). Outdoors, where sources and listeners can lie hundreds of metres apart, ``length_s`` counts from the latest direct sound, from any of ``starts`` (n, 3) to any of ``ends`` (m, 3), so no response is cut off before its sound arrives.""" if room.outdoor is None: return length_s starts = np.atleast_2d(np.asarray(starts, dtype=float)) ends = np.atleast_2d(np.asarray(ends, dtype=float)) farthest = float(np.max(np.linalg.norm(starts[:, None] - ends[None], axis=2))) return farthest / room.speed_of_sound() + length_s def check_late_method(room: Room, settings: SimulationSettings) -> None: """Raise ``ValueError`` if the statistical late method cannot run in ``room``: it needs a closed room, and outdoors there is no diffuse field to reckon it from.""" if settings.late.method != "statistical": return if room.outdoor is not None: raise ValueError( "the statistical late method needs a closed room; outdoors, use the stochastic " "ray tracer (simulation.late.method: stochastic_ray_tracing)" ) if room.volume_m3 is None: raise ValueError("the statistical late method needs a closed model") def _transition(settings: SimulationSettings, room: Room, points) -> float | np.ndarray: """How long after the direct sound the early paths end at each of ``points`` (s). Without a set transition the stochastic tracer hands over by order alone, and the statistical method keeps early paths until the mixing time of the room each point is in.""" if settings.transition_ms is not None: return settings.transition_ms * 1e-3 if settings.late.method == "statistical": return mixing_time(room.volume_at(points)) return math.inf def _max_partitions(settings: SimulationSettings) -> int | None: """The partitions a reflected early path may pass through: with the stochastic tracer, as many as the early stage follows, as the tracer leaves paths through more to the late part; with the statistical method, which takes the early paths' energy out of its own, any number.""" from acoustic_spaces import _native return None if settings.late.method == "statistical" else int(_native.MAX_FORKS) def _seed(base: int, index: int) -> int: return int(np.random.SeedSequence([base, index]).generate_state(1, np.uint64)[0]) def _as_room(room: Room | Scene | str | Path) -> Room: if isinstance(room, Room): return room if isinstance(room, Scene): return Room.from_scene(room) return Room.from_yaml(room) def _pick(items, names, kind): """The items named in ``names``, or with no names those in use: not left out with ``enabled: false``.""" if names is None: used = [item for item in items if item.in_use] if items and not used: raise ValueError(every_left_out(kind)) return used by_name = {item.name: item for item in items} missing = [n for n in names if n not in by_name] if missing: raise ValueError(f"unknown {kind}: {', '.join(missing)}") return [by_name[n] for n in names] def _candidates( model: TraceModel, source: np.ndarray, method: str, order: int, rays: int, threads: int, edges: _Edges | None = None, diffraction: str = "none", ): """The plane sequences the early stage tests at each listener. With edge diffraction on, the rays' first reflections come with the planes of the faces of every diffracting edge (``edges``) that ``source`` lies in front of, in its sight or not: the terms at an edge continue the reflections off its faces, and the rays miss a face the source sees nearly edge-on, such as a wall whose plane it stands close to, or one behind an obstacle.""" if method == "image_sources": return early_stage.exhaustive_candidates(model, source, order) found = early_stage.ray_traced_candidates(model, source, order, rays, threads) if found and edges is not None and diffraction != "none": found[0] = edges.with_faces(source, found[0]) return found class _Edges: """The model's diffracting edges, found when first needed.""" def __init__(self, model: TraceModel) -> None: self.model = model self._edges: Edges | None = None def with_faces(self, source: np.ndarray, first: np.ndarray) -> np.ndarray: """``first`` (n, 1), the planes of the first reflections the rays found, with the planes of the diffracting edges' faces that ``source`` lies in front of, as an edge's terms take it (round the edge from face 0, less than half a turn off the face), and off its plane. Whether the source sees the face is not tested: where something hides it, the reflection off it is a path that an edge cuts off, which the edge fade's terms then stand for. No such face is open sky: the edges the sky meets diffract nothing (:func:`~acoustic_spaces.engine.diffraction.find_edges`).""" model = self.model if self._edges is None: self._edges = find_edges(model) edges = self._edges if not len(edges): return first source = np.asarray(source, dtype=float) _, rho, phi, inside = edges.frame( np.arange(len(edges)), np.broadcast_to(source, (len(edges), 3)) ) reached = inside & (rho > 0.0) planes = np.concatenate( [ edges.plane[reached & (phi < np.pi), 0], edges.plane[reached & (phi > (edges.wedge - 1.0) * np.pi), 1], ] ) planes = np.unique(planes) distance = products.product(model.plane_normal[planes], source) - model.plane_offset[planes] planes = planes[np.abs(distance) > early_stage._ON_PLANE] return np.unique(np.concatenate([first[:, 0], planes]))[:, None] def diffraction( self, mode: str, source: np.ndarray, room: Room, name: str, orientation: np.ndarray, coherent: int = 0, both_sides: bool = False, threads: int = 0, candidates: list[np.ndarray] | None = None, rows: str = "edges", max_order: int = 1, ) -> _Diffraction | None: """Diffraction of the sound of source ``name`` at ``source``, coherent in the lowest ``coherent`` bands, with paths that reflect on both sides of an edge when ``both_sides``, and the sound over the crests of a terrain, on ``threads`` threads (0: every core); with the plane sequences the early stage tests (``candidates``), also the terms at the edges of every specular path, found or just missed, that make it fade in and out there (:mod:`~acoustic_spaces.engine.edge_fade`); with ``rows`` "solver" and early paths up to ``max_order``, the solver for whole rows where it stands for the paths over barriers and buildings (:mod:`~acoustic_spaces.engine.row_paths`). None when off or when there is nothing to bend over.""" if mode == "none": return None if self._edges is None: self._edges = find_edges(self.model) settings = { "speed_of_sound": room.speed_of_sound(), "air": room.air_attenuation(self.model.bands), "directivity": room.directivity(name, self.model.bands), "orientation": orientation, "coherent": coherent, } at_edges = None if len(self._edges): at_edges = EdgeDiffraction( self.model, source, mode=mode, edges=self._edges, both_sides=both_sides, threads=threads, **settings, ) crests = CrestDiffraction.of(self.model, source, **settings) if at_edges is None and crests is None: return None fade = None if at_edges is not None and candidates is not None: fade = EdgeFade(at_edges, candidates) whole = None if at_edges is not None: whole = RowPaths.of(self.model, source, rows, max_order, edges=self._edges, **settings) return _Diffraction(self._edges, at_edges, crests, fade, whole) @dataclass class _Diffraction: """The diffraction at the model's edges and over the terrain's crests, in turn.""" edges: Edges at_edges: EdgeDiffraction | None crests: CrestDiffraction | None fade: EdgeFade | None = None #: The solver for whole rows, where it stands for the paths over barriers and #: buildings in the vertical plane through the source and a listener. rows: RowPaths | None = None def apply( self, listener: np.ndarray, paths: early_stage.EarlyReflections, max_delay_s: float ) -> early_stage.EarlyReflections: # The terms at the edges of every specular path, from the specular paths, less # the edge diffraction's own paths over the edges. specular = paths if self.at_edges is not None: paths = self.at_edges.apply(listener, paths, max_delay_s) terms = ( None if self.fade is None else self.fade.terms(listener, specular, max_delay_s, paths) ) if terms is not None: paths = self.fade.join(paths, terms) if self.rows is not None: paths = self.rows.apply(listener, paths) if self.crests is not None: paths = self.crests.apply(listener, paths, max_delay_s) return paths
[docs] def early_paths( room: Room | Scene | str | Path, source: str | None = None, listener: str | None = None, *, max_order: int | None = None, method: str | None = None, diffraction: str | None = None, threads: int | None = None, ) -> early_stage.EarlyReflections: """Specular and diffracted paths from one source to one listener, without the late part: those a simulation keeps as early paths, up to ``scene.simulation``'s ``transition_ms`` after the direct sound (the mixing time with the statistical late method) and within ``ir_length_s``. Names default to the first source and listener; ``max_order``, ``method`` and ``diffraction`` default to ``scene.simulation.early``, ``threads`` to ``scene.simulation.performance.threads``. Useful for drawing paths. The room's checks, with which a simulation refuses to run, are not made (:meth:`~acoustic_spaces.room.Room.problems`): a listener nearer a surface than a ray can meet it, say, may lack the reflection off it here. """ room = _as_room(room) scene = room.scene cfg = scene.simulation.early if threads is None: threads = scene.simulation.performance.threads src = _pick(scene.sources, None if source is None else [source], "source")[0] lis = _pick(scene.listeners, None if listener is None else [listener], "listener")[0] model = TraceModel.from_room(room) target = np.array(lis.position, dtype=float) order = cfg.max_order if max_order is None else max_order orientation = np.array(src.orientation.rotation()) edges = _Edges(model) elements = src.elements() # A line's or a surface's points are uncorrelated: their paths add in energy. Indoors # each point's own do too; outdoors they add in pressure among themselves. coherent = coherent_bands(scene.simulation, model.absorption.shape[1]) coherent = coherent if len(elements) == 1 or room.outdoor is not None else 0 transition = float(np.squeeze(_transition(scene.simulation, room, target))) length = response_length(room, scene.simulation.ir_length_s, elements, target) eddies = Eddies.of(model, room.speed_of_sound()) parts = [] for position in elements: cutoff = min( float(np.linalg.norm(target - position)) / room.speed_of_sound() + transition, length, ) candidates = _candidates( model, position, method or cfg.method, order, cfg.rays, threads, edges, diffraction or cfg.diffraction, ) paths = straight = early_stage.find_paths( model, position, target, candidates, speed_of_sound=room.speed_of_sound(), air=room.air_attenuation(model.bands), max_delay_s=cutoff, directivity=room.directivity(src.name, model.bands), orientation=orientation, coherent=coherent, max_partitions=_max_partitions(scene.simulation), ) found = edges.diffraction( diffraction or cfg.diffraction, position, room, src.name, orientation, coherent, both_sides=cfg.diffraction_reflections == "both_sides", threads=threads, candidates=candidates, rows=cfg.rows, max_order=order, ) if found is not None: paths = found.apply(target, paths, cutoff) refraction = refraction_for( model, position, speed_of_sound=room.speed_of_sound(), air=room.air_attenuation(model.bands), directivity=room.directivity(src.name, model.bands), orientation=orientation, coherent=coherent, max_order=order, threads=threads, wide_angle=cfg.parabolic_equation == "wide_angle", barrier_frequencies=cfg.barrier_frequencies, open_ground_frequencies=cfg.open_ground_frequencies, edges=None if found is None else found.edges, ) if refraction is not None: paths = refraction.apply(target[None], [straight], [paths], np.array([cutoff]))[0] if model.plants is not None: paths = model.plants.attenuate(paths) if eddies is not None: paths = eddies.attach(paths) parts.append(apply_grazing(model, target, paths)) return _shared(parts, model.absorption.shape[1])
def _mixing( late_from: Mapping[str, Mapping[str, float]], names: list[str], kind: str ) -> tuple[np.ndarray, np.ndarray] | None: """Which of ``names`` are traced for their late part (indices), and the weights of each name's late part on theirs (names, traced); None when all are traced.""" if not any(name in late_from for name in names): return None index = {name: k for k, name in enumerate(names)} traced = [k for k, name in enumerate(names) if name not in late_from] column = {k: j for j, k in enumerate(traced)} weights = np.zeros((len(names), len(traced))) for k, name in enumerate(names): if name not in late_from: weights[k, column[k]] = 1.0 continue if not late_from[name]: raise ValueError(f"the late part of {name!r} comes from no {kind}") for other, weight in late_from[name].items(): if weight <= 0: raise ValueError(f"the late part of {name!r} takes positive weights") if other not in index or other in late_from: raise ValueError( f"the late part of {name!r} comes from {other!r}, which is no {kind} " "traced for its own" ) weights[k, column[index[other]]] += weight return np.array(traced, dtype=np.int64), weights def _mix_listeners(late: late_stage.LateEnergy, weights: np.ndarray) -> late_stage.LateEnergy: """``late``, traced at some listeners, for every listener: a row of ``weights`` each.""" def mix(a: np.ndarray) -> np.ndarray: return np.einsum("lt,t...->l...", weights, a) if a.size else a return dataclasses.replace( late, energy=mix(late.energy), directional=mix(late.directional), moments=mix(late.moments), batches=mix(late.batches), ) def _mixed(parts: Sequence[np.ndarray | Deferred], weights: np.ndarray) -> np.ndarray: """``parts`` (arrays of one shape, those :class:`Deferred` made first) summed with ``weights``.""" made = [part.make() if isinstance(part, Deferred) else part for part in parts] return np.einsum("t,t...->...", weights, np.array(made)) def coherent_bands(settings, bands: int) -> int: """How many of the lowest ``bands`` the early paths add in pressure in, with the simulation ``settings`` (``scene.simulation``).""" wave = settings.wave.max_band_hz if settings.wave.enabled else None return band_count(settings.early.coherent_max_band_hz, bands, wave) def _shared(parts: list[early_stage.EarlyReflections], bands: int) -> early_stage.EarlyReflections: """The paths of a line or surface source's points, each with its share of the power and the point it comes from.""" if len(parts) == 1: return parts[0] share = 1.0 / len(parts) return early_stage.EarlyReflections.concatenate( [ dataclasses.replace(p, energy=share * p.energy, point=np.full(len(p), k)) for k, p in enumerate(parts) ], bands, ) def _where(plan) -> str: """Where a late stage's plan traced the rays, and why, for progress messages.""" where = {"cpu": "the CPU", "gpu": "the GPU", "both": "the CPU and the GPU"}[plan.device] return f"{where} ({plan.reason})" if plan.reason else where def is_fed(source) -> bool: """Whether ``source`` has a feed of its own: a gain, an equalizer or a delay, which its responses take (:meth:`~acoustic_spaces.engine.response.Response.fed`).""" return source.gain_db != 0 or source.eq_db is not None or source.delay_ms > 0
[docs] def simulate( room: Room | Scene | str | Path, *, settings: SimulationSettings | None = None, sources: Sequence[str] | None = None, listeners: Sequence[str] | None = None, threads: int | None = None, progress: Callable[[str], None] | None = None, groups: np.ndarray | None = None, late_from: Mapping[str, Mapping[str, float]] | None = None, share_waves: Collection[str] | None = None, ) -> SimulationResult: """Simulate the room's impulse responses as set in ``scene.simulation``. ``room`` may be a :class:`Room`, a :class:`Scene` or a scene file. ``sources`` and ``listeners`` pick names from the scene, simulated even when left out (``enabled: false``); by default, those in use. ``threads`` overrides ``simulation.performance.threads`` (0 uses every core). Raises ``ValueError`` if :meth:`Room.problems` reports anything (it checks the sources and listeners in use and those named; every source, or every listener, left out is a problem when they are not named), if a name is not the scene's, or if there is no listener to simulate. ``groups`` (the group of each face, or -1; :func:`~acoustic_spaces.engine.reweight.face_groups`) keeps in each response the moments of the late part's reflections off each group, so that :meth:`Response.reweighted` gives it for other absorption (stochastic ray tracing only). ``late_from`` gives listeners or sources the late part of others, mixed: ``{name: {other: weight}}``, the others being listeners (for a listener) or sources (for a source) that keep their own. Only those are traced by the stochastic ray tracer, by far the costliest stage; the statistical method gives everyone their own. Walks use it (:func:`acoustic_spaces.walkthrough.simulate_walk`): the late field changes slowly from place to place, the early sound does not. The traced late parts are kept once, and a response makes its mix of them when it reads its late part (:class:`~acoustic_spaces.engine.response.Deferred`); only a line's or a surface's is mixed for every listener as it is traced. ``share_waves`` names sources whose runs of the parabolic equation (outdoors in wind or temperature gradients) may serve one another: those at one height over one ground, the sound going the same way to their listeners, where the weather and the grounds have no zones (:func:`~acoustic_spaces.engine.refracted.solve`), each listener getting what its own source's run would give it. Walks give it the places of a walking source, which would otherwise each run the equation anew. """ room = _as_room(room) # Sources or listeners named are simulated even when left out. unnamed = [ kind for kind, names in (("sources", sources), ("listeners", listeners)) if names is None ] named = {"sources": sources or (), "listeners": listeners or ()} problems = room.problems(in_use=unnamed, named=named) if problems: raise ValueError("; ".join(problems)) scene = room.scene settings = settings or scene.simulation if threads is None: threads = settings.performance.threads say = progress or (lambda _: None) chosen_sources = _pick(scene.sources, sources, "source") chosen_listeners = _pick(scene.listeners, listeners, "listener") if not chosen_listeners: raise ValueError("no listener to simulate") faces = 0 if groups is None else int(np.max(groups, initial=-1)) + 1 run_size.check( run_size.simulation_need( room, settings, chosen_sources, chosen_listeners, threads, groups=faces, mixed=late_from or (), ) ) # Seeds follow the scene's order, so a run of some sources or listeners gives them # what a run of all does, as coverage maps do. source_index = {source.name: k for k, source in enumerate(scene.sources)} listener_index = {listener.name: k for k, listener in enumerate(scene.listeners)} model = TraceModel.from_room(room, settings) c = room.speed_of_sound() air = room.air_attenuation(model.bands) volume = room.volume_m3 listener_pos = np.array([lis.position for lis in chosen_listeners], dtype=float) # The volume of each listener's room, for its tail's density. The detector is sized # for all the rooms (`volume`), which the rays spread over. volumes = room.volume_at(listener_pos) length = response_length( room, settings.ir_length_s, [point for source in chosen_sources for point in source.elements()], listener_pos, ) seed = settings.seed if seed is None: seed = int(np.random.SeedSequence().generate_state(1, np.uint32)[0]) early_cfg, late_cfg = settings.early, settings.late # Not set in the scene: this computer's default. late_device = tuning.resolve_device(late_cfg.device) statistical = late_cfg.method == "statistical" check_late_method(room, settings) if groups is not None and statistical: raise ValueError("face groups need the stochastic ray tracer, not the statistical method") # Early paths end `transition` after the direct sound, at each listener. transition = _transition(settings, room, listener_pos) max_partitions = _max_partitions(settings) late_from = {} if late_from is None or statistical else late_from unknown = sorted(set(late_from) - {item.name for item in [*chosen_listeners, *chosen_sources]}) if unknown: raise ValueError(f"late_from names {unknown[0]!r}, which is no listener or source here") listener_mix = _mixing(late_from, [lis.name for lis in chosen_listeners], "listener") source_mix = _mixing(late_from, [source.name for source in chosen_sources], "source") # The listeners the late part is traced at. traced_at = slice(None) if listener_mix is None else listener_mix[0] edges = _Edges(model) low_bands = coherent_bands(settings, model.absorption.shape[1]) eddies = Eddies.of(model, c) responses: dict[tuple[str, str], Response] = {} details: dict[str, dict[str, float]] = {} # Refused before any ray is traced: settings given here are not checked against the # scene, which refuses fitted walls outdoors, nor checked again once changed. if settings.wave.enabled and settings.wave.walls == "fitted": if settings.wave.scheme == "isotropic": raise ValueError(FITTED_WALLS_STENCIL) if room.outdoor is not None: raise ValueError(FITTED_WALLS_OUTDOORS) for source in chosen_sources: if settings.wave.enabled and source.extended: raise ValueError( f"source {source.name!r} is a line or surface; the wave solver takes point " "sources only" ) def add(info: dict[str, float], key: str, value: float) -> None: info[key] = info.get(key, 0.0) + value # The air's profiles by their key, which every source bent by it shares # (:meth:`~acoustic_spaces.engine.refracted.Refraction.profile`). profiles: dict = {} def trace_point( name, label, position, directivity, orientation, point_seed, rays, info, single, own_late ) -> Generator: """Direct sound times, early paths and late energy at every listener of one point of the source ``name``, which radiates all the power; timings and counts go into ``info``. Unless ``single``, one of the uncorrelated points of a line or surface, whose paths add in energy (indoors; outdoors in pressure among themselves). Unless ``own_late``, no late energy (None): it comes from other sources. A generator: in wind or temperature gradients it yields its requests of the parabolic equation (:meth:`~acoustic_spaces.engine.refracted.Refraction.plan`) and takes their pressures back (:func:`~acoustic_spaces.engine.refracted.solve`) with its share of the seconds their runs took.""" coherent = low_bands if single or room.outdoor is not None else 0 direct = np.linalg.norm(listener_pos - position, axis=1) / c cutoff = np.minimum(direct + transition, length) started = time.perf_counter() say(f"{label}: early reflections ({early_cfg.method}, order {early_cfg.max_order})") candidates = _candidates( model, position, early_cfg.method, early_cfg.max_order, early_cfg.rays, threads, edges, early_cfg.diffraction, ) paths = straight = [ early_stage.find_paths( model, position, listener_pos[k], candidates, speed_of_sound=c, air=air, max_delay_s=float(cutoff[k]), directivity=directivity, orientation=orientation, coherent=coherent, max_partitions=max_partitions, ) for k in range(len(chosen_listeners)) ] add(info, "candidates", float(sum(len(x) for x in candidates))) diffraction = edges.diffraction( early_cfg.diffraction, position, room, name, orientation, coherent, both_sides=early_cfg.diffraction_reflections == "both_sides", threads=threads, candidates=candidates, rows=early_cfg.rows, max_order=early_cfg.max_order, ) if diffraction is not None: whole = "" if diffraction.rows is None else ", whole rows by the solver" say(f"{label}: edge diffraction ({early_cfg.diffraction}{whole})") paths = [ diffraction.apply(listener_pos[k], paths[k], float(cutoff[k])) for k in range(len(chosen_listeners)) ] info["edges"] = float(len(diffraction.edges)) add(info, "diffracted_paths", float(sum(int(p.diffracted.sum()) for p in paths))) if diffraction.rows is not None: # A listener's octave bands that the solver for whole rows took, and # those it left to the paths over the edges. add(info, "rows_solved", float(diffraction.rows.taken)) add(info, "rows_left_to_edges", float(diffraction.rows.refused)) refraction = refraction_for( model, position, speed_of_sound=c, air=air, directivity=directivity, orientation=orientation, coherent=coherent, max_order=early_cfg.max_order, threads=threads, wide_angle=early_cfg.parabolic_equation == "wide_angle", barrier_frequencies=early_cfg.barrier_frequencies, open_ground_frequencies=early_cfg.open_ground_frequencies, edges=None if diffraction is None else diffraction.edges, profiles=profiles, ) if refraction is not None: say(f"{label}: paths bent by the wind and the temperature") # The parabolic equation's runs come back from whoever drives this, with this # source's share of their time; while they wait, other sources are traced, so # the timer stops, and what only the paths' search needed is let go, the paths # as they were before the bending too (the plan holds what it keeps of them). planned = refraction.plan(listener_pos, straight, paths, cutoff) del candidates, diffraction, straight, paths, refraction add(info, "early_s", time.perf_counter() - started) pressures, seconds = yield planned started = time.perf_counter() - seconds paths = planned.finish(pressures) # The plan, with the paths as they waited, is not kept while the late part is # traced. del planned, pressures direct = direct_times(direct, paths) if model.plants is not None: say(f"{label}: paths through vegetation") paths = [model.plants.attenuate(p) for p in paths] if eddies is not None: paths = [eddies.attach(p) for p in paths] # The diffuse field is reckoned less the paths as they would come without the # audience, so what the seats take from them is lost, not made up by the tail. plain = paths paths = [apply_grazing(model, listener_pos[k], p) for k, p in enumerate(paths)] add(info, "early_s", time.perf_counter() - started) started = time.perf_counter() if statistical: say(f"{label}: statistical late reverberation") t60 = room.reverberation_time("eyring", air_absorption=True, bands=model.bands) late = late_stage.statistical_energy( t60, volume, direct, plain, max_time=length, time_step=TIME_STEP, speed_of_sound=c, decay=late_stage.diffuse_decay(model, position, listener_pos, air, c), ) elif not own_late: late = None else: say(f"{label}: stochastic ray tracing ({rays} rays per band)") radius = late_cfg.receiver_radius if radius is None: # As for a point source with all the rays: the parts' rays add up. clearance = distance_to_surface(room.mesh, listener_pos[traced_at]) radius = late_stage.receiver_radius( volume, late_cfg.rays, length, c, clearance=clearance ) late = late_stage.stochastic_energy( model, position, listener_pos[traced_at], rays=rays, max_time=length, time_step=TIME_STEP, speed_of_sound=c, air=air, reception=late_cfg.reception, covered_order=early_cfg.max_order, covered_time=cutoff[traced_at], radius=radius, directions=fibonacci_sphere(late_cfg.directions), splitting=late_cfg.splitting, seed=point_seed, directivity=directivity, orientation=orientation, threads=threads, groups=groups, device=late_device, batches=late_cfg.batches, ) if late.plan is not None and late_device != "cpu": say(f"{label}: late rays traced on {_where(late.plan)}") add(info, "rays", float(late.rays)) add(info, "escaped_rays", float(late.escaped_rays)) add(info, "traced_rays", float(late.traced_rays)) info["receiver_radius_m"] = float(np.min(radius)) if listener_mix is not None and not single: # A line's or a surface's points are summed listener by listener as they # are traced, so each is mixed for every listener now; a point source's # stays as traced, and its responses mix it when they are read. late = _mix_listeners(late, listener_mix[1]) add(info, "late_s", time.perf_counter() - started) return direct, paths, late done = {} def trace_source(source) -> Generator: """Traces ``source`` into ``done`` and ``details``, its points in turn, yielding their requests of the parabolic equation as :func:`trace_point` does.""" src = np.array(source.position, dtype=float) elements = source.elements() directivity = room.directivity(source.name, model.bands) orientation = np.array(source.orientation.rotation()) info: dict[str, float] = {"seed": _seed(seed, source_index[source.name])} if len(elements) > 1: info["elements"] = float(len(elements)) if length != settings.ir_length_s: info["ir_length_s"] = length own_late = source.name not in late_from traced = [] for e_index, position in enumerate(elements): # One point source of a line or surface: its share of the rays, a seed of its own. single = len(elements) == 1 found = yield from trace_point( source.name, source.name if single else f"{source.name} ({e_index + 1})", position, directivity, orientation, info["seed"] if single else _seed(info["seed"], e_index + 1), math.ceil(late_cfg.rays / len(elements)), info, single, own_late, ) if traced and found[2] is not None: # The points' late energy is summed into the first's as each is traced, # so the source holds one point's at a time besides the sum. total = traced[0][2] total.energy += found[2].energy total.directional += found[2].directional total.moments += found[2].moments total.batches += found[2].batches found = (found[0], found[1], None) traced.append(found) direct = np.min([t[0] for t in traced], axis=0) cutoff = np.minimum(direct + transition, length) if len(traced) == 1: _, paths, late = traced[0] else: bands = model.absorption.shape[1] paths = [ _shared([t[1][k] for t in traced], bands) for k in range(len(chosen_listeners)) ] late = traced[0][2] if late is not None: share = 1.0 / len(traced) late.energy *= share late.directional *= share late.moments *= share late.batches *= share waves: list = [None] * len(chosen_listeners) if settings.wave.enabled: started = time.perf_counter() waves, wave_info = wave_stage.wave_responses( model, src, listener_pos, [listener.name for listener in chosen_listeners], max_band_hz=settings.wave.max_band_hz, # Past the response's end, for the bands' filters. length_s=length + wave_stage.PAST_END_S[model.bands], sample_rate=settings.sample_rate, speed_of_sound=c, points_per_wavelength=settings.wave.points_per_wavelength, threads=threads, device=tuning.resolve_device(settings.wave.device), scheme=settings.wave.scheme, say=say, label=source.name, wind=settings.wave.wind, walls=settings.wave.walls, ) info.update(wave_info) info["wave_s"] = time.perf_counter() - started details[source.name] = info done[source.name] = (src, direct, cutoff, paths, late, waves) sharing = set(share_waves or ()) & {source.name for source in chosen_sources} for source in chosen_sources: if source.name not in sharing: _drive([trace_source(source)]) # The sources that share the parabolic equation: each traced up to its requests, # then all of them run at once, and each traced on. _drive([trace_source(source) for source in chosen_sources if source.name in sharing]) details = {source.name: details[source.name] for source in chosen_sources} def giver(source) -> tuple[late_stage.LateEnergy, np.ndarray | None]: """The late energy traced for ``source`` (in ``done``), and the weights that mix it for every listener where it is still at the listeners it was traced at (``traced_at``); None where it is at all of them.""" mixes = listener_mix is not None and len(source.elements()) == 1 return done[source.name][4], listener_mix[1] if mixes else None def late_array(name: str, givers: list, shares: np.ndarray | None, k: int) -> np.ndarray: """The array ``name`` of the late part of a response at listener ``k``, from the sources it comes from (``givers``, as :func:`giver` gives each) summed with ``shares``, or from the one giver as it is for None. A mix, of the listeners the late part was traced at or of the sources, is made when the response reads it (:class:`Deferred`), of those with a weight alone: the others' energy times 0 would add nothing. Each value is summed over the parts in turn, as a mix of all the listeners at once sums it: the traced arrays are C-contiguous with more than one value a listener, so numpy's einsum does not run along the parts innermost (where it would sum with several accumulators, in another order).""" parts: list[np.ndarray | Deferred] = [] for late, weights in givers: array = getattr(late, name) if weights is None: parts.append(array[k]) else: used = np.flatnonzero(weights[k]) mix = partial(_mixed, [array[t] for t in used], weights[k][used]) parts.append(Deferred(mix)) part = parts[0] if shares is None else Deferred(partial(_mixed, parts, shares)) return part.field() if isinstance(part, Deferred) else part for s_index, source in enumerate(chosen_sources): src, direct, cutoff, paths, late, waves = done[source.name] shares = None if late is not None: givers = [giver(source)] else: row = source_mix[1][s_index] used = np.flatnonzero(row) givers = [giver(chosen_sources[source_mix[0][j]]) for j in used] shares = row[used] late = givers[0][0] if source_mix is None: # No other source takes this one's late part: once its responses have what # they keep of it (a copy, where the source is fed), it can go. del done[source.name] # Of the late part's arrays besides the energy, the response has those the # first source it comes from has, and batches only where every source has as # many. directional = bool(late.directional.size) moments = bool(late.moments.size) batches = bool(late.batches.size) and len({x.batches.shape[1:] for x, _ in givers}) == 1 info = details[source.name] fed = is_fed(source) free_field = None if room.outdoor is not None: free_field = free_field_energy( source.elements(), listener_pos, air, room.directivity(source.name, model.bands), np.array(source.orientation.rotation()), ) for k, listener in enumerate(chosen_listeners): response = Response( source=source.name, listener=listener.name, early=paths[k], late=late_array("energy", givers, shares, k), time_step=late.time_step, length_s=length, direct_delay_s=float(direct[k]), transition_s=float(cutoff[k]), volume_m3=None if volumes is None else float(volumes[k]), speed_of_sound=c, seed=_seed(info["seed"], listener_index[listener.name] + 1), orientation=np.array(listener.orientation.rotation()), late_directions=late.directions, late_directional=late_array("directional", givers, shares, k) if directional else np.zeros((0, 0, 0)), direction_step=late.direction_step, wave=waves[k], source_direction=_towards(src, listener_pos[k]), late_moments=late_array("moments", givers, shares, k) if moments else np.zeros((0, 0, 0)), moment_step=late.moment_step, late_batches=late_array("batches", givers, shares, k) if batches else np.zeros((0, 0, 0)), batch_step=late.batch_step, free_field=None if free_field is None else free_field[k], ) if fed: response = response.fed(source.feed_db(model.bands), source.delay_ms * 1e-3) responses[(source.name, listener.name)] = response return SimulationResult(room=room, settings=settings, responses=responses, details=details)
def _drive(steps: list[Generator]) -> None: """Runs the generators ``steps`` (sources being traced) to their ends, the requests of the parabolic equation each yields solved together with the others' at that point (:func:`~acoustic_spaces.engine.refracted.solve`) and sent back with each one's share of the time that took.""" waiting = [] for step in steps: try: waiting.append((step, next(step))) except StopIteration: pass while waiting: started = time.perf_counter() solved = solve([planned for _, planned in waiting]) # Each source's share of the runs' time. seconds = (time.perf_counter() - started) / len(waiting) if len(solved) != len(waiting): raise ValueError(f"{len(solved)} sets of pressures for {len(waiting)} plans") going = [] # The sources in turn, the first first; each one's plan and pressures are taken # off the lists as they are sent, so that they do not stay while the others are # traced on. waiting.reverse() solved.reverse() while waiting: step = waiting.pop()[0] try: going.append((step, step.send((solved.pop(), seconds)))) except StopIteration: pass waiting = going __all__ = [ "TIME_STEP", "SimulationResult", "check_late_method", "early_paths", "mixing_time", "response_length", "simulate", ]