Skip to content

Commit aa02375

Browse files
authored
Merge pull request #870 from PyAutoLabs/feature/substructure-halo-arrays-overflow
fix: galaxies_to_halo_arrays raises on max_n overflow, accepts max_n=None
2 parents e621014 + efc9673 commit aa02375

2 files changed

Lines changed: 222 additions & 10 deletions

File tree

‎autolens/lens/substructure_util.py‎

Lines changed: 115 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -99,12 +99,90 @@ def precompute_scaling_matrix(plane_redshifts, cosmology=None):
9999
return jnp.array(mat)
100100

101101

102+
def _plane_index_of_halos(galaxies, plane_redshifts, profile_cls):
103+
"""
104+
Return, for each halo of type ``profile_cls`` that sits on one of ``plane_redshifts``,
105+
the index of its plane, in the order the halos appear in ``galaxies``.
106+
"""
107+
z_to_plane = {round(float(z), 8): i for i, z in enumerate(plane_redshifts)}
108+
109+
plane_indexes = []
110+
for g in galaxies:
111+
plane_i = z_to_plane.get(round(float(g.redshift), 8))
112+
if plane_i is None or hasattr(g, "mass_sheet"):
113+
continue
114+
if hasattr(g, "mass") and isinstance(g.mass, profile_cls):
115+
plane_indexes.append(plane_i)
116+
117+
return plane_indexes
118+
119+
120+
def halo_counts_per_plane_from(galaxies, plane_redshifts, profile_cls):
121+
"""
122+
The number of halos of type ``profile_cls`` on each plane of ``plane_redshifts``.
123+
124+
The largest entry is the smallest ``max_n`` that ``galaxies_to_halo_arrays`` accepts for
125+
these galaxies.
126+
"""
127+
counts = np.zeros(len(plane_redshifts), dtype=int)
128+
for plane_i in _plane_index_of_halos(galaxies, plane_redshifts, profile_cls):
129+
counts[plane_i] += 1
130+
return counts
131+
132+
133+
def _check_max_n(counts, plane_redshifts, max_n):
134+
overflowing = [
135+
f"plane {i} (z={float(plane_redshifts[i]):.4f}) holds {int(count)} halos"
136+
for i, count in enumerate(counts)
137+
if count > max_n
138+
]
139+
if overflowing:
140+
raise ValueError(
141+
f"max_n={max_n} is too small: "
142+
+ "; ".join(overflowing)
143+
+ f". Pass max_n={int(max(counts))} or more, or max_n=None to size the arrays "
144+
"to the fullest plane. Halos beyond max_n would be dropped while the "
145+
"negative-convergence sheets still remove their mass."
146+
)
147+
148+
102149
def galaxies_to_halo_arrays(galaxies, plane_redshifts, max_n, profile_cls):
150+
"""
151+
Pack the halos in ``galaxies`` into padded, fixed-shape arrays for the JAX ray-tracing scan.
152+
153+
Parameters
154+
----------
155+
galaxies
156+
The halo galaxies (mass profiles of type ``profile_cls``) and the sheet galaxies or
157+
fields (with a ``mass_sheet``) of one line of sight.
158+
plane_redshifts
159+
The redshift of every plane; galaxies at any other redshift are ignored.
160+
max_n
161+
The number of halo slots per plane. A plane holding more halos than this raises a
162+
``ValueError`` naming the plane and the ``max_n`` needed, because dropping halos while
163+
keeping the sheets that compensate for their mass would break mass conservation.
164+
``None`` sizes the arrays to the fullest plane.
165+
profile_cls
166+
The halo mass profile class, which sets which parameters are packed.
167+
168+
Returns
169+
-------
170+
The halo parameters ``(n_planes, max_n, n_params)``, the slot mask ``(n_planes, max_n)``
171+
and the sheet convergence of each plane ``(n_planes,)``.
172+
"""
103173
import jax.numpy as jnp
104174

105175
n_planes = len(plane_redshifts)
106176
n_params, extract = _halo_parameter_extractor_from(profile_cls=profile_cls)
107177

178+
counts = halo_counts_per_plane_from(
179+
galaxies=galaxies, plane_redshifts=plane_redshifts, profile_cls=profile_cls
180+
)
181+
if max_n is None:
182+
max_n = max(int(counts.max(initial=0)), 1)
183+
else:
184+
_check_max_n(counts=counts, plane_redshifts=plane_redshifts, max_n=max_n)
185+
108186
params = np.zeros((n_planes, max_n, n_params))
109187
mask = np.zeros((n_planes, max_n), dtype=bool)
110188
sheet_kappas = np.zeros(n_planes)
@@ -123,9 +201,8 @@ def galaxies_to_halo_arrays(galaxies, plane_redshifts, max_n, profile_cls):
123201
sheet_kappas[plane_i] = float(g.mass_sheet.kappa)
124202
elif hasattr(g, "mass") and isinstance(g.mass, profile_cls):
125203
slot = int(mask[plane_i].sum())
126-
if slot < max_n:
127-
params[plane_i, slot] = extract(g.mass)
128-
mask[plane_i, slot] = True
204+
params[plane_i, slot] = extract(g.mass)
205+
mask[plane_i, slot] = True
129206

130207
return jnp.array(params), jnp.array(mask), jnp.array(sheet_kappas)
131208

@@ -248,19 +325,47 @@ def los_realizations_to_arrays(
248325
max_n,
249326
profile_cls,
250327
):
328+
"""
329+
Run ``galaxies_to_halo_arrays`` on every line of sight in ``realization_galaxies`` and stack
330+
the results along a leading batch axis.
331+
332+
``max_n=None`` sizes the arrays to the fullest plane across the whole batch, so every
333+
realisation shares one shape. An integer ``max_n`` that any plane of any realisation
334+
overflows raises a ``ValueError``.
335+
"""
251336
import jax.numpy as jnp
252337

338+
if max_n is None:
339+
max_n = max(
340+
[
341+
int(
342+
halo_counts_per_plane_from(
343+
galaxies=galaxies,
344+
plane_redshifts=plane_redshifts,
345+
profile_cls=profile_cls,
346+
).max(initial=0)
347+
)
348+
for galaxies in realization_galaxies
349+
]
350+
+ [1]
351+
)
352+
253353
all_params = []
254354
all_masks = []
255355
all_kappas = []
256356

257-
for galaxies in realization_galaxies:
258-
params, mask, kappas = galaxies_to_halo_arrays(
259-
galaxies=galaxies,
260-
plane_redshifts=plane_redshifts,
261-
max_n=max_n,
262-
profile_cls=profile_cls,
263-
)
357+
for realization_i, galaxies in enumerate(realization_galaxies):
358+
try:
359+
params, mask, kappas = galaxies_to_halo_arrays(
360+
galaxies=galaxies,
361+
plane_redshifts=plane_redshifts,
362+
max_n=max_n,
363+
profile_cls=profile_cls,
364+
)
365+
except ValueError as error:
366+
if "max_n=" not in str(error):
367+
raise
368+
raise ValueError(f"Realisation {realization_i}: {error}") from error
264369
all_params.append(params)
265370
all_masks.append(mask)
266371
all_kappas.append(kappas)

‎test_autolens/lens/test_substructure_util.py‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,3 +130,110 @@ def test__galaxies_to_halo_arrays__packs_yang_profile_parameters():
130130
]
131131
),
132132
)
133+
134+
135+
def _nfw_truncated_halos_on_plane(redshift, total):
136+
return [
137+
al.Galaxy(
138+
redshift=redshift,
139+
mass=al.mp.NFWTruncatedSph(
140+
centre=(0.01 * i, 0.0),
141+
kappa_s=0.01,
142+
scale_radius=1.0,
143+
truncation_radius=2.0,
144+
),
145+
)
146+
for i in range(total)
147+
]
148+
149+
150+
@requires_jax
151+
def test__galaxies_to_halo_arrays__raises_when_a_plane_overflows_max_n():
152+
galaxies = (
153+
_nfw_truncated_halos_on_plane(redshift=0.3, total=2)
154+
+ _nfw_truncated_halos_on_plane(redshift=0.7, total=5)
155+
+ [al.Galaxy(redshift=0.7, mass_sheet=al.mp.MassSheet(kappa=-0.01))]
156+
)
157+
158+
with pytest.raises(ValueError) as error:
159+
substructure_util.galaxies_to_halo_arrays(
160+
galaxies=galaxies,
161+
plane_redshifts=[0.3, 0.7],
162+
max_n=3,
163+
profile_cls=al.mp.NFWTruncatedSph,
164+
)
165+
166+
message = str(error.value)
167+
assert "plane 1 (z=0.7000) holds 5 halos" in message
168+
assert "plane 0" not in message
169+
assert "max_n=5" in message
170+
171+
172+
@requires_jax
173+
def test__galaxies_to_halo_arrays__max_n_none_sizes_to_fullest_plane_and_keeps_every_halo():
174+
galaxies = (
175+
_nfw_truncated_halos_on_plane(redshift=0.3, total=2)
176+
+ _nfw_truncated_halos_on_plane(redshift=0.7, total=5)
177+
+ [al.Galaxy(redshift=0.7, mass_sheet=al.mp.MassSheet(kappa=-0.01))]
178+
)
179+
180+
params, mask, sheet_kappas = substructure_util.galaxies_to_halo_arrays(
181+
galaxies=galaxies,
182+
plane_redshifts=[0.3, 0.7],
183+
max_n=None,
184+
profile_cls=al.mp.NFWTruncatedSph,
185+
)
186+
187+
assert params.shape[:2] == (2, 5)
188+
assert mask.sum(axis=1).tolist() == [2, 5]
189+
assert int(mask.sum()) == 7
190+
np.testing.assert_allclose(
191+
np.asarray(params[1, :, 0]), [0.0, 0.01, 0.02, 0.03, 0.04]
192+
)
193+
assert sheet_kappas.tolist() == [0.0, -0.01]
194+
195+
196+
@requires_jax
197+
def test__galaxies_to_halo_arrays__exact_max_n_is_accepted():
198+
params, mask, _ = substructure_util.galaxies_to_halo_arrays(
199+
galaxies=_nfw_truncated_halos_on_plane(redshift=0.7, total=3),
200+
plane_redshifts=[0.7],
201+
max_n=3,
202+
profile_cls=al.mp.NFWTruncatedSph,
203+
)
204+
205+
assert mask.tolist() == [[True, True, True]]
206+
207+
208+
@requires_jax
209+
def test__los_realizations_to_arrays__max_n_none_sizes_to_fullest_plane_across_batch():
210+
realization_galaxies = [
211+
_nfw_truncated_halos_on_plane(redshift=0.7, total=2),
212+
_nfw_truncated_halos_on_plane(redshift=0.3, total=4),
213+
]
214+
215+
params, mask, _ = substructure_util.los_realizations_to_arrays(
216+
realization_galaxies=realization_galaxies,
217+
plane_redshifts=[0.3, 0.7],
218+
max_n=None,
219+
profile_cls=al.mp.NFWTruncatedSph,
220+
)
221+
222+
assert params.shape[:3] == (2, 2, 4)
223+
assert mask.sum(axis=(1, 2)).tolist() == [2, 4]
224+
225+
226+
@requires_jax
227+
def test__los_realizations_to_arrays__overflow_names_the_realisation():
228+
realization_galaxies = [
229+
_nfw_truncated_halos_on_plane(redshift=0.7, total=2),
230+
_nfw_truncated_halos_on_plane(redshift=0.3, total=4),
231+
]
232+
233+
with pytest.raises(ValueError, match=r"Realisation 1: .*plane 0 \(z=0.3000\) holds 4 halos"):
234+
substructure_util.los_realizations_to_arrays(
235+
realization_galaxies=realization_galaxies,
236+
plane_redshifts=[0.3, 0.7],
237+
max_n=3,
238+
profile_cls=al.mp.NFWTruncatedSph,
239+
)

0 commit comments

Comments
 (0)