Coverage for tests/test_mask.py: 96%
493 statements
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-26 20:37 +0000
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-26 20:37 +0000
1# This file is part of lsst-images.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# Use of this source code is governed by a 3-clause BSD-style
10# license that can be found in the LICENSE file.
12from __future__ import annotations
14import dataclasses
15import os
16from typing import Any
18import astropy.io.fits
19import numpy as np
20import pytest
22import lsst.utils.tests
23from lsst.images import (
24 Box,
25 Mask,
26 MaskPlane,
27 MaskSchema,
28 NoOverlapError,
29 get_legacy_difference_image_mask_planes,
30 get_legacy_non_cell_coadd_mask_planes,
31 get_legacy_optional_mask_planes,
32 get_legacy_template_mask_planes,
33 get_legacy_visit_image_mask_planes,
34)
35from lsst.images._mask import _guess_legacy_plane_map
36from lsst.images.describe import Report
37from lsst.images.tests import ( # noqa: F401
38 RoundtripFits,
39 assert_masks_equal,
40 compare_mask_to_legacy,
41 reset_afw_mask_planes,
42)
44try:
45 from lsst.afw.image import MaskedImageReader as LegacyMaskedImageReader
47except ImportError:
48 type LegacyMaskedImageReader = Any # type: ignore[no-redef]
50EXTERNAL_DATA_DIR = os.environ.get("TESTDATA_IMAGES_DIR", None)
53@dataclasses.dataclass
54class _LegacyTestData:
55 mask: Mask
56 reader: LegacyMaskedImageReader
57 plane_map: dict[str, MaskPlane]
60@pytest.fixture
61def legacy_test_data(reset_afw_mask_planes: None) -> _LegacyTestData: # noqa: F811
62 """Return a Mask read directly from the legacy test dataset and a legacy
63 reader for that image.
65 Skips if TESTDATA_IMAGES_DIR is unset or lsst.afw.image is unavailable.
66 """
67 # reset_afw_mask_planes will have already skipped if afw is not available.
68 from lsst.afw.image import MaskedImageFitsReader
70 if EXTERNAL_DATA_DIR is None: 70 ↛ 72line 70 didn't jump to line 72 because the condition on line 70 was always true
71 pytest.skip("TESTDATA_IMAGES_DIR is not in the environment.")
72 filename = os.path.join(EXTERNAL_DATA_DIR, "dp2", "legacy", "visit_image.fits")
73 plane_map = get_legacy_visit_image_mask_planes()
74 mask = Mask.read_legacy(filename, ext=2, plane_map=plane_map)
75 reader = MaskedImageFitsReader(filename)
76 return _LegacyTestData(mask=mask, reader=reader, plane_map=plane_map)
79def make_mask_planes(rng: np.random.Generator, n_planes: int, n_placeholders: int) -> list[MaskPlane | None]:
80 """Return a shuffled list of MaskPlane objects with placeholder Nones."""
81 planes: list[MaskPlane | None] = []
82 for i in range(n_planes):
83 planes.append(MaskPlane(f"M{i}", f"D{i}"))
84 planes.extend([None] * n_placeholders)
85 rng.shuffle(planes)
86 return planes
89def test_schema() -> None:
90 """Test MaskSchema construction, accessors, and basic operations."""
91 rng = np.random.default_rng(500)
92 planes = make_mask_planes(rng, 17, 5)
93 with pytest.raises(TypeError):
94 MaskSchema.bits_per_element(np.float32)
95 assert MaskSchema.bits_per_element(np.uint8) == 8
96 schema = MaskSchema(planes, dtype=np.uint8)
97 assert list(schema) == planes
98 assert len(schema) == len(planes)
99 assert schema[5] == planes[5]
100 assert eval(repr(schema), {"dtype": np.dtype, "MaskSchema": MaskSchema, "MaskPlane": MaskPlane}) == schema
101 report = schema.describe()
102 plane_table = next(t for t in report.tables if t.title == "Mask planes")
103 assert len(plane_table.rows) == 17
104 assert ["M5" == row[3] for row in plane_table.rows].count(True) == 1
105 bit5 = schema.bit("M5")
106 assert schema == MaskSchema(planes, np.uint8)
107 assert schema != MaskSchema(planes, np.int16)
108 assert schema != MaskSchema(planes[:-1], np.uint8)
109 assert schema.dtype == np.dtype(np.uint8)
110 assert schema.mask_size == 3
111 assert schema.names == {f"M{i}" for i in range(17)}
112 assert schema.descriptions == {f"M{i}": f"D{i}" for i in range(17)}
113 bit7 = schema.bit("M7")
114 bitmask57 = schema.bitmask("M5", "M7")
115 assert bitmask57[bit5.index] & bit5.mask
116 assert bitmask57[bit7.index] & bit7.mask
117 bitmask57[bit5.index] &= ~bit5.mask
118 bitmask57[bit7.index] &= ~bit7.mask
119 assert not bitmask57.any()
120 splits = schema.split(np.int16)
121 assert len(splits) == 2
122 assert splits[0].mask_size == 1
123 assert splits[1].mask_size == 1
124 assert list(splits[0]) + list(splits[1]) == [p for p in planes if p is not None]
125 assert len(splits[0]) == 15
126 assert len(splits[1]) == 2
129def test_schema_describe() -> None:
130 """MaskSchema._describe yields a mask-plane table and eval-able repr."""
131 rng = np.random.default_rng(500)
132 planes = make_mask_planes(rng, 3, 0)
133 schema = MaskSchema(planes, dtype=np.uint8)
135 report = schema.describe()
136 assert isinstance(report, Report)
137 assert report.type_name == "MaskSchema"
139 tables = [t for t in report.tables if t.title == "Mask planes"]
140 assert len(tables) == 1
141 table = tables[0]
142 assert table.columns == ["Bit", "Index", "Mask", "Name", "Description"]
143 assert len(table.rows) == 3
144 # Names appear in the Name column (index 3).
145 assert {row[3] for row in table.rows} == {"M0", "M1", "M2"}
147 # repr is still eval-able and round-trips.
148 reconstructed = eval(repr(schema), {"dtype": np.dtype, "MaskSchema": MaskSchema, "MaskPlane": MaskPlane})
149 assert reconstructed == schema
152def test_schema_from_fits_header() -> None:
153 """Verify MaskSchema.from_fits_header inverts update_header."""
154 planes = [
155 MaskPlane("NO_DATA", "No data was available for this pixel."),
156 MaskPlane("COSMIC_RAY", "A cosmic ray affected this pixel."),
157 MaskPlane("DETECTED", "Pixel was part of a detected source."),
158 ]
159 schema = MaskSchema(planes, dtype=np.uint8)
160 header = astropy.io.fits.Header()
161 schema.update_header(header)
162 result = MaskSchema.from_fits_header(header)
163 assert result.dtype == np.dtype(np.uint8)
164 assert list(result) == planes
165 assert result == schema
168def test_schema_from_fits_header_preserves_gaps() -> None:
169 """Verify None placeholders are reconstructed from gaps in MSKN card
170 numbering.
171 """
172 planes: list[MaskPlane | None] = [MaskPlane("A", "a"), None, MaskPlane("B", "b")]
173 header = astropy.io.fits.Header()
174 MaskSchema(planes, dtype=np.uint8).update_header(header)
175 assert list(MaskSchema.from_fits_header(header)) == planes
178def test_schema_from_fits_header_requires_cards() -> None:
179 """Verify MaskSchema.from_fits_header raises ValueError on a header with
180 no MSKN cards.
181 """
182 with pytest.raises(ValueError, match="no MSKN cards"):
183 MaskSchema.from_fits_header(astropy.io.fits.Header())
186def test_interpret() -> None:
187 """Verify interpret returns correct plane names across a multi-byte
188 schema.
189 """
190 # 3 named planes padded with Nones to exceed 8 bits; A and B land in
191 # byte 0, C lands in byte 1.
192 planes: list[MaskPlane | None] = [
193 MaskPlane("A", "a"),
194 MaskPlane("B", "b"),
195 None,
196 None,
197 None,
198 None,
199 None,
200 None,
201 MaskPlane("C", "c"),
202 ]
203 schema = MaskSchema(planes, dtype=np.uint8)
204 assert schema.mask_size == 2
206 assert set(schema.interpret(schema.bitmask("A", "C"))) == {"A", "C"}
207 assert set(schema.interpret(schema.bitmask("B"))) == {"B"}
208 assert set(schema.interpret(np.zeros(schema.mask_size, dtype=schema.dtype))) == set()
209 assert set(schema.interpret(schema.bitmask("A", "B", "C"))) == {"A", "B", "C"}
212def test_basics() -> None:
213 """Test basic Mask construction, string representation, and error
214 conditions.
215 """
216 rng = np.random.default_rng(500)
217 planes = make_mask_planes(rng, 35, n_placeholders=5)
218 schema = MaskSchema(planes, dtype=np.uint8)
219 bbox = Box.factory[5:50, 6:60]
220 mask = Mask(
221 0,
222 schema=schema,
223 bbox=bbox,
224 metadata={"four_and_a_half": 4.5},
225 )
227 assert mask[...] is not mask
228 assert mask.__eq__(42) == NotImplemented
229 assert mask == mask
230 assert (
231 str(mask)
232 == "Mask([y=5:50, x=6:60], ['M34', 'M15', 'M29', 'M1', 'M20', 'M11', 'M13', 'M7', 'M17', 'M12', "
233 "'M31', 'M16', 'M2', 'M3', 'M8', 'M26', 'M22', 'M5', 'M18', 'M19', 'M24', 'M21', 'M27', 'M6', "
234 "'M28', 'M10', 'M4', 'M23', 'M0', 'M25', 'M9', 'M14', 'M33', 'M32', 'M30'])"
235 )
236 assert repr(mask).startswith(
237 "Mask(..., bbox=Box(y=Interval(start=5, stop=50), x=Interval(start=6, stop=60)), "
238 "schema=MaskSchema([MaskPlane(name='M34', description='D34')"
239 ), f"Repr: {mask!r}"
241 with pytest.raises(TypeError):
242 # No bbox, size or array.
243 Mask(0, schema=schema)
245 with pytest.raises(ValueError, match="Explicit bbox shape"):
246 # Box mismatch.
247 Mask(mask.array, schema=schema, bbox=Box.factory[0:20, -5:45])
249 with pytest.raises(ValueError, match="Explicit shape"):
250 # Shape mismatch.
251 Mask(mask.array, schema=schema, shape=(5, 10, 5))
253 with pytest.raises(ValueError, match="Mask array must be 3-d"):
254 # Cannot be 2-D.
255 Mask(mask.array.reshape((2430, 5)), schema=schema, bbox=Box.factory[0:20, -5:45])
258def test_read_write() -> None:
259 """Test explicit calls to Mask.read and Mask.write through FITS."""
260 rng = np.random.default_rng(500)
261 planes = make_mask_planes(rng, 35, n_placeholders=5)
262 schema = MaskSchema(planes, dtype=np.uint8)
263 bbox = Box.factory[5:50, 6:60]
264 mask = Mask(
265 0,
266 schema=schema,
267 bbox=bbox,
268 metadata={"four_and_a_half": 4.5},
269 )
270 with lsst.utils.tests.getTempFilePath(".fits") as tmpFile:
271 mask.write(tmpFile)
272 new = Mask.read(tmpFile)
273 assert new == mask
274 # __eq__ ignores metadata.
275 assert new.metadata["four_and_a_half"] == 4.5
276 assert new.metadata == mask.metadata
279def test_serialize_multi() -> None:
280 """Test serializing a mask with more than 31 mask planes (multiple
281 HDUs).
282 """
283 rng = np.random.default_rng(500)
284 planes = make_mask_planes(rng, 35, n_placeholders=5)
285 schema = MaskSchema(planes, dtype=np.uint8)
286 bbox = Box.factory[5:50, 6:60]
287 mask = Mask(0, schema=schema, bbox=bbox, metadata={"four_and_a_half": 4.5})
288 shape = bbox.shape
289 for plane in schema:
290 if plane is not None:
291 mask.set(plane.name, rng.random(shape) > 0.5)
292 with RoundtripFits(mask) as roundtrip:
293 fits = roundtrip.inspect()
294 assert fits[1].header["EXTNAME"] == "MASK"
295 assert fits[1].header.get("EXTVER", 1) == 1
296 assert fits[1].header["ZCMPTYPE"] == "GZIP_2"
297 assert fits[2].header["EXTNAME"] == "MASK"
298 assert fits[2].header["EXTVER"] == 2
299 assert fits[2].header["ZCMPTYPE"] == "GZIP_2"
300 n = 0
301 for plane in planes:
302 if plane is not None:
303 hdu = fits[1] if n < 31 else fits[2]
304 assert hdu.header[f"MSKN{(n % 31):04d}"] == plane.name
305 assert hdu.header[f"MSKM{(n % 31):04d}"] == 1 << (n % 31)
306 assert hdu.header[f"MSKD{(n % 31):04d}"] == plane.description
307 n += 1
308 assert_masks_equal(mask, roundtrip.result)
311def test_add_plane_returns_new_mask() -> None:
312 """Verify add_plane returns a new mask without modifying the original or
313 its views.
314 """
315 rng = np.random.default_rng(500)
316 planes = make_mask_planes(rng, 3, n_placeholders=0)
317 schema = MaskSchema(planes, dtype=np.uint8)
318 bbox = Box.factory[5:50, 6:60]
319 mask = Mask(0, schema=schema, bbox=bbox)
320 m0 = rng.random(bbox.shape) > 0.5
321 mask.set("M0", m0)
322 view = mask[bbox] # shares the array and old schema with mask
323 original_array = mask.array
325 new_mask = mask.add_plane("OUTSIDE_STENCIL", "Pixel lies outside the stencil.")
327 # The original mask and any views keep the old schema and array.
328 assert "OUTSIDE_STENCIL" not in mask.schema.names
329 assert "OUTSIDE_STENCIL" not in view.schema.names
330 assert mask.array is original_array
331 # The new mask reallocated a fresh array and carries the new plane.
332 assert new_mask.array is not original_array
333 assert "OUTSIDE_STENCIL" in new_mask.schema.names
334 assert new_mask.schema.descriptions["OUTSIDE_STENCIL"] == "Pixel lies outside the stencil."
335 # The new plane is the fourth (overall index 3) so it lives in byte 0.
336 bit = new_mask.schema.bit("OUTSIDE_STENCIL")
337 assert bit.index == 0
338 assert bit.mask == 1 << 3
339 assert new_mask.schema.mask_size == 1
340 # Existing plane data is preserved and the new plane starts all-False.
341 np.testing.assert_array_equal(new_mask.get("M0"), m0)
342 assert not new_mask.get("OUTSIDE_STENCIL").any()
345def test_add_plane_grows_byte() -> None:
346 """Verify adding a ninth plane crosses the 8-plane boundary into a
347 second byte.
348 """
349 rng = np.random.default_rng(500)
350 planes = make_mask_planes(rng, 8, n_placeholders=0)
351 schema = MaskSchema(planes, dtype=np.uint8)
352 bbox = Box.factory[5:50, 6:60]
353 mask = Mask(0, schema=schema, bbox=bbox)
354 set_planes = {}
355 for plane in planes:
356 assert plane is not None
357 boolean_mask = rng.random(bbox.shape) > 0.5
358 mask.set(plane.name, boolean_mask)
359 set_planes[plane.name] = boolean_mask
361 new_mask = mask.add_plane("OUTSIDE_STENCIL", "Pixel lies outside the stencil.")
363 # The original is unchanged; the new mask spills into a second byte.
364 assert mask.schema.mask_size == 1
365 bit = new_mask.schema.bit("OUTSIDE_STENCIL")
366 assert bit.index == 1
367 assert bit.mask == 1 << 0
368 assert new_mask.schema.mask_size == 2
369 assert new_mask.array.shape == bbox.shape + (2,)
370 assert not new_mask.get("OUTSIDE_STENCIL").any()
371 # Every pre-existing plane keeps its data.
372 for name, boolean_mask in set_planes.items():
373 np.testing.assert_array_equal(new_mask.get(name), boolean_mask)
376def test_add_planes_multiple() -> None:
377 """Verify add_planes adds several planes in a single call."""
378 rng = np.random.default_rng(500)
379 planes = make_mask_planes(rng, 3, n_placeholders=0)
380 bbox = Box.factory[0:4, 0:5]
381 mask = Mask(0, schema=MaskSchema(planes, dtype=np.uint8), bbox=bbox)
382 m0 = rng.random(bbox.shape) > 0.5
383 mask.set("M0", m0)
385 new_mask = mask.add_planes([MaskPlane("A", "plane a"), MaskPlane("B", "plane b")])
387 assert set(mask.schema.names) == {"M0", "M1", "M2"} # original unchanged
388 assert set(new_mask.schema.names) == {"M0", "M1", "M2", "A", "B"}
389 np.testing.assert_array_equal(new_mask.get("M0"), m0)
390 assert not new_mask.get("A").any()
391 assert not new_mask.get("B").any()
394def test_add_planes_drop_reassigns_bits() -> None:
395 """Verify dropping a plane compacts the schema and repacks pixel values."""
396 rng = np.random.default_rng(500)
397 bbox = Box.factory[0:4, 0:5]
398 schema = MaskSchema([MaskPlane("A", "a"), MaskPlane("B", "b"), MaskPlane("C", "c")], dtype=np.uint8)
399 mask = Mask(0, schema=schema, bbox=bbox)
400 a = rng.random(bbox.shape) > 0.5
401 c = rng.random(bbox.shape) > 0.5
402 mask.set("A", a)
403 mask.set("B", rng.random(bbox.shape) > 0.5)
404 mask.set("C", c)
406 new_mask = mask.add_planes([MaskPlane("D", "d")], drop=["B"])
408 # B is gone; D is appended after the retained planes.
409 assert list(new_mask.schema.names) == ["A", "C", "D"]
410 assert "B" not in new_mask.schema.names
411 # C moved down from bit 2 to bit 1; D takes bit 2.
412 assert new_mask.schema.bit("A").mask == 1 << 0
413 assert new_mask.schema.bit("C").mask == 1 << 1
414 assert new_mask.schema.bit("D").mask == 1 << 2
415 # Retained pixel values follow their planes; the new plane is cleared.
416 np.testing.assert_array_equal(new_mask.get("A"), a)
417 np.testing.assert_array_equal(new_mask.get("C"), c)
418 assert not new_mask.get("D").any()
421def test_add_planes_with_placeholder() -> None:
422 """Verify None placeholders reserve bits and survive add_planes and a
423 FITS round-trip.
424 """
425 rng = np.random.default_rng(500)
426 bbox = Box.factory[0:4, 0:5]
427 # Schema with a pre-existing placeholder reserving bit 1.
428 schema = MaskSchema([MaskPlane("A", "a"), None, MaskPlane("B", "b")], dtype=np.uint8)
429 mask = Mask(0, schema=schema, bbox=bbox)
430 a = rng.random(bbox.shape) > 0.5
431 b = rng.random(bbox.shape) > 0.5
432 mask.set("A", a)
433 mask.set("B", b)
435 # Append a block that itself contains an interior placeholder.
436 new_mask = mask.add_planes([MaskPlane("C", "c"), None, MaskPlane("D", "d")])
438 # The pre-existing placeholder stays at bit 1; the added placeholder
439 # stays between C and D (bit 4), not at the end.
440 assert list(new_mask.schema) == [
441 MaskPlane("A", "a"),
442 None,
443 MaskPlane("B", "b"),
444 MaskPlane("C", "c"),
445 None,
446 MaskPlane("D", "d"),
447 ]
448 assert new_mask.schema.bit("A").mask == 1 << 0
449 assert new_mask.schema.bit("B").mask == 1 << 2
450 assert new_mask.schema.bit("C").mask == 1 << 3
451 assert new_mask.schema.bit("D").mask == 1 << 5
452 # Retained pixel values follow their planes; new planes start cleared.
453 np.testing.assert_array_equal(new_mask.get("A"), a)
454 np.testing.assert_array_equal(new_mask.get("B"), b)
455 assert not new_mask.get("C").any()
456 assert not new_mask.get("D").any()
458 with RoundtripFits(new_mask) as roundtrip:
459 assert_masks_equal(new_mask, roundtrip.result)
462def test_add_planes_drop_unknown_raises() -> None:
463 """Verify dropping a non-existent plane raises ValueError."""
464 mask = Mask(0, schema=MaskSchema([MaskPlane("A", "a")], dtype=np.uint8), bbox=Box.factory[0:2, 0:2])
465 with pytest.raises(ValueError, match="Cannot drop mask planes"):
466 mask.add_planes([], drop=["NOPE"])
469def test_add_plane_duplicate_raises() -> None:
470 """Verify adding a plane whose name already exists raises ValueError."""
471 rng = np.random.default_rng(500)
472 planes = make_mask_planes(rng, 3, n_placeholders=0)
473 schema = MaskSchema(planes, dtype=np.uint8)
474 mask = Mask(0, schema=schema, bbox=Box.factory[0:4, 0:4])
475 with pytest.raises(ValueError, match="already exists"):
476 mask.add_plane("M0", "Duplicate of an existing plane.")
479def test_add_plane_roundtrip() -> None:
480 """Verify a runtime-added plane and its data survive a FITS round-trip."""
481 rng = np.random.default_rng(500)
482 planes = make_mask_planes(rng, 8, n_placeholders=0)
483 schema = MaskSchema(planes, dtype=np.uint8)
484 bbox = Box.factory[5:50, 6:60]
485 mask = Mask(0, schema=schema, bbox=bbox)
486 mask = mask.add_plane("OUTSIDE_STENCIL", "Pixel lies outside the stencil.")
487 mask.set("OUTSIDE_STENCIL", rng.random(bbox.shape) > 0.5)
488 with lsst.utils.tests.getTempFilePath(".fits") as tmpFile:
489 mask.write(tmpFile)
490 new = Mask.read(tmpFile)
491 assert new == mask
492 assert new.schema.descriptions["OUTSIDE_STENCIL"] == "Pixel lies outside the stencil."
493 assert_masks_equal(new, mask)
496def test_legacy_non_cell_coadd_plane_map() -> None:
497 """Verify the non-cell coadd map defines a distinct SENSOR_EDGE plane."""
498 plane_map = get_legacy_non_cell_coadd_mask_planes()
499 assert "SENSOR_EDGE" in plane_map
500 assert plane_map["SENSOR_EDGE"].name == "SENSOR_EDGE"
503def test_legacy_optional_plane_map() -> None:
504 """Verify the source injection planes are optional, and so belong to no
505 image's plane map.
506 """
507 optional = get_legacy_optional_mask_planes()
508 assert set(optional) == {
509 "INJECTED",
510 "INJECTED_CORE",
511 "INJECTED_TEMPLATE",
512 "INJECTED_CORE_TEMPLATE",
513 }
514 for old_name, plane in optional.items():
515 assert plane.name == old_name
516 for plane_map in (
517 get_legacy_visit_image_mask_planes(),
518 get_legacy_difference_image_mask_planes(),
519 get_legacy_non_cell_coadd_mask_planes(),
520 get_legacy_template_mask_planes(),
521 ):
522 assert not (plane_map.keys() & optional.keys())
525def test_from_legacy_adds_optional_planes_in_use(reset_afw_mask_planes: None) -> None: # noqa: F811
526 """Verify an optional plane joins the schema when the legacy mask has
527 pixels set in it, and costs nothing when it does not.
528 """
529 # reset_afw_mask_planes will have already skipped if afw is not available.
530 from lsst.afw.image import Mask as LegacyMask
532 legacy = LegacyMask(5, 4)
533 injected = np.arange(20).reshape(4, 5) < 3
534 for old_name in ("INJECTED", "INJECTED_CORE"):
535 legacy.addMaskPlane(old_name)
536 legacy.array[injected] |= legacy.getPlaneBitMask("INJECTED")
537 plane_map = get_legacy_visit_image_mask_planes()
539 mask = Mask.from_legacy(legacy, plane_map=plane_map)
541 assert "INJECTED" in mask.schema.names
542 np.testing.assert_array_equal(mask.get("INJECTED"), injected)
543 # INJECTED_CORE is defined but unused, so it takes up no bit.
544 assert "INJECTED_CORE" not in mask.schema.names
545 assert len(mask.schema) == len(plane_map) + 1
546 # The plane keeps its legacy name on the way back out.
547 round_tripped = mask.to_legacy(plane_map)
548 np.testing.assert_array_equal(
549 (round_tripped.array & round_tripped.getPlaneBitMask("INJECTED")).astype(bool), injected
550 )
553def test_legacy_template_plane_map() -> None:
554 """Verify the template map has the coadd planes and HIGH_VARIANCE."""
555 plane_map = get_legacy_template_mask_planes()
556 non_cell_coadd = get_legacy_non_cell_coadd_mask_planes()
557 assert non_cell_coadd.keys() < plane_map.keys()
558 assert plane_map["HIGH_VARIANCE"].name == "HIGH_VARIANCE"
561def test_guess_legacy_plane_map_coadd_discriminator() -> None:
562 """Verify INEXACT_PSF routes to a coadd map, SENSOR_EDGE discriminates
563 non-cell from cell, and HIGH_VARIANCE marks a template.
564 """
565 non_cell = _guess_legacy_plane_map({"INEXACT_PSF": 11, "SENSOR_EDGE": 14})
566 assert "SENSOR_EDGE" in non_cell
567 assert "HIGH_VARIANCE" not in non_cell
568 cell = _guess_legacy_plane_map({"INEXACT_PSF": 11})
569 assert "SENSOR_EDGE" not in cell
570 template = _guess_legacy_plane_map({"INEXACT_PSF": 11, "SENSOR_EDGE": 14, "HIGH_VARIANCE": 15})
571 assert "HIGH_VARIANCE" in template
574def test_to_legacy_keeps_unmapped_planes(reset_afw_mask_planes: None) -> None: # noqa: F811
575 """Verify a plane the map does not name keeps its pixels and its name.
577 A template is a warped coadd stored as a difference image, so it has
578 CLIPPED set while the difference image map has no entry for it.
579 """
580 plane_map = get_legacy_non_cell_coadd_mask_planes()
581 mask = Mask(0, schema=MaskSchema(list(plane_map.values())), bbox=Box.factory[0:4, 0:5])
582 clipped = np.arange(20).reshape(4, 5) < 3
583 saturated = np.arange(20).reshape(4, 5) > 17
584 mask.set("CLIPPED", clipped)
585 mask.set("SATURATED", saturated)
587 legacy = mask.to_legacy(get_legacy_difference_image_mask_planes())
589 # The unmapped coadd plane is written under the name it already has.
590 assert "CLIPPED" in legacy.getMaskPlaneDict()
591 np.testing.assert_array_equal((legacy.array & legacy.getPlaneBitMask("CLIPPED")).astype(bool), clipped)
592 # A mapped plane still comes back under its legacy name.
593 np.testing.assert_array_equal((legacy.array & legacy.getPlaneBitMask("SAT")).astype(bool), saturated)
594 assert "SATURATED" not in legacy.getMaskPlaneDict()
595 assert_masks_equal(Mask.from_legacy(legacy, plane_map=plane_map), mask)
598def test_legacy_round_trip_with_optional_plane(reset_afw_mask_planes: None) -> None: # noqa: F811
599 """Verify a legacy mask survives a round trip through `Mask`, with the
600 mapped planes renamed both ways and an optional plane carried as it is.
601 """
602 # reset_afw_mask_planes will have already skipped if afw is not available.
603 from lsst.afw.image import Mask as LegacyMask
605 legacy = LegacyMask(5, 4)
606 rows = {"SAT": 0, "INTRP": 1, "INJECTED": 2}
607 pixels = {}
608 for old_name, row in rows.items():
609 legacy.addMaskPlane(old_name)
610 selection = np.zeros(legacy.array.shape, dtype=bool)
611 selection[row, :] = True
612 legacy.array[selection] |= legacy.getPlaneBitMask(old_name)
613 pixels[old_name] = selection
614 # Defined by some other image in this process, but unused here.
615 legacy.addMaskPlane("INJECTED_CORE")
616 plane_map = get_legacy_visit_image_mask_planes()
618 mask = Mask.from_legacy(legacy, plane_map=plane_map)
620 assert {"SATURATED", "INTERPOLATED", "INJECTED"} <= set(mask.schema.names)
621 assert "INJECTED_CORE" not in mask.schema.names
622 np.testing.assert_array_equal(mask.get("SATURATED"), pixels["SAT"])
623 np.testing.assert_array_equal(mask.get("INJECTED"), pixels["INJECTED"])
625 round_tripped = mask.to_legacy(plane_map)
627 compare_mask_to_legacy(mask, round_tripped, plane_map)
628 for old_name, selection in pixels.items():
629 np.testing.assert_array_equal(
630 (round_tripped.array & round_tripped.getPlaneBitMask(old_name)).astype(bool), selection
631 )
632 # The mapped planes go back out under their legacy names, and the
633 # optional plane under the only name it has.
634 assert "SATURATED" not in round_tripped.getMaskPlaneDict()
635 assert "INJECTED" in round_tripped.getMaskPlaneDict()
638def test_read_legacy_adds_optional_planes_in_use(reset_afw_mask_planes: None) -> None: # noqa: F811
639 """Verify reading a legacy FITS mask resolves the optional planes the
640 same way converting one in memory does.
641 """
642 # reset_afw_mask_planes will have already skipped if afw is not available.
643 from lsst.afw.image import MaskedImageF
645 # `read_legacy` reads the MASK extension of a masked image or exposure.
646 masked_image = MaskedImageF(5, 4)
647 legacy = masked_image.mask
648 injected = np.arange(20).reshape(4, 5) < 3
649 for old_name in ("INJECTED", "INJECTED_CORE"):
650 legacy.addMaskPlane(old_name)
651 legacy.array[injected] |= legacy.getPlaneBitMask("INJECTED")
653 with lsst.utils.tests.getTempFilePath(".fits") as tmpFile:
654 masked_image.writeFits(tmpFile)
655 mask = Mask.read_legacy(tmpFile, ext=2, plane_map=get_legacy_visit_image_mask_planes())
657 assert "INJECTED" in mask.schema.names
658 np.testing.assert_array_equal(mask.get("INJECTED"), injected)
659 assert "INJECTED_CORE" not in mask.schema.names
662def test_legacy(legacy_test_data: _LegacyTestData) -> None:
663 """Test Mask.read_legacy, Mask.to_legacy, and Mask.from_legacy."""
664 assert legacy_test_data.mask.schema.names == {p.name for p in legacy_test_data.plane_map.values()}
665 assert legacy_test_data.mask.bbox == Box.from_legacy(legacy_test_data.reader.readBBox())
666 legacy_mask = legacy_test_data.reader.readMask()
667 compare_mask_to_legacy(legacy_test_data.mask, legacy_mask, legacy_test_data.plane_map)
668 compare_mask_to_legacy(
669 legacy_test_data.mask,
670 legacy_test_data.mask.to_legacy(legacy_test_data.plane_map),
671 legacy_test_data.plane_map,
672 )
673 assert_masks_equal(
674 legacy_test_data.mask, Mask.from_legacy(legacy_mask, plane_map=legacy_test_data.plane_map)
675 )
676 # Write the mask out in the new format, and test that we can read it back.
677 with RoundtripFits(legacy_test_data.mask, storage_class="MaskV2") as roundtrip:
678 pass
679 assert_masks_equal(roundtrip.result, legacy_test_data.mask)
682def test_legacy_butler_read(legacy_test_data: _LegacyTestData) -> None:
683 """Test that a round-tripped MaskV2 can be read back as a legacy afw
684 Mask via Butler.
685 """
686 with RoundtripFits(legacy_test_data.mask, storage_class="MaskV2") as roundtrip:
687 legacy_mask = roundtrip.get(storageClass="Mask")
688 assert isinstance(legacy_mask, lsst.afw.image.Mask)
689 compare_mask_to_legacy(legacy_test_data.mask, legacy_mask)
692def test_mask_repr_str_pinned() -> None:
693 """Mask str/repr match their documented forms."""
694 rng = np.random.default_rng(7)
695 schema = MaskSchema(make_mask_planes(rng, 3, 0), dtype=np.uint8)
696 mask = Mask(0, schema=schema, bbox=Box.factory[0:5, 0:4])
697 assert str(mask) == f"Mask({mask.bbox!s}, {list(mask.schema.names)})"
698 assert repr(mask) == f"Mask(..., bbox={mask.bbox!r}, schema={mask.schema!r})"
701def test_mask_describe_detail_reports_set_pixel_counts() -> None:
702 """detail=True adds a 'Set pixels' column with per-plane counts."""
703 schema = MaskSchema([MaskPlane("BAD", "bad"), MaskPlane("DET", "detected")], dtype=np.uint8)
704 mask = Mask(0, schema=schema, bbox=Box.factory[0:4, 0:5])
705 mask.set("BAD", mask.get("BAD") | (np.arange(20).reshape(4, 5) < 3))
707 # Cheap path: no counts, no extra column.
708 plain = mask.describe().children["schema"]
709 plain_table = next(t for t in plain.tables if t.title == "Mask planes")
710 assert "Set pixels" not in plain_table.columns
712 # Detailed path: 'Set pixels' column present with correct counts.
713 detailed = mask.describe(detail=True).children["schema"]
714 table = next(t for t in detailed.tables if t.title == "Mask planes")
715 assert table.columns[-1] == "Set pixels"
716 counts = {row[3]: row[-1] for row in table.rows} # row[3] is the Name column
717 assert counts["BAD"] == 3
718 assert counts["DET"] == 0
721def test_compare() -> None:
722 """Test Mask.compare added/removed counts for a shared plane."""
723 schema = MaskSchema([MaskPlane("A", "dA"), MaskPlane("B", "dB")], dtype=np.uint8)
724 m1 = Mask(0, schema=schema, bbox=Box.factory[0:2, 0:2])
725 m1.set("A", np.array([[True, False], [False, True]]))
726 m2 = Mask(0, schema=schema, bbox=Box.factory[0:2, 0:2])
727 m2.set("A", np.array([[True, True], [False, False]]))
728 # A: m1 set at (0,0),(1,1); m2 set at (0,0),(0,1)
729 assert m1.compare(m2) == {"A": (1, 1)}
732def test_compare_identical_is_empty() -> None:
733 """Test that identical masks yield an empty difference."""
734 schema = MaskSchema([MaskPlane("A", "dA")], dtype=np.uint8)
735 m1 = Mask(0, schema=schema, bbox=Box.factory[0:2, 0:1])
736 m1.set("A", np.array([[True], [False]]))
737 m2 = Mask(0, schema=schema, bbox=Box.factory[0:2, 0:1])
738 m2.set("A", np.array([[True], [False]]))
739 assert m1.compare(m2) == {}
742def test_compare_one_sided_planes() -> None:
743 """Test that planes present in only one mask are counted fully."""
744 schema_a = MaskSchema([MaskPlane("A", "dA")], dtype=np.uint8)
745 schema_b = MaskSchema([MaskPlane("B", "dB")], dtype=np.uint8)
746 m1 = Mask(0, schema=schema_a, bbox=Box.factory[0:2, 0:1])
747 m1.set("A", np.array([[True], [False]]))
748 m2 = Mask(0, schema=schema_b, bbox=Box.factory[0:2, 0:1])
749 m2.set("B", np.array([[True], [True]]))
750 assert m1.compare(m2) == {"A": (1, 0), "B": (0, 2)}
753def test_compare_bbox_mismatch_raises() -> None:
754 """Test that differing bounding boxes raise ValueError."""
755 schema = MaskSchema([MaskPlane("A", "dA")], dtype=np.uint8)
756 m1 = Mask(0, schema=schema, bbox=Box.factory[0:2, 0:1])
757 m2 = Mask(0, schema=schema, bbox=Box.factory[0:3, 0:1])
758 with pytest.raises(ValueError, match="same bounding box"):
759 m1.compare(m2)
762def test_compare_mask_to_legacy_notes_plane_diff(reset_afw_mask_planes: None) -> None: # noqa: F811
763 """Assert that a legacy-mask mismatch adds a per-plane +/- note."""
764 schema = MaskSchema([MaskPlane("A", "dA")], dtype=np.uint8)
765 mask = Mask(0, schema=schema, bbox=Box.factory[0:2, 0:1])
766 mask.set("A", np.array([[True], [False]]))
767 legacy = mask.to_legacy()
768 mask2 = Mask(0, schema=schema, bbox=Box.factory[0:2, 0:1])
769 mask2.set("A", np.array([[True], [True]]))
770 with pytest.raises(AssertionError) as excinfo:
771 compare_mask_to_legacy(mask2, legacy)
772 notes = excinfo.value.__notes__ or []
773 assert any("mask[A]: +1 -0" in n for n in notes)
776def _random_mask(rng: np.random.Generator, schema: MaskSchema, bbox: Box) -> Mask:
777 """Return a mask with roughly a third of each plane's pixels set."""
778 mask = Mask(0, schema=schema, bbox=bbox)
779 for name in schema.names:
780 mask.set(name, rng.random(bbox.shape) < 0.3)
781 return mask
784def _reference_update(lhs: Mask, rhs: Mask) -> Mask:
785 """Return a copy of ``lhs`` updated from ``rhs`` one plane at a time."""
786 result = lhs.copy()
787 try:
788 bbox = result.bbox.intersection(rhs.bbox)
789 except NoOverlapError:
790 return result
791 for name in result.schema.names & rhs.schema.names:
792 result[bbox].set(name, rhs[bbox].get(name))
793 return result
796@pytest.mark.parametrize(
797 ("lhs_dtype", "rhs_dtype"),
798 [
799 (np.uint8, np.int32),
800 (np.int32, np.uint8),
801 (np.uint8, np.uint16),
802 (np.uint16, np.uint8),
803 (np.uint8, np.uint8),
804 (np.int64, np.int32),
805 ],
806)
807@pytest.mark.parametrize(
808 "rhs_bbox",
809 [Box.factory[0:6, 0:7], Box.factory[2:9, -3:4], Box.factory[10:12, 10:12]],
810 ids=["same", "partial", "disjoint"],
811)
812def test_update_matches_per_plane(lhs_dtype: type, rhs_dtype: type, rhs_bbox: Box) -> None:
813 """Test that Mask.update ORs in exactly the shared planes over the
814 overlap, whatever the two schemas' layouts.
815 """
816 rng = np.random.default_rng(42)
817 lhs_planes = make_mask_planes(rng, 20, 4)
818 # M3 is only in lhs; M20-M23 are only in rhs.
819 rhs_planes = [p for p in make_mask_planes(rng, 24, 3) if p is None or p.name != "M3"]
820 lhs = _random_mask(rng, MaskSchema(lhs_planes, dtype=lhs_dtype), Box.factory[0:6, 0:7])
821 rhs = _random_mask(rng, MaskSchema(rhs_planes, dtype=rhs_dtype), rhs_bbox)
822 expected = _reference_update(lhs, rhs)
823 lhs.update(rhs)
824 np.testing.assert_array_equal(lhs.array, expected.array)
827def test_update_through_view() -> None:
828 """Test that updating a subimage view writes into the parent mask."""
829 rng = np.random.default_rng(7)
830 planes = make_mask_planes(rng, 10, 0)
831 parent = Mask(0, schema=MaskSchema(planes, dtype=np.uint8), bbox=Box.factory[0:8, 0:8])
832 rhs = _random_mask(rng, MaskSchema(planes, dtype=np.int32), Box.factory[2:5, 3:6])
833 expected = _reference_update(parent, rhs)
834 parent[Box.factory[2:5, 3:6]].update(rhs)
835 np.testing.assert_array_equal(parent.array, expected.array)