Metadata-Version: 2.4
Name: disk-galaxy-deprojection
Version: 0.5.0
Summary: Learned mass-conserving deprojection of galaxy images -> 3D stellar density, rotation curve, potential.
Author-email: lucyundead <lucyundead@126.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/lucyundead/disk-galaxy-deprojection
Project-URL: Repository, https://github.com/lucyundead/disk-galaxy-deprojection
Project-URL: Issues, https://github.com/lucyundead/disk-galaxy-deprojection/issues
Keywords: astronomy,galaxies,deprojection,rotation-curve,TNG50,photometry
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Astronomy
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.26
Requires-Dist: astropy>=6.0
Requires-Dist: matplotlib>=3.8
Provides-Extra: fast
Requires-Dist: scipy>=1.11; extra == "fast"
Provides-Extra: train
Requires-Dist: torch>=2.1; extra == "train"
Requires-Dist: scipy>=1.11; extra == "train"
Requires-Dist: pandas>=2.1; extra == "train"
Requires-Dist: h5py>=3.10; extra == "train"
Provides-Extra: dev
Requires-Dist: pytest>=7.4; extra == "dev"
Requires-Dist: ruff>=0.1; extra == "dev"
Dynamic: license-file

# Disk Galaxy Deprojection (`dgdp`)

Turn a single galaxy image into its deprojected 3-D stellar-mass distribution,
rotation curve, and (optionally) gravitational potential — with simulation-informed
posterior samples from a **bundled pretrained model**. No training data or GPU required.

## Motivation

Recovering the 3-D stellar-mass structure of a barred galaxy from one 2-D image is
ambiguous: many 3-D distributions reproject to the same picture. `dgdp` treats the
result as a distribution of plausible structures. Posterior draws provide bands
for summaries such as scale height and rotation curve, learned from TNG50
galaxies whose true 3-D structure is known. Their coverage is measured on held-out
galaxies; applying them to observations also requires checking the training domain.

## Method

- The in-plane surface density is anchored geometrically from the image.
- A learned fixed-dictionary sech² vertical profile — trained on 185 TNG50 barred
  galaxies × 198 projections — supplies the disk thickness, mass-conserving by
  construction.
- A reprojection loop corrects the surface-density anchors to improve agreement
  between the thick model's projection and the observed image.
- The model is a mixture density network; sampling its head propagates the posterior
  to RMS|z|(R) and v_c(R) bands, calibrated on a held-out TNG50 split.

Full derivation: [`docs/reports/2026-06-30-mixture-qm-fixed-dictionary.md`](docs/reports/2026-06-30-mixture-qm-fixed-dictionary.md).

## Goal

Given an S4G-like image plus geometry (distance, inclination, PA), return a cylindrical
stellar-mass cube ρ\*(R, φ, z), a rotation curve v_c(R) and vertical scale height h_z(R),
posterior draws for uncertainty bands, and optionally the AGAMA CylSpline potential Φ(R, z).

## Install

```bash
pip install --upgrade disk-galaxy-deprojection
# For repeated inclination and thickness trials with the SciPy backend:
pip install --upgrade 'disk-galaxy-deprojection[fast]'
```

Core install is light (`numpy`, `astropy`, `matplotlib`) and ships the ~1 MB model.
Retraining needs the `[train]` extra (`pip install 'disk-galaxy-deprojection[train]'`);
the optional potential
needs [AGAMA](https://github.com/GalacticDynamics-Oxford/Agama) built from source and on
`PYTHONPATH`.

## Usage

```python
from dgdp import deproject

r = deproject("galaxy.fits", distance_mpc=15.2, inclination_deg=30, pa_onsky_deg=153,
              ml=1.0, stellar_mass=6e10, n_samples=48)

r.density_3d                    # (nR, nphi, nz) stellar mass density [Msun/kpc^3]
r.v_circ([1, 2, 5, 10])         # rotation curve at those radii [km/s]
r.scale_height([1, 5, 10])      # sech^2 scale height h_z(R) [kpc]
r.scale_height_samples([1, 5])  # posterior draws -> uncertainty bands
r.face_on, r.edge_on            # column-mass arrays (R, phi) and (R, z)
r.save("out/")                  # density.npz + rotation_curve.csv + deprojection.png

# Dynamics-ready derivative: retain m=0,2,4 and taper the bar to an
# axisymmetric outer density between 6 and 10 kpc.
dyn = r.bisymmetrize_for_dynamics(inner_radius_kpc=6, outer_radius_kpc=10)
dyn.save("out/dynamical/")
dyn.potential([1, 2, 5, 10], [0, 0, 0, 0])  # optional AGAMA potential
```

CLI:

```bash
dgdp-deproject galaxy.fits --distance-mpc 15.2 --inclination-deg 30 --pa-onsky-deg 153 \
    --ml 1.0 --stellar-mass 6e10 -o out/

# Also write out/dynamical/{density.npz,rotation_curve.csv,potential.npz,postprocess.npz}.
dgdp-deproject galaxy.fits --distance-mpc 15.2 --inclination-deg 30 --pa-onsky-deg 153 \
    --ml 1.0 --stellar-mass 6e10 --dynamical-output 6 10 --potential -o out/
```

The native density remains the image-reprojection-consistent inference. The optional
``dynamical/`` product is a non-negative, exactly bisymmetric 3-D derivative: it removes
all modes except ``m=0,2,4``, conserves the azimuthally averaged ``(R,z)`` mass, and tapers
``m=2,4`` to zero over the requested radial interval. Its projected image is therefore a
diagnostic rather than an exact reproduction of clumpy input structure.

Three or four radial thickness controls can explore alternatives to the learned
vertical structure. Inspect `r.photometric_profiles()` and the image to choose
control locations; the fourth control can separate the inner and outer bar.

```python
# Illustrative NGC1512 locations [kpc] and thickness multipliers, not fitted values.
trial = r.with_thickness([0.6, 4.0, 11.0], [0.6, 0.8, 1.0], reproject_iters=3)
# Add sample_index=0 to start from a stored posterior draw instead of the mean.
trial.reproj                # numerical reprojection diagnostics for this variant
trial.save("out/thickness_trial/")
```

Controls blend smoothly with radius, affect whole annuli, conserve ring mass at
fixed surface-density anchors, and survive `regrid()`. Each variant refits its
anchors independently and preserves total mass. These are sensitivity models;
the existing loop provides no PSF-aware noise likelihood or automatic acceptance
criterion. See the [worked example and limits](docs/reports/2026-09-29-radial-thickness-controls.md).

For three controls, the MCMC parameters can be inclination plus central, bar,
and outer-disk thickness factors. At illustrative radii 0.6, 4, and 11 kpc,
factors `(1, 1, 1)` retain the learned kernels; a factor of `0.5` halves their
heights near its control radius. The central label is an NSD-region proxy.

![Four NGC1512 thickness examples: face-on, edge-on, and radial RMS heights](https://raw.githubusercontent.com/lucyundead/disk-galaxy-deprojection/v0.5.0/docs/figures/ngc1512_four_thickness_cases.png)

The four columns hold inclination at 42 degrees and halve one factor at a time.
Each model has its own image-correction loop; the thinner outer-disk case retains
a larger image discrepancy. See the [comparison and numerical checks](docs/reports/2026-09-29-four-thickness-cases.md).

### Repeated inclination and thickness trials

Install the optional SciPy backend with `pip install 'disk-galaxy-deprojection[fast]'`.
Prepare the fixed
sky image and load the network once; each trial still remaps the image, predicts
the vertical profiles at its inclination, and rebuilds its projection coordinates.

```python
from importlib.resources import files
from dgdp import deproject, prepare_image
from dgdp.model import DeprojectionModel

image = prepare_image("galaxy.fits", distance_mpc=15.2, pa_onsky_deg=153)
model = DeprojectionModel.load(str(files("dgdp.models").joinpath("dgdp_fixed_dict.npz")))

def density_trial(inclination_deg, central_scale, bar_scale, outer_scale):
    base = deproject(image, distance_mpc=15.2, inclination_deg=inclination_deg,
                     stellar_mass=6e10, model=model, reproject_iters=0,
                     grid_overrides={"n_z": 128})
    return base.with_thickness(
        [0.6, 4.0, 11.0],  # illustrative control radii; choose from this galaxy's image
        [central_scale, bar_scale, outer_scale], reproject_iters=2,
        projection_backend="scipy", projection_workers=4)
```

`prepare_image` fixes the sky PA, centre, distance, pixel scale, and masks; prepare
a new image when these change. The SciPy backend retains the same LOS samples and
trilinear interpolation as the default NumPy backend. Worker threads prepare
coordinates and interpolate independent samples; vertical profiles are evaluated
once per proposal and reused during the correction loop. For concurrent chains,
budget CPU workers across chains to avoid oversubscription. These controls retain
the scientific interpretation and reprojection limits described above.

- **Geometry:** pass `pix_arcsec` + `pa_pix_deg` (+ `center`) to bypass WCS (e.g. an S4G
  cutout), or let a FITS WCS supply the pixel scale for an on-sky `pa_onsky_deg`.
- **Mass scale:** the deprojected *shape* is M/L-independent; M/L only sets the v_c
  amplitude. Fix the absolute scale with `stellar_mass` (total M\*), `luminosity` × `ml`,
  or `zeropoint` + `band_solar_mag` + distance; with none, outputs use a relative scale.

---

Developer docs — project handoff, milestone reports, and the cluster/TNG50 ingestion
workflow — live under [`docs/`](docs/) (full original README: [`docs/README-full.md`](docs/README-full.md)).
