Source code for acoustic_spaces.engine.model

"""The room as the propagation methods see it: a BVH, planes and per-face coefficients."""

from __future__ import annotations

from dataclasses import dataclass
from functools import cached_property

import numpy as np

from acoustic_spaces import products
from acoustic_spaces.directivity import PATTERNS, Directivity
from acoustic_spaces.materials import OCTAVE_BANDS_HZ
from acoustic_spaces.materials.bands import Resolution, band_centres
from acoustic_spaces.room import UNASSIGNED, Room

#: Faces whose normals and offsets agree to this (unit normal components, metres) share
#: a plane, and so share image sources.
PLANE_TOLERANCE = 1e-5

#: The lowest reflection order that adds the scattering of a surface's size, for each
#: edge diffraction setting (see :attr:`TraceModel.size_from_order`).
_SIZE_FROM_ORDER = {"none": 1, "direct": 2, "first_order": 3, "second_order": 3}

#: Pressure pattern a + (1 - a) cos(theta) for each named source directivity (the same
#: as :data:`acoustic_spaces.directivity.PATTERNS`).
DIRECTIVITY_A = PATTERNS

#: A straight line through more surfaces that let sound through than this counts as
#: blocked.
MAX_CROSSINGS = 64
#: The size (m) an outdoor scene's ground counts as for the scattering of a surface's size
#: (:func:`size_scattering`): it goes on past its extent. Finite, as the GPU tracer
#: works in single precision.
UNBOUNDED_M = 1e9


def source_weights(
    directivity: Directivity | None,
    orientation: np.ndarray | None,
    directions: np.ndarray,
    bands: int = len(OCTAVE_BANDS_HZ),
    distances: np.ndarray | None = None,
) -> np.ndarray:
    """Energy weights (n, bands) of a source's directivity for unit vectors (n, 3) in
    room coordinates; ``orientation`` has the source's forward, left and up axes as
    columns (default: the room's). Without a directivity, ``bands`` ones. With the
    ``distances`` (n,) the sound travels that way (m), a coherent array with
    ``near_field`` adds up its elements' sound there one by one."""
    directions = np.asarray(directions, dtype=float).reshape(-1, 3)
    if directivity is None:
        return np.ones((len(directions), bands))
    local = directions if orientation is None else products.product(directions, orientation)
    if distances is not None and getattr(directivity, "near", None) is not None:
        return directivity.near_energy(local * np.asarray(distances, dtype=float).reshape(-1, 1))
    return directivity.energy(local)


def free_field_energy(
    elements: np.ndarray,
    points: np.ndarray,
    air: np.ndarray,
    directivity: Directivity | None = None,
    orientation: np.ndarray | None = None,
) -> np.ndarray:
    """Energy per band (points, bands) of a source of unit energy at ``points`` in free
    field: its direct sound over the straight line, with the air's attenuation ``air``
    (1/m per band) and the source's directivity, as the early paths carry it. A line's
    or a surface's points (``elements``, (m, 3)) share the energy equally. NaN at a
    point on the source."""
    elements = np.asarray(elements, dtype=float).reshape(-1, 3)
    points = np.asarray(points, dtype=float).reshape(-1, 3)
    air = np.asarray(air, dtype=float)
    out = np.zeros((len(points), len(air)))
    for element in elements:
        delta = points - element
        distance = np.linalg.norm(delta, axis=1)
        safe = np.where(distance > 0.0, distance, 1.0)
        energy = np.exp(-np.outer(distance, air)) / (4.0 * np.pi * safe[:, None] ** 2)
        energy *= source_weights(
            directivity, orientation, delta / safe[:, None], len(air), distances=distance
        )
        energy[distance <= 0.0] = np.nan
        out += energy
    return out / len(elements)


def _plants(room: Room, bands: Resolution):
    """The vegetation of an outdoor scene in ``bands``, or None."""
    if room.outdoor is None or not room.outdoor.vegetation:
        return None
    from acoustic_spaces.engine.vegetation import Plants

    return Plants.of(room, bands, room.speed_of_sound())


[docs] @dataclass class TraceModel: room: Room bvh: object # acoustic_spaces._native.Bvh #: (F,) plane index of every face. face_plane: np.ndarray #: (P, 3) unit plane normals, pointing into the room when ``oriented`` (and the plane #: is not two-sided). plane_normal: np.ndarray #: (P,) plane offsets: points x on plane p satisfy normal[p] . x == offset[p]. plane_offset: np.ndarray #: True when the rooms are known (a closed model): each face's normal then points #: into the room on its side. oriented: bool #: (F, bands) random-incidence absorption and scattering coefficients. absorption: np.ndarray scattering: np.ndarray #: (P,) planes with a room on both sides of some face: a partition between two #: rooms or a free-standing panel; every plane when the model is not ``oriented``. plane_two_sided: np.ndarray | None = None #: (F, bands) share of sound each face lets through (see #: :meth:`acoustic_spaces.scene.Material.transmission_coefficients`), or None. transmission: np.ndarray | None = None #: (F, 2) the room on the front (the side the mesh's face normal points to) and the #: back of each face (an index into ``room_volumes``), or -1. face_room: np.ndarray | None = None #: (R,) volume of each room (m3). room_volumes: np.ndarray | None = None #: (F, 2) width and length (m) of the surface each face belongs to (see #: :func:`surface_sizes`), when the scattering of a surface's size is added; else #: None. surface_size: np.ndarray | None = None #: Vector-based scattering (the scene's ``simulation.scattering.method``). vector_scattering: bool = True #: Each band traced with rays of its own where the bands scatter differently #: (``simulation.scattering.by_band``). by_band: bool = True #: The bands the coefficients (and so every energy traced) are in. bands: Resolution = "octave" #: Reflections of this order and higher add the scattering of the surface's size. #: Below it, the early stage's edge diffraction accounts for the size of surfaces: #: its terms add coherently to the direct sound and the reflections off the faces of #: an edge (with ``direct`` diffraction), and to the reflections of first-order #: reflections off them too (``first_order``), so those waves keep their full #: specular share. size_from_order: int = 1 #: How ``bvh`` was split (``simulation.performance.ray_tree``); trees built from #: this model's mesh later take the same. ray_tree: str = "sah" #: (F,) the faces of an outdoor scene's open sky, whose edges diffract nothing; None #: in a room. sky: np.ndarray | None = None #: Height (z) of an outdoor scene's ground, whose edges on it diffract nothing; None #: in a room. ground: float | None = None #: (F,) for faces whose material has an impedance (a ground's: see #: :class:`~acoustic_spaces.scene.Impedance`), its row of ``admittance``; -1 for the #: others. None when no material has one. face_impedance: np.ndarray | None = None #: (K, bands, M) the normalised admittance of each material with an impedance at the #: frequencies the early paths are evaluated at #: (:func:`~acoustic_spaces.engine.diffraction.band_frequencies`), at normal #: incidence (a locally reacting ground's at every angle). admittance: np.ndarray | None = None #: (K, bands, M) the same at grazing incidence, which differs for grounds of #: extended reaction (``impedance.reaction``), for the parabolic equation. grazing_admittance: np.ndarray | None = None #: (K,) whether each material with an impedance reacts extendedly: its admittance #: changes with the angle of incidence, and ``impedances[k]`` gives it. impedance_extended: np.ndarray | None = None #: The materials' impedances (:class:`~acoustic_spaces.scene.Impedance`), row by row. impedances: tuple = () #: (F,) for an outdoor scene whose ground has zones (``geometry.ground.zones``), the #: part of the ground each face of it lies in (0 outside the zones, then each zone), #: whose reflections share their Fresnel zone with the parts round them; -1 for the #: faces that are not the ground. None without zones. ground_part: np.ndarray | None = None #: (parts,) a face of each part of the ground, whose material it has; -1 for a part #: with no faces (the zones may cover all the ground). part_face: np.ndarray | None = None #: An outdoor scene's vegetation in ``bands`` #: (:class:`~acoustic_spaces.engine.vegetation.Plants`); None without any. plants: object | None = None #: (F, bands) the absorption that decides for a map's rays in place of #: ``absorption``, wherever the energy a ray carries decides what happens to it (the #: splitting and thinning out, whether it passes a partition): the run then follows #: the rays of the run with this absorption #: (:func:`~acoustic_spaces.engine.late.stochastic_map_energy`). None: its own. deciding: np.ndarray | None = None
[docs] @classmethod def from_room(cls, room: Room, settings=None) -> TraceModel: """The model of ``room`` with the simulation ``settings`` (default: the scene's).""" from acoustic_spaces import _native mesh = room.mesh if np.any(room.face_materials == UNASSIGNED): raise ValueError("every surface needs a material; see Room.problems()") simulation = room.scene.simulation if settings is None else settings ray_tree = simulation.performance.ray_tree bvh = _native.Bvh(mesh.vertices, mesh.faces, split=ray_tree) normals = mesh.face_normals() oriented = len(room.air_cells) > 0 face_room = room.face_room if oriented else np.full((len(mesh.faces), 2), -1, np.int64) air = face_room >= 0 back = air[:, 1] & ~air[:, 0] # A room on both sides, or the inside unknown: one canonical normal direction for # the face's geometric plane, that of the largest component of its normal as the # planes' keys round it (the first of equal ones: a plane at 45 degrees to two # axes has one direction whichever way its faces' normals are rounded). both = air[:, 0] == air[:, 1] rounded = np.round(normals / PLANE_TOLERANCE) flip = np.take_along_axis(rounded, np.abs(rounded).argmax(axis=1)[:, None], 1) < 0 normals = np.where((back | (both & flip[:, 0]))[:, None], -normals, normals) offsets = np.einsum("ij,ij->i", normals, mesh.triangles[:, 0]) keys = np.round(np.column_stack([normals, offsets]) / PLANE_TOLERANCE).astype(np.int64) if both.any() and not both.all(): # A face with a room on both sides in the geometric plane of walls with a room # on one side, none of which faces the canonical way, faces theirs: a partition # or a free-standing panel in line with a wall is in the wall's plane whichever # way the wall faces. walls = int((~both).sum()) rows = np.concatenate([keys[~both], keys[both], -keys[both]]) label = np.unique(rows, axis=0, return_inverse=True)[1].reshape(-1) wall = np.zeros(int(label.max()) + 1, dtype=bool) wall[label[:walls]] = True same, opposite = wall[label[walls:]].reshape(2, -1) turn = both.copy() turn[both] = opposite & ~same normals = np.where(turn[:, None], -normals, normals) offsets = np.where(turn, -offsets, offsets) keys = np.where(turn[:, None], -keys, keys) _, first, face_plane = np.unique(keys, axis=0, return_index=True, return_inverse=True) face_plane = face_plane.reshape(-1) two_sided = np.zeros(len(first), dtype=bool) np.logical_or.at(two_sided, face_plane, both) materials = room.scene.materials coefficients = [materials[n].coefficients(simulation.bands) for n in room.material_names] absorption = np.array([a for a, _ in coefficients]) scattering = np.array([s for _, s in coefficients]) face_impedance = admittance = grazing = extended = None impedances = [materials[n].impedance for n in room.material_names] given: tuple = () if any(i is not None for i in impedances): from acoustic_spaces.engine.diffraction import band_frequencies f = band_frequencies(bands=simulation.bands)[0] rows = [k for k, i in enumerate(impedances) if i is not None] row = np.full(len(impedances), -1, dtype=np.int64) row[rows] = np.arange(len(rows)) face_impedance = row[room.face_materials] given = tuple(impedances[k] for k in rows) admittance = np.array([i.admittance(f, room.speed_of_sound()) for i in given]) extended = np.array([i.extended for i in given], dtype=bool) grazing = admittance if extended.any(): grazing = np.array( [i.admittance(f, room.speed_of_sound(), cosine=0.0) for i in given] ) ground_part = part_face = None if room.outdoor is not None and room.outdoor.zones: ground_part, part_face = _ground_parts(room) size = None if simulation.scattering.from_size: size = np.ascontiguousarray(surface_sizes(mesh.vertices, mesh.faces, face_plane)) if room.outdoor is not None: # The ground goes on past its extent: its size scatters nothing. size[_ground_faces(room)] = UNBOUNDED_M return cls( room=room, bvh=bvh, face_plane=face_plane, plane_normal=normals[first], plane_offset=offsets[first], oriented=oriented, absorption=np.ascontiguousarray(absorption[room.face_materials]), scattering=np.ascontiguousarray(scattering[room.face_materials]), surface_size=size, vector_scattering=simulation.scattering.method == "vector", by_band=simulation.scattering.by_band, bands=simulation.bands, size_from_order=_SIZE_FROM_ORDER[simulation.early.diffraction], plane_two_sided=two_sided, transmission=room.face_transmission(simulation.bands), face_room=face_room, room_volumes=room.room_volumes if oriented else np.zeros(0), ray_tree=ray_tree, sky=None if room.outdoor is None else room.sky_faces(), ground=None if room.outdoor is None else room.outdoor.ground, face_impedance=face_impedance, admittance=admittance, grazing_admittance=grazing, impedance_extended=extended, impedances=given, ground_part=ground_part, part_face=part_face, plants=_plants(room, simulation.bands), )
def __post_init__(self) -> None: if self.plane_two_sided is None: self.plane_two_sided = np.full(self.plane_count, not self.oriented) if self.face_room is None: self.face_room = np.full((len(self.face_plane), 2), -1, dtype=np.int64) if self.room_volumes is None: self.room_volumes = np.zeros(0) if self.transmission is not None: self.transmission = np.ascontiguousarray(self.transmission, dtype=np.float64) @cached_property def transparent(self) -> np.ndarray: """(F,) faces that let all sound through in every band: openings (worked out once, as the early stage asks for every reflection point it places).""" if self.transmission is None: return np.zeros(len(self.face_plane), dtype=bool) return np.all(self.transmission >= 1.0, axis=1) @cached_property def height_error(self) -> float: """The rounding (m) allowed for in a height over a plane worked out from the model's coordinates: 16 units in the last place of the largest of them.""" largest = float(np.abs(self.room.mesh.triangles).max(initial=0.0)) return 16.0 * float(np.spacing(largest)) @cached_property def face_spread(self) -> np.ndarray: """(F,) the largest distance (m) of a vertex of each face from its plane (``face_plane``); 0 where all lie within :attr:`height_error` of it. Faces whose normals and offsets round to the same multiples of :data:`PLANE_TOLERANCE` make one plane, the plane of the first of them, without lying in it exactly (worked out once).""" normal = self.plane_normal[self.face_plane] heights = np.einsum("fvk,fk->fv", self.room.mesh.triangles, normal) heights = np.abs(heights - self.plane_offset[self.face_plane, None]).max(axis=1) return np.where(heights > self.height_error, heights, 0.0) @cached_property def plane_spread(self) -> np.ndarray: """(P,) the largest :attr:`face_spread` of each plane's faces (worked out once).""" spread = np.zeros(self.plane_count) np.maximum.at(spread, self.face_plane, self.face_spread) return spread @cached_property def face_two_sided(self) -> np.ndarray: """(F,) the faces with a room on both sides: a partition between two rooms or a free-standing panel; every face when the model is not ``oriented``. A wall with a room on one side has one side, also where its plane holds such a face (:attr:`plane_two_sided`).""" air = self.face_room >= 0 return self.plane_two_sided[self.face_plane] & (air[:, 0] == air[:, 1]) @cached_property def geometric_plane(self) -> np.ndarray: """(P,) for each plane the first of the planes that lie where it does, whichever way they face: two walls with a room on one side in line with each other that face opposite ways (the wall between two rooms drawn once for each, the two sides of a step in a room's plan) are two planes in one geometric plane, and a point has one image in both (worked out once); a partition or a panel in line with them lies in the plane of one of them. Two planes lie in one place where their normals and offsets, in multiples of :data:`PLANE_TOLERANCE` and with the signs of one plane's turned where it faces the other way, round to numbers at most one apart: always where they differ by less than that tolerance in each, on whichever side of a rounding step either falls. So do two planes that each lie where a third does.""" from scipy.sparse import coo_matrix from scipy.sparse.csgraph import connected_components from scipy.spatial import cKDTree count = self.plane_count keys = np.round(np.column_stack([self.plane_normal, self.plane_offset]) / PLANE_TOLERANCE) # Each plane as it faces and as it faces the other way: the pairs at most one # apart in every number (whole numbers, so nearer than 1.5). either = np.concatenate([keys, -keys]) pairs = cKDTree(either).query_pairs(1.5, p=np.inf, output_type="ndarray") % count graph = coo_matrix((np.ones(len(pairs)), (pairs[:, 0], pairs[:, 1])), shape=(count, count)) label = connected_components(graph, directed=False)[1] first = np.full(count, count, dtype=np.int64) np.minimum.at(first, label, np.arange(count)) return first[label] @cached_property def face_planes(self) -> tuple[np.ndarray, np.ndarray]: """(F, 3) unit normals and (F,) offsets of the plane each face itself lies in, the normal facing the way of its plane's; its plane's own where its :attr:`face_spread` is 0 (worked out once).""" normal = self.plane_normal[self.face_plane] offset = self.plane_offset[self.face_plane] off = np.flatnonzero(self.face_spread > 0.0) tri = self.room.mesh.triangles[off] own = np.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0]) size = np.linalg.norm(own, axis=1) keep = size > 0.0 off, tri, own = off[keep], tri[keep], own[keep] / size[keep, None] own *= np.sign(np.einsum("ij,ij->i", own, normal[off]))[:, None] normal, offset = normal.copy(), offset.copy() normal[off], offset[off] = own, np.einsum("ij,ij->i", own, tri[:, 0]) return normal, offset @cached_property def face_grids(self) -> dict: """The faces of planes whose faces do not all lie in them, binned in squares by ``_face_grid`` of :mod:`acoustic_spaces.engine.early`, by plane and distance allowed (each worked out when first asked for).""" return {} @property def partition(self) -> np.ndarray: """(F,) partitions: faces that let some sound through and reflect some, so a path that meets one goes on both ways. Openings reflect nothing, and neither does a face that absorbs all the sound it does not let through.""" if self.transmission is None: return np.zeros(len(self.face_plane), dtype=bool) return np.any(self.transmission > 0.0, axis=1) & np.any(self.absorption < 1.0, axis=1)
[docs] def in_front(self, distance: np.ndarray, tolerance: float) -> np.ndarray: """Whether points at signed ``distance`` (..., P) from every plane, farther than ``tolerance``, can see it: in front of it, or on either side of a two-sided plane.""" return np.where(self.plane_two_sided, np.abs(distance) > tolerance, distance > tolerance)
[docs] def passes( self, origins: np.ndarray, directions: np.ndarray, lengths: np.ndarray, ignore: np.ndarray, transparent_only: bool = False, counted: np.ndarray | None = None, ) -> tuple[np.ndarray, np.ndarray]: """(n, bands) share of sound that travels from each origin ``lengths`` along its direction (unit): the product of the transmission of the faces it crosses, 0 where a face lets nothing through; and (n,) how many of those faces it crosses that are not openings, or (n, m) how many of each column of ``counted`` (F, m). With ``transparent_only``, only openings let sound through.""" origins = np.ascontiguousarray(origins, dtype=np.float64).reshape(-1, 3) directions = np.ascontiguousarray(directions, dtype=np.float64).reshape(-1, 3) n = len(origins) bands = self.absorption.shape[1] factor = np.ones((n, bands)) transparent = self.transparent counted = ~transparent if counted is None else np.asarray(counted, dtype=bool) crossings = np.zeros((n, *counted.shape[1:]), dtype=np.int64) lengths = np.broadcast_to(np.asarray(lengths, dtype=np.float64), (n,)).copy() skip = np.broadcast_to(np.asarray(ignore, dtype=np.int64), (n,)).copy() start = origins.copy() alive = np.arange(n) for _ in range(MAX_CROSSINGS + 1): if len(alive) == 0: break t, face = self.intersect(start[alive], directions[alive], lengths[alive], skip[alive]) hit = face >= 0 rows, face, t = alive[hit], face[hit], t[hit] if self.transmission is None: factor[rows] = 0.0 break through = self.transmission[face] if transparent_only: through = np.where(transparent[face][:, None], through, 0.0) factor[rows] *= through crossings[rows] += counted[face] start[rows] += directions[rows] * t[:, None] lengths[rows] -= t skip[rows] = face alive = rows[np.any(through > 0.0, axis=1)] else: factor[alive] = 0.0 return factor, crossings
@property def band_hz(self) -> tuple[int, ...]: """Centre frequencies (Hz) of the model's bands.""" return band_centres(self.bands) @property def plane_count(self) -> int: return len(self.plane_offset)
[docs] def mirror(self, points: np.ndarray, planes: np.ndarray) -> np.ndarray: """Mirror each point across the plane with the same row index.""" n = self.plane_normal[planes] distance = np.einsum("ij,ij->i", n, points) - self.plane_offset[planes] return points - 2.0 * distance[:, None] * n
[docs] def impedance_faces(self, faces: np.ndarray) -> np.ndarray: """(n,) whether each of ``faces`` has a material with an impedance.""" if self.face_impedance is None: return np.zeros(np.shape(faces), dtype=bool) return self.face_impedance[np.asarray(faces, dtype=np.int64)] >= 0
[docs] def factor_faces(self, faces: np.ndarray) -> np.ndarray: """(n,) whether reflections off each of ``faces`` take a reflection factor that depends on the path (see :func:`~acoustic_spaces.engine.coherent.ground_factors`): faces with an impedance, and the ground of a scene with ground zones.""" out = self.impedance_faces(faces) if self.ground_part is not None: out = out | (self.ground_part[np.asarray(faces, dtype=np.int64)] >= 0) return out
[docs] def reflection( self, faces: np.ndarray, incoming: np.ndarray, order: int, impedance: bool = False ) -> np.ndarray: """(n, bands) specular energy share of reflections off ``faces`` (n,) of sound that travelled ``incoming`` (n, 3) from the source or the previous reflection, the ``order``-th reflection of its path: (1 - absorption) (1 - scattering), with the scattering of the surface's size when that applies, as the stochastic tracer reflects its rays. With ``impedance``, the faces of :meth:`factor_faces` give (1 - scattering) alone: their reflection factor, which depends on the path, takes the place of the absorption.""" faces = np.asarray(faces, dtype=np.int64) scattering = self.scattering[faces] if self.surface_size is not None and order >= self.size_from_order and len(faces): incoming = np.asarray(incoming, dtype=float).reshape(-1, 3) distance = np.linalg.norm(incoming, axis=1) normal = self.plane_normal[self.face_plane[faces]] cosine = np.abs(np.einsum("ij,ij->i", normal, incoming)) / np.maximum(distance, 1e-300) width, length = self.surface_size[faces].T scattering = size_scattering( width, length, distance, cosine, self.room.speed_of_sound(), scattering, self.band_hz, ) kept = 1.0 - self.absorption[faces] if impedance and (self.face_impedance is not None or self.ground_part is not None): kept = np.where(self.factor_faces(faces)[:, None], 1.0, kept) return kept * (1.0 - scattering)
def intersect( self, origins: np.ndarray, directions: np.ndarray, t_max: np.ndarray, ignore: np.ndarray ) -> tuple[np.ndarray, np.ndarray]: return self.bvh.intersect( np.ascontiguousarray(origins, dtype=np.float64), np.ascontiguousarray(directions, dtype=np.float64), np.ascontiguousarray(t_max, dtype=np.float64), np.ascontiguousarray(ignore, dtype=np.int64), )
def _ground_faces(room: Room) -> np.ndarray: """(F,) the faces of an outdoor scene's ground, flat or a terrain: those built as the ground, its zones included (the model file's faces lying on flat ground are left out of the mesh, see :func:`~acoustic_spaces.geometry.outdoor.standing`).""" from acoustic_spaces.geometry.outdoor import GROUND mesh = room.mesh ground = np.array([GROUND in label for label in mesh.labels] or [False], dtype=bool) return ground[mesh.face_labels] def _ground_parts(room: Room) -> tuple[np.ndarray, np.ndarray]: """For an outdoor scene whose ground has zones: (F,) the part of the ground each face lies in (0 outside the zones, then each zone; -1 for faces that are not the ground, see :func:`_ground_faces`) and (parts,) a face of each part (-1 for a part with none).""" layout = room.outdoor flat = _ground_faces(room) part = np.full(len(flat), -1, dtype=np.int64) part[flat] = layout.zone_at(room.mesh.vertices[room.mesh.faces[flat]].mean(axis=1)) + 1 first = np.full(1 + len(layout.zones), -1, dtype=np.int64) for p in range(len(first)): found = np.flatnonzero(part == p) if len(found): first[p] = found[0] return part, first def size_scattering( width: np.ndarray, length: np.ndarray, distance: np.ndarray, cosine: np.ndarray, speed_of_sound: float, scattering: np.ndarray, frequencies=OCTAVE_BANDS_HZ, ) -> np.ndarray: """Scattering coefficients (n, bands) of reflections off surfaces ``width`` by ``length`` metres (n,), with what their limited size scatters added to their own ``scattering`` (n, bands) at the bands' centre ``frequencies`` (Hz), after Christensen and Rindel (2005), as in ODEON. Below f_w = c d / (2 (w cos)^2) the specular share falls as f / f_w, and below f_l = c d / (2 l^2) as f / f_l as well, d being the distance the sound travelled to the surface (from the source or the previous reflection) and cos the cosine of its angle of incidence. A large surface reflects specularly down to low frequencies; a small one, a distant one or one met at a grazing angle scatters. """ across = np.asarray(width, float) * np.maximum(np.asarray(cosine, float), 1e-3) # c d, never 0: a reflection right where the last one was (a corner) is specular. reach = np.maximum(speed_of_sound * np.asarray(distance, float), 1e-300)[:, None] f = np.asarray(frequencies, float) # Over a large surface (a stadium's ground) that floor overflows to inf: still 1. with np.errstate(over="ignore"): specular = np.minimum(1.0, f * 2.0 * across[:, None] ** 2 / reach) * np.minimum( 1.0, f * 2.0 * np.asarray(length, float)[:, None] ** 2 / reach ) return 1.0 - (1.0 - scattering) * specular def surface_sizes(vertices: np.ndarray, faces: np.ndarray, face_plane: np.ndarray) -> np.ndarray: """(F, 2) width and length (m) of the surface each face belongs to. A surface is the faces of one plane that share edges, whatever their materials (a window in a wall is part of the wall). Its width and length are those of the rectangle with its area and perimeter; a surface rounder than a square (whose perimeter is too short for any rectangle of its area) counts as a square. """ vertices = np.asarray(vertices, dtype=float) faces = np.asarray(faces, dtype=np.int64) n = len(faces) if n == 0: return np.zeros((0, 2)) # Edges as sorted vertex pairs, one row per face corner. pairs = np.sort(np.stack([faces, np.roll(faces, -1, axis=1)], axis=2).reshape(-1, 2), axis=1) owner = np.repeat(np.arange(n), 3) edge_ids, edge = np.unique(pairs, axis=0, return_inverse=True) edge = edge.reshape(-1) # Join faces of one plane across shared edges (label propagation with jumps). order = np.lexsort((face_plane[owner], edge)) e, f = edge[order], owner[order] same = (e[1:] == e[:-1]) & (face_plane[f[1:]] == face_plane[f[:-1]]) a, b = f[:-1][same], f[1:][same] label = np.arange(n) while len(a): low = np.minimum(label[a], label[b]) new = label.copy() np.minimum.at(new, a, low) np.minimum.at(new, b, low) new = new[new] if np.array_equal(new, label): break label = new triangles = vertices[faces] face_area = 0.5 * np.linalg.norm( np.cross(triangles[:, 1] - triangles[:, 0], triangles[:, 2] - triangles[:, 0]), axis=1 ) area = np.bincount(label, weights=face_area, minlength=n) # An edge is on a surface's boundary when only one of the surface's faces has it. key = edge.astype(np.int64) * n + label[owner] keys, count = np.unique(key, return_counts=True) boundary = keys[count == 1] edge_length = np.linalg.norm(vertices[edge_ids[:, 0]] - vertices[edge_ids[:, 1]], axis=1) perimeter = np.bincount(boundary % n, weights=edge_length[boundary // n], minlength=n) quarter = perimeter / 4.0 spread = np.sqrt(np.maximum(quarter**2 - area, 0.0)) side = np.sqrt(area) width = np.where(quarter**2 > area, quarter - spread, side) length = np.where(quarter**2 > area, quarter + spread, side) size = np.column_stack([width[label], length[label]]) return np.maximum(size, 1e-6)