"""Early paths that add in pressure at low frequencies.
The echogram adds the early paths in energy, band by band, as if their phases were
random. At low frequencies they are not: a band's filter rings longer than the early
paths lie apart, and their pressures add. The impulse response has always added them
that way (its paths are impulses that add sample by sample), so the parameters of the
63 and 125 Hz bands read from it differed from the echogram's by up to 2 dB.
In the lowest bands, up to ``simulation.early.coherent_max_band_hz``, every early path
therefore carries its pressure (``EarlyReflections.spectrum``) at the frequencies the
edge diffraction is evaluated at: the phase of each reflection factor on the way, and
for paths over an edge the whole complex UTD coefficient, whose terms then add to the
specular paths in pressure, as the theory has them, rather than through the cross
terms of the higher bands. Its level in each band stays the energy that band gives it.
A surface reflects like a locally reacting one whose admittance has the material's
absorption in every band (:func:`~acoustic_spaces.engine.impedance.fit_admittance`), so
the phases in a band do not depend on how many bands add in pressure: R = (cos theta -
Y) / (cos theta + Y) at the angle of incidence theta. A hard surface reflects in phase at
every angle; an absorbing one turns the phase of sound that grazes it, by half a turn at
grazing incidence. Above those bands each path keeps the phase it has at their top
(:func:`held_phase`).
But for the paths over an edge: in those bands the energy of a wave bent round edges is
that of its pieces added up in pressure already (:mod:`~acoustic_spaces.engine.clusters`),
and each piece carries its share of it. Added in pressure once more, with the phases
held from the bands below, the pieces of one wave counted their interference twice: the
facets of BRAS's hall, thousands of pieces within a period, rendered 16 times their
energy at 250 Hz at the dummy head. A rendered response therefore turns each path over
an edge by a phase of its own (:func:`own_phases`), drawn from the path and the
response's seed, as far as other paths' sound reaches it where it arrives, so that it
adds to them in energy on average, as in the echogram. One that arrives alone keeps its
held phase, which its bands need to join the coherent ones. Reflections keep theirs: two
that arrive together add in pressure, as at a point of a real room, where the echogram
gives their average over the band.
The impulse response builds those bands' early part from the pressures, and the
echogram reads each band's early energy from the same signal through the band filters
of the analysis of measured responses
(:func:`~acoustic_spaces.parameters.band_filter_gains`), as for the wave solver's bands:
an impulse response and the echogram it came from now give the same parameters in those
bands. The filters let in a little of the bands above, where the echogram gives each
path over an edge the mean over seeds of the phase factor a rendered response turns it
by (:func:`with_mean_phases`): with the phases held, the pieces' interference counted
twice reached it through them, twice the early energy at 125 Hz at BRAS's hall's dummy
head.
The late part still adds in energy, and so do the uncorrelated points of a line or
surface source.
"""
from __future__ import annotations
import dataclasses
import functools
import hashlib
import math
from typing import TYPE_CHECKING
import numpy as np
from acoustic_spaces import products, synthesis
from acoustic_spaces.engine.fine import fine_rows, fine_shape
from acoustic_spaces.materials.bands import (
BANDS_PER_OCTAVE,
OCTAVE_BANDS_HZ,
band_centres,
resolution_of,
)
if TYPE_CHECKING:
from acoustic_spaces.engine.early import EarlyReflections
from acoustic_spaces.engine.model import TraceModel
#: Paths whose spectra are built at once.
_CHUNK = 256
#: Outdoors, where every band adds in pressure, at most this many values (paths times
#: frequencies) of the impulse response's spectra are built at once.
_MAX_VALUES = 1 << 22
#: The coherent bands up to this octave band are read through the analysis's band
#: filters (:class:`EarlyPressure`); outdoors, the bands above it from the interference
#: of each pair of paths averaged over the band (:func:`pair_energy`), which costs the
#: same however far the sound travels.
FILTERED_MAX_BAND_HZ = 500
#: How much longer than the last early path the echogram's early part is taken (s),
#: for the band filters' ringing.
_TAIL_S = 0.3
#: Taps of the windowed sinc that puts the paths on, and reads them off, the grid on
#: which :func:`arriving_with` finds the other paths' sound where each arrives.
_TAPS = 32
#: That grid's sample rate, in times the highest frequency of the band.
_OVERSAMPLE = 4.0
#: Silence before the first path and after the last on that grid, in times the inverse
#: of the band's width: longer than the band's filter rings.
_PAD = 12.0
[docs]
def band_count(max_band_hz: int | None, bands: int, wave_max_band_hz: int | None = None) -> int:
"""How many of the lowest of ``bands`` (8 octave or 24 third-octave bands) add in
pressure: those of the octave bands up to ``max_band_hz`` (None: none), and none
when the wave solver runs up to that band or higher (``wave_max_band_hz``), as its
bands take their place."""
if max_band_hz is None:
return 0
if wave_max_band_hz is not None and wave_max_band_hz >= max_band_hz:
return 0
octaves = OCTAVE_BANDS_HZ.index(int(max_band_hz)) + 1
return octaves * BANDS_PER_OCTAVE[resolution_of(bands)]
[docs]
def filtered_bands(paths: EarlyReflections) -> int:
"""How many of the paths' coherent bands are read through the band filters: those
up to :data:`FILTERED_MAX_BAND_HZ`."""
bands = paths.energy.shape[1]
return min(paths.coherent_bands, band_count(FILTERED_MAX_BAND_HZ, bands))
[docs]
def sample_frequencies(bands: int, count: int) -> np.ndarray:
"""(count, M) the frequencies (Hz) a spectrum holds in each of the lowest ``count``
of ``bands`` bands: those the edge diffraction is evaluated at."""
from acoustic_spaces.engine.diffraction import band_frequencies
return band_frequencies(bands=resolution_of(bands))[0][:count]
[docs]
def reflection_phases(
model: TraceModel, faces: np.ndarray, cosines: np.ndarray, count: int
) -> np.ndarray:
"""(n, count, M) e^(j arg R) of the reflections off ``faces`` (n,) of sound that
meets them at incidence cosines ``cosines`` (n,), at the frequencies of
:func:`sample_frequencies` of the lowest ``count`` bands: R is that of a locally
reacting surface whose admittance gives the face's absorption in every band; 1 for the
faces whose reflection :func:`ground_factors` gives (see
:meth:`~acoustic_spaces.engine.model.TraceModel.factor_faces`)."""
faces = np.asarray(faces, dtype=np.int64)
total = model.absorption.shape[1]
f = sample_frequencies(total, count)
out = np.ones((len(faces), *f.shape), dtype=complex)
if len(faces) == 0 or count == 0:
return out
if model.face_impedance is not None or model.ground_part is not None:
fitted = ~model.factor_faces(faces)
if fitted.any():
out[fitted] = _fitted_phases(
model, faces[fitted], np.asarray(cosines)[fitted], f, out[fitted]
)
return out
return _fitted_phases(model, faces, cosines, f, out)
def _fitted_phases(model, faces, cosines, f, out):
""":func:`reflection_phases` into ``out`` for faces without an impedance."""
out[...] = absorption_phases(model.absorption[faces], cosines, f)
return out
[docs]
def absorption_phases(
absorption: np.ndarray, cosines: np.ndarray, f: np.ndarray, admittance_of=None
) -> np.ndarray:
"""(n, count, M) e^(j arg R) at the frequencies ``f`` (count, M) of
reflections at incidence cosines ``cosines`` (n,) off locally reacting surfaces whose
admittance gives the absorption ``absorption`` (n, bands) in every band, as
:func:`reflection_phases` has them. ``admittance_of(row)`` gives the admittance (a
callable of the frequency) of an absorption row; by default the one fitted to it
(:func:`~acoustic_spaces.engine.impedance.fit_admittance`)."""
y = _fitted_admittances(absorption, f, admittance_of)
cos = np.clip(np.asarray(cosines, dtype=float), 0.0, 1.0)[:, None, None]
total_ = cos + y
hard = np.abs(total_) < 1e-12 # a hard surface met at grazing incidence
r = (cos - y) / np.where(hard, 1.0, total_)
magnitude = np.abs(r)
return np.where(hard | (magnitude < 1e-12), 1.0, r / np.maximum(magnitude, 1e-300))
def _fitted_admittances(absorption: np.ndarray, f: np.ndarray, admittance_of=None) -> np.ndarray:
"""(n, *f.shape) the admittances at the frequencies ``f`` of locally reacting
surfaces whose admittance gives the absorption ``absorption`` (n, bands) in every
band: ``admittance_of(row)`` (a callable of the frequency) of each absorption row, by
default the one fitted to it (:func:`~acoustic_spaces.engine.impedance.
fit_admittance`)."""
from acoustic_spaces.engine.impedance import fit_admittance
absorption = np.asarray(absorption, dtype=float)
total = absorption.shape[1]
rows, inverse = np.unique(absorption, axis=0, return_inverse=True)
admittance = np.array(
[
(fit_admittance(row, total, None) if admittance_of is None else admittance_of(row))(f)
for row in rows
]
)
return admittance[inverse.reshape(-1)]
[docs]
def ground_wave_factors(model: TraceModel, faces: np.ndarray, distance: np.ndarray) -> np.ndarray:
"""(n, bands, M) the Weyl-van der Pol factor Q of the sound that runs ``distance``
(n,) m along ``faces`` (n,) at grazing incidence, from a point on them, at the
frequencies of every band's samples: the field there is (1 + Q) = 2 F(w) times the
free one (see :func:`~acoustic_spaces.materials.ground.spherical_reflection`). Faces
with an impedance of their own take :func:`ground_factors`' spherical wave, the
others, a ground zone's among them, that of the admittance fitted to their absorption
(as :func:`reflection_phases` has it); a hard face gives 1."""
from acoustic_spaces.engine.diffraction import band_frequencies
from acoustic_spaces.materials.ground import spherical_reflection
faces = np.asarray(faces, dtype=np.int64)
distance = np.asarray(distance, dtype=float)
out = ground_factors(model, faces, np.zeros(len(faces)), distance)
other = ~model.impedance_faces(faces)
if other.any():
f = band_frequencies(bands=model.bands)[0]
k = 2.0 * np.pi * f / model.room.speed_of_sound()
admittance = _fitted_admittances(model.absorption[faces[other]], f)
out[other] = spherical_reflection(admittance, 0.0, k, distance[other, None, None])
return out
[docs]
def ground_factors(
model: TraceModel,
faces: np.ndarray,
cosines: np.ndarray,
distance: np.ndarray | None,
spherical: bool = True,
ends: tuple[np.ndarray, np.ndarray, np.ndarray] | None = None,
) -> np.ndarray:
"""(n, bands, M) the reflection factors off ``faces`` (n,) of sound that meets them
at incidence cosines ``cosines`` (n,), at the frequencies of every band's samples
(:func:`~acoustic_spaces.engine.diffraction.band_frequencies`): for surfaces with an
impedance, that of the spherical wave (Weyl-van der Pol, see
:func:`~acoustic_spaces.materials.ground.spherical_reflection`) along paths
``distance`` (n,) m long from the image source, or with ``spherical`` False the
plane wave's; 1 for the others.
On the ground of a scene with ground zones, a reflection is the sum of the factors
of the grounds its Fresnel zone covers, each weighted by the share it covers (see
:meth:`~acoustic_spaces.geometry.outdoor.Layout.fresnel_shares`), from the points
``ends`` (n, 3) before the reflection, of the reflection and after it; without
``ends``, the ground's own. There, a ground without an impedance reflects with the
square root of (1 - its absorption) and the phase of :func:`reflection_phases`."""
from acoustic_spaces.engine.diffraction import band_frequencies
faces = np.asarray(faces, dtype=np.int64)
f = band_frequencies(bands=model.bands)[0]
out = np.ones((len(faces), *f.shape), dtype=complex)
mixed = np.zeros(len(faces), dtype=bool)
if model.ground_part is not None:
mixed = model.ground_part[faces] >= 0
rows = np.flatnonzero(model.impedance_faces(faces) & ~mixed)
if len(rows):
length = None if distance is None else np.asarray(distance, dtype=float)[rows]
out[rows] = _surface_factors(model, faces[rows], cosines, rows, length, spherical, f)
rows = np.flatnonzero(mixed)
if len(rows) == 0:
return out
part = model.ground_part[faces[rows]]
if ends is None:
shares = np.zeros((len(rows), f.shape[0], len(model.part_face)))
shares[np.arange(len(rows)), :, part] = 1.0
else:
before, at, after = (np.asarray(p, dtype=float)[rows] for p in ends)
wavelength = model.room.speed_of_sound() / np.asarray(model.band_hz, dtype=float)
shares = model.room.outdoor.fresnel_shares(before, at, after, wavelength)
# A part with no faces (the ground outside zones that cover it all) is the one
# the reflection lies in.
empty = model.part_face < 0
if empty.any():
shares[np.arange(len(rows)), :, part] += shares[..., empty].sum(axis=-1)
shares[..., empty] = 0.0
mix = np.zeros((len(rows), *f.shape), dtype=complex)
length = None if distance is None else np.asarray(distance, dtype=float)[rows]
for p, face in enumerate(model.part_face.tolist()):
some = np.flatnonzero(np.any(shares[:, :, p] > 0.0, axis=1))
if face < 0 or len(some) == 0:
continue
factor = _surface_factors(
model,
np.full(len(some), face),
cosines,
rows[some],
None if length is None else length[some],
spherical,
f,
)
mix[some] += shares[some, :, p, None] * factor
out[rows] = mix
return out
def _surface_factors(model, faces, cosines, rows, distance, spherical, f) -> np.ndarray:
"""(n, bands, M) :func:`ground_factors` off ``faces`` (n,) on their own, at the
incidence cosines ``cosines[rows]``: an impedance's spherical (or plane) wave, or for
a surface without one the square root of (1 - its absorption) with the phase of its
fitted admittance."""
from acoustic_spaces.materials.ground import plane_reflection, spherical_reflection
cos = np.asarray(cosines, dtype=float)[rows]
out = np.empty((len(faces), *f.shape), dtype=complex)
own = model.impedance_faces(faces)
if own.any():
which = model.face_impedance[faces[own]]
admittance = model.admittance[which] # (r, bands, M)
extended = model.impedance_extended[which]
if extended.any():
# The extended reaction: the admittance each path meets at its own angle.
admittance = admittance.copy()
c = model.room.speed_of_sound()
angles = cos[own]
for k in np.unique(which[extended]):
at = np.flatnonzero(extended & (which == k))
admittance[at] = model.impedances[k].admittance(
f[None], c, cosine=angles[at, None, None]
)
if spherical:
k = 2.0 * np.pi * f / model.room.speed_of_sound()
length = np.asarray(distance, dtype=float)[own, None, None]
out[own] = spherical_reflection(admittance, cos[own, None, None], k, length)
else:
out[own] = plane_reflection(admittance, cos[own, None, None])
if not own.all():
other = ~own
phase = _fitted_phases(
model, faces[other], cos[other], f, np.ones((other.sum(), *f.shape), complex)
)
level = np.sqrt(np.clip(1.0 - model.absorption[faces[other]], 0.0, None))
out[other] = level[:, :, None] * phase
return out
[docs]
def shaped(
spectrum: np.ndarray,
bands: int,
f: np.ndarray,
amplitude: np.ndarray,
gains: np.ndarray,
fine: np.ndarray | None = None,
fine_delay: np.ndarray | None = None,
) -> np.ndarray:
"""(n, len(f)) the coherent bands' amplitudes (n, count) through the synthesis's
band ``gains`` (count, len(f)) at frequencies ``f`` (Hz), each band's times the
shape its spectra (n, count, M, :attr:`EarlyReflections.spectrum`) give it: the
magnitude and the unwrapped phase interpolated linearly in log frequency between
the band's own samples and held beyond them. A band so carries its own sound into
the crossovers with its neighbours, not theirs: outdoors a path's bands below the
parabolic equation's top band hold the whole sound over the ground and those above
it the path's own, and a shape drawn across that edge would notch the sum.
Paths with the parabolic equation's samples in a band (``fine`` (n, count, K) and
``fine_delay`` (n,), :attr:`EarlyReflections.fine`) take its shape through those
and the neighbouring bands' instead (:func:`~acoustic_spaces.engine.fine.
fine_shape`), so that both bands of a crossover give the field it has there."""
n, count, per_band = spectrum.shape
samples = np.log2(sample_frequencies(bands, count)) # (count, M)
x = np.log2(np.maximum(np.asarray(f, dtype=float), 1e-6))
out = np.zeros((n, len(f)), dtype=complex)
for b in range(count):
support = np.flatnonzero(gains[b] > 0.0)
if len(support) == 0:
continue
lo, hi = int(support[0]), int(support[-1]) + 1
live = amplitude[:, b]
if fine is not None and fine_delay is not None:
# The paths with the equation's samples here, apart from the others.
rows = fine_rows(fine, b, bands)
if len(rows):
out[rows, lo:hi] += (amplitude[rows, b, None] * gains[b, lo:hi]) * fine_shape(
fine[rows], fine_delay[rows], bands, b, np.asarray(f, dtype=float)[lo:hi]
)
live = live.copy()
live[rows] = 0.0
own = spectrum[:, b]
if per_band == 1:
shape = np.repeat(own, hi - lo, axis=1)
out[:, lo:hi] += (live[:, None] * gains[b, lo:hi]) * shape
continue
xs = np.clip(x[lo:hi], samples[b, 0], samples[b, -1])
j = np.clip(np.searchsorted(samples[b], xs, side="right") - 1, 0, per_band - 2)
w = (xs - samples[b, j]) / (samples[b, j + 1] - samples[b, j])
magnitude = np.abs(own)
phase = np.unwrap(np.angle(own), axis=1)
# The frequencies below the band's first sample and above its last are held to
# it, so all of them have the same shape: worked out once for each run of them
# at the ends, the same in each of its bins.
first = _run(xs == samples[b, 0])
last = len(xs) - _run(xs[::-1] == samples[b, -1])
last = max(last, first)
for start, stop, held in ((0, first, True), (first, last, False), (last, len(xs), True)):
if stop > start:
at = slice(start, start + 1) if held else slice(start, stop)
shape = _between(magnitude, phase, j[at], w[at])
out[:, lo + start : lo + stop] += (
live[:, None] * gains[b, lo + start : lo + stop]
) * shape
return out
def _between(magnitude: np.ndarray, phase: np.ndarray, j: np.ndarray, w: np.ndarray):
"""(n, len(j)) the magnitude and the phase (n, M) taken a share ``w`` of the way from
sample ``j`` to the next, as a complex value."""
level = magnitude[:, j] * (1.0 - w) + magnitude[:, j + 1] * w
angle = phase[:, j] * (1.0 - w) + phase[:, j + 1] * w
return level * np.exp(1j * angle)
def _run(flags: np.ndarray) -> int:
"""How many of ``flags`` from the first are true."""
off = np.flatnonzero(~flags)
return int(off[0]) if len(off) else len(flags)
[docs]
def held_phase(paths: EarlyReflections) -> np.ndarray:
"""(n,) the phase factor of each path at the top of the coherent bands, which it
keeps in the bands above them: there the paths add in energy, and a path whose
phase stepped back to zero at the crossover would cancel itself in it, as two bands
half a turn apart do (ones without coherent bands). Times the path's own phase
(:attr:`~acoustic_spaces.engine.early.EarlyReflections.own_phase`) where a rendered
response gives it one (:func:`with_own_phases`)."""
top = _top_phase(paths)
return top if paths.own_phase is None else top * paths.own_phase
def _top_phase(paths: EarlyReflections) -> np.ndarray:
"""(n,) the phase factor of each path at the top of the coherent bands (ones
without them)."""
if paths.coherent_bands == 0 or len(paths) == 0:
return np.ones(len(paths), dtype=complex)
top = paths.spectrum[:, -1, -1]
magnitude = np.abs(top)
return np.where(magnitude > 1e-12, top / np.maximum(magnitude, 1e-300), 1.0)
[docs]
def with_own_phases(
paths: EarlyReflections, seed: int | None, angles: np.ndarray | None = None
) -> EarlyReflections:
"""``paths`` as a rendered response has them: each path over an edge turned by its
:func:`own_phases` in the bands above the coherent ones. The same paths without such
bands or such paths. ``angles``: their :func:`path_angles` for ``seed``, when worked
out once for every moment of the same paths."""
if paths.coherent_bands >= paths.energy.shape[1] or not paths.diffracted.any():
return paths
return dataclasses.replace(paths, own_phase=own_phases(paths, seed, angles))
[docs]
def own_phases(
paths: EarlyReflections, seed: int | None, angles: np.ndarray | None = None
) -> np.ndarray:
"""(n,) the phase factor beyond the one held from the coherent bands that a rendered
response gives each path above them. A path over an edge is turned by an angle
drawn uniformly from the path (its edge, order, faces, crossings and source point,
and which of the paths alike it is) and ``seed``, times how loud the other paths'
sound is where it arrives against its own (:func:`arriving_with`), up to one: so it
adds to the paths it arrives with in energy on average, and one that arrives alone
keeps its phase. A reflection keeps its phase (one). ``angles``: their
:func:`path_angles`, when worked out already."""
if angles is None:
angles = path_angles(paths, seed)
return np.exp(1j * angles * _turns(paths))
[docs]
def with_mean_phases(paths: EarlyReflections, kept: SameDelays | None = None) -> EarlyReflections:
"""``paths`` as the echogram reads the coherent bands from them
(:class:`EarlyPressure`), through filters that let in a little of the bands above:
each path over an edge with the mean over seeds of the phase factor
:func:`own_phases` gives it there, sinc of how far it is turned. One turned all the
way adds nothing to the others there in pressure, as on average in a rendered
response. The same paths without such bands or such paths. ``kept``: as for
:func:`arriving_with`."""
if paths.coherent_bands >= paths.energy.shape[1] or not paths.diffracted.any():
return paths
return dataclasses.replace(paths, own_phase=np.sinc(_turns(paths, kept)).astype(complex))
def _turns(paths: EarlyReflections, kept: SameDelays | None = None) -> np.ndarray:
"""(n,) how far each path over an edge is turned, as a share of its angle: how loud
the other paths' sound is where it arrives against its own (:func:`arriving_with`),
up to one; zero for reflections."""
return np.where(paths.diffracted, np.minimum(arriving_with(paths, kept), 1.0), 0.0)
[docs]
def arriving_with(paths: EarlyReflections, kept: SameDelays | None = None) -> np.ndarray:
"""(n,) for each path, the largest over the bands above the coherent ones of how loud
the other paths' sound is where it arrives against its own, each path with the
phase held from the coherent bands: the magnitude of the sum over the others of
their pressure times the band filter's autocorrelation at the difference of their
delays, over its pressure. Zero for a path that arrives alone; about one or more
for one that others arrive with. ``kept`` (a :class:`SameDelays`) keeps what each
band's reading takes from the delays and which paths carry the band alone, for the
same paths with other energies and phases."""
bands = paths.energy.shape[1]
held = _top_phase(paths)
out = np.zeros(len(paths))
for b in range(paths.coherent_bands, bands):
amplitude = np.sqrt(paths.energy[:, b])
live = amplitude > 0
if live.sum() < 2:
continue
delay = paths.delay_s if paths.lag is None else paths.delay_s + paths.lag[:, b]
own = amplitude * held
others = np.abs(_band_field(delay, own, b, bands, live, kept) - own)
out = np.maximum(out, np.where(live, others / np.where(live, amplitude, 1.0), 0.0))
return out
def _band_field(
delay: np.ndarray,
values: np.ndarray,
b: int,
bands: int,
live: np.ndarray,
kept: SameDelays | None = None,
) -> np.ndarray:
"""(n,) the sound of all ``values`` (n,) (complex pressures at ``delay`` s) in band
``b`` where each arrives: their sum, each times the autocorrelation of the band's
filter (its gains squared, positive frequencies) at the difference of their delays,
over its value at zero, so that a path alone gives its own value. On a grid of
:data:`_OVERSAMPLE` times the band's highest frequency, the paths placed and read
with a windowed sinc (:func:`_band_grid`, kept in ``kept`` if given)."""
if kept is None:
kernel, index, size, power, alone = _band_grid(delay, b, bands, live)
else:
kernel, index, size, power, alone = kept.band_grid(delay, b, bands, live)
placed = (np.where(live, values, 0.0)[:, None] * kernel).ravel()
grid = np.bincount(index, placed.real, size) + 1j * np.bincount(index, placed.imag, size)
field = np.fft.ifft(np.fft.fft(grid) * power)
return (field[index].reshape(kernel.shape) * kernel).sum(axis=1) / alone
def _band_grid(
delay: np.ndarray, b: int, bands: int, live: np.ndarray
) -> tuple[np.ndarray, np.ndarray, int, np.ndarray, np.ndarray]:
"""What :func:`_band_field` takes from the delays and which paths are ``live``
alone: the windowed sinc of each path (n, taps), the grid sample each of its taps
falls on (n * taps,), the grid's size, the band filter's power on the grid's
frequencies, and each path's own value read back (n,)."""
lo, hi = _band_support(b, bands)
rate = _OVERSAMPLE * hi
pad = _PAD / (hi - lo)
start = float(delay[live].min()) - pad
span = (float(delay[live].max()) - start + pad) * rate + _TAPS
size = 1 << int(math.ceil(math.log2(span)))
position = (delay - start) * rate
base = np.floor(position).astype(np.int64)
taps = np.arange(-_TAPS // 2 + 1, _TAPS // 2 + 1)
x = taps[None, :] - (position - base)[:, None]
kernel = np.sinc(x) * np.cos(np.pi * x / _TAPS) ** 2
index = ((base[:, None] + taps[None, :]) % size).ravel()
f = np.fft.fftfreq(size, 1.0 / rate)
power = np.where(f > 0, _band_shape(np.abs(f), b, bands) ** 2, 0.0)
correlation = np.fft.ifft(power)[(taps[:, None] - taps[None, :]) % size]
alone = np.einsum("nk,kl,nl->n", kernel, correlation, kernel).real
return kernel, index, size, power, alone
def _band_edges(bands: int) -> tuple[np.ndarray, float]:
"""The log2 frequencies of the edges between the synthesis's bands, with one more
a band above the top one, and the crossovers' width (octaves)."""
edges = np.log2(synthesis.crossover_frequencies(bands))
per_octave = BANDS_PER_OCTAVE[resolution_of(bands)]
return np.append(edges, edges[-1] + 1.0 / per_octave), synthesis.crossover_width(bands)
def _band_support(b: int, bands: int) -> tuple[float, float]:
"""The lowest and highest frequency (Hz) of band ``b`` of the synthesis, the top
band as wide as the others."""
edges, width = _band_edges(bands)
lo = 2.0 ** (edges[b - 1] - width / 2) if b > 0 else 0.0
return lo, float(2.0 ** (edges[b] + width / 2))
def _band_shape(f: np.ndarray, b: int, bands: int) -> np.ndarray:
"""The synthesis's gain of band ``b`` at frequencies ``f`` (Hz)
(:func:`~acoustic_spaces.synthesis.band_gains`), the top band as wide as the
others."""
edges, width = _band_edges(bands)
log_f = np.log2(np.maximum(f, 1e-6))
def step(edge: float) -> np.ndarray:
x = np.clip((log_f - (edge - width / 2)) / width, 0.0, 1.0)
return np.sin(0.5 * np.pi * x) ** 2
lower = step(edges[b - 1]) if b > 0 else np.ones_like(log_f)
return lower - step(edges[b])
[docs]
def path_angles(paths: EarlyReflections, seed: int | None) -> np.ndarray:
"""(n,) an angle in [-pi, pi) for each path over an edge, zero for the others,
drawn from what the path is and ``seed``: wherever the source and the listener
stand, the same path gets the same angle, and at every moment of the eddies."""
out = np.zeros(len(paths))
seen: dict[tuple, int] = {}
for i in np.flatnonzero(paths.diffracted):
faces = tuple(int(face) for face in paths.faces[i]) if paths.faces else ()
key = (
int(paths.edge[i]),
int(paths.order[i]),
int(paths.crossings[i]),
int(paths.point[i]),
faces,
)
repeat = seen.get(key, 0)
seen[key] = repeat + 1
digest = hashlib.blake2b(repr((seed, key, repeat)).encode(), digest_size=8).digest()
out[i] = 2.0 * math.pi * (int.from_bytes(digest, "little") / 2.0**64) - math.pi
return out
[docs]
def amplitude_spectra(
paths: EarlyReflections, f: np.ndarray, gains: np.ndarray, only_coherent: bool = False
) -> np.ndarray:
"""(n, len(f)) each path's pressure at frequencies ``f`` relative to its delay, as
the impulse response has it: its amplitude in each band through the synthesis's
band ``gains`` (bands, len(f)) at those frequencies, in the coherent bands times its
spectrum's shape in that band (:func:`shaped`) and above them times its
:func:`held_phase`; with ``only_coherent``, the coherent bands alone."""
bands = paths.energy.shape[1]
count = paths.coherent_bands
amplitude = np.sqrt(synthesis.ENERGY_TO_IR * paths.energy)
if count:
low = shaped(
paths.spectrum,
bands,
f,
amplitude[:, :count],
gains[:count],
paths.fine,
paths.fine_delay,
)
else:
low = np.zeros((len(paths), len(f)), dtype=complex)
if not only_coherent:
low = (
low + products.product(amplitude[:, count:], gains[count:]) * held_phase(paths)[:, None]
)
lagged = lag_phase(paths, f)
return low if lagged is None else low * lagged
def lag_phase(paths: EarlyReflections, f: np.ndarray) -> np.ndarray | None:
"""(n, len(f)) at a moment of turbulence, the phase factor of each path's
:attr:`~acoustic_spaces.engine.early.EarlyReflections.lag` at frequencies ``f``
(Hz), the lag interpolated linearly in log frequency between the bands' centres and
held beyond the first and the last; None without one."""
if paths.lag is None:
return None
f = np.asarray(f, dtype=float)
centres = np.log2(np.asarray(band_centres(resolution_of(paths.energy.shape[1])), float))
x = np.log2(np.clip(f, 2.0 ** centres[0], 2.0 ** centres[-1]))
j = np.clip(np.searchsorted(centres, x, side="right") - 1, 0, len(centres) - 2)
w = (x - centres[j]) / (centres[j + 1] - centres[j])
lag = paths.lag[:, j] * (1.0 - w) + paths.lag[:, j + 1] * w
return np.exp(-2j * np.pi * lag * f)
[docs]
def band_impulses(
paths: EarlyReflections, n: int, sample_rate: float, gains: np.ndarray | None = None
) -> tuple[np.ndarray, np.ndarray | None]:
"""The band signals (bands, n) of the early paths above the coherent bands, each
path times ``gains`` (paths,) (default ones), as :func:`synthesis.place_impulses`
has them, and those of the quarter turn of their :func:`held_phase` for
:func:`synthesis.combine_bands` (None when no path has one)."""
amplitudes = np.sqrt(synthesis.ENERGY_TO_IR * paths.energy)
amplitudes[:, : paths.coherent_bands] = 0.0 # those come from their pressure
if gains is not None:
amplitudes = amplitudes * np.asarray(gains, dtype=float)[:, None]
held = held_phase(paths)
def place(values: np.ndarray) -> np.ndarray:
if paths.lag is None:
return synthesis.place_impulses(paths.delay_s, values, n, sample_rate)
# At a moment of turbulence each band's paths come at their own delays.
out = np.zeros((values.shape[1], n))
for b in range(paths.coherent_bands, values.shape[1]):
delay = paths.delay_s + paths.lag[:, b]
out[b] = synthesis.place_impulses(delay, values[:, b : b + 1], n, sample_rate)[0]
return out
if np.all(np.abs(held.imag) < 1e-12):
return place(amplitudes * held.real[:, None]), None
return place(amplitudes * held.real[:, None]), place(amplitudes * held.imag[:, None])
[docs]
def signal(
paths: EarlyReflections, n: int, sample_rate: float, weights: np.ndarray | None = None
) -> np.ndarray:
"""(n, K) the coherent bands' part of the early paths' impulse response, at
``sample_rate``, each path weighted by ``weights`` (paths, K) (default: one column
of ones). Zero without coherent bands."""
k = 1 if weights is None else np.asarray(weights).shape[1]
count = paths.coherent_bands
if count == 0 or len(paths) == 0:
return np.zeros((n, k))
bands = paths.energy.shape[1]
n_fft = synthesis.fft_size(n, sample_rate)
gains = synthesis.band_gains(n_fft, sample_rate, bands)
support = np.flatnonzero(gains[:count].sum(axis=0) > 0.0)
top = int(support.max()) + 1
f = np.fft.rfftfreq(n_fft, 1.0 / sample_rate)[:top]
weights = np.ones((len(paths), 1)) if weights is None else np.asarray(weights, dtype=float)
out = np.zeros((n_fft // 2 + 1, k), dtype=complex)
chunk = _CHUNK
if count > filtered_bands(paths): # every band: long spectra
chunk = max(1, min(_CHUNK, _MAX_VALUES // top))
for start in range(0, len(paths), chunk):
part = slice(start, start + chunk)
spectra = amplitude_spectra(paths[part], f, gains[:, :top], only_coherent=True)
spectra *= np.exp(-2j * np.pi * np.outer(paths.delay_s[part], f))
for column in range(k): # one at a time: a mono response and W add alike
products.add_product(out[:top, column], spectra.T, weights[part, column])
return np.fft.irfft(out, n_fft, axis=0)[:n]
[docs]
def total_energy(paths: EarlyReflections) -> np.ndarray:
"""(bands,) the paths' energy together in each band: their sum, and in the coherent
bands that of their pressures added at each of the band's frequencies, averaged over
them; each frequency stands for its slice of the band, over which the interference
of two paths that arrive far apart averages out; in turbulence it takes their
coherence factor (:meth:`~acoustic_spaces.engine.turbulence.Wander.coherence`).
Paths of different points of a line or a surface source add in energy."""
from acoustic_spaces.engine.diffraction import band_frequencies
out = paths.energy.sum(axis=0)
count = paths.coherent_bands
if count == 0 or len(paths) == 0:
return out
bands = paths.energy.shape[1]
f, width = band_frequencies(bands=resolution_of(bands))
f, width = f[:count], width[:count]
pressure = np.sqrt(paths.energy[:, :count, None]) * paths.spectrum
pressure = pressure * np.exp(-2j * np.pi * paths.delay_s[:, None, None] * f[None])
apart = paths.delay_s[:, None] - paths.delay_s[None, :]
same = paths.point[:, None] == paths.point[None, :]
for b in range(count):
here = pressure[:, b]
lagged = lag_phase(paths, f[b])
if lagged is not None:
here = here * lagged
products = np.real(here[:, None] * np.conj(here[None, :]))
if paths.wander is not None:
products = products * paths.wander.coherence(f[b])
out[b] = float(np.sum(products.mean(axis=2) * np.sinc(apart * width[b]) * same))
return out
[docs]
def pair_energy(
paths: EarlyReflections,
bands: range,
time_step: float,
slots: int,
axis: np.ndarray | None = None,
exponent: int = 2,
origin: float = 0.0,
memo: dict | None = None,
) -> np.ndarray:
"""(len(bands), slots) energy per time slot of ``time_step`` (slot 0 at ``origin``,
s from emission) in ``bands`` of the paths' coherent ones, adding them in pressure:
each path's own energy where it arrives, and the cross term of each pair of paths,
averaged over the band's frequencies as in :func:`total_energy` (with their
coherence factor in turbulence), shared between the two paths' slots as their
energies are (a slot that would go below zero is left at zero). With ``axis``, that
of a figure of eight facing it (``exponent`` as in :meth:`EarlyPressure.energy`; with
1 the cross terms take the geometric mean of the two paths' weights). ``memo`` (a
dict), if given, keeps what each band takes whatever the axis (:func:`_pair_terms`)
for the next call on the same paths."""
from acoustic_spaces.engine.diffraction import band_frequencies
out = np.zeros((len(bands), slots))
if len(paths) == 0:
return out
f, width = band_frequencies(bands=resolution_of(paths.energy.shape[1]))
slot = np.floor((paths.delay_s - origin) / time_step + 1e-9).astype(np.int64)
keep = (slot >= 0) & (slot < slots)
weight = np.ones(len(paths))
if axis is not None:
cosine = paths.direction @ np.asarray(axis, dtype=float)
weight = cosine if exponent == 2 else np.sqrt(np.abs(cosine))
for row, b in enumerate(bands):
held = None if memo is None else memo.get(b)
if held is None:
held = _pair_terms(paths, b, f, width)
if memo is not None:
memo[b] = held
plain, sinc, share = held
cross = plain * (sinc * np.outer(weight, weight))
mine = np.sum(cross * share, axis=1)
np.add.at(out[row], slot[keep], mine[keep])
return np.maximum(out, 0.0)
def _pair_terms(paths, b, f, width) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""What :func:`pair_energy` takes of band ``b`` whatever the axis: each pair's cross
term averaged over the band's frequencies ``f[b]`` (with their coherence in
turbulence), the sinc of how far apart they arrive over the band's width, and the
share of it each path takes (read-only)."""
energy = paths.energy[:, b]
pressure = np.sqrt(energy)[:, None] * paths.spectrum[:, b]
pressure = pressure * np.exp(-2j * np.pi * np.outer(paths.delay_s, f[b]))
lagged = lag_phase(paths, f[b])
if lagged is not None:
pressure = pressure * lagged
if paths.wander is None:
# pressure @ pressure.conj().T
cross = np.real(products.product(pressure, pressure.T, conj_b=True)) / f.shape[1]
else:
together = paths.wander.coherence(f[b])
cross = np.einsum("im,jm,ijm->ij", pressure, pressure.conj(), together).real
cross /= f.shape[1]
sinc = np.sinc((paths.delay_s[:, None] - paths.delay_s[None, :]) * width[b])
# A pair's cross terms, 2 Re(p_i p_j*), shared between its two paths.
total = energy[:, None] + energy[None, :]
share = np.divide(2.0 * energy[:, None], total, out=np.zeros_like(cross), where=total > 0)
np.fill_diagonal(share, 1.0)
for a in (cross, sinc, share):
a.flags.writeable = False
return cross, sinc, share
[docs]
def coherent_energy(
paths: EarlyReflections,
time_step: float,
slots: int,
axis: np.ndarray | None = None,
exponent: int = 2,
origin: float = 0.0,
start: float | None = None,
cache: dict | None = None,
kept: SameDelays | None = None,
) -> np.ndarray:
"""(coherent bands, slots) the coherent bands' energy per time slot (arguments as
for :meth:`EarlyPressure.energy`): through the band filters up to
:data:`FILTERED_MAX_BAND_HZ` and by :func:`pair_energy` above. The paths of each of
a line's or a surface's points add in pressure, those of different points in
energy. The band filters let in a little of the bands above, where each path over an
edge has the mean of the phase a rendered response turns it by
(:func:`with_mean_phases`). ``cache`` (a dict) keeps the :class:`EarlyPressure` of
each point between calls on the same paths; ``kept`` (a :class:`SameDelays`) what
they take from the paths' delays alone, between calls on paths that differ in their
energies and spectra only."""
count = paths.coherent_bands
filtered = filtered_bands(paths)
points = np.unique(paths.point)
if len(points) <= 1 and count == filtered:
pressure = _pressure(paths, 0, cache, kept)
return pressure.energy(time_step, slots, axis, exponent, origin, start)
out = np.zeros((count, slots))
# With ``kept`` (the draws of a spread), each point's paths and what pair_energy
# takes from them whatever the axis are kept in ``cache`` for the draw's echograms.
keep = cache is not None and kept is not None
for point in points:
if len(points) <= 1:
part = paths
elif keep and ("paths", int(point)) in cache:
part = cache["paths", int(point)]
else:
part = paths[paths.point == point]
if keep:
cache["paths", int(point)] = part
if filtered:
pressure = _pressure(part, int(point), cache, kept)
out[:filtered] += pressure.energy(time_step, slots, axis, exponent, origin, start)
if count > filtered:
memo = cache.setdefault(("pairs", int(point)), {}) if keep else None
out[filtered:] += pair_energy(
part, range(filtered, count), time_step, slots, axis, exponent, origin, memo
)
return out
def _pressure(
paths: EarlyReflections, point: int, cache: dict | None, kept: SameDelays | None = None
) -> EarlyPressure:
if cache is None:
return EarlyPressure(with_mean_phases(paths, kept), kept=kept)
if point not in cache:
cache[point] = EarlyPressure(with_mean_phases(paths, kept), kept=kept)
return cache[point]
[docs]
class SameDelays:
"""What :class:`EarlyPressure` and :func:`arriving_with` take from the early paths'
delays alone (and which paths carry a band), kept for paths that differ in nothing
else but their energies and spectra: those of one traced response re-weighted for
draw after draw of the absorption
(:func:`~acoustic_spaces.engine.uncertainty.material_spread`). Each value is kept
under the bytes of the arrays it is made from, as every echogram slices each
point's paths anew, and is read-only. An :class:`EarlyPressure` given one also keeps
each band's filtered pressure (:meth:`EarlyPressure.band`) for the echograms that
read it.
The delay phases are the most of it: a complex value for each path and frequency
of the echogram's spectra, about 6 MB for a hall's response of 200 paths, up to
110 MB for a line source of 10 points outdoors (examples/street, in wind and
turbulence too). What is kept stops at ``limit`` bytes in all (128 MiB by default);
past it, each value is worked out again each time, as without one. The filtered
pressures and what :func:`coherent_energy` keeps for a draw's echograms are not
counted in it: they go with the draw's response, about 25 MB for the street's."""
def __init__(self, limit: int = 1 << 27) -> None:
self.limit = limit
self.size = 0
self._phases: dict[tuple, np.ndarray] = {}
self._grids: dict[tuple, tuple] = {}
def _keep(self, *arrays: np.ndarray) -> bool:
"""Whether ``arrays`` fit within the limit, counted in if so and made read-only."""
size = sum(a.nbytes for a in arrays)
if self.size + size > self.limit:
return False
self.size += size
for a in arrays:
a.flags.writeable = False
return True
[docs]
def delay_phases(self, shift: np.ndarray, n_fft: int, rate: float) -> np.ndarray:
"""exp(-2j pi outer(``shift``, f)): the phase of paths ``shift`` s late at the
frequencies f of an rFFT of ``n_fft`` points at ``rate``."""
key = (shift.tobytes(), n_fft, rate)
held = self._phases.get(key)
if held is None:
f = np.fft.rfftfreq(n_fft, 1.0 / rate)
held = np.exp(-2j * np.pi * np.outer(shift, f))
if self._keep(held):
self._phases[key] = held
return held
[docs]
def band_grid(
self, delay: np.ndarray, b: int, bands: int, live: np.ndarray
) -> tuple[np.ndarray, np.ndarray, int, np.ndarray, np.ndarray]:
""":func:`_band_grid` of these arguments."""
key = (delay.tobytes(), b, bands, live.tobytes())
held = self._grids.get(key)
if held is None:
held = _band_grid(delay, b, bands, live)
kernel, index, _, power, alone = held
if self._keep(kernel, index, power, alone):
self._grids[key] = held
return held
@functools.lru_cache(maxsize=8)
def _band_filters(n_fft: int, rate: float, bands: int) -> np.ndarray:
"""The analysis's band filters (:func:`~acoustic_spaces.parameters.band_filter_gains`),
kept for the next point: read-only."""
from acoustic_spaces.parameters import band_filter_gains
gains = band_filter_gains(n_fft, rate, bands)
gains.flags.writeable = False
return gains
[docs]
class EarlyPressure:
"""The early part of an impulse response at a low sample rate, as the echogram
reads the coherent bands from it: as spectra from 0.2 s before emission, the
pressure and the three components of the paths' arrival directions times it, or
with ``weights`` (paths, K) the sums of the paths weighted by each column.
Each band is scaled so that every path alone carries its energy in it: the analysis
filters also let in a little of the neighbouring bands, whose levels differ, and the
filters of the impulse response's bands overlap with them. What is left is the
paths' interference, which in turbulence takes each two paths' coherence factor:
there each path's spectrum is kept, and :meth:`energy` adds the filtered paths'
products.
With ``kept`` (a :class:`SameDelays`), the paths' delay phases are taken from it
and kept in it, and each band's filtered pressure is kept for the next reading."""
def __init__(
self,
paths: EarlyReflections,
weights: np.ndarray | None = None,
kept: SameDelays | None = None,
) -> None:
bands = paths.energy.shape[1]
self.bands = bands
self.count = filtered_bands(paths)
top = band_centres(resolution_of(bands))[max(self.count, 1) - 1]
# Rate high enough for the band filters of the coherent bands to have died out,
# and a whole number of samples to a millisecond; each sample stands for the
# interval it is the middle of.
self.rate = 1000.0 * 2.0 ** math.ceil(math.log2(max(32.0 * top / 1000.0, 1.0)))
self.lead = synthesis._PAD_S
last = float(paths.delay_s.max()) if len(paths) else 0.0
length = int(math.ceil((self.lead + last + _TAIL_S) * self.rate))
self.n_fft = 1 << max(int(math.ceil(math.log2(length))), 4)
f = np.fft.rfftfreq(self.n_fft, 1.0 / self.rate)
gains = synthesis.band_gains(self.n_fft, self.rate, bands)
if weights is None:
weights = np.column_stack([np.ones(len(paths)), paths.direction])
self.spectra = np.zeros((np.shape(weights)[1], len(f)), dtype=complex)
self._alone = np.zeros(len(f)) # the paths' squared spectra, summed
self._energy = paths.energy[:, : self.count].sum(axis=0)
self._wander = paths.wander if len(paths) > 1 else None
if self._wander is not None:
self._each = np.zeros((len(paths), len(f)), dtype=complex)
self._weights = np.asarray(weights, dtype=float)
# A path that carries nothing in a band is left out of that band's reading:
# what its neighbouring bands' filters let into this one would otherwise count
# against the paths that do carry it (outdoors, where the parabolic equation's
# bands sit on one path of a family and the others are silent in them).
self._silent = paths.energy[:, : self.count] <= 0.0 # (n, count)
partly = [
b
for b in range(self.count)
if self._silent[:, b].any() and not self._silent[:, b].all()
]
self._spectra_of = {b: np.zeros_like(self.spectra) for b in partly}
self._alone_of = {b: np.zeros(len(f)) for b in partly}
self._bands: dict[tuple, tuple[np.ndarray, np.ndarray, float]] | None = (
None if kept is None else {}
)
for start in range(0, len(paths), _CHUNK):
part = slice(start, start + _CHUNK)
spectra = amplitude_spectra(paths[part], f, gains)
squared = np.abs(spectra) ** 2
self._alone += np.sum(squared, axis=0)
shift = paths.delay_s[part] + self.lead - 0.5 / self.rate
if kept is None:
spectra *= np.exp(-2j * np.pi * np.outer(shift, f))
else:
spectra *= kept.delay_phases(shift, self.n_fft, self.rate)
products.add_product(self.spectra, weights[part].T, spectra)
for b in partly:
heard = ~self._silent[part, b]
self._alone_of[b] += np.sum(squared[heard], axis=0)
# the sums over the paths heard in band b
products.add_product(
self._spectra_of[b], np.asarray(weights[part]).T, spectra, rows=heard
)
if self._wander is not None:
self._each[part] = spectra
[docs]
def band(
self,
b: int,
time_step: float,
slots: int,
origin: float = 0.0,
start: float | None = None,
) -> tuple[np.ndarray, np.ndarray, float]:
"""The spectra through band b's analysis filter (K, T) at the samples that fall
into the ``slots`` of ``time_step``, slot 0 at ``origin`` (s from emission); the
slot of each sample (T,); and the factor that makes a squared sample energy.
The filters ring before an arrival as much as after it: what they spread to
before ``start`` (s from emission; default ``origin``), the arrival of the
direct sound, counts as arriving with it, as in the analysis of a measured
response. Kept for the next reading of the same arguments (read-only) when
the pressure was made with a :class:`SameDelays`."""
key = (b, time_step, slots, origin, start)
if self._bands is not None and key in self._bands:
return self._bands[key]
gain, keep, slot, scale = self._filter(b, time_step, slots, origin, start)
spectra = self._spectra_of.get(b, self.spectra)
pressure = np.fft.irfft(gain * spectra, self.n_fft, axis=1)[:, keep]
if self._bands is not None:
pressure.flags.writeable = slot.flags.writeable = False
self._bands[key] = (pressure, slot, scale)
return pressure, slot, scale
def _filter(self, b, time_step, slots, origin, start):
"""Band b's analysis filter, which samples fall into the slots, their slots,
and the factor that makes a squared sample energy (see :meth:`band`)."""
gain = _band_filters(self.n_fft, self.rate, self.bands)[b]
time = np.arange(self.n_fft) / self.rate - self.lead # where each interval begins
time = np.maximum(time, origin if start is None else max(start, origin)) - origin
slot = (time / time_step + 1e-9).astype(np.int64)
keep = slot < slots
weights = np.full(len(gain), 2.0)
weights[0] = weights[-1] = 1.0
alone = float(np.sum(weights * gain**2 * self._alone_of.get(b, self._alone))) / self.n_fft
scale = float(self._energy[b]) / alone if alone > 0.0 else 0.0
return gain, keep, slot[keep], scale
def _turbulent(self, b, time_step, slots, axis, exponent, origin, start) -> np.ndarray:
"""(slots,) band b's energy with each two paths' products taken by their
coherence factor, averaged over the band's frequencies."""
from acoustic_spaces.engine.diffraction import band_frequencies
gain, keep, slot, scale = self._filter(b, time_step, slots, origin, start)
signals = np.fft.irfft(gain * self._each, self.n_fft, axis=1)[:, keep]
signals[self._silent[:, b]] = 0.0
f = band_frequencies(bands=resolution_of(self.bands))[0][b]
together = self._wander.coherence(f).mean(axis=2)
plain = self._weights[:, 0]
if axis is None:
first = second = plain
else:
side = self._weights[:, 1:] @ np.asarray(axis, dtype=float)
first, second = side, (side if exponent == 2 else plain)
power = np.sum(
(first[:, None] * signals) * products.product(together, second[:, None] * signals), 0
)
if axis is not None and exponent != 2:
power = np.abs(power)
return np.bincount(slot, power * scale, minlength=slots)[:slots]
[docs]
def energy(
self,
time_step: float,
slots: int,
axis: np.ndarray | None = None,
exponent: int = 2,
origin: float = 0.0,
start: float | None = None,
) -> np.ndarray:
"""(count, slots) energy per coherent band and time slot, as
:meth:`~acoustic_spaces.engine.wave.WaveResponse.energy` reads the wave
solver's bands, through each band's analysis filter (``origin`` and ``start``
as for :meth:`band`). With ``axis``, that of a figure of eight facing it
(``exponent`` as there)."""
out = np.zeros((self.count, slots))
for b in range(self.count):
if self._wander is not None:
out[b] = self._turbulent(b, time_step, slots, axis, exponent, origin, start)
continue
pressure, slot, scale = self.band(b, time_step, slots, origin, start)
if axis is None:
power = pressure[0] ** 2
else:
side = products.product(axis, pressure[1:])
power = side**2 if exponent == 2 else np.abs(side * pressure[0])
out[b] = np.bincount(slot, power * scale, minlength=slots)[:slots]
return out
__all__ = [
"FILTERED_MAX_BAND_HZ",
"EarlyPressure",
"SameDelays",
"absorption_phases",
"amplitude_spectra",
"arriving_with",
"band_count",
"band_impulses",
"coherent_energy",
"filtered_bands",
"ground_factors",
"ground_wave_factors",
"held_phase",
"own_phases",
"pair_energy",
"path_angles",
"reflection_phases",
"sample_frequencies",
"shaped",
"signal",
"total_energy",
"with_mean_phases",
"with_own_phases",
]