cuap3mpy 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.
Files changed (70) hide show
  1. cuap3mpy-0.1.0/LICENSE +28 -0
  2. cuap3mpy-0.1.0/PKG-INFO +225 -0
  3. cuap3mpy-0.1.0/README.md +170 -0
  4. cuap3mpy-0.1.0/cuap3mpy/__init__.py +37 -0
  5. cuap3mpy-0.1.0/cuap3mpy/__main__.py +109 -0
  6. cuap3mpy-0.1.0/cuap3mpy/cache.py +12 -0
  7. cuap3mpy-0.1.0/cuap3mpy/core/__init__.py +21 -0
  8. cuap3mpy-0.1.0/cuap3mpy/core/config.py +125 -0
  9. cuap3mpy-0.1.0/cuap3mpy/core/cosmology.py +245 -0
  10. cuap3mpy-0.1.0/cuap3mpy/core/dither.py +59 -0
  11. cuap3mpy-0.1.0/cuap3mpy/core/linear_power.py +310 -0
  12. cuap3mpy-0.1.0/cuap3mpy/core/particles.py +281 -0
  13. cuap3mpy-0.1.0/cuap3mpy/core/pinned.py +19 -0
  14. cuap3mpy-0.1.0/cuap3mpy/core/time_schedule.py +558 -0
  15. cuap3mpy-0.1.0/cuap3mpy/demo.py +59 -0
  16. cuap3mpy-0.1.0/cuap3mpy/forces/__init__.py +10 -0
  17. cuap3mpy-0.1.0/cuap3mpy/forces/patch_pp_gravity.py +202 -0
  18. cuap3mpy-0.1.0/cuap3mpy/forces/pm_gravity.py +52 -0
  19. cuap3mpy-0.1.0/cuap3mpy/gravity/__init__.py +1 -0
  20. cuap3mpy-0.1.0/cuap3mpy/gravity/reference.py +100 -0
  21. cuap3mpy-0.1.0/cuap3mpy/gravity/root_pm/__init__.py +12 -0
  22. cuap3mpy-0.1.0/cuap3mpy/gravity/root_pm/mesh.py +246 -0
  23. cuap3mpy-0.1.0/cuap3mpy/gravity/root_pm/potential.py +299 -0
  24. cuap3mpy-0.1.0/cuap3mpy/gravity/root_pm/solver.py +252 -0
  25. cuap3mpy-0.1.0/cuap3mpy/gravity/short_range/__init__.py +5 -0
  26. cuap3mpy-0.1.0/cuap3mpy/gravity/short_range/cell_list.py +155 -0
  27. cuap3mpy-0.1.0/cuap3mpy/gravity/short_range/core/__init__.py +23 -0
  28. cuap3mpy-0.1.0/cuap3mpy/gravity/short_range/core/fit.py +212 -0
  29. cuap3mpy-0.1.0/cuap3mpy/gravity/short_range/core/kernel.py +47 -0
  30. cuap3mpy-0.1.0/cuap3mpy/gravity/short_range/core/solver.py +119 -0
  31. cuap3mpy-0.1.0/cuap3mpy/gravity/short_range/mesh.py +247 -0
  32. cuap3mpy-0.1.0/cuap3mpy/gravity/short_range/pairs/__init__.py +12 -0
  33. cuap3mpy-0.1.0/cuap3mpy/gravity/short_range/pairs/fit.py +270 -0
  34. cuap3mpy-0.1.0/cuap3mpy/gravity/short_range/pairs/solver.py +432 -0
  35. cuap3mpy-0.1.0/cuap3mpy/gravity/short_range/patch/__init__.py +14 -0
  36. cuap3mpy-0.1.0/cuap3mpy/gravity/short_range/patch/kernel.py +113 -0
  37. cuap3mpy-0.1.0/cuap3mpy/gravity/short_range/patch/plan.py +259 -0
  38. cuap3mpy-0.1.0/cuap3mpy/gravity/short_range/patch/solver.py +255 -0
  39. cuap3mpy-0.1.0/cuap3mpy/halos/__init__.py +13 -0
  40. cuap3mpy-0.1.0/cuap3mpy/halos/catalog.py +168 -0
  41. cuap3mpy-0.1.0/cuap3mpy/halos/fof.py +151 -0
  42. cuap3mpy-0.1.0/cuap3mpy/halos/slab.py +378 -0
  43. cuap3mpy-0.1.0/cuap3mpy/ic/__init__.py +5 -0
  44. cuap3mpy-0.1.0/cuap3mpy/ic/abacus_rvzel.py +327 -0
  45. cuap3mpy-0.1.0/cuap3mpy/ic/cross_pancake.py +54 -0
  46. cuap3mpy-0.1.0/cuap3mpy/ic/gadget.py +107 -0
  47. cuap3mpy-0.1.0/cuap3mpy/ic/lattice_lpt.py +554 -0
  48. cuap3mpy-0.1.0/cuap3mpy/ic/plummer.py +102 -0
  49. cuap3mpy-0.1.0/cuap3mpy/ic/zeldovich.py +48 -0
  50. cuap3mpy-0.1.0/cuap3mpy/power.py +91 -0
  51. cuap3mpy-0.1.0/cuap3mpy/resident.py +130 -0
  52. cuap3mpy-0.1.0/cuap3mpy/run_lpt_streaming.py +107 -0
  53. cuap3mpy-0.1.0/cuap3mpy/run_music.py +81 -0
  54. cuap3mpy-0.1.0/cuap3mpy/simulation.py +259 -0
  55. cuap3mpy-0.1.0/cuap3mpy/snapshot.py +352 -0
  56. cuap3mpy-0.1.0/cuap3mpy/streaming/__init__.py +1 -0
  57. cuap3mpy-0.1.0/cuap3mpy/streaming/host.py +112 -0
  58. cuap3mpy-0.1.0/cuap3mpy/streaming/root.py +132 -0
  59. cuap3mpy-0.1.0/cuap3mpy/streaming/sim.py +269 -0
  60. cuap3mpy-0.1.0/cuap3mpy/streaming/tile_force.py +109 -0
  61. cuap3mpy-0.1.0/cuap3mpy/streaming/tiles.py +165 -0
  62. cuap3mpy-0.1.0/cuap3mpy/validate.py +617 -0
  63. cuap3mpy-0.1.0/cuap3mpy.egg-info/PKG-INFO +225 -0
  64. cuap3mpy-0.1.0/cuap3mpy.egg-info/SOURCES.txt +68 -0
  65. cuap3mpy-0.1.0/cuap3mpy.egg-info/dependency_links.txt +1 -0
  66. cuap3mpy-0.1.0/cuap3mpy.egg-info/entry_points.txt +2 -0
  67. cuap3mpy-0.1.0/cuap3mpy.egg-info/requires.txt +14 -0
  68. cuap3mpy-0.1.0/cuap3mpy.egg-info/top_level.txt +1 -0
  69. cuap3mpy-0.1.0/pyproject.toml +35 -0
  70. cuap3mpy-0.1.0/setup.cfg +4 -0
cuap3mpy-0.1.0/LICENSE ADDED
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, the cuap3mpy authors
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,225 @@
1
+ Metadata-Version: 2.4
2
+ Name: cuap3mpy
3
+ Version: 0.1.0
4
+ Summary: GPU cosmological N-body simulation: adaptive P3M on CuPy
5
+ License: BSD 3-Clause License
6
+
7
+ Copyright (c) 2026, the cuap3mpy authors
8
+
9
+ Redistribution and use in source and binary forms, with or without
10
+ modification, are permitted provided that the following conditions are met:
11
+
12
+ 1. Redistributions of source code must retain the above copyright notice, this
13
+ list of conditions and the following disclaimer.
14
+
15
+ 2. Redistributions in binary form must reproduce the above copyright notice,
16
+ this list of conditions and the following disclaimer in the documentation
17
+ and/or other materials provided with the distribution.
18
+
19
+ 3. Neither the name of the copyright holder nor the names of its
20
+ contributors may be used to endorse or promote products derived from
21
+ this software without specific prior written permission.
22
+
23
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
24
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
27
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
29
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33
+
34
+ Project-URL: Homepage, https://github.com/cuap3mpy/cuap3mpy
35
+ Project-URL: Repository, https://github.com/cuap3mpy/cuap3mpy
36
+ Classifier: Programming Language :: Python :: 3
37
+ Classifier: License :: OSI Approved :: BSD License
38
+ Classifier: Environment :: GPU :: NVIDIA CUDA
39
+ Classifier: Topic :: Scientific/Engineering :: Astronomy
40
+ Classifier: Topic :: Scientific/Engineering :: Physics
41
+ Requires-Python: >=3.9
42
+ Description-Content-Type: text/markdown
43
+ License-File: LICENSE
44
+ Requires-Dist: numpy
45
+ Requires-Dist: h5py
46
+ Provides-Extra: cuda12
47
+ Requires-Dist: cupy-cuda12x; extra == "cuda12"
48
+ Provides-Extra: cuda11
49
+ Requires-Dist: cupy-cuda11x; extra == "cuda11"
50
+ Provides-Extra: camb
51
+ Requires-Dist: camb; extra == "camb"
52
+ Provides-Extra: class
53
+ Requires-Dist: classy; extra == "class"
54
+ Dynamic: license-file
55
+
56
+ # cuap3mpy
57
+
58
+ GPU cosmological *N*-body simulation in Python, built on CuPy. `cuap3mpy` combines a scalar BCC18 particle-mesh telescope (interlaced root PM, adaptive $4\times$ patches, and dense $16\times$ cores) with directed radial short-range pair forces and transition-safe local r-RESPA time stepping.
59
+
60
+ One call evolves from cosmological parameters (internal 2LPT) or a MUSIC/Gadget HDF5 initial condition to $z = 0$ phase space, matter power spectra, and spherical-overdensity FoF halo catalogs.
61
+
62
+ ---
63
+
64
+ ## 1. System requirements
65
+
66
+ - **OS**: Linux x86-64 (tested on Ubuntu 22.04 LTS).
67
+ - **Software**: Python >= 3.9, `numpy`, `h5py`, and `cupy` matching the installed CUDA toolkit (tested with Python 3.12, NumPy 2.5, h5py 3.16, CuPy 14.2, CUDA 12.9).
68
+ - Optional Boltzmann transfer tables (`transfer="camb"` or `"class"`) import `camb` or `classy` only once when building an uncached table; the default `"eh98"` needs neither.
69
+ - **Hardware**: One NVIDIA GPU (CUDA compute capability >= 6.0):
70
+ - **>= 8 GB VRAM** for demos, validation, and runs up to $N = 384$;
71
+ - **>= 20 GB VRAM** for GPU-resident $N = 512$ runs (tested on RTX 4090 24 GB and RTX 5090 32 GB; live peak ~16 GiB via CUDA's stream-ordered `MemoryAsyncPool`);
72
+ - Larger runs (e.g. $N = 1008$, $1.02 \times 10^9$ particles) automatically stream eight octant tiles from pinned host RAM (`26 B/particle`, or `30 B/particle` with persistent IDs — ~27–31 GB host RAM at $1008^3$).
73
+
74
+ ---
75
+
76
+ ## 2. Installation
77
+
78
+ From the repository root (pure Python + runtime NVRTC kernel compilation; installs in a few seconds):
79
+
80
+ ```bash
81
+ pip install . # if CuPy is already installed
82
+ pip install ".[cuda12]" # or install CuPy for CUDA 12 (".[cuda11]" for CUDA 11)
83
+ ```
84
+
85
+ Force and transfer tables are generated automatically on first use (~30 s on an RTX 4090) and cached under `~/.cache/cuap3mpy` (override with the `CUAP3MPY_CACHE` environment variable).
86
+
87
+ ---
88
+
89
+ ## 3. Quick validation & demo
90
+
91
+ ### Static force validation
92
+
93
+ ```bash
94
+ python -m cuap3mpy.validate
95
+ ```
96
+
97
+ Runs five gated tests against double-precision Ewald references (~50 s on RTX 4090 including first-time table generation, ~25 s cached):
98
+ - **A**: Radial pair-table holdout fit accuracy (`RMS < 1e-3`, measured `2.9e-4`)
99
+ - **B**: CUDA pair-kernel vs. host reference & two-body momentum antisymmetry (`< 2e-5` of $1/r^2$, `1` velocity quantum)
100
+ - **C**: Two-body routing sweep across root PM, band pairs, $q=8$ patches, and $q=32$ cores
101
+ - **D**: Patch telescope consistency (`RMS < 2e-5`, measured `1.0e-5`)
102
+ - **E**: BCC18 $6^3$ sub-cell phase-mean response (`mean RMS < 1e-3`, measured `3.0e-4`)
103
+
104
+ ### End-to-end cosmological demo
105
+
106
+ ```bash
107
+ python -m cuap3mpy.demo # in-memory run; optionally pass snap.hdf5
108
+ ```
109
+
110
+ Generates $128^3$ 2LPT initial conditions in a $100\ \text{Mpc}/h$ box (`Om0=0.3`, `sigma8=0.8`, `seed=42`), evolves from $z = 99$ to $z = 0$ (~14 s on RTX 4090), and prints $P(k)$ alongside linear theory and FoF halo counts (~5,475 halos).
111
+
112
+ ---
113
+
114
+ ## 4. Python API
115
+
116
+ ### Minimal in-memory usage (scripts & Jupyter notebooks)
117
+
118
+ By default `sim.run()` writes no files to disk and releases internal solver GPU memory upon completion:
119
+
120
+ ```python
121
+ import cuap3mpy as cap
122
+
123
+ sim = cap.Simulation(N=256, box=200.0, Om0=0.3, sigma8=0.8, seed=42)
124
+ sim.run()
125
+
126
+ pos = sim.P.pos # (3, n) float32 comoving positions [Mpc/h]
127
+ vel = sim.P.vel # (3, n) float32 peculiar velocities [km/s]
128
+ m200c = sim.halos.m200c[sim.halos.valid] # FoF halo M200c [Msun/h]
129
+ k, Pk, nmodes = sim.power_spectrum() # k [h/Mpc], shot-noise-subtracted P(k) [(Mpc/h)^3]
130
+ ```
131
+
132
+ ### Multi-redshift snapshots, wCDM / Boltzmann transfers, MUSIC ICs & persistent IDs
133
+
134
+ ```python
135
+ import cuap3mpy as cap
136
+
137
+ sim = cap.Simulation(
138
+ N=512, box=350.0, # N^3 particles, box in Mpc/h
139
+ Om0=0.3, OmL=0.7, Ob0=0.048, h=0.7,
140
+ sigma8=0.8, ns=0.96, z_init=99.0, seed=42,
141
+ transfer="eh98", # "eh98", "camb", or "class"
142
+ w0=-1.0, wa=0.0, # CPL dark energy w(a) = w0 + wa(1 - a)
143
+ ic="gaussian", # "gaussian", "fixed", "inverted", "fixed_inverted"
144
+ zout=(3, 2, 1, 0.5), # intermediate snapshot redshifts
145
+ ids=True, # track persistent particle IDs across steps
146
+ softening=0.05, # nominal eps in root cells dx
147
+ softening_law="gadget_spline", # "gadget_spline" or "single_spline"
148
+ streaming="auto", # "auto", False (GPU), or True (host-streamed)
149
+ )
150
+
151
+ # Or initialize directly from a MUSIC / Gadget HDF5 file:
152
+ # sim = cap.Simulation(music="IC.hdf5", zout=(2, 1), ids=True)
153
+
154
+ # Writes snap_z3.hdf5, snap_z2.hdf5, snap_z1.hdf5, snap_z0.5.hdf5, and z=0 snap.hdf5
155
+ # (pass halos=False to skip z=0 FoF halo finding):
156
+ sim.run("snap.hdf5")
157
+ sim.save_halos("halos.hdf5")
158
+ ```
159
+
160
+ ### Standalone analysis & I/O helpers
161
+
162
+ - `cap.power_spectrum(pos, box, nmesh)`: Interlaced dual-grid TSC power spectrum with window deconvolution and shot-noise subtraction on any `(3, n)` `Mpc/h` array.
163
+ - `cap.find_halos(pos, box, Om0=0.3, softening=0.05, streaming="auto")`: Exact periodic FoF ($b = 0.2$, $\ge 20$ particles) + spherical-overdensity properties (`M200c`, `R200c`, `Vmax`, shrinking-sphere `Center`, and `1, 2, 4, 8 eps` aperture masses).
164
+ - `cap.load_halos("halos.hdf5")`: Load a saved HDF5 or `.npz` halo catalog into a `Halos` object.
165
+ - `cap.load_snapshot("snap/")` & `cap.load_ids("snap/")`: Memory-mapped read of native fixed-point snapshot directories.
166
+
167
+ ---
168
+
169
+ ## 5. Command-line interface
170
+
171
+ After `pip install .`, run via `cuap3mpy` or `python -m cuap3mpy`:
172
+
173
+ ```bash
174
+ # 2LPT cosmological run -> Gadget HDF5 snapshots + FoF halo catalog
175
+ cuap3mpy --N 512 --box 350 --transfer camb --zout 2,1,0.5 --ids \
176
+ --out snap.hdf5 --halos halos.hdf5
177
+
178
+ # Run from a MUSIC HDF5 initial condition (skip halo finding with --no-halos)
179
+ cuap3mpy --music IC.hdf5 --out snap.hdf5 --halos halos.hdf5
180
+ ```
181
+
182
+ Run `cuap3mpy --help` for the full list of options (`--w0`, `--wa`, `--ic`, `--softening`, `--softening-law`, `--streaming`, `--no-halos`, `--steps`).
183
+
184
+ ---
185
+
186
+ ## 6. Output file formats
187
+
188
+ Snapshot paths automatically select their format by suffix:
189
+
190
+ 1. **Gadget/AREPO HDF5 (`.hdf5` or `.h5`)**
191
+ - `Header`: `BoxSize` (`kpc/h`), `MassTable[1]` ($10^{10}\ M_\odot/h$), `Time` ($a$), `Redshift` ($z$), `Omega0`, `OmegaLambda`, `OmegaBaryon`, `HubbleParam`, `NumPart_Total`, `NumPart_Total_HighWord`, `Flag_DoublePrecision = 0`, `PersistentParticleIDs`.
192
+ - `PartType1/Coordinates`: `(n, 3)` `float32`, comoving position in `[0, BoxSize)` `kpc/h`.
193
+ - `PartType1/Velocities`: `(n, 3)` `float32`, Gadget velocity $u = v_{\text{pec}} / \sqrt{a}$ in `km/s`.
194
+ - `PartType1/ParticleIDs`: `(n,)` `uint32` (`uint64` when $n \ge 2^{32}$). When `ids=True`, stores persistent Lagrangian lattice IDs `(ix * N + iy) * N + iz` (or input MUSIC `ParticleIDs`) across all redshifts.
195
+
196
+ 2. **Native fixed-point directory (any path without `.hdf5`/`.h5`)**
197
+ - Lossless phase-space dump: `header.json`, `qpos.npy` (`(3, n)` `uint32`, $x = (q + 0.5) L / 2^{32}$), `qvel.npy` (`(3, n)` `int32`, $a v_{\text{pec}} = q\,\text{dv}$), and optional `pid.npy`.
198
+
199
+ 3. **FoF Halo Catalog (`.hdf5`/`.h5` or `.npz`)**
200
+ - HDF5 layout: `/Header` metadata plus `/Halos/{Npart, M200c [Msun/h], R200c [Mpc/h], Vmax [km/s], Center (nh, 3) [Mpc/h], ApertureMass (nh, 4) [Msun/h], Valid}`.
201
+
202
+ ---
203
+
204
+ ## 7. Package layout
205
+
206
+ ```text
207
+ cuap3mpy/
208
+ ├── simulation.py High-level Simulation API & standalone find_halos
209
+ ├── __main__.py Unified CLI entry point (cuap3mpy / python -m cuap3mpy)
210
+ ├── resident.py Single-GPU resident r-RESPA simulation driver
211
+ ├── streaming/ Pinned-host octant-streamed driver (N = 1008+ path)
212
+ ├── core/ Config, Cosmology, LinearPower (EH98/CAMB/CLASS), Particles, TimeSchedule
213
+ ├── gravity/ BCC18 root PM, adaptive q=8 patches, q=32 cores, radial pair kernels
214
+ ├── forces/ Root PM and short-range routing & local-tier kick orchestration
215
+ ├── ic/ GPU de-aliased 2LPT, MUSIC/Gadget HDF5, Zeldovich, Abacus RVZel, test ICs
216
+ ├── halos/ GPU lock-free FoF, slab-union FoF, shrinking-sphere & SO properties
217
+ ├── power.py Interlaced TSC matter power spectrum estimator
218
+ ├── snapshot.py Native fixed-point, Gadget HDF5, and halo catalog I/O
219
+ ├── validate.py Five-stage static force validation suite
220
+ └── demo.py Self-contained 128^3 end-to-end cosmological demo
221
+ ```
222
+
223
+ ## License
224
+
225
+ BSD 3-Clause; see [LICENSE](LICENSE).
@@ -0,0 +1,170 @@
1
+ # cuap3mpy
2
+
3
+ GPU cosmological *N*-body simulation in Python, built on CuPy. `cuap3mpy` combines a scalar BCC18 particle-mesh telescope (interlaced root PM, adaptive $4\times$ patches, and dense $16\times$ cores) with directed radial short-range pair forces and transition-safe local r-RESPA time stepping.
4
+
5
+ One call evolves from cosmological parameters (internal 2LPT) or a MUSIC/Gadget HDF5 initial condition to $z = 0$ phase space, matter power spectra, and spherical-overdensity FoF halo catalogs.
6
+
7
+ ---
8
+
9
+ ## 1. System requirements
10
+
11
+ - **OS**: Linux x86-64 (tested on Ubuntu 22.04 LTS).
12
+ - **Software**: Python >= 3.9, `numpy`, `h5py`, and `cupy` matching the installed CUDA toolkit (tested with Python 3.12, NumPy 2.5, h5py 3.16, CuPy 14.2, CUDA 12.9).
13
+ - Optional Boltzmann transfer tables (`transfer="camb"` or `"class"`) import `camb` or `classy` only once when building an uncached table; the default `"eh98"` needs neither.
14
+ - **Hardware**: One NVIDIA GPU (CUDA compute capability >= 6.0):
15
+ - **>= 8 GB VRAM** for demos, validation, and runs up to $N = 384$;
16
+ - **>= 20 GB VRAM** for GPU-resident $N = 512$ runs (tested on RTX 4090 24 GB and RTX 5090 32 GB; live peak ~16 GiB via CUDA's stream-ordered `MemoryAsyncPool`);
17
+ - Larger runs (e.g. $N = 1008$, $1.02 \times 10^9$ particles) automatically stream eight octant tiles from pinned host RAM (`26 B/particle`, or `30 B/particle` with persistent IDs — ~27–31 GB host RAM at $1008^3$).
18
+
19
+ ---
20
+
21
+ ## 2. Installation
22
+
23
+ From the repository root (pure Python + runtime NVRTC kernel compilation; installs in a few seconds):
24
+
25
+ ```bash
26
+ pip install . # if CuPy is already installed
27
+ pip install ".[cuda12]" # or install CuPy for CUDA 12 (".[cuda11]" for CUDA 11)
28
+ ```
29
+
30
+ Force and transfer tables are generated automatically on first use (~30 s on an RTX 4090) and cached under `~/.cache/cuap3mpy` (override with the `CUAP3MPY_CACHE` environment variable).
31
+
32
+ ---
33
+
34
+ ## 3. Quick validation & demo
35
+
36
+ ### Static force validation
37
+
38
+ ```bash
39
+ python -m cuap3mpy.validate
40
+ ```
41
+
42
+ Runs five gated tests against double-precision Ewald references (~50 s on RTX 4090 including first-time table generation, ~25 s cached):
43
+ - **A**: Radial pair-table holdout fit accuracy (`RMS < 1e-3`, measured `2.9e-4`)
44
+ - **B**: CUDA pair-kernel vs. host reference & two-body momentum antisymmetry (`< 2e-5` of $1/r^2$, `1` velocity quantum)
45
+ - **C**: Two-body routing sweep across root PM, band pairs, $q=8$ patches, and $q=32$ cores
46
+ - **D**: Patch telescope consistency (`RMS < 2e-5`, measured `1.0e-5`)
47
+ - **E**: BCC18 $6^3$ sub-cell phase-mean response (`mean RMS < 1e-3`, measured `3.0e-4`)
48
+
49
+ ### End-to-end cosmological demo
50
+
51
+ ```bash
52
+ python -m cuap3mpy.demo # in-memory run; optionally pass snap.hdf5
53
+ ```
54
+
55
+ Generates $128^3$ 2LPT initial conditions in a $100\ \text{Mpc}/h$ box (`Om0=0.3`, `sigma8=0.8`, `seed=42`), evolves from $z = 99$ to $z = 0$ (~14 s on RTX 4090), and prints $P(k)$ alongside linear theory and FoF halo counts (~5,475 halos).
56
+
57
+ ---
58
+
59
+ ## 4. Python API
60
+
61
+ ### Minimal in-memory usage (scripts & Jupyter notebooks)
62
+
63
+ By default `sim.run()` writes no files to disk and releases internal solver GPU memory upon completion:
64
+
65
+ ```python
66
+ import cuap3mpy as cap
67
+
68
+ sim = cap.Simulation(N=256, box=200.0, Om0=0.3, sigma8=0.8, seed=42)
69
+ sim.run()
70
+
71
+ pos = sim.P.pos # (3, n) float32 comoving positions [Mpc/h]
72
+ vel = sim.P.vel # (3, n) float32 peculiar velocities [km/s]
73
+ m200c = sim.halos.m200c[sim.halos.valid] # FoF halo M200c [Msun/h]
74
+ k, Pk, nmodes = sim.power_spectrum() # k [h/Mpc], shot-noise-subtracted P(k) [(Mpc/h)^3]
75
+ ```
76
+
77
+ ### Multi-redshift snapshots, wCDM / Boltzmann transfers, MUSIC ICs & persistent IDs
78
+
79
+ ```python
80
+ import cuap3mpy as cap
81
+
82
+ sim = cap.Simulation(
83
+ N=512, box=350.0, # N^3 particles, box in Mpc/h
84
+ Om0=0.3, OmL=0.7, Ob0=0.048, h=0.7,
85
+ sigma8=0.8, ns=0.96, z_init=99.0, seed=42,
86
+ transfer="eh98", # "eh98", "camb", or "class"
87
+ w0=-1.0, wa=0.0, # CPL dark energy w(a) = w0 + wa(1 - a)
88
+ ic="gaussian", # "gaussian", "fixed", "inverted", "fixed_inverted"
89
+ zout=(3, 2, 1, 0.5), # intermediate snapshot redshifts
90
+ ids=True, # track persistent particle IDs across steps
91
+ softening=0.05, # nominal eps in root cells dx
92
+ softening_law="gadget_spline", # "gadget_spline" or "single_spline"
93
+ streaming="auto", # "auto", False (GPU), or True (host-streamed)
94
+ )
95
+
96
+ # Or initialize directly from a MUSIC / Gadget HDF5 file:
97
+ # sim = cap.Simulation(music="IC.hdf5", zout=(2, 1), ids=True)
98
+
99
+ # Writes snap_z3.hdf5, snap_z2.hdf5, snap_z1.hdf5, snap_z0.5.hdf5, and z=0 snap.hdf5
100
+ # (pass halos=False to skip z=0 FoF halo finding):
101
+ sim.run("snap.hdf5")
102
+ sim.save_halos("halos.hdf5")
103
+ ```
104
+
105
+ ### Standalone analysis & I/O helpers
106
+
107
+ - `cap.power_spectrum(pos, box, nmesh)`: Interlaced dual-grid TSC power spectrum with window deconvolution and shot-noise subtraction on any `(3, n)` `Mpc/h` array.
108
+ - `cap.find_halos(pos, box, Om0=0.3, softening=0.05, streaming="auto")`: Exact periodic FoF ($b = 0.2$, $\ge 20$ particles) + spherical-overdensity properties (`M200c`, `R200c`, `Vmax`, shrinking-sphere `Center`, and `1, 2, 4, 8 eps` aperture masses).
109
+ - `cap.load_halos("halos.hdf5")`: Load a saved HDF5 or `.npz` halo catalog into a `Halos` object.
110
+ - `cap.load_snapshot("snap/")` & `cap.load_ids("snap/")`: Memory-mapped read of native fixed-point snapshot directories.
111
+
112
+ ---
113
+
114
+ ## 5. Command-line interface
115
+
116
+ After `pip install .`, run via `cuap3mpy` or `python -m cuap3mpy`:
117
+
118
+ ```bash
119
+ # 2LPT cosmological run -> Gadget HDF5 snapshots + FoF halo catalog
120
+ cuap3mpy --N 512 --box 350 --transfer camb --zout 2,1,0.5 --ids \
121
+ --out snap.hdf5 --halos halos.hdf5
122
+
123
+ # Run from a MUSIC HDF5 initial condition (skip halo finding with --no-halos)
124
+ cuap3mpy --music IC.hdf5 --out snap.hdf5 --halos halos.hdf5
125
+ ```
126
+
127
+ Run `cuap3mpy --help` for the full list of options (`--w0`, `--wa`, `--ic`, `--softening`, `--softening-law`, `--streaming`, `--no-halos`, `--steps`).
128
+
129
+ ---
130
+
131
+ ## 6. Output file formats
132
+
133
+ Snapshot paths automatically select their format by suffix:
134
+
135
+ 1. **Gadget/AREPO HDF5 (`.hdf5` or `.h5`)**
136
+ - `Header`: `BoxSize` (`kpc/h`), `MassTable[1]` ($10^{10}\ M_\odot/h$), `Time` ($a$), `Redshift` ($z$), `Omega0`, `OmegaLambda`, `OmegaBaryon`, `HubbleParam`, `NumPart_Total`, `NumPart_Total_HighWord`, `Flag_DoublePrecision = 0`, `PersistentParticleIDs`.
137
+ - `PartType1/Coordinates`: `(n, 3)` `float32`, comoving position in `[0, BoxSize)` `kpc/h`.
138
+ - `PartType1/Velocities`: `(n, 3)` `float32`, Gadget velocity $u = v_{\text{pec}} / \sqrt{a}$ in `km/s`.
139
+ - `PartType1/ParticleIDs`: `(n,)` `uint32` (`uint64` when $n \ge 2^{32}$). When `ids=True`, stores persistent Lagrangian lattice IDs `(ix * N + iy) * N + iz` (or input MUSIC `ParticleIDs`) across all redshifts.
140
+
141
+ 2. **Native fixed-point directory (any path without `.hdf5`/`.h5`)**
142
+ - Lossless phase-space dump: `header.json`, `qpos.npy` (`(3, n)` `uint32`, $x = (q + 0.5) L / 2^{32}$), `qvel.npy` (`(3, n)` `int32`, $a v_{\text{pec}} = q\,\text{dv}$), and optional `pid.npy`.
143
+
144
+ 3. **FoF Halo Catalog (`.hdf5`/`.h5` or `.npz`)**
145
+ - HDF5 layout: `/Header` metadata plus `/Halos/{Npart, M200c [Msun/h], R200c [Mpc/h], Vmax [km/s], Center (nh, 3) [Mpc/h], ApertureMass (nh, 4) [Msun/h], Valid}`.
146
+
147
+ ---
148
+
149
+ ## 7. Package layout
150
+
151
+ ```text
152
+ cuap3mpy/
153
+ ├── simulation.py High-level Simulation API & standalone find_halos
154
+ ├── __main__.py Unified CLI entry point (cuap3mpy / python -m cuap3mpy)
155
+ ├── resident.py Single-GPU resident r-RESPA simulation driver
156
+ ├── streaming/ Pinned-host octant-streamed driver (N = 1008+ path)
157
+ ├── core/ Config, Cosmology, LinearPower (EH98/CAMB/CLASS), Particles, TimeSchedule
158
+ ├── gravity/ BCC18 root PM, adaptive q=8 patches, q=32 cores, radial pair kernels
159
+ ├── forces/ Root PM and short-range routing & local-tier kick orchestration
160
+ ├── ic/ GPU de-aliased 2LPT, MUSIC/Gadget HDF5, Zeldovich, Abacus RVZel, test ICs
161
+ ├── halos/ GPU lock-free FoF, slab-union FoF, shrinking-sphere & SO properties
162
+ ├── power.py Interlaced TSC matter power spectrum estimator
163
+ ├── snapshot.py Native fixed-point, Gadget HDF5, and halo catalog I/O
164
+ ├── validate.py Five-stage static force validation suite
165
+ └── demo.py Self-contained 128^3 end-to-end cosmological demo
166
+ ```
167
+
168
+ ## License
169
+
170
+ BSD 3-Clause; see [LICENSE](LICENSE).
@@ -0,0 +1,37 @@
1
+ """cuap3mpy -- GPU cosmological N-body simulation (CuPy).
2
+
3
+ import cuap3mpy as cap
4
+ sim = cap.Simulation(N=512, box=350.0, Om0=0.3, sigma8=0.8)
5
+ sim.run("snap.hdf5")
6
+ sim.P.pos, sim.P.vel, sim.halos
7
+
8
+ Every CuPy allocation goes through the driver's stream-ordered pool
9
+ (``cudaMallocAsync``), set here once before any array exists: physical
10
+ pages map into fresh address ranges without block-splitting fragmentation
11
+ (L100N512 peaks at 16.0 GiB live and completes on a 24 GB card).
12
+
13
+ ``Simulation`` (simulation.py) is the one-call entry point; the solver
14
+ itself is ``core`` (state), ``gravity`` + ``forces`` (the force split),
15
+ ``resident`` / ``streaming`` (the two drivers), ``ic`` and ``halos``.
16
+ """
17
+
18
+ import cupy as cp
19
+
20
+ pool = cp.cuda.MemoryAsyncPool()
21
+ cp.cuda.set_allocator(pool.malloc)
22
+
23
+ __version__ = "0.1.0"
24
+
25
+ from .core import Config
26
+ from .power import power_spectrum
27
+ from .simulation import Simulation, find_halos
28
+ from .snapshot import (
29
+ Halos,
30
+ load_halos,
31
+ load_ids,
32
+ load_snapshot,
33
+ save_gadget,
34
+ save_halos,
35
+ save_output,
36
+ save_snapshot,
37
+ )
@@ -0,0 +1,109 @@
1
+ """Unified command-line entry point in physical units (Mpc/h, km/s, Msun/h).
2
+
3
+ python -m cuap3mpy --N 512 --box 350 --out snap.hdf5 --halos halos.hdf5
4
+ python -m cuap3mpy --music IC.hdf5 --zout 2,1 --ids --out snap.hdf5
5
+ """
6
+
7
+ import argparse
8
+ import builtins
9
+ import time
10
+
11
+ from . import pool
12
+ from .simulation import Simulation
13
+
14
+ t0 = time.perf_counter()
15
+ orig_print = builtins.print
16
+
17
+
18
+ def stamped(msg="", flush=False):
19
+ orig_print(f"[{time.perf_counter() - t0:8.1f}s] {msg}", flush=flush)
20
+
21
+
22
+ def parse_args():
23
+ p = argparse.ArgumentParser(
24
+ prog="cuap3mpy",
25
+ description="GPU cosmological N-body simulation (adaptive P3M on CuPy).",
26
+ )
27
+ p.add_argument("--N", type=int, default=512,
28
+ help="Particle lattice and root PM grid size N (N^3 particles).")
29
+ p.add_argument("--box", type=float, default=350.0,
30
+ help="Comoving box size in Mpc/h (default: 350).")
31
+ p.add_argument("--music", type=str, default=None,
32
+ help="Path to a MUSIC / Gadget HDF5 initial-condition file.")
33
+ p.add_argument("--out", type=str, default=None,
34
+ help="Output snapshot path (.hdf5/.h5 -> Gadget HDF5, else directory).")
35
+ p.add_argument("--halos", type=str, default=None,
36
+ help="Output z=0 FoF halo catalog path (.hdf5/.h5 or .npz).")
37
+ p.add_argument("--no-halos", action="store_true",
38
+ help="Skip z=0 FoF halo finding when --halos is not given.")
39
+ p.add_argument("--ids", action="store_true",
40
+ help="Carry persistent particle IDs across steps and snapshots.")
41
+ p.add_argument("--zout", type=str, default="",
42
+ help="Comma-separated intermediate snapshot redshifts (e.g. 3,2,1,0.5).")
43
+ p.add_argument("--Om0", type=float, default=0.3)
44
+ p.add_argument("--OmL", type=float, default=0.7)
45
+ p.add_argument("--Ob0", type=float, default=0.048)
46
+ p.add_argument("--h", type=float, default=0.7)
47
+ p.add_argument("--sigma8", type=float, default=0.8)
48
+ p.add_argument("--ns", type=float, default=0.96)
49
+ p.add_argument("--z-init", type=float, default=99.0)
50
+ p.add_argument("--seed", type=int, default=42)
51
+ p.add_argument("--transfer", choices=("eh98", "camb", "class"), default="eh98")
52
+ p.add_argument("--Tcmb", type=float, default=2.725)
53
+ p.add_argument("--Neff", type=float, default=3.044)
54
+ p.add_argument("--w0", type=float, default=-1.0)
55
+ p.add_argument("--wa", type=float, default=0.0)
56
+ p.add_argument("--ic", choices=("gaussian", "fixed", "inverted", "fixed_inverted"),
57
+ default="gaussian")
58
+ p.add_argument("--softening", type=float, default=0.05,
59
+ help="Nominal softening eps in root cells dx (default: 0.05).")
60
+ p.add_argument("--softening-law", choices=("gadget_spline", "single_spline"),
61
+ default="gadget_spline")
62
+ p.add_argument("--streaming", choices=("auto", "true", "false"), default="auto")
63
+ p.add_argument("--steps", type=int, default=None,
64
+ help="Optional step cap for short test runs.")
65
+ return p.parse_args()
66
+
67
+
68
+ def main():
69
+ args = parse_args()
70
+ builtins.print = stamped
71
+
72
+ zout = ()
73
+ if args.zout:
74
+ zout = tuple([float(z) for z in args.zout.split(",")])
75
+ streaming = "auto"
76
+ if args.streaming == "true":
77
+ streaming = True
78
+ elif args.streaming == "false":
79
+ streaming = False
80
+
81
+ sim = Simulation(
82
+ N=args.N, box=args.box,
83
+ Om0=args.Om0, OmL=args.OmL, Ob0=args.Ob0, h=args.h,
84
+ sigma8=args.sigma8, ns=args.ns, z_init=args.z_init, seed=args.seed,
85
+ transfer=args.transfer, Tcmb=args.Tcmb, Neff=args.Neff,
86
+ w0=args.w0, wa=args.wa, ic=args.ic, zout=zout, ids=args.ids,
87
+ softening=args.softening, softening_law=args.softening_law,
88
+ streaming=streaming, music=args.music,
89
+ )
90
+ if args.steps is not None:
91
+ sim.driver.schedule.nsteps = min(args.steps, sim.driver.schedule.nsteps)
92
+ nsteps = sim.driver.schedule.nsteps
93
+
94
+ want_halos = (args.halos is not None) or (not args.no_halos)
95
+ t1 = time.perf_counter()
96
+ sim.run(args.out, halos=want_halos)
97
+ dt = time.perf_counter() - t1
98
+
99
+ if args.halos is not None:
100
+ sim.save_halos(args.halos)
101
+ print(f"halos saved: {args.halos} ({sim.halos.n} groups)", flush=True)
102
+ elif sim.halos is not None:
103
+ print(f"FoF halos: {sim.halos.n} groups", flush=True)
104
+ print(f"DONE: {nsteps} steps, run+post {dt:.1f} s, "
105
+ f"pool peak {pool.total_bytes() / 2**30:.2f} GiB", flush=True)
106
+
107
+
108
+ if __name__ == "__main__":
109
+ main()
@@ -0,0 +1,12 @@
1
+ """Table cache root: ``$CUAP3MPY_CACHE``, else ``~/.cache/cuap3mpy``.
2
+
3
+ Force and transfer tables are built on first use and saved under this
4
+ root; every file or directory name spells out the parameters it depends
5
+ on. Deleting the root forces a rebuild.
6
+ """
7
+
8
+ import os
9
+ from pathlib import Path
10
+
11
+ cache_root = Path(os.environ.get(
12
+ "CUAP3MPY_CACHE", Path.home() / ".cache" / "cuap3mpy"))
@@ -0,0 +1,21 @@
1
+ """Simulation state and cosmological inputs.
2
+
3
+ Reading order:
4
+ config.py the one dataclass every module reads
5
+ particles.py SoA store: uint32 fixed-point positions +
6
+ int32 fixed-point velocities, with the CUDA
7
+ pack / drift kernels; impulse-based, no
8
+ acceleration array
9
+ cosmology.py FLRW background E(a) (matter, radiation,
10
+ Lambda), leapfrog clocks, growth (one RK4 for
11
+ table and LPT)
12
+ linear_power.py z=0 P(k), sigma8-normalized: Eisenstein--Hu fit
13
+ or the cached CAMB/CLASS transfer table
14
+ time_schedule.py formation-shaped power-law nodes and the dt
15
+ tables the driver steps with
16
+ """
17
+
18
+ from .config import Config
19
+ from .particles import Particles
20
+ from .cosmology import Cosmology
21
+ from .linear_power import LinearPower