Skip to content

Add MultipoleExpansionPotential for multipole expansion of arbitrary densities#829

Open
jobovy wants to merge 11 commits intomainfrom
multipole-expansion-potential
Open

Add MultipoleExpansionPotential for multipole expansion of arbitrary densities#829
jobovy wants to merge 11 commits intomainfrom
multipole-expansion-potential

Conversation

@jobovy
Copy link
Owner

@jobovy jobovy commented Feb 13, 2026

Summary

  • Adds MultipoleExpansionPotential, a new potential class that decomposes a given density function into real spherical harmonics on a radial grid and computes the gravitational potential via classical multipole integrals (galaxiesbook.org Ch. 12.3, eq. 12.76 & 12.79)
  • Supports spherical, axisymmetric, and general (non-axisymmetric) density profiles via the symmetry parameter; accepts density as a callable (1/2/3 args) with or without astropy units, or a galpy Potential instance
  • Analytical forces via SphericalHarmonicPotentialMixin providing the spherical-to-cylindrical force chain rule (_Rforce, _zforce, _phitorque); radial force derivatives include spline derivative corrections for inner/outer integrals, ensuring forces are the true negative gradient of the interpolated potential
  • Second derivatives computed numerically via NumericalPotentialDerivativesMixin

Refactoring

  • Extract shared spherical harmonics utilities (compute_legendre, sph_harm_normalization) from SCFPotential into galpy/util/special.py
  • Extract shared spherical-to-cylindrical force chain rule from SCFPotential into SphericalHarmonicPotentialMixin; SCFPotential now inherits from the mixin, removing duplicated code

Other changes

  • Add MultipoleExpansionPotential to estimateDeltaStaeckel special-case handling (like SCFPotential) to avoid negative delta2 from numerical second derivatives
  • Add adiabatic fallback for MultipoleExpansionPotential in orbit analytic parameter tests (ecc, rperi, rap, zmax)
  • Exclude SphericalHarmonicPotentialMixin from orbit/potential test lists
  • Add tolerances for MultipoleExpansionPotential in test_potential.py (Poisson, 2nd derivatives)

Test plan

  • 34 tests in tests/test_MultipoleExpansionPotential.py covering spherical (Hernquist), axisymmetric (MiyamotoNagai), SCF cross-validation, density reconstruction, normalization, isNonAxi flag, input variants (1/2/3-arg callable, Potential instance), analytical forces, and edge cases (r=0, infinity, phi=None)
  • Astropy unit density tests (1/2/3-arg) in test_quantity.py::test_potential_paramunits
  • All 50 existing SCF tests pass after mixin refactoring
  • All test_potential.py and test_orbit.py tests pass for MultipoleExpansionPotential

@codecov
Copy link

codecov bot commented Feb 13, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.49%. Comparing base (a1150fa) to head (805c485).
⚠️ Report is 8 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #829      +/-   ##
==========================================
- Coverage   99.91%   98.49%   -1.42%     
==========================================
  Files         215      219       +4     
  Lines       30920    33509    +2589     
  Branches      618      662      +44     
==========================================
+ Hits        30893    33005    +2112     
- Misses         27      504     +477     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@jobovy jobovy force-pushed the multipole-expansion-potential branch 2 times, most recently from efbc445 to a345cf9 Compare February 15, 2026 20:14
@jobovy jobovy changed the title Add MultiPoleExpansionPotential for multipole expansion of arbitrary densities Add MultipoleExpansionPotential for multipole expansion of arbitrary densities Feb 15, 2026
@jobovy jobovy force-pushed the multipole-expansion-potential branch 8 times, most recently from 70a383d to b9b9d48 Compare February 19, 2026 21:04
@jobovy jobovy force-pushed the multipole-expansion-potential branch from 42ce48b to eb045a1 Compare February 25, 2026 02:39
jobovy and others added 7 commits February 25, 2026 09:07
…densities

Add MultipoleExpansionPotential, a new potential class that decomposes a
given density function into real spherical harmonics on a radial grid and
computes the gravitational potential via classical multipole integrals
(galaxiesbook Ch. 12.3, eq. 12.76 & 12.79). Supports spherical, axisymmetric,
and general (non-axisymmetric) density profiles via the symmetry parameter;
accepts density as a callable (1/2/3 args) with or without astropy units,
or a galpy Potential instance.

Analytical forces are computed via a shared SphericalHarmonicPotentialMixin
that provides the spherical-to-cylindrical force chain rule (_Rforce,
_zforce, _phitorque). The radial force derivative includes spline
derivative corrections for the inner/outer integrals, ensuring forces are
the true negative gradient of the interpolated potential and giving
excellent energy conservation in orbit integrations. Second derivatives
are computed numerically via NumericalPotentialDerivativesMixin.

Refactoring:
- Extract shared spherical harmonics utilities (compute_legendre,
  sph_harm_normalization) from SCFPotential into galpy/util/special.py
- Extract shared spherical-to-cylindrical force chain rule from
  SCFPotential into SphericalHarmonicPotentialMixin
- SCFPotential now inherits from the mixin, removing duplicated code

Other changes:
- Add MultipoleExpansionPotential to estimateDeltaStaeckel special-case
  handling (like SCFPotential) to avoid negative delta2 from numerical
  second derivatives
- Add adiabatic fallback for MultipoleExpansionPotential in orbit
  analytic parameter tests (ecc, rperi, rap, zmax)
- Exclude SphericalHarmonicPotentialMixin from orbit/potential test lists
- Add tolerances for MultipoleExpansionPotential in test_potential.py
  (Poisson, 2nd derivatives)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Implement analytical second derivatives via the spherical-to-cylindrical
chain rule, replacing NumericalPotentialDerivativesMixin. This improves
accuracy from ~1e-5 to machine precision for derivative self-consistency,
allowing all test tolerances to use defaults.

- Extend compute_legendre to support deriv=2 (d²P/dx²)
- Add _compute_spher_2nd_derivs_at_point to MultipoleExpansionPotential
- Add chain rule helpers (_evaluate_cyl_2nd_deriv) to SphericalHarmonicPotentialMixin
- Add configurable spline degree k parameter (default k=3)
- Remove NumericalPotentialDerivativesMixin dependency
- Remove MultipoleExpansionPotential from estimateDeltaStaeckel special-casing
- Remove custom tolerances for 2nd deriv and Poisson tests (now use defaults)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…ines and auto-truncating non-axi terms

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…tegration

Implements potential evaluation, forces, and density in C using GSL splines
for radial functions and shared Legendre utilities from SCFPotential.c.
Enables ~255x speedup for orbit integration and ~19x for dynamical friction.

Key implementation details:
- Type 44 in the C potential system
- GSL cubic splines for radial interpolation (Radial_cos/sin, rho_cos/sin)
- Point-mass extrapolation for r > rmax: R_lm(r) = R_lm(rmax)*(rmax/r)^{l+1}
- Density clamps to rmin for r < rmin (prevents sigma_r divergence in CDF)
- Spline init follows ChandrasekharDynamicalFriction pattern (before nargs
  loop, with saved flag before wrapper parsing) for correct pot_args ordering
- Force caching for repeated evaluations at same coordinates

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…ion, to pick up coordinates given as keywords (dens(R,z=0,phi=0))
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…radial derivatives

Replace the single R_lm(r) IUS spline with separate BPoly splines for
the cumulative integrals I_inner(r) and I_outer(r), with pref_blm
absorbed. Compute R, dR/dr, and d²R/dr² analytically via the product
rule from the spline values and derivatives. This avoids the dynamic
range issues that caused large interpolation errors for high-l terms.

For r < rmin, assume constant density rho(rmin) and extend the
cumulative integrals analytically. For r > rmax, use point-mass
extrapolation (rho=0). Update both Python and C implementations.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@jobovy jobovy force-pushed the multipole-expansion-potential branch 2 times, most recently from ac21794 to 7f7d327 Compare February 27, 2026 01:56
…fficients directly for exact Python/C parity, combine radial evaluations, and replace MD5 caching with tuple keys

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@jobovy jobovy force-pushed the multipole-expansion-potential branch from 7f7d327 to 2a42e7c Compare February 27, 2026 02:33
@jobovy jobovy force-pushed the multipole-expansion-potential branch from 0a880b3 to 2876d13 Compare March 6, 2026 02:04
jobovy and others added 2 commits March 6, 2026 15:14
- Remove k parameter from public API (BPoly sets degree, old docstring misleading)
- Skip sin integral computation for m=0 (never used, zero bytes reach C)
- Enhance SCF test to verify only l=0,1 coefficients are non-zero
- Add C coverage tests for below-grid log branch (line 255), d²R (lines 286-288), and non-axi potential evaluation

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…computation

Split __init__ into spline-accepting __init__ and from_density classmethod,
following the SCFPotential pattern. __init__ now takes precomputed
rho_cos_splines/rho_sin_splines; from_density handles density decomposition.
Make _parse_density and _compute_rho_lm static methods. Update class docstring
to use real-valued spherical harmonic formulas with explicit projection integrals.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@jobovy jobovy force-pushed the multipole-expansion-potential branch from b4370a1 to 805c485 Compare March 6, 2026 20:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant