Coverage for tests/test_pipelines.py: 95%
139 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-21 02:06 -0800
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-21 02:06 -0800
1# This file is part of ap_pipe.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <http://www.gnu.org/licenses/>.
22import itertools
23import tempfile
24import unittest
26import lsst.daf.butler.tests as butlerTests
27import lsst.pipe.base
28from lsst.pipe.base.tests.pipelineStepTester import PipelineStepTester # Can't use fully-qualified name
29import lsst.utils
30import lsst.utils.tests
32from lsst.resources import ResourcePath
35class PipelineDefintionsTestSuite(lsst.utils.tests.TestCase):
36 """Tests of the self-consistency of our pipeline definitions.
37 """
38 def setUp(self):
39 self.path = ResourcePath("eups://ap_pipe/pipelines/", forceDirectory=True)
40 # Each pipeline file should have a subset that represents it in
41 # higher-level pipelines.
42 self.synonyms = {"ApPipe.yaml": "apPipe",
43 "ApPipe-legacy.yaml": "apPipe",
44 "ApPipeDaytime.yaml": "apPipe",
45 "ApPipe-DECam-templates.yaml": "apPipe",
46 "ApPipeDaytime-DECam-templates.yaml": "apPipe",
47 "ApPipeDaytime-LSSTCam-templates.yaml": "apPipe",
48 "ApPipeWithIsrTaskLSST.yaml": "apPipe",
49 "ApPipeWithPreconvolution.yaml": "apPipe",
50 "ApPipeWithPreconvolution-legacy.yaml": "apPipe",
51 "ApPipeWithFakes.yaml": "apPipe",
52 "SingleFrame.yaml": "singleFrame",
53 "SingleFrameWithIsrTaskLSST.yaml": "singleFrame",
54 "RunIsrForCrosstalkSources.yaml": "runOverscan",
55 "CreateInjectionCatalogs.yaml": "fakeCreation",
56 }
58 def test_graph_build(self):
59 """Test that each pipeline definition file can be
60 used to build a graph.
61 """
62 files = ResourcePath.findFileResources([self.path], file_filter=r".*\.yaml$")
63 for file in files:
64 if "QuickTemplate" in file.path:
65 # Our QuickTemplate definition cannot be tested here because it
66 # depends on drp_tasks, which we cannot make a dependency here.
67 continue
68 if "PromptTemplate" in file.path:
69 # Our PromptTemplate definition cannot be tested here because it
70 # depends on drp_tasks, which we cannot make a dependency here.
71 continue
72 with self.subTest(file=str(file)):
73 pipeline = lsst.pipe.base.Pipeline.from_uri(file)
74 pipeline.addConfigOverride("parameters", "apdb_config", "some/file/path.yaml")
75 # If this fails, it will produce a useful error message.
76 pipeline.to_graph()
78 def test_datasets(self):
79 files = ResourcePath.findFileResources(
80 [self.path.join("_ingredients", forceDirectory=True)], file_filter=r".*\.yaml$"
81 )
82 for file in files:
83 if "QuickTemplate" in file.path:
84 # Our QuickTemplate definition cannot be tested here because it
85 # depends on drp_tasks, which we cannot make a dependency here.
86 continue
87 if "injection/" in file.path:
88 # The source-injection post-processing ingredient is a partial
89 # pipeline merged into full AP pipelines at build time;
90 # it is validated separately by test_injection_ingredient.
91 continue
92 with self.subTest(file=str(file)):
93 expected_inputs = {
94 # ISR
95 "raw", "camera", "crosstalk", "crosstalkSources", "bias", "dark", "flat", "ptc",
96 "fringe", "straylightData", "bfKernel", "newBFKernel", "defects", "linearizer",
97 "opticsTransmission", "filterTransmission", "atmosphereTransmission",
98 "illumMaskedImage", "deferredChargeCalib",
99 # ISR-LSST
100 "bfk", "cti", "dnlLUT", "gain_correction",
101 # Everything else
102 "skyMap", "gaia_dr3_20230707", "gaia_dr2_20200414", "ps1_pv3_3pi_20170110",
103 "template_coadd", "pretrainedModelPackage", "dia_source_apdb"
104 }
105 # Detect source-injection pipelines by task label rather than
106 # relying on filename conventions.
107 temp_pipeline = lsst.pipe.base.Pipeline.from_uri(file)
108 temp_pipeline.addConfigOverride("parameters", "apdb_config", "some/file/path.yaml")
109 if "injectVisit" in temp_pipeline.task_labels:
110 expected_inputs.add("injection_catalog")
111 expected_inputs.add("VisitDetectorFakeSourceCat")
112 tester = PipelineStepTester(
113 filename=file,
114 step_suffixes=[""], # Test full pipeline
115 initial_dataset_types=[("ps1_pv3_3pi_20170110", {"htm7"}, "SimpleCatalog", False),
116 ("gaia_dr2_20200414", {"htm7"}, "SimpleCatalog", False),
117 ("gaia_dr3_20230707", {"htm7"}, "SimpleCatalog", False),
118 ],
119 expected_inputs=expected_inputs,
120 # Pipeline outputs highly in flux, don't test
121 expected_outputs=set(),
122 pipeline_patches={"parameters:apdb_config": "some/file/path.yaml",
123 },
124 )
125 # Tester modifies Butler registry, so need a fresh repo every time
126 with tempfile.TemporaryDirectory() as tempRepo:
127 butler = butlerTests.makeTestRepo(tempRepo)
128 tester.run(butler, self)
130 def test_whole_subset(self):
131 """Test that each pipeline's synonymous subset includes all tasks,
132 including those imported from other files.
133 """
134 files = ResourcePath.findFileResources([self.path], file_filter=r".*\.yaml$")
135 for file in files:
136 if "QuickTemplate" in file.path:
137 # Our QuickTemplate definition cannot be tested here because it
138 # depends on drp_tasks, which we cannot make a dependency here.
139 continue
140 elif "injection/" in file.path:
141 # PostInjectedTasksApPipe is not actually an AP pipeline
142 continue
143 elif "ApdbDeduplication" in file.path:
144 # The task to export catalogs from the APDB and re-run
145 # association is not intended to be part of Prompt Processing
146 # or batch AP pipeline runs.
147 continue
148 elif "PromptTemplate" in file.path:
149 # Our PromptTemplate definition cannot be tested here because it
150 # depends on drp_tasks, which we cannot make a dependency here.
151 continue
152 with self.subTest(file=str(file)):
153 pipeline = lsst.pipe.base.Pipeline.from_uri(file)
154 subset = self.synonyms.get(file.basename(), "<unknown_synonym>")
155 self.assertEqual(pipeline.subsets.get(subset, "<missing>"), set(pipeline.task_labels),
156 msg=f"These tasks are missing from subset '{subset}'")
158 def test_ap_pipe_subsets(self):
159 """Test the unique subsets of ApPipe.
160 """
161 files = ResourcePath.findFileResources([self.path], file_filter=r"^ApPipe.*\.yaml$")
162 required_subsets = {"preload", "prompt", "afterburner"}
163 # getRegionTimeFromVisit is part of no subset besides apPipe. This is a
164 # very deliberate exception; see RFC-997.
165 no_subset_wanted = {"getRegionTimeFromVisit"}
167 for file in files:
168 if "injection/" in file.path: 168 ↛ 170line 168 didn't jump to line 170 because the condition on line 168 was never true
169 # PostInjectedTasksApPipe is not actually an AP pipeline
170 continue
171 with self.subTest(file=str(file)):
172 pipeline = lsst.pipe.base.Pipeline.from_uri(file)
173 # Do all steps exist?
174 self.assertGreaterEqual(pipeline.subsets.keys(), required_subsets,
175 msg="An AP pipeline is missing subsets "
176 f"{required_subsets - pipeline.subsets.keys()}.")
177 # Is each task part of exactly one step?
178 for set1, set2 in itertools.product(required_subsets, required_subsets):
179 if set1 == set2:
180 continue
181 tasks1 = pipeline.subsets[set1]
182 tasks2 = pipeline.subsets[set2]
183 self.assertTrue(tasks1.isdisjoint(tasks2),
184 msg=f"Subsets '{set1}' and '{set2}' share tasks "
185 f"{tasks1.intersection(tasks2)}.")
186 subsetted = set().union(*[pipeline.subsets[s] for s in required_subsets])
187 self.assertEqual(subsetted, set(pipeline.task_labels) - no_subset_wanted,
188 msg=f"These tasks are not in any of the subsets {required_subsets}.")
190 def test_daytime_stage_subsets(self):
191 """Test that each apPipe task is in exactly one daytime stage.
192 """
193 files = ResourcePath.findFileResources([self.path], file_filter=r"^ApPipe.*\.yaml$")
194 stages = ("DiffimAndSingleFrame", "AssociationAndConsolidation")
195 # Daytime runs read the APDB directly at association and never run
196 # the preload tasks.
197 not_staged = {"loadDiaCatalogs", "analyzeLoadDiaCatalogsMetrics"}
199 for file in files:
200 if "injection/" in file.path: 200 ↛ 202line 200 didn't jump to line 202 because the condition on line 200 was never true
201 # PostInjectedTasksApPipe is not actually an AP pipeline
202 continue
203 if "WithFakes" in file.path:
204 # Daytime runs never inject fakes, and the generated fakes
205 # pipelines add the injection tasks only to apPipe and prompt.
206 continue
207 with self.subTest(file=str(file)):
208 pipeline = lsst.pipe.base.Pipeline.from_uri(file)
209 self.assertGreaterEqual(pipeline.subsets.keys(), set(stages),
210 msg="An AP pipeline is missing daytime stage subsets.")
211 stage1, stage2 = (pipeline.subsets[stage] for stage in stages)
212 self.assertTrue(stage1.isdisjoint(stage2),
213 msg=f"Daytime stages share tasks {stage1 & stage2}.")
214 self.assertTrue((stage1 | stage2).isdisjoint(not_staged),
215 msg=f"Daytime stages include tasks {(stage1 | stage2) & not_staged} "
216 "that daytime runs should not run.")
217 self.assertEqual(stage1 | stage2, pipeline.subsets["apPipe"] - not_staged,
218 msg="Daytime stages do not match the apPipe subset.")
220 def test_injection_ingredient(self):
221 """Test the source-injection post-processing ingredient pipeline.
223 PostInjectedTasksApPipe is a partial pipeline merged into full AP
224 pipelines at build time by make_injection_pipeline. This test
225 validates that it can build a graph and contains the expected tasks.
226 """
227 ingredient = self.path.join("_ingredients").join("injection").join("PostInjectedTasksApPipe.yaml")
228 with self.subTest(file=str(ingredient)):
229 pipeline = lsst.pipe.base.Pipeline.from_uri(ingredient)
230 expected_tasks = {
231 "injectedMatchDiaSrc",
232 "injectedMatchAssocDiaSrc",
233 "consolidateMatchDiaSrc",
234 "consolidateMatchAssocDiaSrc",
235 }
236 self.assertGreaterEqual(
237 set(pipeline.task_labels),
238 expected_tasks,
239 msg="Source-injection post-processing ingredient is missing expected tasks.",
240 )
242 def test_generated_pipeline_readiness(self):
243 """Test that the generated ApPipeWithFakes ingredient exists and is valid.
245 pipelines/_ingredients/ApPipeWithFakes.yaml is generated at build time
246 by make_injection_pipeline (invoked via scons). This test verifies that
247 generation occurred before pipeline tests run, and that the generated
248 pipeline includes the source-injection task. If this test is skipped,
249 run 'scons' in the ap_pipe root directory first.
250 """
251 generated = self.path.join("_ingredients/ApPipeWithFakes.yaml")
252 if not generated.exists(): 252 ↛ 255line 252 didn't jump to line 255 because the condition on line 252 was never true
253 # fail the test with a message that explains how to fix the problem,
254 # rather than silently skipping it
255 self.fail(
256 f"{generated} has not been generated yet. "
257 "Run 'scons' in the ap_pipe root directory to generate it."
258 )
259 with self.subTest(file=str(generated)):
260 pipeline = lsst.pipe.base.Pipeline.from_uri(generated)
261 pipeline.addConfigOverride("parameters", "apdb_config", "some/file/path.yaml")
262 self.assertIn(
263 "injectVisit",
264 pipeline.task_labels,
265 msg="Generated ApPipeWithFakes.yaml is missing the 'injectVisit' task.",
266 )
268 def test_preconvolution_isr_matches_ap_pipe(self):
269 """Test that, for each instrument, ApPipeWithPreconvolution defines
270 the same isr task (class and config) as the corresponding ApPipe.
272 Preconvolution changes only image subtraction and DIA-source
273 detection; instrument signature removal must be unaffected.
274 """
275 files = [
276 f for f in ResourcePath.findFileResources(
277 [self.path], file_filter=r"^ApPipeWithPreconvolution\.yaml$"
278 )
279 if "_ingredients" not in f.path
280 ]
281 # Sanity-check that this test actually has cameras to compare.
282 self.assertGreater(len(files), 0,
283 msg="No camera-specific ApPipeWithPreconvolution.yaml files found.")
285 for precon_file in files:
286 with self.subTest(file=str(precon_file)):
287 base_file = precon_file.dirname().join("ApPipe.yaml")
288 self.assertTrue(base_file.exists(),
289 msg=f"Expected sibling ApPipe.yaml next to {precon_file}: "
290 f"{base_file} does not exist.")
292 precon = lsst.pipe.base.Pipeline.from_uri(precon_file)
293 base = lsst.pipe.base.Pipeline.from_uri(base_file)
294 # apdb_config has no default and must be set before to_graph().
295 precon.addConfigOverride("parameters", "apdb_config", "some/file/path.yaml")
296 base.addConfigOverride("parameters", "apdb_config", "some/file/path.yaml")
298 precon_isr = precon.to_graph().tasks["isr"]
299 base_isr = base.to_graph().tasks["isr"]
301 self.assertEqual(precon_isr.task_class_name, base_isr.task_class_name,
302 msg=f"isr task class differs between ApPipe.yaml and "
303 f"ApPipeWithPreconvolution.yaml in {precon_file.dirname()}.")
304 # Can't just do `assertEqual(precon_isr, base_isr)` since
305 # Task nodes are intentionally not equality comparable.
306 self.assertTrue(
307 base_isr.config.compare(precon_isr.config, shortcut=False),
308 msg=f"isr task config differs between ApPipe.yaml and "
309 f"ApPipeWithPreconvolution.yaml in {precon_file.dirname()}."
310 )
312 def test_inherited_subsets(self):
313 """Test that instrument-specific pipelines have all the subsets of their
314 generic counterparts.
316 Note that this does not check inheritance *within* `_ingredients`!
317 """
318 files = [
319 f for f in ResourcePath.findFileResources([self.path], file_filter=r".*\.yaml$")
320 if "_ingredients" not in f.path
321 ]
322 for file in files:
323 if "QuickTemplate" in file.path:
324 # Our QuickTemplate definition cannot be tested here because it
325 # depends on drp_tasks, which we cannot make a dependency here.
326 continue
327 with self.subTest(file=str(file)):
328 generic = self.path.join("_ingredients/", forceDirectory=True).join(file.basename())
329 if not generic.exists():
330 continue
331 special_subsets = lsst.pipe.base.Pipeline.from_uri(file).subsets.keys()
332 generic_subsets = lsst.pipe.base.Pipeline.from_uri(generic).subsets.keys()
333 self.assertGreaterEqual(special_subsets, generic_subsets,
334 msg="The instrument-specific pipeline is missing subsets "
335 f"{generic_subsets - special_subsets}.")
338class MemoryTester(lsst.utils.tests.MemoryTestCase):
339 pass
342def setup_module(module):
343 lsst.utils.tests.init()
346if __name__ == "__main__": 346 ↛ 347line 346 didn't jump to line 347 because the condition on line 346 was never true
347 lsst.utils.tests.init()
348 unittest.main()