Coverage for tests/test_referenceObjectLoader.py: 12%
300 statements
« prev ^ index » next coverage.py v6.5.0, created at 2022-11-19 10:17 +0000
« prev ^ index » next coverage.py v6.5.0, created at 2022-11-19 10:17 +0000
1# This file is part of meas_algorithms.
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# 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 <https://www.gnu.org/licenses/>.
22import itertools
23import os.path
24import tempfile
25import unittest
26import glob
28import numpy as np
29from smatch.matcher import sphdist
30import astropy.time
32import lsst.daf.butler
33import lsst.afw.geom as afwGeom
34import lsst.afw.table as afwTable
35from lsst.daf.butler import DatasetType, DeferredDatasetHandle
36from lsst.daf.butler.script import ingest_files
37from lsst.meas.algorithms import (ConvertReferenceCatalogTask, ReferenceObjectLoader,
38 getRefFluxField, getRefFluxKeys)
39from lsst.meas.algorithms.testUtils import MockReferenceObjectLoaderFromFiles
40from lsst.meas.algorithms.loadReferenceObjects import hasNanojanskyFluxUnits, convertToNanojansky
41import lsst.utils
42import lsst.geom
44import convertReferenceCatalogTestBase
47class ReferenceObjectLoaderGenericTests(lsst.utils.tests.TestCase):
48 """Test parts of the reference loader that don't depend on loading a
49 catalog, for example schema creation, filter maps, units, and metadata.
50 """
51 def testFilterMapVsAnyFilterMapsToThis(self):
52 config = ReferenceObjectLoader.ConfigClass()
53 # check that a filterMap-only config passes validation
54 config.filterMap = {"b": "a"}
55 try:
56 config.validate()
57 except lsst.pex.config.FieldValidationError:
58 self.fail("`filterMap`-only LoadReferenceObjectsConfig should not fail validation.")
60 # anyFilterMapsToThis and filterMap are mutually exclusive
61 config.anyFilterMapsToThis = "c"
62 with self.assertRaises(lsst.pex.config.FieldValidationError):
63 config.validate()
65 # check that a anyFilterMapsToThis-only config passes validation
66 config.filterMap = {}
67 try:
68 config.validate()
69 except lsst.pex.config.FieldValidationError:
70 self.fail("`anyFilterMapsToThis`-only LoadReferenceObjectsConfig should not fail validation.")
72 def testMakeMinimalSchema(self):
73 """Make a schema and check it."""
74 for filterNameList in (["r"], ["foo", "_bar"]):
75 for (addIsPhotometric, addIsResolved, addIsVariable,
76 coordErrDim, addProperMotion, properMotionErrDim,
77 addParallax) in itertools.product(
78 (False, True), (False, True), (False, True),
79 (-1, 0, 1, 2, 3, 4), (False, True), (-1, 0, 1, 2, 3, 4),
80 (False, True)):
81 argDict = dict(
82 filterNameList=filterNameList,
83 addIsPhotometric=addIsPhotometric,
84 addIsResolved=addIsResolved,
85 addIsVariable=addIsVariable,
86 coordErrDim=coordErrDim,
87 addProperMotion=addProperMotion,
88 properMotionErrDim=properMotionErrDim,
89 addParallax=addParallax,
90 )
91 if coordErrDim not in (0, 2, 3) or \
92 (addProperMotion and properMotionErrDim not in (0, 2, 3)):
93 with self.assertRaises(ValueError):
94 ReferenceObjectLoader.makeMinimalSchema(**argDict)
95 else:
96 refSchema = ReferenceObjectLoader.makeMinimalSchema(**argDict)
97 self.assertTrue("coord_ra" in refSchema)
98 self.assertTrue("coord_dec" in refSchema)
99 for filterName in filterNameList:
100 fluxField = filterName + "_flux"
101 self.assertIn(fluxField, refSchema)
102 self.assertNotIn("x" + fluxField, refSchema)
103 fluxErrField = fluxField + "Err"
104 self.assertIn(fluxErrField, refSchema)
105 self.assertEqual(getRefFluxField(refSchema, filterName), filterName + "_flux")
106 self.assertEqual("resolved" in refSchema, addIsResolved)
107 self.assertEqual("variable" in refSchema, addIsVariable)
108 self.assertEqual("photometric" in refSchema, addIsPhotometric)
109 self.assertEqual("photometric" in refSchema, addIsPhotometric)
110 self.assertEqual("epoch" in refSchema, addProperMotion or addParallax)
111 self.assertEqual("coord_raErr" in refSchema, coordErrDim > 0)
112 self.assertEqual("coord_decErr" in refSchema, coordErrDim > 0)
113 self.assertEqual("coord_ra_dec_Cov" in refSchema, coordErrDim == 3)
114 self.assertEqual("pm_ra" in refSchema, addProperMotion)
115 self.assertEqual("pm_dec" in refSchema, addProperMotion)
116 self.assertEqual("pm_raErr" in refSchema, addProperMotion and properMotionErrDim > 0)
117 self.assertEqual("pm_decErr" in refSchema, addProperMotion and properMotionErrDim > 0)
118 self.assertEqual("pm_flag" in refSchema, addProperMotion)
119 self.assertEqual("pm_ra_dec_Cov" in refSchema,
120 addProperMotion and properMotionErrDim == 3)
121 self.assertEqual("parallax" in refSchema, addParallax)
122 self.assertEqual("parallaxErr" in refSchema, addParallax)
123 self.assertEqual("parallax_flag" in refSchema, addParallax)
125 def testFilterAliasMap(self):
126 """Make a schema with filter aliases."""
127 for filterMap in ({}, {"camr": "r"}):
128 config = ReferenceObjectLoader.ConfigClass()
129 config.filterMap = filterMap
130 loader = ReferenceObjectLoader(None, None, name=None, config=config)
131 refSchema = ReferenceObjectLoader.makeMinimalSchema(filterNameList="r")
132 loader._addFluxAliases(refSchema,
133 anyFilterMapsToThis=config.anyFilterMapsToThis,
134 filterMap=config.filterMap)
136 self.assertIn("r_flux", refSchema)
137 self.assertIn("r_fluxErr", refSchema)
139 # camera filters aliases are named <filter>_camFlux
140 if "camr" in filterMap:
141 self.assertEqual(getRefFluxField(refSchema, "camr"), "camr_camFlux")
142 else:
143 with self.assertRaisesRegex(RuntimeError,
144 r"Could not find flux field\(s\) camr_camFlux, camr_flux"):
145 getRefFluxField(refSchema, "camr")
147 refCat = afwTable.SimpleCatalog(refSchema)
148 refObj = refCat.addNew()
149 refObj["r_flux"] = 1.23
150 self.assertAlmostEqual(refCat[0].get(getRefFluxField(refSchema, "r")), 1.23)
151 if "camr" in filterMap:
152 self.assertAlmostEqual(refCat[0].get(getRefFluxField(refSchema, "camr")), 1.23)
153 refObj["r_fluxErr"] = 0.111
154 if "camr" in filterMap:
155 self.assertEqual(refCat[0].get("camr_camFluxErr"), 0.111)
156 fluxKey, fluxErrKey = getRefFluxKeys(refSchema, "r")
157 self.assertEqual(refCat[0].get(fluxKey), 1.23)
158 self.assertEqual(refCat[0].get(fluxErrKey), 0.111)
159 if "camr" in filterMap:
160 fluxKey, fluxErrKey = getRefFluxKeys(refSchema, "camr")
161 self.assertEqual(refCat[0].get(fluxErrKey), 0.111)
162 else:
163 with self.assertRaises(RuntimeError):
164 getRefFluxKeys(refSchema, "camr")
166 def testAnyFilterMapsToThisAlias(self):
167 # test anyFilterMapsToThis
168 config = ReferenceObjectLoader.ConfigClass()
169 config.anyFilterMapsToThis = "gg"
170 loader = ReferenceObjectLoader(None, None, name=None, config=config)
171 refSchema = ReferenceObjectLoader.makeMinimalSchema(filterNameList=["gg"])
172 loader._addFluxAliases(refSchema,
173 anyFilterMapsToThis=config.anyFilterMapsToThis,
174 filterMap=config.filterMap)
175 self.assertEqual(getRefFluxField(refSchema, "r"), "gg_flux")
176 # raise if "gg" is not in the refcat filter list
177 with self.assertRaises(RuntimeError):
178 refSchema = ReferenceObjectLoader.makeMinimalSchema(filterNameList=["rr"])
179 refSchema = loader._addFluxAliases(refSchema,
180 anyFilterMapsToThis=config.anyFilterMapsToThis,
181 filterMap=config.filterMap)
183 def testCheckFluxUnits(self):
184 """Test that we can identify old style fluxes in a schema."""
185 schema = ReferenceObjectLoader.makeMinimalSchema(['r', 'z'])
186 # the default schema should pass
187 self.assertTrue(hasNanojanskyFluxUnits(schema))
188 schema.addField('bad_fluxSigma', doc='old flux units', type=float, units='')
189 self.assertFalse(hasNanojanskyFluxUnits(schema))
191 schema = ReferenceObjectLoader.makeMinimalSchema(['r', 'z'])
192 schema.addField('bad_flux', doc='old flux units', type=float, units='')
193 self.assertFalse(hasNanojanskyFluxUnits(schema))
195 schema = ReferenceObjectLoader.makeMinimalSchema(['r', 'z'])
196 schema.addField('bad_flux', doc='old flux units', type=float, units='Jy')
197 self.assertFalse(hasNanojanskyFluxUnits(schema))
199 schema = ReferenceObjectLoader.makeMinimalSchema(['r', 'z'])
200 schema.addField('bad_fluxErr', doc='old flux units', type=float, units='')
201 self.assertFalse(hasNanojanskyFluxUnits(schema))
203 schema = ReferenceObjectLoader.makeMinimalSchema(['r', 'z'])
204 schema.addField('bad_fluxErr', doc='old flux units', type=float, units='Jy')
205 self.assertFalse(hasNanojanskyFluxUnits(schema))
207 schema = ReferenceObjectLoader.makeMinimalSchema(['r', 'z'])
208 schema.addField('bad_fluxSigma', doc='old flux units', type=float, units='')
209 self.assertFalse(hasNanojanskyFluxUnits(schema))
211 def testConvertOldFluxes(self):
212 """Check that we can convert old style fluxes in a catalog."""
213 flux = 1.234
214 fluxErr = 5.678
215 log = lsst.log.Log()
217 def make_catalog():
218 schema = ReferenceObjectLoader.makeMinimalSchema(['r', 'z'])
219 schema.addField('bad_flux', doc='old flux units', type=float, units='')
220 schema.addField('bad_fluxErr', doc='old flux units', type=float, units='Jy')
221 refCat = afwTable.SimpleCatalog(schema)
222 refObj = refCat.addNew()
223 refObj["bad_flux"] = flux
224 refObj["bad_fluxErr"] = fluxErr
225 return refCat
227 oldRefCat = make_catalog()
228 newRefCat = convertToNanojansky(oldRefCat, log)
229 self.assertEqual(newRefCat['bad_flux'], [flux*1e9, ])
230 self.assertEqual(newRefCat['bad_fluxErr'], [fluxErr*1e9, ])
231 self.assertEqual(newRefCat.schema['bad_flux'].asField().getUnits(), 'nJy')
232 self.assertEqual(newRefCat.schema['bad_fluxErr'].asField().getUnits(), 'nJy')
234 # check that doConvert=False returns None (it also logs a summary)
235 oldRefCat = make_catalog()
236 newRefCat = convertToNanojansky(oldRefCat, log, doConvert=False)
237 self.assertIsNone(newRefCat)
239 def testGetMetadataCircle(self):
240 center = lsst.geom.SpherePoint(100*lsst.geom.degrees, 45*lsst.geom.degrees)
241 radius = lsst.geom.Angle(1*lsst.geom.degrees)
242 loader = ReferenceObjectLoader(None, None, name=None)
243 metadata = loader.getMetadataCircle(center, radius, "fakeR")
244 self.assertEqual(metadata['RA'], center.getLongitude().asDegrees())
245 self.assertEqual(metadata['DEC'], center.getLatitude().asDegrees())
246 self.assertEqual(metadata['RADIUS'], radius.asDegrees())
247 self.assertEqual(metadata['SMATCHV'], 2)
248 self.assertEqual(metadata['FILTER'], 'fakeR')
249 self.assertEqual(metadata['JEPOCH'], None)
250 self.assertEqual(metadata['TIMESYS'], 'TAI')
252 epoch = astropy.time.Time(2023.0, format="jyear", scale="tai")
253 metadata = loader.getMetadataCircle(center, radius, "fakeR", epoch=epoch)
254 self.assertEqual(metadata['JEPOCH'], epoch.jyear)
257class ReferenceObjectLoaderLoadTests(convertReferenceCatalogTestBase.ConvertReferenceCatalogTestBase,
258 lsst.utils.tests.TestCase):
259 """Tests of loading reference catalogs, using an in-memory generated fake
260 sky catalog that is converted to an LSST refcat.
262 This effectively is a partial integration test of the refcat conversion,
263 ingestion, and loading sequence, focusing mostly on testing the different
264 ways to load a refcat. It significantly overlaps in coverage with
265 ``nopytest_convertReferenceCatalog.py``, but uses a very trivial test
266 refcat and only one core during the conversion.
267 """
268 @classmethod
269 def setUpClass(cls):
270 super().setUpClass()
272 # Generate a catalog, with arbitrary ids
273 inTempDir = tempfile.TemporaryDirectory()
274 inPath = inTempDir.name
275 skyCatalogFile, _, skyCatalog = cls.makeSkyCatalog(inPath, idStart=25, seed=123)
277 cls.skyCatalog = skyCatalog
279 # override some field names.
280 config = convertReferenceCatalogTestBase.makeConvertConfig(withRaDecErr=True, withMagErr=True,
281 withPm=True, withPmErr=True)
282 # use a very small HTM pixelization depth
283 depth = 2
284 config.dataset_config.indexer.active.depth = depth
285 # np.savetxt prepends '# ' to the header lines, so use a reader that understands that
286 config.file_reader.format = 'ascii.commented_header'
287 config.n_processes = 1
288 config.id_name = 'id' # Use the ids from the generated catalogs
289 cls.repoTempDir = tempfile.TemporaryDirectory()
290 repoPath = cls.repoTempDir.name
292 # Convert the input data files to our HTM indexed format.
293 dataTempDir = tempfile.TemporaryDirectory()
294 dataPath = dataTempDir.name
295 converter = ConvertReferenceCatalogTask(output_dir=dataPath, config=config)
296 converter.run([skyCatalogFile])
298 # Make a temporary butler to ingest them into.
299 butler = cls.makeTemporaryRepo(repoPath, config.dataset_config.indexer.active.depth)
300 dimensions = [f"htm{depth}"]
301 datasetType = DatasetType(config.dataset_config.ref_dataset_name,
302 dimensions,
303 "SimpleCatalog",
304 universe=butler.registry.dimensions,
305 isCalibration=False)
306 butler.registry.registerDatasetType(datasetType)
308 # Ingest the files into the new butler.
309 run = "testingRun"
310 htmTableFile = os.path.join(dataPath, "filename_to_htm.ecsv")
311 ingest_files(repoPath,
312 config.dataset_config.ref_dataset_name,
313 run,
314 htmTableFile,
315 transfer="auto")
317 # Test if we can get back the catalogs, with a new butler.
318 butler = lsst.daf.butler.Butler(repoPath)
319 datasetRefs = list(butler.registry.queryDatasets(config.dataset_config.ref_dataset_name,
320 collections=[run]).expanded())
321 handles = []
322 for dataRef in datasetRefs:
323 handles.append(DeferredDatasetHandle(butler=butler, ref=dataRef, parameters=None))
325 cls.datasetRefs = datasetRefs
326 cls.handles = handles
328 inTempDir.cleanup()
329 dataTempDir.cleanup()
331 def test_loadSkyCircle(self):
332 """Test the loadSkyCircle routine."""
333 loader = ReferenceObjectLoader([dataRef.dataId for dataRef in self.datasetRefs],
334 self.handles,
335 name="testrefcat")
336 center = lsst.geom.SpherePoint(180.0*lsst.geom.degrees, 0.0*lsst.geom.degrees)
337 cat = loader.loadSkyCircle(
338 center,
339 30.0*lsst.geom.degrees,
340 filterName='a',
341 ).refCat
342 # Check that the max distance is less than the radius
343 dist = sphdist(180.0, 0.0, np.rad2deg(cat['coord_ra']), np.rad2deg(cat['coord_dec']))
344 self.assertLess(np.max(dist), 30.0)
346 # Check that all the objects from the two catalogs are here.
347 dist = sphdist(180.0, 0.0, self.skyCatalog['ra_icrs'], self.skyCatalog['dec_icrs'])
348 inside, = (dist < 30.0).nonzero()
349 self.assertEqual(len(cat), len(inside))
351 self.assertTrue(cat.isContiguous())
352 self.assertEqual(len(np.unique(cat['id'])), len(cat))
353 # A default-loaded sky circle should not have centroids
354 self.assertNotIn('centroid_x', cat.schema)
355 self.assertNotIn('centroid_y', cat.schema)
356 self.assertNotIn('hasCentroid', cat.schema)
358 def test_loadPixelBox(self):
359 """Test the loadPixelBox routine."""
360 # This will create a box 50 degrees on a side.
361 loaderConfig = ReferenceObjectLoader.ConfigClass()
362 loaderConfig.pixelMargin = 0
363 loader = ReferenceObjectLoader([dataRef.dataId for dataRef in self.datasetRefs],
364 self.handles,
365 name="testrefcat",
366 config=loaderConfig)
367 bbox = lsst.geom.Box2I(corner=lsst.geom.Point2I(0, 0), dimensions=lsst.geom.Extent2I(1000, 1000))
368 crpix = lsst.geom.Point2D(500, 500)
369 crval = lsst.geom.SpherePoint(180.0*lsst.geom.degrees, 0.0*lsst.geom.degrees)
370 cdMatrix = afwGeom.makeCdMatrix(scale=0.05*lsst.geom.degrees)
371 wcs = afwGeom.makeSkyWcs(crpix=crpix, crval=crval, cdMatrix=cdMatrix)
373 cat = loader.loadPixelBox(bbox, wcs, 'a', bboxToSpherePadding=0).refCat
375 # This is a sanity check on the ranges; the exact selection depends
376 # on cos(dec) and the tangent-plane projection.
377 self.assertLess(np.max(np.rad2deg(cat['coord_ra'])), 180.0 + 25.0)
378 self.assertGreater(np.max(np.rad2deg(cat['coord_ra'])), 180.0 - 25.0)
379 self.assertLess(np.max(np.rad2deg(cat['coord_dec'])), 25.0)
380 self.assertGreater(np.min(np.rad2deg(cat['coord_dec'])), -25.0)
382 # The following is to ensure the reference catalog coords are
383 # getting corrected for proper motion when an epoch is provided.
384 # Use an extreme epoch so that differences in corrected coords
385 # will be significant. Note that this simply tests that the coords
386 # do indeed change when the epoch is passed. It makes no attempt
387 # at assessing the correctness of the change. This is left to the
388 # explicit testProperMotion() test below.
389 catWithEpoch = loader.loadPixelBox(
390 bbox,
391 wcs,
392 'a',
393 bboxToSpherePadding=0,
394 epoch=astropy.time.Time(30000, format='mjd', scale='tai')).refCat
396 self.assertFloatsNotEqual(cat['coord_ra'], catWithEpoch['coord_ra'], rtol=1.0e-4)
397 self.assertFloatsNotEqual(cat['coord_dec'], catWithEpoch['coord_dec'], rtol=1.0e-4)
399 def test_filterMap(self):
400 """Test filterMap parameters."""
401 loaderConfig = ReferenceObjectLoader.ConfigClass()
402 loaderConfig.filterMap = {'aprime': 'a'}
403 loader = ReferenceObjectLoader([dataRef.dataId for dataRef in self.datasetRefs],
404 self.handles,
405 name="testrefcat",
406 config=loaderConfig)
407 center = lsst.geom.SpherePoint(180.0*lsst.geom.degrees, 0.0*lsst.geom.degrees)
408 result = loader.loadSkyCircle(
409 center,
410 30.0*lsst.geom.degrees,
411 filterName='aprime',
412 )
413 self.assertEqual(result.fluxField, 'aprime_camFlux')
414 self.assertFloatsEqual(result.refCat['aprime_camFlux'], result.refCat['a_flux'])
416 def test_properMotion(self):
417 """Test proper motion correction."""
418 loaderConfig = ReferenceObjectLoader.ConfigClass()
419 loaderConfig.filterMap = {'aprime': 'a'}
420 loader = ReferenceObjectLoader([dataRef.dataId for dataRef in self.datasetRefs],
421 self.handles,
422 name="testrefcat",
423 config=loaderConfig)
424 center = lsst.geom.SpherePoint(180.0*lsst.geom.degrees, 0.0*lsst.geom.degrees)
425 cat = loader.loadSkyCircle(
426 center,
427 30.0*lsst.geom.degrees,
428 filterName='a'
429 ).refCat
431 # Zero epoch change --> no proper motion correction (except minor numerical effects)
432 cat_pm = loader.loadSkyCircle(
433 center,
434 30.0*lsst.geom.degrees,
435 filterName='a',
436 epoch=self.epoch
437 ).refCat
439 self.assertFloatsAlmostEqual(cat_pm['coord_ra'], cat['coord_ra'], rtol=1.0e-14)
440 self.assertFloatsAlmostEqual(cat_pm['coord_dec'], cat['coord_dec'], rtol=1.0e-14)
441 self.assertFloatsEqual(cat_pm['coord_raErr'], cat['coord_raErr'])
442 self.assertFloatsEqual(cat_pm['coord_decErr'], cat['coord_decErr'])
444 # One year difference
445 cat_pm = loader.loadSkyCircle(
446 center,
447 30.0*lsst.geom.degrees,
448 filterName='a',
449 epoch=self.epoch + 1.0*astropy.units.yr
450 ).refCat
452 self.assertFloatsEqual(cat_pm['pm_raErr'], cat['pm_raErr'])
453 self.assertFloatsEqual(cat_pm['pm_decErr'], cat['pm_decErr'])
454 for orig, ref in zip(cat, cat_pm):
455 self.assertAnglesAlmostEqual(orig.getCoord().separation(ref.getCoord()),
456 self.properMotionAmt, maxDiff=1.0e-6*lsst.geom.arcseconds)
457 self.assertAnglesAlmostEqual(orig.getCoord().bearingTo(ref.getCoord()),
458 self.properMotionDir, maxDiff=1.0e-4*lsst.geom.arcseconds)
459 predictedRaErr = np.hypot(cat["coord_raErr"], cat["pm_raErr"])
460 predictedDecErr = np.hypot(cat["coord_decErr"], cat["pm_decErr"])
461 self.assertFloatsAlmostEqual(cat_pm["coord_raErr"], predictedRaErr)
462 self.assertFloatsAlmostEqual(cat_pm["coord_decErr"], predictedDecErr)
464 def test_requireProperMotion(self):
465 """Tests of the requireProperMotion config field."""
466 loaderConfig = ReferenceObjectLoader.ConfigClass()
467 loaderConfig.requireProperMotion = True
468 loader = ReferenceObjectLoader([dataRef.dataId for dataRef in self.datasetRefs],
469 self.handles,
470 name="testrefcat",
471 config=loaderConfig)
472 center = lsst.geom.SpherePoint(180.0*lsst.geom.degrees, 0.0*lsst.geom.degrees)
474 # Test that we require an epoch set.
475 msg = 'requireProperMotion=True but epoch not provided to loader'
476 with self.assertRaisesRegex(RuntimeError, msg):
477 loader.loadSkyCircle(
478 center,
479 30.0*lsst.geom.degrees,
480 filterName='a'
481 )
484class Version0Version1ReferenceObjectLoaderTestCase(lsst.utils.tests.TestCase):
485 """Test cases for reading version 0 and version 1 catalogs."""
486 def testLoadVersion0(self):
487 """Test reading a pre-written format_version=0 (Jy flux) catalog.
488 It should be converted to have nJy fluxes.
489 """
490 path = os.path.join(
491 os.path.dirname(os.path.abspath(__file__)),
492 'data',
493 'version0',
494 'ref_cats',
495 'cal_ref_cat'
496 )
498 filenames = sorted(glob.glob(os.path.join(path, '????.fits')))
500 loader = MockReferenceObjectLoaderFromFiles(filenames, name='cal_ref_cat', htmLevel=4)
501 result = loader.loadSkyCircle(convertReferenceCatalogTestBase.make_coord(10, 20),
502 5*lsst.geom.degrees,
503 'a')
505 self.assertTrue(hasNanojanskyFluxUnits(result.refCat.schema))
506 catalog = afwTable.SimpleCatalog.readFits(filenames[0])
507 self.assertFloatsEqual(catalog['a_flux']*1e9, result.refCat['a_flux'])
508 self.assertFloatsEqual(catalog['a_fluxSigma']*1e9, result.refCat['a_fluxErr'])
509 self.assertFloatsEqual(catalog['b_flux']*1e9, result.refCat['b_flux'])
510 self.assertFloatsEqual(catalog['b_fluxSigma']*1e9, result.refCat['b_fluxErr'])
512 def testLoadVersion1(self):
513 """Test reading a format_version=1 catalog (fluxes unchanged)."""
514 path = os.path.join(
515 os.path.dirname(os.path.abspath(__file__)),
516 'data',
517 'version1',
518 'ref_cats',
519 'cal_ref_cat'
520 )
522 filenames = sorted(glob.glob(os.path.join(path, '????.fits')))
524 loader = MockReferenceObjectLoaderFromFiles(filenames, name='cal_ref_cat', htmLevel=4)
525 result = loader.loadSkyCircle(convertReferenceCatalogTestBase.make_coord(10, 20),
526 5*lsst.geom.degrees,
527 'a')
529 self.assertTrue(hasNanojanskyFluxUnits(result.refCat.schema))
530 catalog = afwTable.SimpleCatalog.readFits(filenames[0])
531 self.assertFloatsEqual(catalog['a_flux'], result.refCat['a_flux'])
532 self.assertFloatsEqual(catalog['a_fluxErr'], result.refCat['a_fluxErr'])
533 self.assertFloatsEqual(catalog['b_flux'], result.refCat['b_flux'])
534 self.assertFloatsEqual(catalog['b_fluxErr'], result.refCat['b_fluxErr'])
537class TestMemory(lsst.utils.tests.MemoryTestCase):
538 pass
541def setup_module(module):
542 lsst.utils.tests.init()
545if __name__ == "__main__": 545 ↛ 546line 545 didn't jump to line 546, because the condition on line 545 was never true
546 lsst.utils.tests.init()
547 unittest.main()