stl2bem 0.1.0__tar.gz

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-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Junhyeong Kwon
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
stl2bem-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,205 @@
1
+ Metadata-Version: 2.4
2
+ Name: stl2bem
3
+ Version: 0.1.0
4
+ Summary: Boundary element solver for sound scattering by rigid objects given as closed STL meshes, on the CPU or GPU
5
+ Author: Junhyeong Kwon
6
+ License-Expression: MIT
7
+ Project-URL: Repository, https://github.com/Kwon-Junhyeong/stl2bem
8
+ Project-URL: Issues, https://github.com/Kwon-Junhyeong/stl2bem/issues
9
+ Keywords: acoustics,boundary element method,BEM,microphone array,steering vector,array manifold,scattering,direction of arrival,CHIEF,GPU
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Topic :: Scientific/Engineering :: Physics
16
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Analysis
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: numpy>=1.22
21
+ Requires-Dist: scipy>=1.8
22
+ Requires-Dist: h5py>=3.0
23
+ Requires-Dist: tqdm
24
+ Provides-Extra: gpu
25
+ Requires-Dist: cupy-cuda12x; extra == "gpu"
26
+ Provides-Extra: prep
27
+ Requires-Dist: scikit-image>=0.19; extra == "prep"
28
+ Provides-Extra: plot
29
+ Requires-Dist: matplotlib; extra == "plot"
30
+ Requires-Dist: pillow; extra == "plot"
31
+ Provides-Extra: sofa
32
+ Requires-Dist: sofar>=1.1; extra == "sofa"
33
+ Provides-Extra: crosscheck
34
+ Requires-Dist: bempp-cl>=0.4; extra == "crosscheck"
35
+ Provides-Extra: dev
36
+ Requires-Dist: pytest; extra == "dev"
37
+ Requires-Dist: scikit-image>=0.19; extra == "dev"
38
+ Requires-Dist: matplotlib; extra == "dev"
39
+ Requires-Dist: pillow; extra == "dev"
40
+ Requires-Dist: sofar>=1.1; extra == "dev"
41
+ Requires-Dist: build; extra == "dev"
42
+ Requires-Dist: twine; extra == "dev"
43
+ Dynamic: license-file
44
+
45
+ # stl2bem
46
+
47
+ Computes the sound pressure on and around a rigid object from a closed STL mesh, with the boundary element method.
48
+ It runs on a CPU or an NVIDIA GPU and writes tables over directions and frequencies, for example the response of
49
+ every microphone on a device, as HDF5 or SOFA files.
50
+
51
+ ![stl2bem: an STL triangle mesh in, the sound pressure on its surface out](https://raw.githubusercontent.com/Kwon-Junhyeong/stl2bem/main/docs/img/fig_pipeline.png)
52
+
53
+ <table>
54
+ <tr>
55
+ <td width="33%"><img src="https://raw.githubusercontent.com/Kwon-Junhyeong/stl2bem/main/docs/img/gallery_star.gif" alt="star, 4 kHz"></td>
56
+ <td width="33%"><img src="https://raw.githubusercontent.com/Kwon-Junhyeong/stl2bem/main/docs/img/gallery_boat.gif" alt="toy boat, 3 kHz"></td>
57
+ <td width="33%"><img src="https://raw.githubusercontent.com/Kwon-Junhyeong/stl2bem/main/docs/img/gallery_mug.gif" alt="mug, 2.5 kHz"></td>
58
+ </tr>
59
+ <tr>
60
+ <td align="center">star, 4 kHz</td><td align="center">toy boat, 3 kHz</td><td align="center">mug, 2.5 kHz</td>
61
+ </tr>
62
+ <tr>
63
+ <td><img src="https://raw.githubusercontent.com/Kwon-Junhyeong/stl2bem/main/docs/img/gallery_bottle.gif" alt="wine bottle, 144 Hz"></td>
64
+ <td><img src="https://raw.githubusercontent.com/Kwon-Junhyeong/stl2bem/main/docs/img/gallery_bell.gif" alt="bell, 2.5 kHz"></td>
65
+ <td><img src="https://raw.githubusercontent.com/Kwon-Junhyeong/stl2bem/main/docs/img/gallery_pipe.gif" alt="elbow pipe, 1.4 kHz"></td>
66
+ </tr>
67
+ <tr>
68
+ <td align="center">wine bottle, 144 Hz</td><td align="center">bell, 2.5 kHz</td><td align="center">elbow pipe, 1.4 kHz</td>
69
+ </tr>
70
+ </table>
71
+
72
+ Plane waves passing six objects modeled in Fusion (3,800 to 12,000 triangles each): real part of the total
73
+ pressure on a slice through each object, over one period. Surface pressure and cavity resonances of the same
74
+ objects are in [docs/validation.md](https://github.com/Kwon-Junhyeong/stl2bem/blob/main/docs/validation.md#gallery).
75
+
76
+ ## Install
77
+
78
+ ```bash
79
+ git clone https://github.com/Kwon-Junhyeong/stl2bem
80
+ cd stl2bem
81
+ pip install . # NumPy, SciPy, h5py (CPU)
82
+ pip install ".[prep,sofa]" # optional: merging CAD parts, SOFA export
83
+ pip install cupy-cuda12x # optional GPU backend; pick the CuPy package of your CUDA version
84
+ ```
85
+
86
+ ## Quick start
87
+
88
+ ```bash
89
+ stl2bem --stl device.stl --units mm --mics mics.csv --out out/ --dry_run # check mesh, microphones, resources
90
+ stl2bem --stl device.stl --units mm --mics mics.csv --out out/ # 0-8 kHz, 1-degree direction grid
91
+ stl2bem --stl device.stl --units mm --mics mics.csv --out out/ --source_distance 0.5 # sources 0.5 m away
92
+ ```
93
+
94
+ `mics.csv` has one `x, y, z` row per microphone, in the STL units; each microphone is moved to the closest point of
95
+ the surface. Without `--source_distance` the sources are plane waves (far field). The dry run prints the distance
96
+ 2D²/λ beyond which that holds for your body; closer sources need `--source_distance`. It also estimates the
97
+ run time: the default grid of 65,160 directions takes minutes on a GPU but hours on a CPU, and `--n_el 19`
98
+ (10 degrees in elevation) makes a CPU run about eight times faster. `stl2bem --help` lists all options.
99
+
100
+ From Python:
101
+
102
+ ```python
103
+ import numpy as np
104
+ from stl2bem import build_mesh, surface_receivers, solve_table, spherical_doa_grid
105
+
106
+ mesh = build_mesh("device.stl", units="mm", recenter="none")
107
+ mics, weights, _ = surface_receivers(np.loadtxt("mics.csv", delimiter=",") / 1000, mesh)
108
+ doa, az, el = spherical_doa_grid(360, 19) # 1 deg azimuth, 10 deg elevation
109
+ freqs = np.linspace(0, 4000, 129)
110
+ solve_table(mesh.verts, mesh.tris, mesh.centroids, mesh.normals, mesh.areas, freqs, doa, "table.h5",
111
+ receivers=mics, receiver_elements=weights)
112
+ ```
113
+
114
+ The pressure on a plane through the body, as in the gallery:
115
+
116
+ ```python
117
+ from stl2bem.viz import plane_grid, field_on_points
118
+ pts, shape = plane_grid(center=(0, 0, 0), u=(1, 0, 0), v=(0, 0, 1), half=(0.2, 0.2), n=(241, 241))
119
+ field = field_on_points(mesh, 2000.0, doa=(1, 0, 0), points=pts).reshape(shape) # NaN inside the body
120
+ ```
121
+
122
+ The localization error that the body causes for a free-field SRP-PHAT:
123
+
124
+ ```python
125
+ from stl2bem.analysis import load_table, free_field, doa_error, summarize
126
+ body = load_table("table.h5", elevations=[0])
127
+ print(summarize(doa_error(body, free_field(body), band=(300, 3000), method="srp-phat", search="azimuth")))
128
+ ```
129
+
130
+ ## Output
131
+
132
+ One HDF5 file per body:
133
+
134
+ | dataset | shape | meaning |
135
+ |---|---|---|
136
+ | `p` | (R, D, F) complex64 | total pressure at receiver r for source d at frequency f, relative to the incident pressure at the origin |
137
+ | `doa_grid` | (D, 3) | unit vectors towards the sources; az x el grids are stored az-major (`i_az * n_el + i_el`) |
138
+ | `source_positions` | (D, 3) | point sources only: their positions (m) |
139
+ | `freqs` | (F,) | Hz |
140
+ | `positions` | (R, 3) | where `p` is evaluated (m, mesh frame); `centroids` is an older name for the same array |
141
+ | `chief_points` | (N_c, 3) | only when CHIEF is used: the interior points |
142
+
143
+ Attributes hold the mesh report, the solver options and the convention. `--sofa` (or
144
+ `python -m stl2bem.sofa table.h5`) also writes the table as a SOFA file (AES69, GeneralTF).
145
+
146
+ **Convention.** e^{+jωt}, incident wave exp(+jk d·r). For a source signal s(t) from direction d, the FFT/STFT bin
147
+ (usual e^{-jωt} kernel) at microphone m is S(ω)·p[m, d, ω], so tables and FFT-domain signals combine directly
148
+ without conjugation. The phase reference is the center of the bounding box (`--recenter bbox`); `--recenter none`
149
+ keeps the CAD origin.
150
+
151
+ ## Accuracy
152
+
153
+ ![sphere field](https://raw.githubusercontent.com/Kwon-Junhyeong/stl2bem/main/docs/img/fig_sphere_field.png)
154
+
155
+ Rigid sphere with 5,120 elements at ka = 3.7 against the exact solution: the median difference is 8.6 × 10⁻⁴ of
156
+ the incident amplitude. The singular part of the integrals is evaluated exactly, and microphones on the surface are
157
+ second-order accurate, also on edges and vertices.
158
+
159
+ ![cross-check](https://raw.githubusercontent.com/Kwon-Junhyeong/stl2bem/main/docs/img/fig_crosscheck.png)
160
+
161
+ The six gallery meshes solved again with [bempp-cl](https://github.com/bempp/bempp-cl), which uses a different
162
+ formulation (Burton-Miller, linear elements): the fields differ by 0.01-0.4 % (median) and the resonance
163
+ frequencies by at most 0.5 %. One frequency with 6,840 directions takes 1 s for 4,800 elements and 11 s for
164
+ 14,700 on an RTX 4060 Ti (8 GB).
165
+
166
+ Convergence, the comparison with the original code, resonances and timings: [docs/validation.md](https://github.com/Kwon-Junhyeong/stl2bem/blob/main/docs/validation.md).
167
+ Equations and implementation: [docs/method.md](https://github.com/Kwon-Junhyeong/stl2bem/blob/main/docs/method.md).
168
+
169
+ ## Preparing CAD
170
+
171
+ The solver needs one closed, consistently oriented surface. A single solid exported from CAD usually is one (all
172
+ gallery models are); an assembly usually is not, because its parts overlap. `stl2bem-prep` merges the parts:
173
+
174
+ ```bash
175
+ stl2bem-prep chassis.stl board.stl battery.stl --pitch 8 --units mm --out body.stl
176
+ ```
177
+
178
+ It voxelizes the parts (pitch = element size), fills enclosed cavities and extracts a closed surface. Features
179
+ smaller than the pitch disappear and thin plates become one pitch thick; `--align_z` keeps a flat microphone board
180
+ flat. In Fusion, set the maximum edge length of the STL export to about λ/6 at the highest frequency; the mesh
181
+ report prints the frequency limit from the mean edge length.
182
+
183
+ ## Limits
184
+
185
+ * Rigid bodies in free space: no absorption, no vibrating surfaces, no floor or walls.
186
+ * Dense matrices: for N elements the GPU needs about 2.5 GB + 20 bytes × N² (an 8 GB GPU handles about 15,000
187
+ elements) and the CPU about 1.5 GB + 55 bytes × N² of RAM; time grows with N³. The dry run prints both.
188
+ * CHIEF points need room inside the body. Thin-walled objects (in the gallery, the bottle and the pipe) are solved
189
+ with the CBIE alone, which is safe there: their irregular frequencies start near c / 2t for wall thickness t,
190
+ far above the band the mesh resolves.
191
+ * `--formulation burton-miller` is experimental: as accurate as the default away from resonances, but it damps
192
+ sharp cavity resonances. See [docs/method.md](https://github.com/Kwon-Junhyeong/stl2bem/blob/main/docs/method.md#burton-miller-experimental-option).
193
+
194
+ ## Used in
195
+
196
+ An earlier version of this solver computed the microphone responses of a robot body in:
197
+
198
+ * [robot-body-sound-localization](https://github.com/Kwon-Junhyeong/robot-body-sound-localization): direction of
199
+ a speaker from four microphones on a robot body, by matching recordings to the computed responses.
200
+ * [calibration-free-sound-localization](https://github.com/Kwon-Junhyeong/calibration-free-sound-localization):
201
+ the same task without calibrating the microphone channels.
202
+
203
+ ## License
204
+
205
+ MIT (see [LICENSE](https://github.com/Kwon-Junhyeong/stl2bem/blob/main/LICENSE)).
@@ -0,0 +1,161 @@
1
+ # stl2bem
2
+
3
+ Computes the sound pressure on and around a rigid object from a closed STL mesh, with the boundary element method.
4
+ It runs on a CPU or an NVIDIA GPU and writes tables over directions and frequencies, for example the response of
5
+ every microphone on a device, as HDF5 or SOFA files.
6
+
7
+ ![stl2bem: an STL triangle mesh in, the sound pressure on its surface out](https://raw.githubusercontent.com/Kwon-Junhyeong/stl2bem/main/docs/img/fig_pipeline.png)
8
+
9
+ <table>
10
+ <tr>
11
+ <td width="33%"><img src="https://raw.githubusercontent.com/Kwon-Junhyeong/stl2bem/main/docs/img/gallery_star.gif" alt="star, 4 kHz"></td>
12
+ <td width="33%"><img src="https://raw.githubusercontent.com/Kwon-Junhyeong/stl2bem/main/docs/img/gallery_boat.gif" alt="toy boat, 3 kHz"></td>
13
+ <td width="33%"><img src="https://raw.githubusercontent.com/Kwon-Junhyeong/stl2bem/main/docs/img/gallery_mug.gif" alt="mug, 2.5 kHz"></td>
14
+ </tr>
15
+ <tr>
16
+ <td align="center">star, 4 kHz</td><td align="center">toy boat, 3 kHz</td><td align="center">mug, 2.5 kHz</td>
17
+ </tr>
18
+ <tr>
19
+ <td><img src="https://raw.githubusercontent.com/Kwon-Junhyeong/stl2bem/main/docs/img/gallery_bottle.gif" alt="wine bottle, 144 Hz"></td>
20
+ <td><img src="https://raw.githubusercontent.com/Kwon-Junhyeong/stl2bem/main/docs/img/gallery_bell.gif" alt="bell, 2.5 kHz"></td>
21
+ <td><img src="https://raw.githubusercontent.com/Kwon-Junhyeong/stl2bem/main/docs/img/gallery_pipe.gif" alt="elbow pipe, 1.4 kHz"></td>
22
+ </tr>
23
+ <tr>
24
+ <td align="center">wine bottle, 144 Hz</td><td align="center">bell, 2.5 kHz</td><td align="center">elbow pipe, 1.4 kHz</td>
25
+ </tr>
26
+ </table>
27
+
28
+ Plane waves passing six objects modeled in Fusion (3,800 to 12,000 triangles each): real part of the total
29
+ pressure on a slice through each object, over one period. Surface pressure and cavity resonances of the same
30
+ objects are in [docs/validation.md](https://github.com/Kwon-Junhyeong/stl2bem/blob/main/docs/validation.md#gallery).
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ git clone https://github.com/Kwon-Junhyeong/stl2bem
36
+ cd stl2bem
37
+ pip install . # NumPy, SciPy, h5py (CPU)
38
+ pip install ".[prep,sofa]" # optional: merging CAD parts, SOFA export
39
+ pip install cupy-cuda12x # optional GPU backend; pick the CuPy package of your CUDA version
40
+ ```
41
+
42
+ ## Quick start
43
+
44
+ ```bash
45
+ stl2bem --stl device.stl --units mm --mics mics.csv --out out/ --dry_run # check mesh, microphones, resources
46
+ stl2bem --stl device.stl --units mm --mics mics.csv --out out/ # 0-8 kHz, 1-degree direction grid
47
+ stl2bem --stl device.stl --units mm --mics mics.csv --out out/ --source_distance 0.5 # sources 0.5 m away
48
+ ```
49
+
50
+ `mics.csv` has one `x, y, z` row per microphone, in the STL units; each microphone is moved to the closest point of
51
+ the surface. Without `--source_distance` the sources are plane waves (far field). The dry run prints the distance
52
+ 2D²/λ beyond which that holds for your body; closer sources need `--source_distance`. It also estimates the
53
+ run time: the default grid of 65,160 directions takes minutes on a GPU but hours on a CPU, and `--n_el 19`
54
+ (10 degrees in elevation) makes a CPU run about eight times faster. `stl2bem --help` lists all options.
55
+
56
+ From Python:
57
+
58
+ ```python
59
+ import numpy as np
60
+ from stl2bem import build_mesh, surface_receivers, solve_table, spherical_doa_grid
61
+
62
+ mesh = build_mesh("device.stl", units="mm", recenter="none")
63
+ mics, weights, _ = surface_receivers(np.loadtxt("mics.csv", delimiter=",") / 1000, mesh)
64
+ doa, az, el = spherical_doa_grid(360, 19) # 1 deg azimuth, 10 deg elevation
65
+ freqs = np.linspace(0, 4000, 129)
66
+ solve_table(mesh.verts, mesh.tris, mesh.centroids, mesh.normals, mesh.areas, freqs, doa, "table.h5",
67
+ receivers=mics, receiver_elements=weights)
68
+ ```
69
+
70
+ The pressure on a plane through the body, as in the gallery:
71
+
72
+ ```python
73
+ from stl2bem.viz import plane_grid, field_on_points
74
+ pts, shape = plane_grid(center=(0, 0, 0), u=(1, 0, 0), v=(0, 0, 1), half=(0.2, 0.2), n=(241, 241))
75
+ field = field_on_points(mesh, 2000.0, doa=(1, 0, 0), points=pts).reshape(shape) # NaN inside the body
76
+ ```
77
+
78
+ The localization error that the body causes for a free-field SRP-PHAT:
79
+
80
+ ```python
81
+ from stl2bem.analysis import load_table, free_field, doa_error, summarize
82
+ body = load_table("table.h5", elevations=[0])
83
+ print(summarize(doa_error(body, free_field(body), band=(300, 3000), method="srp-phat", search="azimuth")))
84
+ ```
85
+
86
+ ## Output
87
+
88
+ One HDF5 file per body:
89
+
90
+ | dataset | shape | meaning |
91
+ |---|---|---|
92
+ | `p` | (R, D, F) complex64 | total pressure at receiver r for source d at frequency f, relative to the incident pressure at the origin |
93
+ | `doa_grid` | (D, 3) | unit vectors towards the sources; az x el grids are stored az-major (`i_az * n_el + i_el`) |
94
+ | `source_positions` | (D, 3) | point sources only: their positions (m) |
95
+ | `freqs` | (F,) | Hz |
96
+ | `positions` | (R, 3) | where `p` is evaluated (m, mesh frame); `centroids` is an older name for the same array |
97
+ | `chief_points` | (N_c, 3) | only when CHIEF is used: the interior points |
98
+
99
+ Attributes hold the mesh report, the solver options and the convention. `--sofa` (or
100
+ `python -m stl2bem.sofa table.h5`) also writes the table as a SOFA file (AES69, GeneralTF).
101
+
102
+ **Convention.** e^{+jωt}, incident wave exp(+jk d·r). For a source signal s(t) from direction d, the FFT/STFT bin
103
+ (usual e^{-jωt} kernel) at microphone m is S(ω)·p[m, d, ω], so tables and FFT-domain signals combine directly
104
+ without conjugation. The phase reference is the center of the bounding box (`--recenter bbox`); `--recenter none`
105
+ keeps the CAD origin.
106
+
107
+ ## Accuracy
108
+
109
+ ![sphere field](https://raw.githubusercontent.com/Kwon-Junhyeong/stl2bem/main/docs/img/fig_sphere_field.png)
110
+
111
+ Rigid sphere with 5,120 elements at ka = 3.7 against the exact solution: the median difference is 8.6 × 10⁻⁴ of
112
+ the incident amplitude. The singular part of the integrals is evaluated exactly, and microphones on the surface are
113
+ second-order accurate, also on edges and vertices.
114
+
115
+ ![cross-check](https://raw.githubusercontent.com/Kwon-Junhyeong/stl2bem/main/docs/img/fig_crosscheck.png)
116
+
117
+ The six gallery meshes solved again with [bempp-cl](https://github.com/bempp/bempp-cl), which uses a different
118
+ formulation (Burton-Miller, linear elements): the fields differ by 0.01-0.4 % (median) and the resonance
119
+ frequencies by at most 0.5 %. One frequency with 6,840 directions takes 1 s for 4,800 elements and 11 s for
120
+ 14,700 on an RTX 4060 Ti (8 GB).
121
+
122
+ Convergence, the comparison with the original code, resonances and timings: [docs/validation.md](https://github.com/Kwon-Junhyeong/stl2bem/blob/main/docs/validation.md).
123
+ Equations and implementation: [docs/method.md](https://github.com/Kwon-Junhyeong/stl2bem/blob/main/docs/method.md).
124
+
125
+ ## Preparing CAD
126
+
127
+ The solver needs one closed, consistently oriented surface. A single solid exported from CAD usually is one (all
128
+ gallery models are); an assembly usually is not, because its parts overlap. `stl2bem-prep` merges the parts:
129
+
130
+ ```bash
131
+ stl2bem-prep chassis.stl board.stl battery.stl --pitch 8 --units mm --out body.stl
132
+ ```
133
+
134
+ It voxelizes the parts (pitch = element size), fills enclosed cavities and extracts a closed surface. Features
135
+ smaller than the pitch disappear and thin plates become one pitch thick; `--align_z` keeps a flat microphone board
136
+ flat. In Fusion, set the maximum edge length of the STL export to about λ/6 at the highest frequency; the mesh
137
+ report prints the frequency limit from the mean edge length.
138
+
139
+ ## Limits
140
+
141
+ * Rigid bodies in free space: no absorption, no vibrating surfaces, no floor or walls.
142
+ * Dense matrices: for N elements the GPU needs about 2.5 GB + 20 bytes × N² (an 8 GB GPU handles about 15,000
143
+ elements) and the CPU about 1.5 GB + 55 bytes × N² of RAM; time grows with N³. The dry run prints both.
144
+ * CHIEF points need room inside the body. Thin-walled objects (in the gallery, the bottle and the pipe) are solved
145
+ with the CBIE alone, which is safe there: their irregular frequencies start near c / 2t for wall thickness t,
146
+ far above the band the mesh resolves.
147
+ * `--formulation burton-miller` is experimental: as accurate as the default away from resonances, but it damps
148
+ sharp cavity resonances. See [docs/method.md](https://github.com/Kwon-Junhyeong/stl2bem/blob/main/docs/method.md#burton-miller-experimental-option).
149
+
150
+ ## Used in
151
+
152
+ An earlier version of this solver computed the microphone responses of a robot body in:
153
+
154
+ * [robot-body-sound-localization](https://github.com/Kwon-Junhyeong/robot-body-sound-localization): direction of
155
+ a speaker from four microphones on a robot body, by matching recordings to the computed responses.
156
+ * [calibration-free-sound-localization](https://github.com/Kwon-Junhyeong/calibration-free-sound-localization):
157
+ the same task without calibrating the microphone channels.
158
+
159
+ ## License
160
+
161
+ MIT (see [LICENSE](https://github.com/Kwon-Junhyeong/stl2bem/blob/main/LICENSE)).
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "stl2bem"
7
+ version = "0.1.0"
8
+ description = "Boundary element solver for sound scattering by rigid objects given as closed STL meshes, on the CPU or GPU"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Junhyeong Kwon" }]
14
+ keywords = ["acoustics", "boundary element method", "BEM", "microphone array", "steering vector",
15
+ "array manifold", "scattering", "direction of arrival", "CHIEF", "GPU"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Science/Research",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3 :: Only",
22
+ "Topic :: Scientific/Engineering :: Physics",
23
+ "Topic :: Multimedia :: Sound/Audio :: Analysis",
24
+ ]
25
+ dependencies = ["numpy>=1.22", "scipy>=1.8", "h5py>=3.0", "tqdm"]
26
+
27
+ [project.optional-dependencies]
28
+ gpu = ["cupy-cuda12x"] # CUDA 12; for other CUDA versions install the matching CuPy
29
+ prep = ["scikit-image>=0.19"]
30
+ plot = ["matplotlib", "pillow"]
31
+ sofa = ["sofar>=1.1"]
32
+ crosscheck = ["bempp-cl>=0.4"]
33
+ dev = ["pytest", "scikit-image>=0.19", "matplotlib", "pillow", "sofar>=1.1", "build", "twine"]
34
+
35
+ [project.urls]
36
+ Repository = "https://github.com/Kwon-Junhyeong/stl2bem"
37
+ Issues = "https://github.com/Kwon-Junhyeong/stl2bem/issues"
38
+
39
+ [project.scripts]
40
+ stl2bem = "stl2bem.run:main"
41
+ stl2bem-prep = "stl2bem.prep:main"
42
+
43
+ [tool.setuptools]
44
+ packages = ["stl2bem"]
45
+
46
+ [tool.pytest.ini_options]
47
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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
+ ]
@@ -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}")