22__all__ = [
'IsolatedStarAssociationConnections',
23 'IsolatedStarAssociationConfig',
24 'IsolatedStarAssociationTask']
28from smatch.matcher
import Matcher
37 dimensions=(
'instrument',
'tract',
'skymap',),
39 source_table_visit = pipeBase.connectionTypes.Input(
40 doc=
'Source table in parquet format, per visit',
41 name=
'sourceTable_visit',
42 storageClass=
'DataFrame',
43 dimensions=(
'instrument',
'visit'),
47 skymap = pipeBase.connectionTypes.Input(
48 doc=
"Input definition of geometry/bbox and projection/wcs for warped exposures",
49 name=BaseSkyMap.SKYMAP_DATASET_TYPE_NAME,
50 storageClass=
'SkyMap',
51 dimensions=(
'skymap',),
53 isolated_star_sources = pipeBase.connectionTypes.Output(
54 doc=
'Catalog of individual sources for the isolated stars',
55 name=
'isolated_star_sources',
56 storageClass=
'DataFrame',
57 dimensions=(
'instrument',
'tract',
'skymap'),
59 isolated_star_cat = pipeBase.connectionTypes.Output(
60 doc=
'Catalog of isolated star positions',
61 name=
'isolated_star_cat',
62 storageClass=
'DataFrame',
63 dimensions=(
'instrument',
'tract',
'skymap'),
68 pipelineConnections=IsolatedStarAssociationConnections):
69 """Configuration for IsolatedStarAssociationTask."""
71 inst_flux_field = pexConfig.Field(
72 doc=(
'Full name of instFlux field to use for s/n selection and persistence. '
73 'The associated flag will be implicity included in bad_flags. '
74 'Note that this is expected to end in ``instFlux``.'),
76 default=
'apFlux_12_0_instFlux',
78 match_radius = pexConfig.Field(
79 doc=
'Match radius (arcseconds)',
83 isolation_radius = pexConfig.Field(
84 doc=(
'Isolation radius (arcseconds). Any stars with average centroids '
85 'within this radius of another star will be rejected from the final '
86 'catalog. This radius should be at least 2x match_radius.'),
90 band_order = pexConfig.ListField(
91 doc=((
'Ordered list of bands to use for matching/storage. '
92 'Any bands not listed will not be matched.')),
94 default=[
'i',
'z',
'r',
'g',
'y',
'u'],
96 id_column = pexConfig.Field(
97 doc=
'Name of column with source id.',
101 ra_column = pexConfig.Field(
102 doc=
'Name of column with right ascension.',
106 dec_column = pexConfig.Field(
107 doc=
'Name of column with declination.',
111 physical_filter_column = pexConfig.Field(
112 doc=
'Name of column with physical filter name',
114 default=
'physical_filter',
116 band_column = pexConfig.Field(
117 doc=
'Name of column with band name',
121 extra_columns = pexConfig.ListField(
122 doc=
'Extra names of columns to read and persist (beyond instFlux and error).',
126 'apFlux_17_0_instFlux',
127 'apFlux_17_0_instFluxErr',
129 'localBackground_instFlux',
130 'localBackground_flag']
132 source_selector = sourceSelectorRegistry.makeField(
133 doc=
'How to select sources. Under normal usage this should not be changed.',
141 source_selector.setDefaults()
143 source_selector.doFlags =
True
144 source_selector.doUnresolved =
True
145 source_selector.doSignalToNoise =
True
146 source_selector.doIsolated =
True
148 source_selector.signalToNoise.minimum = 10.0
149 source_selector.signalToNoise.maximum = 1000.0
153 source_selector.flags.bad = [
'pixelFlags_edge',
154 'pixelFlags_interpolatedCenter',
155 'pixelFlags_saturatedCenter',
156 'pixelFlags_crCenter',
158 'pixelFlags_interpolated',
159 'pixelFlags_saturated',
166 source_selector.isolated.parentName =
'parentSourceId'
167 source_selector.isolated.nChildName =
'deblend_nChild'
169 source_selector.unresolved.maximum = 0.5
170 source_selector.unresolved.name =
'extendedness'
174 """Associate sources into isolated star catalogs.
176 ConfigClass = IsolatedStarAssociationConfig
177 _DefaultName = 'isolatedStarAssociation'
179 def __init__(self, **kwargs):
180 super().__init__(**kwargs)
182 self.makeSubtask(
'source_selector')
184 self.source_selector.log.setLevel(self.source_selector.log.WARN)
187 input_ref_dict = butlerQC.get(inputRefs)
189 tract = butlerQC.quantum.dataId[
'tract']
191 source_table_refs = input_ref_dict[
'source_table_visit']
193 self.log.info(
'Running with %d source_table_visit dataRefs',
194 len(source_table_refs))
196 source_table_ref_dict_temp = {source_table_ref.dataId[
'visit']: source_table_ref
for
197 source_table_ref
in source_table_refs}
199 bands = {source_table_ref.dataId[
'band']
for source_table_ref
in source_table_refs}
201 if band
not in self.config.band_order:
202 self.log.warning(
'Input data has data from band %s but that band is not '
203 'configured for matching', band)
207 source_table_ref_dict = {visit: source_table_ref_dict_temp[visit]
for
208 visit
in sorted(source_table_ref_dict_temp.keys())}
210 struct = self.
run(input_ref_dict[
'skymap'], tract, source_table_ref_dict)
212 butlerQC.put(pd.DataFrame(struct.star_source_cat),
213 outputRefs.isolated_star_sources)
214 butlerQC.put(pd.DataFrame(struct.star_cat),
215 outputRefs.isolated_star_cat)
217 def run(self, skymap, tract, source_table_ref_dict):
218 """Run the isolated star association task.
222 skymap : `lsst.skymap.SkyMap`
226 source_table_ref_dict : `dict`
227 Dictionary of source_table refs. Key is visit, value
is dataref.
231 struct : `lsst.pipe.base.struct`
232 Struct
with outputs
for persistence.
236 primary_bands = self.config.band_order
241 if len(primary_star_cat) == 0:
242 return pipeBase.Struct(star_source_cat=np.zeros(0, star_source_cat.dtype),
243 star_cat=np.zeros(0, primary_star_cat.dtype))
248 if len(primary_star_cat) == 0:
249 return pipeBase.Struct(star_source_cat=np.zeros(0, star_source_cat.dtype),
250 star_cat=np.zeros(0, primary_star_cat.dtype))
253 inner_tract_ids = skymap.findTractIdArray(primary_star_cat[self.config.ra_column],
254 primary_star_cat[self.config.dec_column],
256 use = (inner_tract_ids == tract)
257 self.log.info(
'Total of %d isolated stars in inner tract.', use.sum())
259 primary_star_cat = primary_star_cat[use]
261 if len(primary_star_cat) == 0:
262 return pipeBase.Struct(star_source_cat=np.zeros(0, star_source_cat.dtype),
263 star_cat=np.zeros(0, primary_star_cat.dtype))
268 len(primary_star_cat))
271 star_source_cat, primary_star_cat = self.
_match_sources(primary_bands,
275 return pipeBase.Struct(star_source_cat=star_source_cat,
276 star_cat=primary_star_cat)
278 def _make_all_star_sources(self, tract_info, source_table_ref_dict):
279 """Make a catalog of all the star sources.
284 Information about the tract.
285 source_table_ref_dict : `dict`
286 Dictionary of source_table refs. Key is visit, value
is dataref.
290 star_source_cat : `np.ndarray`
291 Catalog of star sources.
297 poly = tract_info.outer_sky_polygon
300 for visit
in source_table_ref_dict:
301 source_table_ref = source_table_ref_dict[visit]
302 df = source_table_ref.get(parameters={
'columns': all_columns})
303 df.reset_index(inplace=
True)
305 goodSrc = self.source_selector.selectSources(df)
307 table = df[persist_columns][goodSrc.selected].to_records()
311 table = np.lib.recfunctions.append_fields(table,
314 [np.where(goodSrc.selected)[0],
315 np.zeros(goodSrc.selected.sum(), dtype=np.int32)],
321 tract_use = poly.contains(np.deg2rad(table[self.config.ra_column]),
322 np.deg2rad(table[self.config.dec_column]))
324 tables.append(table[tract_use])
327 star_source_cat = np.concatenate(tables)
329 return star_source_cat
331 def _get_source_table_visit_column_names(self):
332 """Get the list of sourceTable_visit columns from the config.
336 all_columns : `list` [`str`]
338 persist_columns : `list` [`str`]
339 Columns to persist (excluding selection columns)
341 columns = [self.config.id_column,
343 self.config.ra_column, self.config.dec_column,
344 self.config.physical_filter_column, self.config.band_column,
345 self.config.inst_flux_field, self.config.inst_flux_field +
'Err']
346 columns.extend(self.config.extra_columns)
348 all_columns = columns.copy()
349 if self.source_selector.config.doFlags:
350 all_columns.extend(self.source_selector.config.flags.bad)
351 if self.source_selector.config.doUnresolved:
352 all_columns.append(self.source_selector.config.unresolved.name)
353 if self.source_selector.config.doIsolated:
354 all_columns.append(self.source_selector.config.isolated.parentName)
355 all_columns.append(self.source_selector.config.isolated.nChildName)
357 return all_columns, columns
359 def _match_primary_stars(self, primary_bands, star_source_cat):
360 """Match primary stars.
364 primary_bands : `list` [`str`]
365 Ordered list of primary bands.
366 star_source_cat : `np.ndarray`
367 Catalog of star sources.
371 primary_star_cat : `np.ndarray`
372 Catalog of primary star positions
374 ra_col = self.config.ra_column
375 dec_col = self.config.dec_column
379 primary_star_cat = None
380 for primary_band
in primary_bands:
381 use = (star_source_cat[
'band'] == primary_band)
383 ra = star_source_cat[ra_col][use]
384 dec = star_source_cat[dec_col][use]
386 with Matcher(ra, dec)
as matcher:
389 idx = matcher.query_groups(self.config.match_radius/3600., min_match=1)
390 except AttributeError:
392 idx = matcher.query_self(self.config.match_radius/3600., min_match=1)
397 self.log.info(
'Found 0 primary stars in %s band.', primary_band)
400 band_cat = np.zeros(count, dtype=dtype)
401 band_cat[
'primary_band'] = primary_band
407 if ra.min() < 60.0
and ra.max() > 300.0:
408 ra_temp = (ra + 180.0) % 360. - 180.
414 for i, row
in enumerate(idx):
416 band_cat[ra_col][i] = np.mean(ra_temp[row])
417 band_cat[dec_col][i] = np.mean(dec[row])
421 band_cat[ra_col] %= 360.0
424 if primary_star_cat
is None or len(primary_star_cat) == 0:
425 primary_star_cat = band_cat
427 with Matcher(band_cat[ra_col], band_cat[dec_col])
as matcher:
428 idx = matcher.query_radius(primary_star_cat[ra_col],
429 primary_star_cat[dec_col],
430 self.config.match_radius/3600.)
432 match_indices = np.array([i
for i
in range(len(idx))
if len(idx[i]) > 0])
433 if len(match_indices) > 0:
434 band_cat = np.delete(band_cat, match_indices)
436 primary_star_cat = np.append(primary_star_cat, band_cat)
437 self.log.info(
'Found %d primary stars in %s band.', len(band_cat), primary_band)
440 if primary_star_cat
is None:
441 primary_star_cat = np.zeros(0, dtype=dtype)
443 return primary_star_cat
445 def _remove_neighbors(self, primary_star_cat):
446 """Remove neighbors from the primary star catalog.
450 primary_star_cat : `np.ndarray`
451 Primary star catalog.
455 primary_star_cat_cut : `np.ndarray`
456 Primary star cat with neighbors removed.
458 ra_col = self.config.ra_column
459 dec_col = self.config.dec_column
461 with Matcher(primary_star_cat[ra_col], primary_star_cat[dec_col])
as matcher:
466 idx = matcher.query_groups(self.config.isolation_radius/3600., min_match=2)
467 except AttributeError:
469 idx = matcher.query_self(self.config.isolation_radius/3600., min_match=2)
472 neighbor_indices = np.concatenate(idx)
474 neighbor_indices = np.zeros(0, dtype=int)
476 if len(neighbor_indices) > 0:
477 neighbored = np.unique(neighbor_indices)
478 self.log.info(
'Cutting %d objects with close neighbors.', len(neighbored))
479 primary_star_cat = np.delete(primary_star_cat, neighbored)
481 return primary_star_cat
483 def _match_sources(self, bands, star_source_cat, primary_star_cat):
484 """Match individual sources to primary stars.
488 bands : `list` [`str`]
490 star_source_cat : `np.ndarray`
491 Array of star sources.
492 primary_star_cat : `np.ndarray`
493 Array of primary stars.
497 star_source_cat_sorted : `np.ndarray`
498 Sorted and cropped array of star sources.
499 primary_star_cat : `np.ndarray`
500 Catalog of isolated stars,
with indexes to star_source_cat_cut.
502 ra_col = self.config.ra_column
503 dec_col = self.config.dec_column
507 n_source_per_band_per_obj = np.zeros((len(bands),
508 len(primary_star_cat)),
512 with Matcher(primary_star_cat[ra_col], primary_star_cat[dec_col])
as matcher:
513 for b, band
in enumerate(bands):
514 band_use, = np.where(star_source_cat[
'band'] == band)
516 idx = matcher.query_radius(star_source_cat[ra_col][band_use],
517 star_source_cat[dec_col][band_use],
518 self.config.match_radius/3600.)
519 n_source_per_band_per_obj[b, :] = np.array([len(row)
for row
in idx])
521 band_uses.append(band_use)
523 n_source_per_obj = np.sum(n_source_per_band_per_obj, axis=0)
525 primary_star_cat[
'nsource'] = n_source_per_obj
526 primary_star_cat[
'source_cat_index'][1:] = np.cumsum(n_source_per_obj)[:-1]
528 n_tot_source = primary_star_cat[
'source_cat_index'][-1] + primary_star_cat[
'nsource'][-1]
531 source_index = np.zeros(n_tot_source, dtype=np.int32)
532 obj_index = np.zeros(n_tot_source, dtype=np.int32)
535 for i
in range(len(primary_star_cat)):
536 obj_index[ctr: ctr + n_source_per_obj[i]] = i
537 for b
in range(len(bands)):
538 source_index[ctr: ctr + n_source_per_band_per_obj[b, i]] = band_uses[b][idxs[b][i]]
539 ctr += n_source_per_band_per_obj[b, i]
541 source_cat_index_band_offset = np.cumsum(n_source_per_band_per_obj, axis=0)
543 for b, band
in enumerate(bands):
544 primary_star_cat[f
'nsource_{band}'] = n_source_per_band_per_obj[b, :]
547 primary_star_cat[f
'source_cat_index_{band}'] = primary_star_cat[
'source_cat_index']
550 primary_star_cat[f
'source_cat_index_{band}'] = (primary_star_cat[
'source_cat_index']
551 + source_cat_index_band_offset[b - 1, :])
553 star_source_cat = star_source_cat[source_index]
554 star_source_cat[
'obj_index'] = obj_index
556 return star_source_cat, primary_star_cat
558 def _compute_unique_ids(self, skymap, tract, nstar):
559 """Compute unique star ids.
561 This is a simple hash of the tract
and star to provide an
562 id that
is unique
for a given processing.
566 skymap : `lsst.skymap.Skymap`
576 Array of unique star ids.
579 mult = 10**(int(np.log10(len(skymap))) + 1)
581 return (np.arange(nstar) + 1)*mult + tract
583 def _get_primary_dtype(self, primary_bands):
584 """Get the numpy datatype for the primary star catalog.
588 primary_bands : `list` [`str`]
589 List of primary bands.
593 dtype : `numpy.dtype`
594 Datatype of the primary catalog.
596 max_len = max([len(primary_band) for primary_band
in primary_bands])
598 dtype = [(
'isolated_star_id',
'i8'),
599 (self.config.ra_column,
'f8'),
600 (self.config.dec_column,
'f8'),
601 (
'primary_band', f
'U{max_len}'),
602 (
'source_cat_index',
'i4'),
605 for band
in primary_bands:
606 dtype.append((f
'source_cat_index_{band}',
'i4'))
607 dtype.append((f
'nsource_{band}',
'i4'))
def _get_source_table_visit_column_names(self)
def run(self, skymap, tract, source_table_ref_dict)
def _make_all_star_sources(self, tract_info, source_table_ref_dict)
def runQuantum(self, butlerQC, inputRefs, outputRefs)
def _compute_unique_ids(self, skymap, tract, nstar)
def _match_primary_stars(self, primary_bands, star_source_cat)
def _match_sources(self, bands, star_source_cat, primary_star_cat)
def _get_primary_dtype(self, primary_bands)
def _remove_neighbors(self, primary_star_cat)