Skip to content

feat: LensTool-native dPIE parameterization (from_lenstool) + parity validation #485

Closed

Description

@Jammy2211

Overview

dPIEMass / dPIEMassSph are direct ports of LensTool's C code but are parameterized as (ra, rs, b0) in arcsec, while LensTool users think in (σ_LT [km/s], r_core, r_cut) as read out of .par files and papers. This task adds a LensTool-facing constructor with a verified parameter conversion, unit-tested conversion math, and a cross-implementation parity script — the foundation for the flagship "PyAutoLens for LensTool users" cluster example (PyAutoMind docs/cluster/8_lenstool_users_example.md).

Autonomy: supervised --auto (launched 2026-07-08, no heart-ack). Judgment gates are batched as issue questions; run checkpoints here.

Plan

  • Verify LensTool's exact input conventions against the public LensTool source (piemd/ci05 routines): the σ prefactor (6π fiducial vs 4π central), the .par ellipticite definition and its internal conversion to the Kassiola & Kovner ε, the position-angle convention, and radius units (core_radius vs core_radius_kpc).
  • Add from_lenstool(...) classmethod constructors to dPIEMass and dPIEMassSph converting (σ_LT, r_core, r_cut, ellipticity, angle, z_lens, z_source, cosmology) → (b0, ra, rs, ell_comps).
  • Unit-test the conversion math (numpy-only): sqrt(3/2) σ relation, limiting-case b0 = θ_E (ra→0, rs→∞, q=1), analytic M(R) anchor from Bergamini et al. 2019 App. C.
  • Add a numerical parity script in autolens_workspace_test/scripts/cluster/ comparing convergence/deflection/potential against an independent dPIE implementation and published values.
  • Document any irreconcilable convention differences prominently (they bound how close the flagship example can get).
Detailed implementation plan

Affected Repositories

  • PyAutoGalaxy (primary — profile + unit tests)
  • PyAutoLens (docs autosummary mirror if API surface grows)
  • autolens_workspace_test (parity script; cross-package checks live here, never in library test dirs)

Branch Survey

Repository Current Branch Dirty?
./PyAutoGalaxy main clean (parallel claim psf-oversample-refactor touches only autogalaxy/operate/image.py — disjoint)
./PyAutoLens main clean
./autolens_workspace_test main dirty (pre-existing, other tasks; worktree branches from origin/main)

Suggested branch: feature/dpie-lenstool-param
Worktree: ~/Code/PyAutoLabs-wt/dpie-lenstool-param/

Implementation Steps

  1. Phase 1 — convention verification (research-first). Fetch the public LensTool source (git-cral.univ-lyon1.fr or GitHub mirror) and read the piemd / ci05 / scaling routines to pin down: (a) exact b0 normalization from v_disp (expected: E0 = 6π (σ_LT/c)² D_LS/D_S with σ_LT = Elíasdóttir's σ_dPIE; b0 = E0·(rs²−ra²)/rs² per the existing docstring chain, equivalently b0 = 4π (σ_0/c)²·D_LS/D_S·(rs²−ra²)/rs² with σ_0 = √(3/2)·σ_LT); (b) whether .par ellipticite is (a²−b²)/(a²+b²) and where LensTool converts it to the KK93 ε = (a−b)/(a+b) that ci05 consumes (the PyAutoGalaxy port's _ellip() uses |ell_comps| = (1−q)/(1+q) directly as eps — dual_pseudo_isothermal_mass.py:458); (c) position-angle zero-point and rotation direction vs PyAuto's phi (counter-clockwise from positive x? vs from north); (d) core_radius/cut_radius arcsec vs _kpc variants. Record findings in the docstring and on this issue.
  2. Phase 2 — converter. dPIEMass.from_lenstool(centre, ellipticity, angle, sigma, r_core, r_cut, redshift_object, redshift_source, cosmology=ag.cosmo.Planck15()) classmethod: ellipticity → axis-ratio q = √((1−e)/(1+e)) → ell_comps via the existing convert helpers; σ_LT → b0 via the verified prefactor and D_LS/D_S from the cosmology object; kpc-variant support via kwargs or a documented pre-conversion. dPIEMassSph.from_lenstool(...) without ellipticity/angle. Docstring must loudly document the √(3/2) fiducial-vs-central σ trap and cite Elíasdóttir et al. 2007 App. A / Bergamini et al. 2019.
  3. Phase 3 — unit tests in test_autogalaxy/profiles/mass/total/test_dual_pseudo_isothermal_mass.py: conversion round-trips, limiting cases (ra→0, rs→∞, e=0 recovers isothermal θ_E = 4π σ_0²/c² D_LS/D_S), M(R) analytic anchor, ellipticity/angle mapping vs a directly-constructed profile. Numpy-only (no JAX in unit tests).
  4. Phase 4 — parity script autolens_workspace_test/scripts/cluster/lenstool_parity.py: convergence/potential/deflection grids from a from_lenstool-constructed profile vs an independent implementation (e.g. lenstronomy's dPIE/PJaffe) and/or published LensTool model values; report max fractional deviations; assert tolerances.
  5. Phase 5 — docs: autosummary entries (PyAutoGalaxy + PyAutoLens mirror if needed).

Key Files

  • PyAutoGalaxy/autogalaxy/profiles/mass/total/dual_pseudo_isothermal_mass.py — dPIEMass/dPIEMassSph, _ellip(), existing docstring conversion chain
  • PyAutoGalaxy/autogalaxy/profiles/mass/total/dual_pseudo_isothermal_potential.py — potential-parameterized sibling (out of scope unless conventions force it in)
  • PyAutoGalaxy/test_autogalaxy/profiles/mass/total/test_dual_pseudo_isothermal_mass.py — unit tests
  • autolens_workspace_test/scripts/cluster/lenstool_parity.py — new parity script

Open questions (batched — answer at leisure; run proceeds on the recommended default)

  1. Constructor vs wrapper class: from_lenstool classmethod (recommended, no new model-space class) suffices for constructing instances, but users wanting to fit directly in LensTool parameters (priors on σ_LT/r_cut) would need a dPIEMassLensTool profile class whose init takes LensTool params. Default: classmethod now; wrapper class deferred until the flagship example (task 8) demonstrates the need.
  2. Cosmology default: Planck15 (PyAuto default) vs LensTool's typical default (ΩM=0.3, ΩΛ=0.7, h=0.7). Default: PyAuto's Planck15, with the cosmology argument documented as the knob for exact LensTool comparison.

Original Prompt

Click to expand starting prompt

$(cat PyAutoMind/feature/cluster/6_dpie_lenstool_parameterization.md)

Activity

  1. Jammy2211 commented on Jul 8, 2026

    @Jammy2211
    CollaboratorAuthor

    Routing note (supervised --auto): proceeding in a parallel worktree despite the task-level PyAutoGalaxy claim by psf-oversample-refactor — that task is awaiting-merge with a frozen diff touching only autogalaxy/operate/image.py, disjoint from the dPIE files. Disjointness will be re-verified at ship sign-off. Flag here if you'd rather this parks until psf-oversample-refactor merges.

  2. Jammy2211 commented on Jul 8, 2026

    @Jammy2211
    CollaboratorAuthor

    Phase 1 complete — conventions verified against LensTool source (git-cral.univ-lyon1.fr/lenstool/lenstool, shallow clone):

    1. b0 normalization (set_potfile.c:430, bayesapp.c:447): b0 = 6·pia_c2·σ² with pia_c2 = 648000/c² (c in km/s; constant.h:14) — i.e. 6π(σ_LT/c)² in arcsec, for the fiducial σ_LT. SIS types use 4·pia_c2. LensTool's stored b0 does not include D_LS/D_S — e_grad.c:23 ('multiply by dlsds to obtain the true gradient'). PyAutoGalaxy's b0 is fully normalized, so: b0_pyauto = 6π(σ_LT/c)²·(D_LS/D_S) [arcsec]. Cross-check: σ₀ = √(3/2)σ_LT (Bergamini+19) gives 4π(σ₀/c)²·D_LS/D_S = 6π(σ_LT/c)²·D_LS/D_S ✓ (matches existing docstring). No (rs²−ra²)/rs² factor in LensTool's b0 (that belongs to Elíasdóttir's E0 definition only).
    2. Ellipticity (set_lens.c:103-109): .par input is emass = (a²−b²)/(a²+b²); LensTool converts internally to epot = (1−√(1−emass²))/emass = (1−q)/(1+q), and e_grad.c case(81) passes epot to ci05f — identical call structure to the PyAutoGalaxy port, whose _ellip() = |ell_comps| = (1−q)/(1+q) already. Converter maps emass → q = √((1−e)/(1+e)) → ell_comps.
    3. Radii: rc/rcut in arcsec ↔ ra/rs one-to-one (kpc variants via cosmology kpc-per-arcsec).
    4. Angle: LensTool angle_pos is degrees counter-clockwise from the x-axis in its tangent plane; sign flips only matter at real-data WCS ingestion (documented, not converted).

    Proceeding to Phase 2 (from_lenstool constructors).

  3. Jammy2211 commented on Jul 8, 2026

    @Jammy2211
    CollaboratorAuthor

    Phases 2–4 complete. Implementation summary:

    • dPIEMass.from_lenstool(...) + dPIEMassSph.from_lenstool(...) classmethods: (σ_LT, emass, angle, r_core, r_cut, z_l, z_s, cosmology) → (b0, ell_comps, ra, rs), with the √(3/2) fiducial-vs-central σ trap documented loudly in the docstrings.
    • _ellip() now min-clamps at 1e-5 (both PIEMass and dPIEMass): the ci05 integral is degenerate (NaN) at exactly zero ellipticity — Lenstool clamps identically at setup (set_lens.c). This also fixes a pre-existing NaN trap for directly-constructed ell_comps=(0,0) dPIE profiles.
    • Found and fixed en route: dPIEMass.potential_2d_from was an MGE approximation that disagreed with the ci05f deflections by 6–15% (growing with radius) for elliptical profiles — the MGE reconstructs a different elliptical geometry than the Kassiola-Kovner pseudo-elliptical mass model (spherical limit agreed to 1e-5, so the MGE machinery itself is fine). Replaced with the analytic KK93 I0.5 potential ported from Lenstool's pi05 (e_pcpx.c) / e_pot.c case 81: ψ = b0·rs/(rs−ra)·(pi05(ra) − pi05(rs)). Finite-difference ∇ψ now matches deflections to 1.7e-8 (was 0.15).
    • Unit tests: 8 new (conversion math, sqrt(3/2) cross-check via cosmology.velocity_dispersion_from, emass→epot vs Lenstool's own formula, angle/radii mapping, sph↔elliptical consistency, isothermal-limit b0=θ_E, potential-gradient consistency ×2). File now 13/13 green.
    • Parity script autolens_workspace_test/scripts/cluster/lenstool_parity.py: 6 legs, all passing at 1e-7–1e-10 (conversion parity, deflection-vs-convergence quadrature, analytic aperture-mass anchor, ∇ψ vs deflections, Hessian vs FD, original Lenstool reference values re-derived through the conversion layer). Includes a recipe for regenerating true Lenstool references with a .par file for anyone with a Lenstool build.
    • One documented convention note: analytical_hessian_2d_from evaluates in the profile frame (no transform decorator) — components match world-frame derivatives only at angle=0; det (magnification) is rotation-invariant so downstream use is unaffected.

    Full PyAutoGalaxy suite running now; ship gate next.

  4. Jammy2211 commented on Jul 8, 2026

    @Jammy2211
    CollaboratorAuthor

    Parked at ship sign-off (supervised --auto checkpoint). Implementation is complete and validated in the worktree (~/Code/PyAutoLabs-wt/dpie-lenstool-param, uncommitted); nothing is pushed until you sign off here.

    Test evidence

    • PyAutoGalaxy full suite: 952 passed (worktree)
    • Downstream PyAutoLens suite against worktree PyAutoGalaxy: 336 passed
    • test_dual_pseudo_isothermal_mass.py: 13/13 (8 new)
    • lenstool_parity.py: 6/6 legs, agreement 1e-7 to 1e-10

    API Changes (review surface)

    • Added: dPIEMass.from_lenstool(...), dPIEMassSph.from_lenstool(...) classmethods (additive).
    • Behaviour changed: dPIEMass.potential_2d_from — MGE approximation replaced by the analytic Lenstool pi05 port. The old values were up to 15% wrong for elliptical profiles; new values are consistent with deflections to 1e-8. Any downstream consumer of dPIE potentials (time delays) gets different — correct — numbers.
    • Behaviour changed (edge): PIEMass._ellip / dPIEMass._ellip now min-clamp at 1e-5 (Lenstool-identical): ell_comps=(0,0) elliptical profiles previously returned NaN deflections, now return the tiny-ellipticity limit.

    Scripts Changed

    • New: autolens_workspace_test/scripts/cluster/lenstool_parity.py (separate PR on autolens_workspace_test, library-first merge order).

    Heart YELLOW at ship (needs acknowledgement to proceed)

    1. TEST RUN NOT ready — 613p/5f/71s with 58 stale parked scripts (pre-existing, tracked)
    2. VERSION SKEW — autolens_assistant pinned 2026.5.29.4 vs installed 2026.7.6.649 (known)
    3. WORKTREE DRIFT — dirty states belong to other parked tasks' worktrees

    Batched judgment questions (defaults proceed unless overridden)

    1. Classmethod vs dPIEMassLensTool wrapper class for fitting in Lenstool parameters → default: classmethod now, wrapper deferred to flagship-example need.
    2. Cosmology default Planck15 vs Lenstool-typical (0.3/0.7/h=0.7) → default: Planck15, documented knob.

    Reply 'ship it' (optionally with heart-ack) and the run resumes: commit → push → PRs (PyAutoGalaxy + autolens_workspace_test) → back here for merge offer.

  5. Jammy2211 commented on Jul 8, 2026

    @Jammy2211
    CollaboratorAuthor

    Shipped to PR-open (in-session ship authorization + wrapper-class rework).

    PRs (merge order: library first):

    1. feat: Lenstool-native dPIE parameterization (from_lenstool + dPIEMassLenstool) and analytic potential #487 — from_lenstool constructors, dPIEMassLenstool/Sph wrapper profiles (model-fitting in Lenstool parameters, per user directive), analytic pi05 potential, _ellip min-clamp. pending-release ✓
    2. docs: add dPIEMassLenstool / dPIEMassLenstoolSph to mass API autosummary PyAutoLens#576 — docs autosummary mirror. pending-release ✓
    3. test: Lenstool dPIE parity script (6 numerical legs) autolens_workspace_test#151 — 6-leg parity script (after feat: Lenstool-native dPIE parameterization (from_lenstool + dPIEMassLenstool) and analytic potential #487). pending-release ✓

    Gate record: tests PyAutoGalaxy 956 pass + downstream PyAutoLens 336 pass · smoke: guides/profiles/mass.py (maintained dPIE consumer) passes against the branch; cluster/start_here.py/modeling.py time out at 500s identically on canonical main (exit 124 control run) — pre-existing, consistent with their no_run.yaml parking ('test mode breaks it'); not caused by this change · review surface CLEAN (deletions = the two _ellip returns + MGE potential body, all intentional) · Heart YELLOW acked in-session (stale-parked scripts / autolens_assistant version skew / other tasks' worktree drift).

    Workspace impact: API changes are Added + two behaviour corrections. No workspace script consumes potential_2d_from on dPIE or |ell_comps|<1e-5 dPIE profiles (grep clean), so no migration needed — recommendation (i): the new-demos follow-up is the flagship 'PyAutoLens for Lenstool users' example (PyAutoMind docs/cluster/8_lenstool_users_example.md), which the wrapper classes were built for.

    Follow-up noted: the cluster start_here/modeling TEST_MODE slowness (>500s, no_run-parked) predates this task and intersects the point-solver work queued in feature/cluster/10_solver_over_under_prediction.md.

    Merge stays with you (both this and the two companions).

  6. Jammy2211 commented on Jul 9, 2026

    @Jammy2211
    CollaboratorAuthor

    All three PRs merged (PyAutoGalaxy#487, PyAutoLens#576, autolens_workspace_test#151). Lenstool-native dPIE construction + fitting is live on main; the 6-leg parity script guards the conventions. Closing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions