dansur-hm 1.0.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.
Files changed (33) hide show
  1. dansur_hm-1.0.0/.github/workflows/publish.yml +20 -0
  2. dansur_hm-1.0.0/.gitignore +44 -0
  3. dansur_hm-1.0.0/LICENSE +21 -0
  4. dansur_hm-1.0.0/PKG-INFO +342 -0
  5. dansur_hm-1.0.0/README.md +274 -0
  6. dansur_hm-1.0.0/dansur/__init__.py +19 -0
  7. dansur_hm-1.0.0/dansur/bilby_source.py +331 -0
  8. dansur_hm-1.0.0/dansur/surrogate/DANSur_HM_jitted.pt +4 -0
  9. dansur_hm-1.0.0/dansur/surrogate/__init__.py +11 -0
  10. dansur_hm-1.0.0/dansur/surrogate/sur_utils.py +897 -0
  11. dansur_hm-1.0.0/dansur/surrogate/waveform_generation.py +79 -0
  12. dansur_hm-1.0.0/dansur/surrogate/waveform_generation_HM.py +86 -0
  13. dansur_hm-1.0.0/dansur/training/__init__.py +7 -0
  14. dansur_hm-1.0.0/dansur/training/jit_model.py +64 -0
  15. dansur_hm-1.0.0/dansur/training/sxs_hm.py +975 -0
  16. dansur_hm-1.0.0/dansur/training/train_decoder_ensemble.py +760 -0
  17. dansur_hm-1.0.0/dansur/utils/__init__.py +145 -0
  18. dansur_hm-1.0.0/dansur/utils/common.py +67 -0
  19. dansur_hm-1.0.0/dansur/utils/data.py +269 -0
  20. dansur_hm-1.0.0/dansur/utils/generation.py +218 -0
  21. dansur_hm-1.0.0/dansur/utils/helpers.py +39 -0
  22. dansur_hm-1.0.0/dansur/utils/losses.py +114 -0
  23. dansur_hm-1.0.0/dansur/utils/nn.py +168 -0
  24. dansur_hm-1.0.0/dansur/utils/sxs_utils.py +41 -0
  25. dansur_hm-1.0.0/dansur/utils/training.py +201 -0
  26. dansur_hm-1.0.0/dansur/utils/utils.py +20 -0
  27. dansur_hm-1.0.0/dansur/utils/waveforms.py +241 -0
  28. dansur_hm-1.0.0/examples/quickstart.ipynb +309 -0
  29. dansur_hm-1.0.0/examples/waveform_example.py +65 -0
  30. dansur_hm-1.0.0/pyproject.toml +74 -0
  31. dansur_hm-1.0.0/scripts/bilby_run_injection.py +785 -0
  32. dansur_hm-1.0.0/scripts/calculate_sxs_mismatches.py +399 -0
  33. dansur_hm-1.0.0/scripts/config.yaml +53 -0
@@ -0,0 +1,20 @@
1
+ # Publishes to PyPI when a GitHub release is published.
2
+ # One-time setup: on pypi.org, add a "pending trusted publisher" for project
3
+ # dansur-hm with this repository, workflow "publish.yml" and environment "pypi".
4
+ name: Publish to PyPI
5
+
6
+ on:
7
+ release:
8
+ types: [published]
9
+
10
+ jobs:
11
+ publish:
12
+ runs-on: ubuntu-latest
13
+ environment: pypi
14
+ permissions:
15
+ id-token: write
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+ - uses: astral-sh/setup-uv@v6
19
+ - run: uv build
20
+ - run: uv publish --trusted-publishing always
@@ -0,0 +1,44 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.pyo
5
+ *.pyd
6
+ .Python
7
+ *.egg
8
+ *.egg-info/
9
+ dist/
10
+ build/
11
+ *.whl
12
+
13
+ # Virtual environments
14
+ .venv/
15
+ venv/
16
+ env/
17
+
18
+ # IDE / editor
19
+ .vscode/
20
+ .idea/
21
+ *.swp
22
+ *.swo
23
+
24
+ # Data files (not tracked in git)
25
+ data/
26
+ *.hdf
27
+ *.hdf5
28
+ *.h5
29
+ sxs/
30
+
31
+ # Output directories
32
+ outdir_*/
33
+ plots/
34
+ logs/
35
+
36
+ # Jupyter notebook checkpoints
37
+ .ipynb_checkpoints/
38
+
39
+ # OS
40
+ .DS_Store
41
+ Thumbs.db
42
+
43
+ # PyTorch cache
44
+ .torch_cache/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 DANSur Team
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.
@@ -0,0 +1,342 @@
1
+ Metadata-Version: 2.5
2
+ Name: dansur-hm
3
+ Version: 1.0.0
4
+ Summary: DANSur: Dual-stage Artificial Neural Surrogate for higher-mode gravitational wave signals
5
+ Project-URL: Homepage, https://github.com/osvaldogramaxo/DANSur_HM
6
+ Project-URL: Repository, https://github.com/osvaldogramaxo/DANSur_HM
7
+ Project-URL: Bug Tracker, https://github.com/osvaldogramaxo/DANSur_HM/issues
8
+ Author: Osvaldo Gramaxo Freitas
9
+ License: MIT License
10
+
11
+ Copyright (c) 2024 DANSur Team
12
+
13
+ Permission is hereby granted, free of charge, to any person obtaining a copy
14
+ of this software and associated documentation files (the "Software"), to deal
15
+ in the Software without restriction, including without limitation the rights
16
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
+ copies of the Software, and to permit persons to whom the Software is
18
+ furnished to do so, subject to the following conditions:
19
+
20
+ The above copyright notice and this permission notice shall be included in all
21
+ copies or substantial portions of the Software.
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
+ SOFTWARE.
30
+ License-File: LICENSE
31
+ Classifier: Development Status :: 4 - Beta
32
+ Classifier: Intended Audience :: Science/Research
33
+ Classifier: License :: OSI Approved :: MIT License
34
+ Classifier: Programming Language :: Python :: 3
35
+ Classifier: Programming Language :: Python :: 3.11
36
+ Classifier: Topic :: Scientific/Engineering :: Physics
37
+ Requires-Python: >=3.11
38
+ Requires-Dist: gwsurrogate>=1.1.8
39
+ Requires-Dist: gwtools>=1.2.0
40
+ Requires-Dist: numba>=0.61.0
41
+ Requires-Dist: numpy>=2.0
42
+ Requires-Dist: torch>=2.9.0
43
+ Provides-Extra: bilby
44
+ Requires-Dist: bilby>=2.7.0; extra == 'bilby'
45
+ Requires-Dist: lalsuite>=7.26.1; extra == 'bilby'
46
+ Provides-Extra: dev
47
+ Requires-Dist: black>=24.0.0; extra == 'dev'
48
+ Requires-Dist: flake8>=7.0.0; extra == 'dev'
49
+ Requires-Dist: isort>=5.13.0; extra == 'dev'
50
+ Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
51
+ Requires-Dist: pytest>=8.0.0; extra == 'dev'
52
+ Provides-Extra: train
53
+ Requires-Dist: bilby>=2.7.0; extra == 'train'
54
+ Requires-Dist: gwpy>=3.0.13; extra == 'train'
55
+ Requires-Dist: h5py>=3.15.1; extra == 'train'
56
+ Requires-Dist: joblib>=1.5.2; extra == 'train'
57
+ Requires-Dist: lalsuite>=7.26.1; extra == 'train'
58
+ Requires-Dist: matplotlib>=3.10.7; extra == 'train'
59
+ Requires-Dist: pandas>=2.3.3; extra == 'train'
60
+ Requires-Dist: pytorch-optimizer>=3.8.1; extra == 'train'
61
+ Requires-Dist: pyyaml>=6.0.0; extra == 'train'
62
+ Requires-Dist: scikit-learn>=1.7.2; extra == 'train'
63
+ Requires-Dist: scipy>=1.16.2; extra == 'train'
64
+ Requires-Dist: seaborn>=0.13.2; extra == 'train'
65
+ Requires-Dist: torch-pca>=1.1.0; extra == 'train'
66
+ Requires-Dist: tqdm>=4.66.0; extra == 'train'
67
+ Description-Content-Type: text/markdown
68
+
69
+ # DANSur_HM — Dual-stage Artificial Neural Surrogate (Now with Higher-Modes!)
70
+
71
+ A fast, accurate neural surrogate for gravitational waveforms from
72
+ quasi-circular, aligned-spin binary black hole mergers, including
73
+ higher-order spherical harmonic modes. Follow up to [arXiv:2412.06946](https://arxiv.org/abs/2412.06946), where only the (2,2) mode was considered.
74
+
75
+ Results published in: [arXiv:2609.03025](https://arxiv.org/abs/2609.03025)
76
+
77
+ [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/osvaldogramaxo/DANSur_HM/blob/main/examples/quickstart.ipynb)
78
+
79
+ **Try it in 30 seconds:**
80
+
81
+ ```bash
82
+ pip install "dansur-hm @ git+https://github.com/osvaldogramaxo/DANSur_HM"
83
+ ```
84
+
85
+ ```python
86
+ from dansur import DANSur
87
+ t, h_modes, _ = DANSur()(q=3.0, chiA0=0.3, chiB0=-0.1) # trained model is bundled
88
+ ```
89
+
90
+ Or open the [quickstart notebook](examples/quickstart.ipynb) in Colab — no install needed.
91
+
92
+ ## Overview
93
+
94
+ **DANSur_HM** is a two-stage neural network approximant:
95
+
96
+ 1. **Stage 1 (Decoder)** — A PCA-based decoder network, pre-trained on
97
+ ~1 million waveforms from `NRHybSur3dq8`, maps binary parameters to
98
+ per-mode waveform coefficients.
99
+ 2. **Stage 2 (Fine-tuning)** — The ensemble is fine-tuned directly on
100
+ SXS numerical relativity waveforms using a sphere-projected mismatch loss.
101
+
102
+ **Supported parameter space:**
103
+ | Parameter | Range |
104
+ |---|---|
105
+ | Mass ratio *q* = m₁/m₂ | [1, 8] |
106
+ | Aligned spin χ₁z | [−0.8, 0.8] |
107
+ | Aligned spin χ₂z | [−0.8, 0.8] |
108
+ | Eccentricity | ≈ 0 (quasi-circular) |
109
+
110
+ **Included modes:** (2,2), (3,3), (2,1), (4,4), (3,2), (5,5), (4,3)
111
+
112
+ ---
113
+
114
+ ## Repository Structure
115
+
116
+ ```
117
+ .
118
+ ├── dansur/ # Main Python package
119
+ │ ├── bilby_source.py # bilby source model (dansur_binary_black_hole)
120
+ │ ├── surrogate/
121
+ │ │ ├── DANSur_HM_jitted.pt # Trained TorchScript model (~41 MB), bundled
122
+ │ │ ├── sur_utils.py # DANSur evaluator class (inference)
123
+ │ │ ├── waveform_generation.py # Waveform generation utilities (22-mode)
124
+ │ │ └── waveform_generation_HM.py # Waveform generation (higher-mode)
125
+ │ ├── training/
126
+ │ │ ├── sxs_hm.py # Main HM training script (SXS fine-tuning)
127
+ │ │ ├── train_decoder_ensemble.py # Decoder architecture + training loop
128
+ │ │ └── jit_model.py # Export trained model to TorchScript
129
+ │ └── utils/
130
+ │ ├── nn.py # Neural network decoder, PCA layers, activations
131
+ │ ├── waveforms.py # Phase unwrap, overlap/mismatch metrics, Cover_Sphere
132
+ │ ├── data.py # SXSDataset, DataLoaders, normalizers, HDF5 helpers
133
+ │ ├── losses.py # Spherical harmonic mismatch loss (HMLoss), ASDL1Loss
134
+ │ ├── training.py # EarlyStopping, train/test loops, basis filters
135
+ │ ├── generation.py # Approximant waveform generation (SEOBNR, Phenom)
136
+ │ └── helpers.py # Logging, path handling, and plotting helpers
137
+ ├── scripts/
138
+ │ ├── calculate_sxs_mismatches.py # Evaluate model against SXS catalog
139
+ │ ├── bilby_run_injection.py # GW parameter estimation (injection tests)
140
+ │ └── config.yaml # Training configuration
141
+ ├── examples/
142
+ │ ├── quickstart.ipynb # Colab notebook: modes, strain, batches, bilby
143
+ │ └── waveform_example.py # Minimal usage example
144
+ ├── pyproject.toml
145
+ └── LICENSE
146
+ ```
147
+
148
+ ---
149
+
150
+ ## Setup
151
+
152
+ The base install covers waveform evaluation (torch, numpy, numba, gwsurrogate).
153
+ Extras add what the rest of the repository needs:
154
+
155
+ | Install | For |
156
+ |---|---|
157
+ | `pip install dansur-hm` | Evaluating waveforms |
158
+ | `pip install "dansur-hm[bilby]"` | The bilby source model (adds bilby, lalsuite) |
159
+ | `pip install "dansur-hm[train]"` | Training, evaluation and PE scripts in `scripts/` |
160
+
161
+ Until the package is on PyPI, install from GitHub:
162
+ `pip install "dansur-hm[bilby] @ git+https://github.com/osvaldogramaxo/DANSur_HM"`.
163
+
164
+ > **Note:** `gwsurrogate` is distributed as source only, so installation needs a C compiler
165
+ > (available on Linux, macOS with Xcode tools, and Colab).
166
+
167
+ ### Development install
168
+
169
+ ```bash
170
+ git clone https://github.com/osvaldogramaxo/DANSur_HM && cd DANSur_HM
171
+ uv sync --extra train # or: pip install -e ".[train]"
172
+ ```
173
+
174
+ ---
175
+
176
+ ## Usage
177
+
178
+ ### Waveform evaluation (inference)
179
+
180
+ ```python
181
+ import numpy as np
182
+ from dansur import DANSur
183
+
184
+ sur = DANSur() # bundled model; DANSur(device="cuda") runs the network on a GPU
185
+
186
+ q, chi1z, chi2z = 3.0, 0.3, -0.1 # q = m1/m2 >= 1, aligned spins
187
+ times = np.arange(-3996, 100, 0.5) # geometric units (M), peak at t = 0
188
+
189
+ # Modes: returns (times, {(l, m): complex h_lm}, None), including m < 0
190
+ t, h_modes, _ = sur(q=q, chiA0=chi1z, chiB0=chi2z, times=times)
191
+ print(h_modes[(3, 3)].shape) # (8192,)
192
+
193
+ # Strain h = h+ - i hx at a given inclination, in physical units
194
+ t_s, h, _ = sur(q=q, chiA0=chi1z, chiB0=chi2z, M=60.0, dist_mpc=500.0, units="mks",
195
+ times=np.arange(-1.0, 0.03, 1 / 4096), inclination=np.pi / 4, phi_ref=0.0)
196
+ hp, hc = h.real, -h.imag
197
+ ```
198
+
199
+ **Batches:** pass arrays of `q` and spins as `(N, 3)` vectors with zero in-plane
200
+ components (e.g. `np.stack([zeros, zeros, chi1z], -1)`); outputs then have shape `(N, n_times)`.
201
+
202
+ **GPU:** with `DANSur(device="cuda")` the network and all post-processing run on the GPU,
203
+ in chunks of 1024 waveforms; only the final arrays are copied back. Strain for 10,000
204
+ waveforms takes ~1.4 s on a V100 vs ~7 s on 32 CPU cores. A single waveform takes ~20 ms
205
+ and is fastest on CPU, so prefer the CPU for one-at-a-time use such as bilby sampling.
206
+
207
+ See [`examples/waveform_example.py`](examples/waveform_example.py) for a runnable script
208
+ with plotting, and [`examples/quickstart.ipynb`](examples/quickstart.ipynb) for a notebook.
209
+
210
+ ### Using DANSur_HM in bilby
211
+
212
+ Requires the `bilby` extra.
213
+
214
+ ```python
215
+ import bilby
216
+ from dansur.bilby_source import dansur_binary_black_hole
217
+
218
+ waveform_generator = bilby.gw.WaveformGenerator(
219
+ duration=4, sampling_frequency=2048,
220
+ time_domain_source_model=dansur_binary_black_hole,
221
+ parameter_conversion=bilby.gw.conversion.convert_to_lal_binary_black_hole_parameters,
222
+ )
223
+ ```
224
+
225
+ Use it like any other bilby waveform generator (sample in `chirp_mass`/`mass_ratio` or
226
+ `mass_1`/`mass_2`, with aligned spins `chi_1`, `chi_2`). Polarizations follow the LAL
227
+ convention. The waveform covers about 4000 M before merger, so the (2,2) mode starts at
228
+ roughly 18 Hz × (70 M☉ / M); pick the analysis minimum frequency above that.
229
+ To use a different model instance, call `dansur.bilby_source.model_gen_func(model, times, **params)`.
230
+
231
+ ---
232
+
233
+ ## Training Data Format
234
+
235
+ DANSur_HM relies on HDF5 files formatted for each of its two training stages:
236
+
237
+ ### 1. Pretraining Dataset (Stage 1)
238
+
239
+ Used by `train_decoder_ensemble.py` to pretrain single-mode decoders on synthetic waveforms generated from baseline approximants (e.g., via `dansur.utils.generation.generate_dataset` using `NRHybSur3dq8`):
240
+
241
+ An HDF5 file containing:
242
+ - **`Waveforms`**: Complex array of shape `(N, n_modes, time_samples)` (`complex128`), with modes following the order: `[(2,2), (3,3), (2,1), (4,4), (3,2), (5,5), (4,3)]`.
243
+ - **`Parameters`**: Float array of shape `(N, 3)` (`float32`) containing binary parameters: `[q, chi_1z, chi_2z]`, where $q = m_1/m_2 \ge 1$.
244
+ - Attribute: `Parameters.attrs['names'] = ['mass_ratio', 'chi_1', 'chi_2']`.
245
+
246
+ ### 2. Numerical Relativity SXS Dataset (Stage 2 & Evaluation)
247
+
248
+ Used by `sxs_hm.py` (fine-tuning) and `calculate_sxs_mismatches.py` (evaluation), loaded via `dansur.utils.data.SXSDataset`:
249
+
250
+ An HDF5 file where each top-level key corresponds to a simulation ID (e.g., `SXS:BBH:0001`):
251
+
252
+ ```
253
+ sxs_waveforms.h5
254
+ ├── <simulation_id>/ # e.g. "SXS:BBH:0001"
255
+ │ ├── waveform/ # Mode datasets
256
+ │ │ ├── (2,2) # 1D complex128 array of time-aligned samples
257
+ │ │ ├── (3,3)
258
+ │ │ ├── (2,1)
259
+ │ │ ├── (4,4)
260
+ │ │ ├── (3,2)
261
+ │ │ ├── (5,5)
262
+ │ │ └── (4,3)
263
+ │ ├── metadata/ # Simulation physical parameters
264
+ │ │ ├── mass_ratio # Float: q = m1/m2 >= 1
265
+ │ │ ├── dimensionless_spin1 # Array of floats: [s1x, s1y, s1z]
266
+ │ │ ├── dimensionless_spin2 # Array of floats: [s2x, s2y, s2z]
267
+ │ │ ├── chi1_perp # Float: in-plane spin magnitude for BH 1
268
+ │ │ ├── chi2_perp # Float: in-plane spin magnitude for BH 2
269
+ │ │ └── eccentricity # Float: residual orbital eccentricity
270
+ │ └── TS_metadata/ # Time-series metadata (sample times, dt, etc.)
271
+ ```
272
+
273
+ ---
274
+
275
+ ## Training
276
+
277
+ ### 1. Pretraining
278
+
279
+ Pretrain individual mode decoders on a large dataset (e.g., from `NRHybSur3dq8`).
280
+ Each decoder learns to reconstruct a single spherical harmonic mode from a PCA basis:
281
+
282
+ ```bash
283
+ # Run for each mode index 0–6 (corresponding to (2,2),(3,3),(2,1),(4,4),(3,2),(5,5),(4,3))
284
+ python -m dansur.training.train_decoder_ensemble --mode 0
285
+ ```
286
+
287
+ ### 2. HM Fine-tuning on SXS NR data
288
+
289
+ Fine-tune the full multi-mode ensemble on SXS numerical relativity waveforms
290
+ using a sphere-projected mismatch loss:
291
+
292
+ ```bash
293
+ python -m dansur.training.sxs_hm \
294
+ --config scripts/config.yaml \
295
+ --sxs-file /path/to/sxs_waveforms.h5
296
+ ```
297
+
298
+ Key configuration options are in [`scripts/config.yaml`](scripts/config.yaml).
299
+
300
+ ### 3. Export to TorchScript (JIT)
301
+
302
+ After training, export the model for fast inference:
303
+
304
+ ```bash
305
+ python -m dansur.training.jit_model \
306
+ --config scripts/config.yaml \
307
+ --output-path dansur/surrogate/DANSur_HM_jitted.pt
308
+ ```
309
+
310
+ ---
311
+
312
+ ## Evaluation
313
+
314
+ Compute mismatches of DANSur_HM and NRHybSur3dq8 against the SXS catalog:
315
+
316
+ ```bash
317
+ python scripts/calculate_sxs_mismatches.py \
318
+ --sxs-file /path/to/sxs_waveforms.h5 \
319
+ --out-dir plots/
320
+ ```
321
+
322
+ ---
323
+
324
+ ## Citation
325
+
326
+ If you use DANSur_HM in your research, please cite:
327
+
328
+ ```bibtex
329
+ @article{gramaxo2026dansur,
330
+ title = {DANSur_HM: Modularly incorporating higher modes in a deep learning based gravitational-wave surrogate},
331
+ author = {Gramaxo Freitas, Osvaldo and others},
332
+ year = {2026},
333
+ eprint = {2609.03025},
334
+ archivePrefix = {arXiv},
335
+ }
336
+ ```
337
+
338
+ ---
339
+
340
+ ## License
341
+
342
+ This project is licensed under the MIT License. See [`LICENSE`](LICENSE) for details.