LSST Applications g0b6bd0c080+a72a5dd7e6,g1182afd7b4+2a019aa3bb,g17e5ecfddb+2b8207f7de,g1d67935e3f+06cf436103,g38293774b4+ac198e9f13,g396055baef+6a2097e274,g3b44f30a73+6611e0205b,g480783c3b1+98f8679e14,g48ccf36440+89c08d0516,g4b93dc025c+98f8679e14,g5c4744a4d9+a302e8c7f0,g613e996a0d+e1c447f2e0,g6c8d09e9e7+25247a063c,g7271f0639c+98f8679e14,g7a9cd813b8+124095ede6,g9d27549199+a302e8c7f0,ga1cf026fa3+ac198e9f13,ga32aa97882+7403ac30ac,ga786bb30fb+7a139211af,gaa63f70f4e+9994eb9896,gabf319e997+ade567573c,gba47b54d5d+94dc90c3ea,gbec6a3398f+06cf436103,gc6308e37c7+07dd123edb,gc655b1545f+ade567573c,gcc9029db3c+ab229f5caf,gd01420fc67+06cf436103,gd877ba84e5+06cf436103,gdb4cecd868+6f279b5b48,ge2d134c3d5+cc4dbb2e3f,ge448b5faa6+86d1ceac1d,gecc7e12556+98f8679e14,gf3ee170dca+25247a063c,gf4ac96e456+ade567573c,gf9f5ea5b4d+ac198e9f13,gff490e6085+8c2580be5c,w.2022.27
LSST Data Management Base Package
Classes | Functions
lsst.meas.algorithms.loadReferenceObjects Namespace Reference

Classes

class  _FilterCatalog
 
class  LoadReferenceObjectsConfig
 
class  LoadReferenceObjectsTask
 
class  ReferenceObjectLoader
 
class  ReferenceObjectLoaderBase
 

Functions

def isOldFluxField (name, units)
 
def hasNanojanskyFluxUnits (schema)
 
def getFormatVersionFromRefCat (refCat)
 
def convertToNanojansky (catalog, log, doConvert=True)
 
def getRefFluxField (schema, filterName)
 
def getRefFluxKeys (schema, filterName)
 
def joinMatchListWithCatalogImpl (refObjLoader, matchCat, sourceCat)
 
def applyProperMotionsImpl (log, catalog, epoch)
 

Function Documentation

◆ applyProperMotionsImpl()

def lsst.meas.algorithms.loadReferenceObjects.applyProperMotionsImpl (   log,
  catalog,
  epoch 
)
Apply proper motion correction to a reference catalog.

Adjust position and position error in the ``catalog``
for proper motion to the specified ``epoch``,
modifying the catalog in place.

Parameters
----------
log : `lsst.log.Log` or `logging.getLogger`
    Log object to write to.
catalog : `lsst.afw.table.SimpleCatalog`
    Catalog of positions, containing:

    - Coordinates, retrieved by the table's coordinate key.
    - ``coord_raErr`` : Error in Right Ascension (rad).
    - ``coord_decErr`` : Error in Declination (rad).
    - ``pm_ra`` : Proper motion in Right Ascension (rad/yr,
        East positive)
    - ``pm_raErr`` : Error in ``pm_ra`` (rad/yr), optional.
    - ``pm_dec`` : Proper motion in Declination (rad/yr,
        North positive)
    - ``pm_decErr`` : Error in ``pm_dec`` (rad/yr), optional.
    - ``epoch`` : Mean epoch of object (an astropy.time.Time)
epoch : `astropy.time.Time`
    Epoch to which to correct proper motion.

Definition at line 1309 of file loadReferenceObjects.py.

1309def applyProperMotionsImpl(log, catalog, epoch):
1310 """Apply proper motion correction to a reference catalog.
1311
1312 Adjust position and position error in the ``catalog``
1313 for proper motion to the specified ``epoch``,
1314 modifying the catalog in place.
1315
1316 Parameters
1317 ----------
1318 log : `lsst.log.Log` or `logging.getLogger`
1319 Log object to write to.
1321 Catalog of positions, containing:
1322
1323 - Coordinates, retrieved by the table's coordinate key.
1324 - ``coord_raErr`` : Error in Right Ascension (rad).
1325 - ``coord_decErr`` : Error in Declination (rad).
1326 - ``pm_ra`` : Proper motion in Right Ascension (rad/yr,
1327 East positive)
1328 - ``pm_raErr`` : Error in ``pm_ra`` (rad/yr), optional.
1329 - ``pm_dec`` : Proper motion in Declination (rad/yr,
1330 North positive)
1331 - ``pm_decErr`` : Error in ``pm_dec`` (rad/yr), optional.
1332 - ``epoch`` : Mean epoch of object (an astropy.time.Time)
1333 epoch : `astropy.time.Time`
1334 Epoch to which to correct proper motion.
1335 """
1336 if "epoch" not in catalog.schema or "pm_ra" not in catalog.schema or "pm_dec" not in catalog.schema:
1337 log.warning("Proper motion correction not available from catalog")
1338 return
1339 if not catalog.isContiguous():
1340 raise RuntimeError("Catalog must be contiguous")
1341 catEpoch = astropy.time.Time(catalog["epoch"], scale="tai", format="mjd")
1342 log.info("Correcting reference catalog for proper motion to %r", epoch)
1343 # Use `epoch.tai` to make sure the time difference is in TAI
1344 timeDiffsYears = (epoch.tai - catEpoch).to(astropy.units.yr).value
1345 coordKey = catalog.table.getCoordKey()
1346 # Compute the offset of each object due to proper motion
1347 # as components of the arc of a great circle along RA and Dec
1348 pmRaRad = catalog["pm_ra"]
1349 pmDecRad = catalog["pm_dec"]
1350 offsetsRaRad = pmRaRad*timeDiffsYears
1351 offsetsDecRad = pmDecRad*timeDiffsYears
1352 # Compute the corresponding bearing and arc length of each offset
1353 # due to proper motion, and apply the offset
1354 # The factor of 1e6 for computing bearing is intended as
1355 # a reasonable scale for typical values of proper motion
1356 # in order to avoid large errors for small values of proper motion;
1357 # using the offsets is another option, but it can give
1358 # needlessly large errors for short duration
1359 offsetBearingsRad = numpy.arctan2(pmDecRad*1e6, pmRaRad*1e6)
1360 offsetAmountsRad = numpy.hypot(offsetsRaRad, offsetsDecRad)
1361 for record, bearingRad, amountRad in zip(catalog, offsetBearingsRad, offsetAmountsRad):
1362 record.set(coordKey,
1363 record.get(coordKey).offset(bearing=bearingRad*geom.radians,
1364 amount=amountRad*geom.radians))
1365 # Increase error in RA and Dec based on error in proper motion
1366 if "coord_raErr" in catalog.schema:
1367 catalog["coord_raErr"] = numpy.hypot(catalog["coord_raErr"],
1368 catalog["pm_raErr"]*timeDiffsYears)
1369 if "coord_decErr" in catalog.schema:
1370 catalog["coord_decErr"] = numpy.hypot(catalog["coord_decErr"],
1371 catalog["pm_decErr"]*timeDiffsYears)
table::Key< int > to
Custom catalog class for record/table subclasses that are guaranteed to have an ID,...
Definition: SortedCatalog.h:42
This static class includes a variety of methods for interacting with the the logging module.
Definition: Log.h:724

◆ convertToNanojansky()

def lsst.meas.algorithms.loadReferenceObjects.convertToNanojansky (   catalog,
  log,
  doConvert = True 
)
Convert fluxes in a catalog from jansky to nanojansky.

Parameters
----------
catalog : `lsst.afw.table.SimpleCatalog`
    The catalog to convert.
log : `lsst.log.Log` or `logging.Logger`
    Log to send messages to.
doConvert : `bool`, optional
    Return a converted catalog, or just identify the fields that need to be converted?
    This supports the "write=False" mode of `bin/convert_to_nJy.py`.

Returns
-------
catalog : `lsst.afw.table.SimpleCatalog` or None
    The converted catalog, or None if ``doConvert`` is False.

Notes
-----
Support for old units in reference catalogs will be removed after the
release of late calendar year 2019.
Use `meas_algorithms/bin/convert_to_nJy.py` to update your reference catalog.

Definition at line 86 of file loadReferenceObjects.py.

86def convertToNanojansky(catalog, log, doConvert=True):
87 """Convert fluxes in a catalog from jansky to nanojansky.
88
89 Parameters
90 ----------
92 The catalog to convert.
93 log : `lsst.log.Log` or `logging.Logger`
94 Log to send messages to.
95 doConvert : `bool`, optional
96 Return a converted catalog, or just identify the fields that need to be converted?
97 This supports the "write=False" mode of `bin/convert_to_nJy.py`.
98
99 Returns
100 -------
101 catalog : `lsst.afw.table.SimpleCatalog` or None
102 The converted catalog, or None if ``doConvert`` is False.
103
104 Notes
105 -----
106 Support for old units in reference catalogs will be removed after the
107 release of late calendar year 2019.
108 Use `meas_algorithms/bin/convert_to_nJy.py` to update your reference catalog.
109 """
110 # Do not share the AliasMap: for refcats, that gets created when the
111 # catalog is read from disk and should not be propagated.
112 mapper = afwTable.SchemaMapper(catalog.schema, shareAliasMap=False)
113 mapper.addMinimalSchema(afwTable.SimpleTable.makeMinimalSchema())
114 input_fields = []
115 output_fields = []
116 for field in catalog.schema:
117 oldName = field.field.getName()
118 oldUnits = field.field.getUnits()
119 if isOldFluxField(oldName, oldUnits):
120 units = 'nJy'
121 # remap Sigma flux fields to Err, so we can drop the alias
122 if oldName.endswith('_fluxSigma'):
123 name = oldName.replace('_fluxSigma', '_fluxErr')
124 else:
125 name = oldName
126 newField = afwTable.Field[field.dtype](name, field.field.getDoc(), units)
127 mapper.addMapping(field.getKey(), newField)
128 input_fields.append(field.field)
129 output_fields.append(newField)
130 else:
131 mapper.addMapping(field.getKey())
132
133 fluxFieldsStr = '; '.join("(%s, '%s')" % (field.getName(), field.getUnits()) for field in input_fields)
134
135 if doConvert:
136 newSchema = mapper.getOutputSchema()
137 output = afwTable.SimpleCatalog(newSchema)
138 output.reserve(len(catalog))
139 output.extend(catalog, mapper=mapper)
140 for field in output_fields:
141 output[field.getName()] *= 1e9
142 log.info("Converted refcat flux fields to nJy (name, units): %s", fluxFieldsStr)
143 return output
144 else:
145 log.info("Found old-style refcat flux fields (name, units): %s", fluxFieldsStr)
146 return None
147
148
A mapping between the keys of two Schemas, used to copy data between them.
Definition: SchemaMapper.h:21
def convertToNanojansky(catalog, log, doConvert=True)
A description of a field in a table.
Definition: Field.h:24

◆ getFormatVersionFromRefCat()

def lsst.meas.algorithms.loadReferenceObjects.getFormatVersionFromRefCat (   refCat)
"Return the format version stored in a reference catalog header.

Parameters
----------
refCat : `lsst.afw.table.SimpleCatalog`
    Reference catalog to inspect.

Returns
-------
version : `int`
    Format verison integer. Returns `0` if the catalog has no metadata
    or the metadata does not include a "REFCAT_FORMAT_VERSION" key.

Definition at line 63 of file loadReferenceObjects.py.

64 """"Return the format version stored in a reference catalog header.
65
66 Parameters
67 ----------
69 Reference catalog to inspect.
70
71 Returns
72 -------
73 version : `int`
74 Format verison integer. Returns `0` if the catalog has no metadata
75 or the metadata does not include a "REFCAT_FORMAT_VERSION" key.
76 """
77 md = refCat.getMetadata()
78 if md is None:
79 return 0
80 try:
81 return md.getScalar("REFCAT_FORMAT_VERSION")
82 except KeyError:
83 return 0
84
85

◆ getRefFluxField()

def lsst.meas.algorithms.loadReferenceObjects.getRefFluxField (   schema,
  filterName 
)
Get the name of a flux field from a schema.

return the alias of "anyFilterMapsToThis", if present
else:
    return "*filterName*_camFlux" if present
    else return "*filterName*_flux" if present (camera filter name
        matches reference filter name)
    else throw RuntimeError

Parameters
----------
schema : `lsst.afw.table.Schema`
    Reference catalog schema.
filterName : `str`
    Name of camera filter.

Returns
-------
fluxFieldName : `str`
    Name of flux field.

Raises
------
RuntimeError
    If an appropriate field is not found.

Definition at line 1025 of file loadReferenceObjects.py.

1025def getRefFluxField(schema, filterName):
1026 """Get the name of a flux field from a schema.
1027
1028 return the alias of "anyFilterMapsToThis", if present
1029 else:
1030 return "*filterName*_camFlux" if present
1031 else return "*filterName*_flux" if present (camera filter name
1032 matches reference filter name)
1033 else throw RuntimeError
1034
1035 Parameters
1036 ----------
1037 schema : `lsst.afw.table.Schema`
1038 Reference catalog schema.
1039 filterName : `str`
1040 Name of camera filter.
1041
1042 Returns
1043 -------
1044 fluxFieldName : `str`
1045 Name of flux field.
1046
1047 Raises
1048 ------
1049 RuntimeError
1050 If an appropriate field is not found.
1051 """
1052 if not isinstance(schema, afwTable.Schema):
1053 raise RuntimeError("schema=%s is not a schema" % (schema,))
1054 try:
1055 return schema.getAliasMap().get("anyFilterMapsToThis")
1056 except LookupError:
1057 pass # try the filterMap next
1058
1059 fluxFieldList = [filterName + "_camFlux", filterName + "_flux"]
1060 for fluxField in fluxFieldList:
1061 if fluxField in schema:
1062 return fluxField
1063
1064 raise RuntimeError("Could not find flux field(s) %s" % (", ".join(fluxFieldList)))
1065
1066
Defines the fields and offsets for a table.
Definition: Schema.h:51

◆ getRefFluxKeys()

def lsst.meas.algorithms.loadReferenceObjects.getRefFluxKeys (   schema,
  filterName 
)
Return keys for flux and flux error.

Parameters
----------
schema : `lsst.afw.table.Schema`
    Reference catalog schema.
filterName : `str`
    Name of camera filter.

Returns
-------
keys : `tuple` of (`lsst.afw.table.Key`, `lsst.afw.table.Key`)
    Two keys:

    - flux key
    - flux error key, if present, else None

Raises
------
RuntimeError
    If flux field not found.

Definition at line 1067 of file loadReferenceObjects.py.

1067def getRefFluxKeys(schema, filterName):
1068 """Return keys for flux and flux error.
1069
1070 Parameters
1071 ----------
1072 schema : `lsst.afw.table.Schema`
1073 Reference catalog schema.
1074 filterName : `str`
1075 Name of camera filter.
1076
1077 Returns
1078 -------
1079 keys : `tuple` of (`lsst.afw.table.Key`, `lsst.afw.table.Key`)
1080 Two keys:
1081
1082 - flux key
1083 - flux error key, if present, else None
1084
1085 Raises
1086 ------
1087 RuntimeError
1088 If flux field not found.
1089 """
1090 fluxField = getRefFluxField(schema, filterName)
1091 fluxErrField = fluxField + "Err"
1092 fluxKey = schema[fluxField].asKey()
1093 try:
1094 fluxErrKey = schema[fluxErrField].asKey()
1095 except Exception:
1096 fluxErrKey = None
1097 return (fluxKey, fluxErrKey)
1098
1099
A class used as a handle to a particular field in a table.
Definition: Key.h:53

◆ hasNanojanskyFluxUnits()

def lsst.meas.algorithms.loadReferenceObjects.hasNanojanskyFluxUnits (   schema)
Return True if the units of all flux and fluxErr are correct (nJy).

Definition at line 54 of file loadReferenceObjects.py.

54def hasNanojanskyFluxUnits(schema):
55 """Return True if the units of all flux and fluxErr are correct (nJy).
56 """
57 for field in schema:
58 if isOldFluxField(field.field.getName(), field.field.getUnits()):
59 return False
60 return True
61
62

◆ isOldFluxField()

def lsst.meas.algorithms.loadReferenceObjects.isOldFluxField (   name,
  units 
)
Return True if this name/units combination corresponds to an
"old-style" reference catalog flux field.

Definition at line 43 of file loadReferenceObjects.py.

43def isOldFluxField(name, units):
44 """Return True if this name/units combination corresponds to an
45 "old-style" reference catalog flux field.
46 """
47 unitsCheck = units != 'nJy' # (units == 'Jy' or units == '' or units == '?')
48 isFlux = name.endswith('_flux')
49 isFluxSigma = name.endswith('_fluxSigma')
50 isFluxErr = name.endswith('_fluxErr')
51 return (isFlux or isFluxSigma or isFluxErr) and unitsCheck
52
53

◆ joinMatchListWithCatalogImpl()

def lsst.meas.algorithms.loadReferenceObjects.joinMatchListWithCatalogImpl (   refObjLoader,
  matchCat,
  sourceCat 
)
Relink an unpersisted match list to sources and reference
objects.

A match list is persisted and unpersisted as a catalog of IDs
produced by afw.table.packMatches(), with match metadata
(as returned by the astrometry tasks) in the catalog's metadata
attribute. This method converts such a match catalog into a match
list, with links to source records and reference object records.

Parameters
----------
refObjLoader
    Reference object loader to use in getting reference objects
matchCat : `lsst.afw.table.BaseCatalog`
    Unperisted packed match list.
    ``matchCat.table.getMetadata()`` must contain match metadata,
    as returned by the astrometry tasks.
sourceCat : `lsst.afw.table.SourceCatalog`
    Source catalog. As a side effect, the catalog will be sorted
    by ID.

Returns
-------
matchList : `lsst.afw.table.ReferenceMatchVector`
    Match list.

Definition at line 1248 of file loadReferenceObjects.py.

1248def joinMatchListWithCatalogImpl(refObjLoader, matchCat, sourceCat):
1249 """Relink an unpersisted match list to sources and reference
1250 objects.
1251
1252 A match list is persisted and unpersisted as a catalog of IDs
1253 produced by afw.table.packMatches(), with match metadata
1254 (as returned by the astrometry tasks) in the catalog's metadata
1255 attribute. This method converts such a match catalog into a match
1256 list, with links to source records and reference object records.
1257
1258 Parameters
1259 ----------
1260 refObjLoader
1261 Reference object loader to use in getting reference objects
1262 matchCat : `lsst.afw.table.BaseCatalog`
1263 Unperisted packed match list.
1264 ``matchCat.table.getMetadata()`` must contain match metadata,
1265 as returned by the astrometry tasks.
1266 sourceCat : `lsst.afw.table.SourceCatalog`
1267 Source catalog. As a side effect, the catalog will be sorted
1268 by ID.
1269
1270 Returns
1271 -------
1273 Match list.
1274 """
1275 matchmeta = matchCat.table.getMetadata()
1276 version = matchmeta.getInt('SMATCHV')
1277 if version != 1:
1278 raise ValueError('SourceMatchVector version number is %i, not 1.' % version)
1279 filterName = matchmeta.getString('FILTER').strip()
1280 try:
1281 epoch = matchmeta.getDouble('EPOCH')
1282 except (LookupError, TypeError):
1283 epoch = None # Not present, or not correct type means it's not set
1284 if 'RADIUS' in matchmeta:
1285 # This is a circle style metadata, call loadSkyCircle
1286 ctrCoord = geom.SpherePoint(matchmeta.getDouble('RA'),
1287 matchmeta.getDouble('DEC'), geom.degrees)
1288 rad = matchmeta.getDouble('RADIUS')*geom.degrees
1289 refCat = refObjLoader.loadSkyCircle(ctrCoord, rad, filterName, epoch=epoch).refCat
1290 elif "INNER_UPPER_LEFT_RA" in matchmeta:
1291 # This is the sky box type (only triggers in the LoadReferenceObject class, not task)
1292 # Only the outer box is required to be loaded to get the maximum region, all filtering
1293 # will be done by the unpackMatches function, and no spatial filtering needs to be done
1294 # by the refObjLoader
1295 box = []
1296 for place in ("UPPER_LEFT", "UPPER_RIGHT", "LOWER_LEFT", "LOWER_RIGHT"):
1297 coord = geom.SpherePoint(matchmeta.getDouble(f"OUTER_{place}_RA"),
1298 matchmeta.getDouble(f"OUTER_{place}_DEC"),
1299 geom.degrees).getVector()
1300 box.append(coord)
1301 outerBox = sphgeom.ConvexPolygon(box)
1302 refCat = refObjLoader.loadRegion(outerBox, filterName, epoch=epoch).refCat
1303
1304 refCat.sort()
1305 sourceCat.sort()
1306 return afwTable.unpackMatches(matchCat, refCat, sourceCat)
1307
1308
Point in an unspecified spherical coordinate system.
Definition: SpherePoint.h:57
bool strip
Definition: fits.cc:911
std::vector< Match< typename Cat1::Record, typename Cat2::Record > > unpackMatches(BaseCatalog const &matches, Cat1 const &cat1, Cat2 const &cat2)
Reconstruct a MatchVector from a BaseCatalog representation of the matches and a pair of catalogs.
Definition: Match.cc:455
def joinMatchListWithCatalogImpl(refObjLoader, matchCat, sourceCat)