In my last post, I proved that I could build a spherically symmetric initial-conditions code and N-body simulator with Cursor. My main conclusion was that AI-powered coding tools dramatically reduce the time it takes an expert to reach a usable result. Along the way, there were many points where plausible implementation choices could obscure or quietly violate the scientific intent. I want to continue that investigation here and use this series to explore questions at the intersection of galactic dynamics and machine learning.
To that end, I assert the following scientific goal: learn a useful representation of how Milky Way–like galaxies move through phase space as they evolve. Real galaxies are not spherical like the ones we explored in the last post. Galaxy disks are not necessarily axisymmetric; many feature spiral structure, central bars, or both. Can a model organize multi-million-particle simulations by meaningful dynamics—stability, bar growth, spiral structure, vertical bending, and dynamical age—rather than by superficial image similarity? Furthermore, can we decode dynamically stable galaxy models from those learned coordinates?
Answering these questions requires a controlled training corpus. I need many self-consistent galaxy models, each connected to the physical parameters that created it, evolved over billions of years, and accompanied by validation artifacts and interpretable labels. Those known variables make the learned coordinates scientifically testable. This post stops at the machinery and pilot campaign used to build that corpus, but I think the insights from this phase are worth their own post.
Building the pilot required two enabling systems: a reliable generator of equilibrium galaxies and an efficient simulator capable of evolving them at scale. Over a couple of weeks, I used AI coding tools to bootstrap PyGalactICS, which reconstructs and validates the initial-condition workflow, and ntropy, a lightweight N-body backend with a GPU Barnes–Hut force solver. Here I extend that work to rotating disk–bulge–halo galaxies and the engineering needed to evolve them at corpus scale.
Neither PyGalactICS nor ntropy appeared from a blank prompt. The design draws on decades of work in galactic dynamics and scientific computing, with GalactICS providing the equilibrium framework and codes such as GADGET supplying architectural inspiration for scalable N-body evolution. Domain knowledge supplied the physical contracts, numerical tests, and judgment about what had to remain true. AI accelerated the software archaeology: porting routines, reconstructing interfaces, generating tests, and propagating changes across Python, C, MPI, and CUDA. It also produced plausible mistakes—including the GPU indexing failure discussed below—that only physics-aware validation and scaling tests exposed.
The scientific lineage motivating this line of questioning lies in a paper by my old PhD supervisor, Dynamical Blueprints for Galaxies. The study treated the Milky Way not as one best-fit object but as a family of equilibrium models that could satisfy the same observational constraints while differing in structure and dynamical response. This project is a modern extension of that idea: turn a parameterized family of blueprints into a time-resolved corpus, then ask whether a learned phase-space representation recovers the structure of their possible futures.
The contrast is already visible before any machine learning. Four models can begin as credible equilibrium systems and evolve with the same numerical machinery, yet develop bars at different times and with different strengths. A useful representation should preserve those differences, explain how they emerge, and reveal where each trajectory belongs relative to the rest of the corpus.

From one spherical halo to a galaxy corpus
The last post began with the cleanest useful validation problem: a spherical, isotropic dark-matter halo. In that case, the smooth density depends only on radius, the velocity distribution has no preferred direction, and the equilibrium distribution function can be written as a function of binding energy alone:
Eddington inversion then connects the density profile to the energy distribution needed to support it. That problem is numerically nontrivial, but its symmetry removes most of the orbital structure that makes a disk galaxy interesting.
A Milky Way–like model adds a rotating stellar disk and often a central bulge. The disk is flattened rather than spherical. Its stars have substantial ordered rotation, but also radial and vertical random motion. The density, velocity dispersions, and gravitational potential must all be compatible with one another. A model that matches the desired density but assigns the wrong orbit population will immediately heat, contract, expand, or rearrange itself when evolved.
The corpus therefore begins with a parameterized family of near-equilibrium systems,
where includes disk mass, scale length, scale height, radial velocity dispersion, bulge properties, halo structure, and other choices that control the galaxy’s stability. The objective is to sample a broad but credible region of this parameter space, evolve every realization, and retain both the physical parameters and the resulting morphology.
Axisymmetric equilibrium is a phase-space construction
In a time-independent potential, Jeans’ theorem tells us that a steady collisionless system can be built from distribution functions that depend on integrals of motion. For a general axisymmetric potential, two exact classical integrals are the orbital energy,
and the angular momentum about the symmetry axis,
A useful description of regular disk orbits also requires a third quantity that describes motion away from the equatorial circular orbit. GalactICS uses an approximate three-integral disk distribution function that can be written schematically as
where is an approximate vertical energy. The angular momentum
identifies a guiding-center radius through the circular orbit with the same angular momentum. The remaining energy is divided into radial and vertical excursions about that guiding center.
This decomposition is what allows the model to specify more than a density profile. The disk distribution function controls:
- how mass is distributed across guiding-center radii;
- the radial velocity dispersion and therefore the disk’s susceptibility to non-axisymmetric structure;
- the vertical energy distribution and the resulting scale height; and
- the difference between the circular speed of the potential and the mean streaming speed of the stars.
The bulge and halo are simpler in the models used here. Under the adopted spherical and isotropic assumptions, their distribution functions depend primarily on binding energy. All three components nevertheless share the same total potential. Changing the disk alters the potential seen by the bulge and halo; changing the halo changes the circular orbits and frequencies used by the disk DF.
Solving for a self-consistent potential
The density implied by a distribution function depends on the gravitational potential, while the potential itself is generated by the combined density of the disk, bulge, and halo. GalactICS separates the self-consistent potential solve from the final disk-DF correction. During the Poisson iteration, the halo and bulge enter through tabulated relations derived from their energy DFs, where
is the relative potential stored by GalactICS (equal to
up to an additive constant). The disk enters through a potential-dependent density ansatz. The algorithm is:
- start from trial component densities and a trial potential;
- evaluate the halo and bulge
tables and the disk-density ansatz in that potential;
- project the combined density, evaluated on fixed spherical shells, onto even Legendre harmonics;
- solve Poisson’s equation mode by mode for the harmonic contribution while retaining the separate approximate analytic disk potential; and
- update the tidal boundary and repeat, increasing the active harmonic order until the potential converges.
Once the potential has converged, GalactICS tabulates the orbital frequencies and corrects the three-integral disk DF against the target density before sampling the particles.
The axisymmetric density and the harmonic contribution to the potential are represented on spherical shells with even Legendre polynomials:
The term is the spherical average. Higher even terms describe flattening and other departures from spherical symmetry. Odd terms vanish because the initial model is symmetric above and below the midplane. Because a thin disk converges slowly in a low-order spherical-harmonic expansion, GalactICS supplements the multipoles with an approximate analytic disk potential.

The final particle realization is sampled from these DFs, not from the density alone. Positions and velocities are therefore tied to the same reconstructed potential.
Circular speed is not the mean stellar rotation speed
One useful diagnostic is the circular-speed curve,
This is a property of the gravitational potential. It is not the same as the mean azimuthal velocity of the disk particles. A dynamically warm stellar disk receives some radial support from random motion, so its mean streaming speed satisfies
That difference—often called asymmetric drift—is a feature of a valid warm disk rather than evidence that the sampler has failed.
How can an equilibrium galaxy form a bar?
The word equilibrium is easy to overinterpret. In the collisionless idealization, it means that the smooth distribution function is stationary in the reconstructed potential. The sampled GalactICS models are only near-equilibrium because the third integral and potential representation are approximate. Equilibrium does not mean that every perturbation to that state decays.
A system can be in equilibrium and still be unstable. The distinction is the same one that separates a force-balanced configuration from a stable one: the first derivative can vanish even when a small displacement grows rather than being restored.
An N-body realization never begins with perfect continuous symmetry. Sampling a smooth DF with a finite number of particles introduces low-amplitude fluctuations at many azimuthal wavenumbers. Roundoff, tree-force approximation, and the discrete particle distribution provide additional tiny seeds. In a stable disk, those perturbations remain small or shear away. In an unstable disk, self-gravity selectively amplifies them.
Spiral structure can grow through swing amplification and related collective responses in the rotating disk. A global mode can grow into a bar. As the pattern develops, the disk exchanges angular momentum internally and with resonant orbits in the live bulge and halo. The bar is therefore not inserted into the initial condition, nor is it necessarily evidence that the initial condition was out of equilibrium. It can be the physically expected instability of an otherwise valid equilibrium model.
The parameter vector controls which outcome occurs. A colder or more self-gravitating disk is generally more responsive. The central mass concentration, disk thickness, halo structure, and distribution of resonant orbits all affect whether a perturbation is damped, becomes transient spiral structure, or grows into a long-lived bar.
This is why the corpus needs delayed and weak responses as well as rapidly growing strong bars. If every model formed the same bar on the same schedule, the result could indicate a systematic problem in the initial conditions or integrator. A range of growth histories—correlated with the physical parameters—is the behavior we want a later representation model to learn.
Verifying the equilibrium before trusting the evolution
Before interpreting the 2.0 Gyr evolution, I compared the initial particle realization with the 0.489 Gyr snapshot of the delayed-bar model. I selected this model because strong non-axisymmetric growth had not yet begun at that time. This is not an instantaneous equilibrium test; it asks whether the sampled system survives almost half a gigayear without gross numerical rearrangement. The checks included:
- the disk surface-density profile
;
- the halo density profile
;
- the circular-speed curve, mean disk streaming velocity, and radial velocity dispersion
;
- the halo particle binding-energy distribution compared with the GalactICS DF reference; and
- the disk distributions in angular momentum, in-plane energy, and vertical energy.
These checks establish a practical contract for the pilot campaign. The initial-condition generator supplies a credible equilibrium, and the N-body solver evolves it for 0.489 Gyr without grossly rearranging the radial mass distribution or numerically dissolving the halo.
Only after satisfying that contract does later morphological diversity become scientifically interesting.
The computational bottleneck is evolution
Sampling an equilibrium galaxy is relatively cheap. Evolving it for billions of years is not.
A useful morphology corpus needs enough disk particles that a bar or spiral pattern is not dominated by shot noise. The experiments shown here use roughly one million disk particles and about 1.75 million particles in total after including the bulge and halo. A direct all-pairs force calculation would require interactions at every step.
Barnes–Hut reduces that cost to approximately by organizing particles into a spatial hierarchy. Nearby cells are opened and inspected in more detail. A sufficiently distant cell is replaced by one monopole at its center of mass, with the opening angle controlling the accuracy–cost tradeoff.
One hybrid CPU/GPU force evaluation
The gpu_bh path in ntropy deliberately divides the problem by hardware strength:
- CPU: Morton-sort the particles and construct the adaptive octree.
- Host-to-device transfer: flatten cells, leaf pointers, particle data, and aggregate properties into compact buffers.
- GPU unpack: convert the flat node rows into a structure-of-arrays representation suitable for coalesced access.
- GPU walk: assign one CUDA thread to each target particle. The thread opens nearby nodes, accepts distant monopoles, and accumulates the softened acceleration.
The irregular tree construction remains convenient on the CPU. The large collection of independent target walks is the parallel workload that belongs on the GPU.
An instructive AI coding mistake
The indexing error is worth discussing because it is exactly the kind of failure an AI coding agent can introduce while optimizing unfamiliar systems code. The generated CUDA kernel was locally plausible: it assigned one thread per target and produced sensible results within a single CUDA block. What it missed was the thread’s global index across the CUDA grid. Small tests and a correctness-preserving chunked workaround concealed the scaling failure until the benchmark reached hundreds of thousands of particles.
Before the fix, the chunked path took about 9.7 seconds at 100,000 particles and timed out beyond 300 seconds at 500,000. After the global index and single-launch path were restored, the walk took about 8.3 milliseconds at 100,000 particles, 91 milliseconds at one million, and 2.7 seconds at ten million. Between roughly 50,000 and one million particles, the normalized cost remained close to the expected trend.
The bug does not make a case against using AI to write GPU kernels. The generated kernel looked reasonable and passed small tests, while the correctness-preserving workaround was still catastrophically slow at scale. Avoiding that class of failure requires hardware-aware review, tests that cross block and grid boundaries, accuracy checks, and benchmarks at realistic particle counts.
A second failure was more serious. The GPU tree walk used a fixed 64-entry traversal stack and silently discarded child nodes when it filled. The initial AI-generated unit tests did not reveal this because they exercised small synthetic systems, not the concentrated, mixed-component trees used in production. A direct comparison of gpu_bh and bh_c on a real 1.75-million-particle galaxy would have found it immediately: 37.4% of a representative 20,000-target sample had particle-wise relative force errors above , and the sample-wide relative
force error was 0.263. The corrected kernel sizes its stack from the total source-particle count and treats any remaining overflow as an error instead of returning an incomplete force.
The benchmark also has a deliberately narrow scope. It measures the device tree walk, not the complete simulation step. The production path still pays for CPU tree construction, buffer preparation, host-to-device transfer, leapfrog integration, and diagnostics. In separate million-particle comparisons on this machine, the GPU walk was typically about four to eight times faster than the corresponding C tree walk under the tested workloads; that figure should not be read as a universal end-to-end speedup.
Scaling beyond one process
The CPU Barnes–Hut MPI path implements part of this design. It partitions targets into Morton-sorted spatial domains, builds a local tree on each rank, and exchanges a Local Essential Tree containing the remote monopoles and leaf data needed for each target domain. Tree memory therefore scales with the local particles plus the imported LET nodes.
The implementation is not yet fully distributed. Every rank still retains the complete particle arrays and gathers a complete acceleration array after each force evaluation. The gpu_bh backend also bypasses the LET path and builds a replicated global tree, then divides only the target walks among ranks. The current multi-rank GPU path therefore parallelizes computation without removing the per-rank particle state or global-tree storage.
There is a known GADGET-style route past this limit. Each rank can own and integrate only its spatial-domain particles, migrate particles as the domains change, exchange only the remote tree nodes or exported target requests required by each walk, and avoid the final all-gather. Particle storage then approaches , plus the imported tree and communication working set. Implementing that distributed GPU path is future work, not a property of the runs shown here.
No single optimization made the corpus practical. The distribution function constrains the starting state; Barnes–Hut controls force complexity; the CPU constructs the irregular hierarchy; and the GPU evaluates millions of independent walks.
One family of initial conditions, many dynamical outcomes
Once the evolution engine is fast enough, the parameter sweep becomes interesting.
This pilot campaign followed four disk–bulge–halo systems, each containing 1.75 million particles, for 2.0 billion years with the same numerical pipeline. Every displayed evolution was rerun from after both CUDA bugs described above were fixed. No snapshot or diagnostic below was produced by the faulty kernel.
The reported final fractional energy changes are point estimates ranging from 0.05% to 0.28%. The diagnostic uses a fixed sample of one million particle pairs; its one-snapshot standard errors are roughly 0.3%–0.5% of , larger than the quoted drifts. Reusing the same pairs reduces noise in changes, but the diagnostic does not yet report an uncertainty on
. I therefore use these values to rule out gross, multi-percent failures, not to claim resolved sub-percent energy conservation. The equilibrium and structural checks carry the rest of the physical validation.
At initialization, the four stellar disks look deceptively similar. Their later trajectories do not. Three develop unmistakable bars, while the fourth remains much less responsive through most of the integration and only develops a weak, late distortion. Bar onset, saturation amplitude, and vertical response all differ across the small sample.
The timing contains as much information as the final images. One bar grows within the first few hundred million years, another becomes prominent after roughly 0.6 Gyr, and a third after roughly 0.9 Gyr. The weak case approaches the 0.15 guide used here only near the end of the 2.0 Gyr run.
All four models undergo some early settling. That is expected when a finite-particle realization sampled from a truncated harmonic representation and approximate analytic disk potential is transferred to a softened tree-force calculation. The important feature is what happens after that common transient: the models diverge, with the largest late thickening in two strong-bar systems but no monotonic ordering with final bar amplitude.
This behavior is qualitatively consistent with the bar growth and disk thickening seen in cosmological disk simulations (Bauer & Widrow 2019). These idealized models are not meant to reproduce the full cosmological environment. Their advantage is that they isolate how a controlled change in the equilibrium blueprint changes the subsequent trajectory.
Turning morphology into interpretable labels
Images are useful, but a corpus should also carry quantitative descriptions of its dynamics.
Bar strength
I measure the coherent two-fold structure with the integrated Fourier amplitude of the disk inside radius
:
The value reported here is , using every disk particle inside the aperture and no vertical cut. This differs from the local normalized profile
shown below: the integrated statistic asks how much of the inner disk participates coherently in one global two-fold pattern. At 2.0 Gyr, the four amplitudes are 0.338, 0.369, 0.162, and 0.330. Using the 0.15 guide adopted for this figure, three have clearly developed strong integrated
structure; the fourth has only just crossed the guide and is better described as weak or incipient (Sellwood & Wilkinson 1993; Athanassoula 2003; Debattista & Sellwood 2000).
Vertical thickness and central concentration
For vertical structure, I track the mass-weighted root-mean-square height in radial bins:
I also track its global value inside 8 kpc and pair it with the disk mass enclosed within 1 kpc. Normalizing both quantities by their initial values makes the common settling and later model-to-model divergence visible in the same plot.
By 2.0 Gyr, the global vertical thickness reaches roughly 1.5–2.5 times its initial value, while the disk mass enclosed within 1 kpc reaches roughly 1.35–1.85 times its initial value. The largest thickness changes occur in two strong-bar systems, but neither structural measure follows one-for-one. A four-model pilot cannot establish a unique causal pathway. The model-specific divergence after a common transient is consistent with different dynamical responses, but it does not by itself rule out a shared numerical bias.
Coherent bending
Thickness and bending are not the same measurement. The quantity can increase when stars move farther from the midplane in both directions, leaving the mean midplane flat. A bending mode instead measures a coherent displacement of that midplane as a function of azimuth. In each radial annulus I calculate
The mode varies once around the disk: one side is displaced upward while the opposite side is displaced downward. With the normalization used here,
is a Fourier coefficient. For an azimuthally uniform disk with a pure sinusoidal bend,
, the peak displacement is
; nonuniform particle-mass weighting can modify that conversion. Dividing the coefficient by the local
gives a dimensionless measure of coherent bending relative to the disk’s total vertical rms extent, which includes coherent displacement as well as symmetric thickness. I remove the disk’s center-of-mass translation before computing the mode, but I do not fit and subtract a tilted disk plane at each snapshot. A coherent global tilt can therefore contribute to this fixed-frame
signal.
The largest coefficient reaches about 0.1 kpc at 8 kpc. In an azimuthally uniform disk with a pure sinusoidal bend, that would correspond to a peak displacement of about 0.2 kpc; in these barred disks, the conversion is only approximate. The final normalized profiles also separate coherent bending from the much larger increase in overall thickness. A model can therefore be thick without being strongly bent, or carry a noticeable distortion without having the strongest bar.
These labels make the dataset useful for more than image generation. They support retrieval, conditional sampling, surrogate modeling, and tests of whether a learned representation has organized systems by physically meaningful behavior.
The larger pattern: simulation as a data product
The practical result is a pipeline connecting four layers:
- Physically constrained generation. Distribution functions and a self-consistent potential produce credible initial conditions.
- Scalable evolution. Hybrid CPU/GPU Barnes–Hut gravity makes million-particle experiments practical in batches.
- Validation. Density profiles, energy distributions, and kinematic diagnostics detect numerical or modeling failures.
- Interpretable labeling. Structural parameters, dynamical age, bar amplitude, and vertical modes turn snapshots into a searchable corpus.
Synthetic data becomes valuable when the simulator is not treated as a black-box image generator, but as an instrumented production system with validity checks, throughput constraints, and domain-specific labels.
In this case, the quiet equilibrium is only the scaffold. The actual data product is the family of trajectories that unfolds after gravity is allowed to act.
That distinction sets up the next problem: once the corpus exists, how should it be organized so that nearby points correspond to meaningfully similar galaxies?
The implementation, benchmark harness, validation tooling, and campaign pipeline are available in the PyGalactICS repository. The most useful feedback is not whether one image “looks like a galaxy,” but whether the physical contract, performance evidence, and resulting labels are strong enough to support the representation-learning experiments that follow.
Next in the series: how the evolved corpus sits in a learned library space, combining field maps, a teacher encoder, compact latent coordinates, and the original physical parameters .
References
- Kuijken & Dubinski 1995, MNRAS, 277, 1341 — equilibrium disk–bulge–halo models.
- Widrow & Dubinski 2005, ApJ, 631, 838 — dynamical models of the Milky Way and M31.
- Widrow, Pym & Dubinski 2008, ApJ, 679, 1239 — equilibrium galaxy blueprints.
- Binney & Tremaine 2008, Galactic Dynamics — distribution functions and multipole methods.
- Barnes & Hut 1986, Nature, 324, 446 — the Barnes–Hut tree algorithm.
- Springel 2005, MNRAS, 364, 1105 — GADGET-2 domain decomposition and scalable N-body architecture.
- Sellwood & Wilkinson 1993, Reports on Progress in Physics, 56, 173 — barred-galaxy dynamics.
- Athanassoula 2003, MNRAS, 341, 1179 — angular-momentum exchange and bar evolution.
- Debattista & Sellwood 2000, ApJ, 543, 704 — bars and live dark-matter halos.
- Bauer, Widrow & Erkal 2018, MNRAS, 476, 198 — disk–halo interactions and vertical response.
- Bauer & Widrow 2019, MNRAS, 486, 523 — bar formation in cosmological disk simulations.
Leave a Reply