stl2bem 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
stl2bem/__init__.py ADDED
@@ -0,0 +1,20 @@
1
+ """stl2bem: sound scattering by rigid objects from STL files (CBIE + CHIEF boundary element method), for plane
2
+ waves (far field) or point sources (near field), on the GPU (CuPy) or the CPU (NumPy)."""
3
+ from .analytic import rigid_sphere, rigid_sphere_point
4
+ from .backend import HAS_CUPY, Backend, gpu_available
5
+ from .bem_core import (compute_p_total_panel_major, estimate_cost, solve_table,
6
+ spherical_doa_grid, write_free_field)
7
+ from .chief import chief_points, points_inside
8
+ from .panels import (auto_panel_targets, load_mic_positions, map_to_elements, project_to_surface,
9
+ surface_receivers)
10
+ from .stl_io import Mesh, build_mesh, mesh_from_arrays, read_stl, write_stl
11
+
12
+ __version__ = "0.1.0"
13
+
14
+ __all__ = [
15
+ "build_mesh", "mesh_from_arrays", "read_stl", "write_stl", "Mesh",
16
+ "chief_points", "points_inside",
17
+ "load_mic_positions", "auto_panel_targets", "map_to_elements", "project_to_surface", "surface_receivers",
18
+ "spherical_doa_grid", "estimate_cost", "solve_table", "compute_p_total_panel_major",
19
+ "write_free_field", "rigid_sphere", "rigid_sphere_point", "Backend", "HAS_CUPY", "gpu_available",
20
+ ]
stl2bem/analysis.py ADDED
@@ -0,0 +1,156 @@
1
+ """Analysis of response tables: loading, free-field references, direction-of-arrival error caused by the body.
2
+
3
+ Typical question: an array is mounted on a device; the localization algorithm uses free-field steering vectors
4
+ (microphone positions only). How far off are its estimates because of the body? `doa_error` feeds the table of the
5
+ body (the "truth") to an estimator steered with another model (free field, or another table) and returns the angular
6
+ error per source direction.
7
+
8
+ from stl2bem.analysis import load_table, free_field, doa_error
9
+ body = load_table("p_total_robot_..._4panel.h5")
10
+ err = doa_error(body, free_field(body), band=(300, 2600), method="srp-phat", search="azimuth")
11
+ """
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import dataclass, field
15
+
16
+ import h5py
17
+ import numpy as np
18
+
19
+
20
+ @dataclass
21
+ class Table:
22
+ p: np.ndarray # (R, D, F) complex, package convention (see bem_core.CONVENTION)
23
+ doa: np.ndarray # (D, 3) unit vectors towards the source
24
+ freqs: np.ndarray # (F,)
25
+ positions: np.ndarray # (R, 3) receiver positions [m]
26
+ attrs: dict = field(default_factory=dict)
27
+ sources: np.ndarray | None = None # (D, 3) point-source positions [m] (near field); None for plane waves
28
+
29
+ @property
30
+ def az_el(self):
31
+ """(azimuth, elevation) in degrees of every direction."""
32
+ az = np.degrees(np.arctan2(self.doa[:, 1], self.doa[:, 0])) % 360
33
+ el = np.degrees(np.arcsin(np.clip(self.doa[:, 2], -1, 1)))
34
+ return az, el
35
+
36
+ def select(self, receivers=None, doa=None, freqs=None) -> "Table":
37
+ r = slice(None) if receivers is None else receivers
38
+ d = slice(None) if doa is None else doa
39
+ f = slice(None) if freqs is None else freqs
40
+ return Table(self.p[r][:, d][:, :, f], self.doa[d], self.freqs[f], self.positions[r], dict(self.attrs),
41
+ None if self.sources is None else self.sources[d])
42
+
43
+
44
+ def load_table(path, receivers=None, elevations=None, band=None) -> Table:
45
+ """Read a table; optionally only some receivers, the directions at given elevations (degrees, nearest grid
46
+ row of an az x el grid) and the frequencies within band=(lo, hi) Hz. Reads only what is needed."""
47
+ with h5py.File(path, "r") as f:
48
+ doa = f["doa_grid"][:].astype(np.float64)
49
+ freqs = f["freqs"][:].astype(np.float64)
50
+ pos = (f["positions"] if "positions" in f else f["centroids"])[:].astype(np.float64)
51
+ attrs = {k: (v.decode() if isinstance(v, bytes) else v) for k, v in f.attrs.items()}
52
+ r_idx = np.arange(len(pos)) if receivers is None else np.asarray(receivers)
53
+ if elevations is not None:
54
+ el = np.degrees(np.arcsin(np.clip(doa[:, 2], -1, 1)))
55
+ levels = np.unique(np.round(el, 6))
56
+ d_idx = np.concatenate([np.nonzero(np.isclose(el, levels[np.argmin(np.abs(levels - e))]))[0]
57
+ for e in np.atleast_1d(elevations)])
58
+ else:
59
+ d_idx = np.arange(len(doa))
60
+ f_idx = (np.arange(len(freqs)) if band is None
61
+ else np.nonzero((freqs >= band[0]) & (freqs <= band[1]))[0])
62
+ p = f["p"][np.sort(r_idx)][:, np.sort(d_idx)][:, :, np.sort(f_idx)]
63
+ src = f["source_positions"][:][np.sort(d_idx)] if "source_positions" in f else None
64
+ return Table(p, doa[np.sort(d_idx)], freqs[np.sort(f_idx)], pos[np.sort(r_idx)], attrs, src)
65
+
66
+
67
+ def free_field(t: Table, positions=None, doa=None, c: float = 343.0) -> Table:
68
+ """Free-field table (no body) at the given (or the table's) receiver positions and directions; point sources
69
+ if the table has them (same normalization as the solver: 1 at the origin)."""
70
+ pos = t.positions if positions is None else np.asarray(positions, np.float64)
71
+ k = 2 * np.pi * t.freqs / c
72
+ if t.sources is not None and doa is None:
73
+ s = t.sources
74
+ r = np.linalg.norm(pos[:, None] - s[None], axis=2) # (R, D)
75
+ r0 = np.linalg.norm(s, axis=1)[None]
76
+ dr = ((pos * pos).sum(1)[:, None] - 2 * pos @ s.T) / (r + r0)
77
+ p = (r0 / r)[:, :, None] * np.exp(-1j * dr[:, :, None] * k[None, None, :])
78
+ return Table(p, t.doa.copy(), t.freqs.copy(), pos, {"mesh_type": "free_field"}, s.copy())
79
+ d = t.doa if doa is None else np.asarray(doa, np.float64)
80
+ p = np.exp(1j * (pos @ d.T)[:, :, None] * k[None, None, :])
81
+ return Table(p, d, t.freqs.copy(), pos, {"mesh_type": "free_field"})
82
+
83
+
84
+ def azimuth_ring(n: int = 360, elevation_deg: float = 0.0) -> np.ndarray:
85
+ a = np.radians(np.arange(n) * 360.0 / n)
86
+ e = np.radians(elevation_deg)
87
+ return np.column_stack([np.cos(e) * np.cos(a), np.cos(e) * np.sin(a), np.full(n, np.sin(e))])
88
+
89
+
90
+ def _srp_phat(X, S):
91
+ """X (R, F) one source; S (R, G, F) steering. Sum over microphone pairs and bins of PHAT-weighted cross-spectra
92
+ projected on the steering phases (DiBiase 2000)."""
93
+ R = X.shape[0]
94
+ out = np.zeros(S.shape[1])
95
+ for i in range(R):
96
+ for j in range(i + 1, R):
97
+ g = X[i] * np.conj(X[j])
98
+ g = g / (np.abs(g) + 1e-30)
99
+ s = S[i] * np.conj(S[j])
100
+ s = s / (np.abs(s) + 1e-30)
101
+ out += np.real(np.conj(s) @ g)
102
+ return out
103
+
104
+
105
+ def _music(X, S, n_src: int = 1):
106
+ """Narrowband MUSIC per bin with the rank-one covariance of X, pseudo-spectra normalized and averaged."""
107
+ R, F = X.shape
108
+ out = np.zeros(S.shape[1])
109
+ for fi in range(F):
110
+ x = X[:, fi:fi + 1]
111
+ C = x @ x.conj().T + 1e-9 * np.real(np.vdot(x, x)) * np.eye(R)
112
+ w, V = np.linalg.eigh(C)
113
+ En = V[:, : R - n_src]
114
+ a = S[:, :, fi]
115
+ a = a / (np.linalg.norm(a, axis=0, keepdims=True) + 1e-30)
116
+ ps = 1.0 / (np.sum(np.abs(En.conj().T @ a) ** 2, axis=0) + 1e-12)
117
+ out += ps / ps.max()
118
+ return out
119
+
120
+
121
+ def angle_between(u, v) -> np.ndarray:
122
+ return np.degrees(np.arccos(np.clip(np.sum(u * v, -1), -1, 1)))
123
+
124
+
125
+ def doa_error(truth: Table, model: Table, band=None, method: str = "srp-phat", search: str = "azimuth",
126
+ sources=None) -> dict:
127
+ """Localization error when the observations come from `truth` and the estimator is steered with `model`.
128
+
129
+ truth, model: tables with the same receivers and frequencies; model.doa is the search grid.
130
+ search='azimuth': estimate the azimuth only (planar arrays, sources near the horizon); the error is the signed
131
+ azimuth difference. search='full': search all model directions; the error is the great-circle angle.
132
+ sources: indices of truth directions to test (default all). Returns a dict of arrays."""
133
+ if truth.p.shape[0] != model.p.shape[0] or not np.allclose(truth.freqs, model.freqs):
134
+ raise ValueError("truth and model need the same receivers and frequencies")
135
+ f_sel = (np.ones(len(truth.freqs), bool) if band is None
136
+ else (truth.freqs >= band[0]) & (truth.freqs <= band[1]))
137
+ S = model.p[:, :, f_sel]
138
+ est_fn = {"srp-phat": _srp_phat, "music": _music}[method]
139
+ src = np.arange(len(truth.doa)) if sources is None else np.asarray(sources)
140
+ est = np.empty((len(src), 3))
141
+ for n, s in enumerate(src):
142
+ est[n] = model.doa[int(np.argmax(est_fn(truth.p[:, s, f_sel], S)))]
143
+ true = truth.doa[src]
144
+ out = {"true": true, "estimate": est, "angle": angle_between(true, est)}
145
+ if search == "azimuth":
146
+ az_t = np.degrees(np.arctan2(true[:, 1], true[:, 0]))
147
+ az_e = np.degrees(np.arctan2(est[:, 1], est[:, 0]))
148
+ out["azimuth_error"] = (az_e - az_t + 180) % 360 - 180
149
+ return out
150
+
151
+
152
+ def summarize(err: dict, key: str = None) -> str:
153
+ e = err[key or ("azimuth_error" if "azimuth_error" in err else "angle")]
154
+ a = np.abs(e)
155
+ return (f"mean |err| {a.mean():.2f} deg, 95th pct {np.percentile(a, 95):.2f}, max {a.max():.2f}, "
156
+ f"mean signed {e.mean():+.2f}")
stl2bem/analytic.py ADDED
@@ -0,0 +1,100 @@
1
+ """Reference solution: plane wave scattered by a rigid sphere (in the package convention).
2
+
3
+ Physics form (e^{-iwt}, incident exp(i k u.r), u the propagation direction):
4
+ p = sum_n (2n + 1) i^n [ j_n(kr) - j_n'(ka) / h_n'(ka) h_n(kr) ] P_n(cos gamma), cos gamma = u . r_hat
5
+ and on the surface r = a (Wronskian): p = sum_n (2n + 1) i^n (i / (ka)^2) / h_n'(ka) P_n(cos gamma).
6
+ The package convention (e^{+jwt}, incident exp(+jk d.r), d towards the source) is the complex conjugate with u = -d.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import numpy as np
11
+ from scipy.special import eval_legendre, spherical_jn, spherical_yn
12
+
13
+
14
+ def _n_terms(x_max: float) -> int:
15
+ return int(x_max + 10 * max(x_max, 1e-3) ** (1 / 3) + 12)
16
+
17
+
18
+ def rigid_sphere(k: float, a: float, points, doa) -> np.ndarray:
19
+ """Total pressure (P, D) at points (P, 3) on or outside a rigid sphere of radius a centered at the origin, for
20
+ plane waves from directions doa (D, 3) (unit vectors towards the source). Package convention."""
21
+ points = np.atleast_2d(np.asarray(points, np.float64))
22
+ doa = np.atleast_2d(np.asarray(doa, np.float64))
23
+ r = np.linalg.norm(points, axis=1)
24
+ if (r < a * (1 - 1e-6)).any():
25
+ raise ValueError("points inside the sphere")
26
+ rhat = points / r[:, None]
27
+ cos_g = -(rhat @ doa.T) # u = -d
28
+ ka = k * a
29
+ n = np.arange(_n_terms(k * r.max()) + 1)
30
+ hp = spherical_jn(n, ka, True) + 1j * spherical_yn(n, ka, True) # h_n^(1)'(ka)
31
+ P = np.stack([eval_legendre(int(m), cos_g) for m in n]) # (n, P, D)
32
+ on = np.isclose(r, a, rtol=1e-6)
33
+ out = np.empty(cos_g.shape, np.complex128)
34
+ if on.any():
35
+ coef = (2 * n + 1) * (1j ** n) * (1j / ka ** 2) / hp
36
+ out[on] = np.einsum("n,npd->pd", coef, P[:, on])
37
+ if (~on).any():
38
+ kr = k * r[~on]
39
+ jn = spherical_jn(n[:, None], kr[None])
40
+ hn = jn + 1j * spherical_yn(n[:, None], kr[None])
41
+ radial = jn - (spherical_jn(n, ka, True) / hp)[:, None] * hn # (n, P')
42
+ coef = (2 * n + 1) * (1j ** n)
43
+ out[~on] = np.einsum("n,np,npd->pd", coef, radial, P[:, ~on])
44
+ return np.conj(out)
45
+
46
+
47
+ def rigid_sphere_point(k: float, a: float, points, sources) -> np.ndarray:
48
+ """Total pressure (P, S) at points (P, 3) on or outside a rigid sphere of radius a centered at the origin, for
49
+ point sources at positions sources (S, 3), each farther from the center than every point. Normalized like
50
+ stl2bem tables: divided by the free-field pressure the source produces at the origin. Package convention.
51
+
52
+ Physics form (e^{-iwt}), source at distance r_s, a <= r < r_s, cos gamma = r_hat . s_hat:
53
+ p = (ik / 4 pi) sum_n (2n + 1) h_n(k r_s) [ j_n(kr) - j_n'(ka) / h_n'(ka) h_n(kr) ] P_n(cos gamma),
54
+ on the surface the bracket is i / ((ka)^2 h_n'(ka)) (Wronskian); free field at the origin exp(i k r_s) / (4 pi r_s).
55
+ """
56
+ points = np.atleast_2d(np.asarray(points, np.float64))
57
+ sources = np.atleast_2d(np.asarray(sources, np.float64))
58
+ r = np.linalg.norm(points, axis=1)
59
+ rs = np.linalg.norm(sources, axis=1)
60
+ if (r < a * (1 - 1e-6)).any():
61
+ raise ValueError("points inside the sphere")
62
+ if r.max() >= rs.min():
63
+ raise ValueError("every point must be closer to the center than every source")
64
+ cos_g = (points / r[:, None]) @ (sources / rs[:, None]).T # (P, S)
65
+ ka = k * a
66
+ ratio = r.max() / rs.min() # terms decay like ratio^n
67
+ n_max = min(_n_terms(k * rs.max()) + int(np.ceil(np.log(1e-12) / np.log(ratio))), 120)
68
+ n = np.arange(n_max + 1)
69
+ hp = spherical_jn(n, ka, True) + 1j * spherical_yn(n, ka, True) # h_n'(ka)
70
+ hs = spherical_jn(n[:, None], k * rs[None]) + 1j * spherical_yn(n[:, None], k * rs[None]) # (n, S)
71
+ P = np.stack([eval_legendre(int(m), cos_g) for m in n]) # (n, P, S)
72
+ on = np.isclose(r, a, rtol=1e-6)
73
+ out = np.empty(cos_g.shape, np.complex128)
74
+ if on.any():
75
+ coef = (2 * n + 1) * (1j / ka ** 2) / hp # (n,)
76
+ out[on] = np.einsum("n,ns,nps->ps", coef, hs, P[:, on])
77
+ if (~on).any():
78
+ kr = k * r[~on]
79
+ jn = spherical_jn(n[:, None], kr[None])
80
+ hn = jn + 1j * spherical_yn(n[:, None], kr[None])
81
+ radial = jn - (spherical_jn(n, ka, True) / hp)[:, None] * hn # (n, P')
82
+ out[~on] = np.einsum("n,np,ns,nps->ps", 2 * n + 1, radial, hs, P[:, ~on])
83
+ out *= 1j * k / (4 * np.pi)
84
+ if not np.isfinite(out).all():
85
+ raise FloatingPointError("series overflow; move the sources farther from the points")
86
+ free0 = np.exp(1j * k * rs) / (4 * np.pi * rs) # free field at the origin
87
+ return np.conj(out / free0[None, :])
88
+
89
+
90
+ def interior_dirichlet_ka(n_max: int = 3, count: int = 3) -> list[tuple[float, int]]:
91
+ """Irregular frequencies of the CBIE for a sphere: zeros ka of j_n (interior Dirichlet eigenvalues)."""
92
+ from scipy.optimize import brentq
93
+ out = []
94
+ for n in range(n_max + 1):
95
+ f = lambda x: spherical_jn(n, x)
96
+ xs = np.linspace(0.5, 20, 4000)
97
+ v = f(xs)
98
+ roots = [brentq(f, xs[i], xs[i + 1]) for i in range(len(xs) - 1) if v[i] * v[i + 1] < 0][:count]
99
+ out += [(float(x), n) for x in roots]
100
+ return sorted(out)
stl2bem/backend.py ADDED
@@ -0,0 +1,116 @@
1
+ """Array backend: CuPy on an NVIDIA GPU when available, NumPy/SciPy on the CPU otherwise.
2
+
3
+ The solver is written once against ``Backend.xp`` (the array module) and ``Backend`` linear-algebra wrappers,
4
+ so small meshes run anywhere and large ones use the GPU without code changes.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import numpy as np
9
+ import scipy.linalg as _sp_la
10
+
11
+ import functools
12
+
13
+ try: # optional GPU backend
14
+ import cupy as _cp
15
+ import cupyx.scipy.linalg as _cpx_la
16
+ HAS_CUPY = True # CuPy can be imported; whether a GPU can be used is checked by gpu_available()
17
+ except Exception: # ImportError, or a CUDA runtime that cannot be loaded
18
+ _cp = _cpx_la = None
19
+ HAS_CUPY = False
20
+
21
+
22
+ @functools.lru_cache(maxsize=1)
23
+ def gpu_available() -> tuple[bool, str]:
24
+ """(True, "") if CuPy can run on a GPU here, else (False, reason). Checked once, on first use: importing CuPy
25
+ succeeds on machines without a GPU or with a mismatched driver, and fails only at the first kernel."""
26
+ if not HAS_CUPY:
27
+ return False, "CuPy is not installed"
28
+ try:
29
+ if _cp.cuda.runtime.getDeviceCount() < 1:
30
+ return False, "no CUDA device found"
31
+ a = _cp.arange(16, dtype=_cp.complex64).reshape(4, 4) + 4 * _cp.eye(4, dtype=_cp.complex64)
32
+ float(_cp.abs(_cp.linalg.qr(a)[1]).sum()) # a kernel and cuSOLVER, as the solver uses them
33
+ return True, ""
34
+ except Exception as e: # driver/runtime mismatch, missing libraries, ...
35
+ return False, f"CuPy cannot use the GPU ({type(e).__name__}: {str(e).splitlines()[0][:120]})"
36
+
37
+
38
+ class Backend:
39
+ """Thin wrapper over NumPy/SciPy or CuPy with the few operations the solver needs.
40
+
41
+ name: "auto" (GPU if one can be used, otherwise CPU), "cupy" (GPU, error if not possible) or "numpy" (CPU)."""
42
+
43
+ def __init__(self, name: str = "auto"):
44
+ self.fallback_reason = ""
45
+ if name == "auto":
46
+ ok, why = gpu_available()
47
+ name = "cupy" if ok else "numpy"
48
+ self.fallback_reason = why
49
+ elif name == "cupy":
50
+ ok, why = gpu_available()
51
+ if not ok:
52
+ raise RuntimeError(f"backend 'cupy' requested but {why} "
53
+ "(pip install cupy-cuda12x matching your CUDA version, or use --backend numpy)")
54
+ if name not in ("cupy", "numpy"):
55
+ raise ValueError(f"unknown backend {name!r} (use auto, cupy or numpy)")
56
+ self.name = name
57
+ self.gpu = name == "cupy"
58
+ self.xp = _cp if self.gpu else np
59
+ self._la = _cpx_la if self.gpu else _sp_la
60
+
61
+ # Transfers
62
+ def asarray(self, a, dtype=None):
63
+ return self.xp.asarray(a, dtype=dtype)
64
+
65
+ def asnumpy(self, a) -> np.ndarray:
66
+ return _cp.asnumpy(a) if self.gpu else np.asarray(a)
67
+
68
+ def free(self):
69
+ """Return cached GPU blocks to the driver (no-op on the CPU)."""
70
+ if self.gpu:
71
+ _cp.get_default_memory_pool().free_all_blocks()
72
+
73
+ def free_memory_gb(self) -> float | None:
74
+ if not self.gpu:
75
+ return None
76
+ return _cp.cuda.Device().mem_info[0] / 1024 ** 3
77
+
78
+ # Dense linear algebra
79
+ def qr(self, a):
80
+ return self.xp.linalg.qr(a, mode="reduced")
81
+
82
+ def solve_triangular(self, r, b):
83
+ return self._la.solve_triangular(r, b, lower=False)
84
+
85
+ def lstsq_factor(self, a):
86
+ """Factor a tall matrix (m >= n, the CHIEF-augmented system) for repeated least-squares solves.
87
+
88
+ GPU: reduced QR (cuSOLVER). CPU: normal equations A^H A x = A^H b in double precision with a Cholesky
89
+ factor. Dense QR is several times slower than Cholesky in common CPU LAPACK builds; forming the Gram matrix in
90
+ complex128 keeps the rounding error (cond(A)^2 * 1e-16) far below the error already present in A
91
+ (single-precision assembly), for the moderate condition numbers of CHIEF-augmented systems."""
92
+ if self.gpu:
93
+ q, r = self.xp.linalg.qr(a, mode="reduced")
94
+ return ("qr", q, r)
95
+ a64 = np.asarray(a, dtype=np.complex128 if np.iscomplexobj(a) else np.float64)
96
+ gram = a64.conj().T @ a64
97
+ c = _sp_la.cho_factor(gram, lower=False, overwrite_a=True, check_finite=False)
98
+ return ("chol", a64, c)
99
+
100
+ def lstsq_solve(self, fac, b):
101
+ """Least-squares solution of the factored system for right-hand sides b (m, k)."""
102
+ if fac[0] == "qr":
103
+ _, q, r = fac
104
+ return self._la.solve_triangular(r, q.conj().T @ b, lower=False)
105
+ _, a64, c = fac
106
+ rhs = a64.conj().T @ np.asarray(b, dtype=a64.dtype)
107
+ return _sp_la.cho_solve(c, rhs, overwrite_b=True, check_finite=False).astype(b.dtype, copy=False)
108
+
109
+ def lu_factor(self, a):
110
+ return self._la.lu_factor(a, overwrite_a=True)
111
+
112
+ def lu_solve(self, lu_piv, b):
113
+ return self._la.lu_solve(lu_piv, b, overwrite_b=True)
114
+
115
+ def __repr__(self):
116
+ return f"Backend({self.name})"