LSSTApplications  18.0.0+106,18.0.0+50,19.0.0,19.0.0+1,19.0.0+10,19.0.0+11,19.0.0+13,19.0.0+17,19.0.0+2,19.0.0-1-g20d9b18+6,19.0.0-1-g425ff20,19.0.0-1-g5549ca4,19.0.0-1-g580fafe+6,19.0.0-1-g6fe20d0+1,19.0.0-1-g7011481+9,19.0.0-1-g8c57eb9+6,19.0.0-1-gb5175dc+11,19.0.0-1-gdc0e4a7+9,19.0.0-1-ge272bc4+6,19.0.0-1-ge3aa853,19.0.0-10-g448f008b,19.0.0-12-g6990b2c,19.0.0-2-g0d9f9cd+11,19.0.0-2-g3d9e4fb2+11,19.0.0-2-g5037de4,19.0.0-2-gb96a1c4+3,19.0.0-2-gd955cfd+15,19.0.0-3-g2d13df8,19.0.0-3-g6f3c7dc,19.0.0-4-g725f80e+11,19.0.0-4-ga671dab3b+1,19.0.0-4-gad373c5+3,19.0.0-5-ga2acb9c+2,19.0.0-5-gfe96e6c+2,w.2020.01
LSSTDataManagementBasePackage
functors.py
Go to the documentation of this file.
1 import yaml
2 import re
3 
4 import pandas as pd
5 import numpy as np
6 import astropy.units as u
7 
8 from lsst.daf.persistence import doImport
9 from .parquetTable import MultilevelParquetTable
10 
11 
12 def init_fromDict(initDict, basePath='lsst.pipe.tasks.functors', typeKey='functor'):
13  """Initialize an object defined in a dictionary
14 
15  The object needs to be importable as
16  '{0}.{1}'.format(basePath, initDict[typeKey])
17  The positional and keyword arguments (if any) are contained in
18  "args" and "kwargs" entries in the dictionary, respectively.
19  This is used in `functors.CompositeFunctor.from_yaml` to initialize
20  a composite functor from a specification in a YAML file.
21 
22  Parameters
23  ----------
24  initDict : dictionary
25  Dictionary describing object's initialization. Must contain
26  an entry keyed by ``typeKey`` that is the name of the object,
27  relative to ``basePath``.
28  basePath : str
29  Path relative to module in which ``initDict[typeKey]`` is defined.
30  typeKey : str
31  Key of ``initDict`` that is the name of the object
32  (relative to `basePath`).
33  """
34  initDict = initDict.copy()
35  # TO DO: DM-21956 We should be able to define functors outside this module
36  pythonType = doImport('{0}.{1}'.format(basePath, initDict.pop(typeKey)))
37  args = []
38  if 'args' in initDict:
39  args = initDict.pop('args')
40  if isinstance(args, str):
41  args = [args]
42 
43  return pythonType(*args, **initDict)
44 
45 
46 class Functor(object):
47  """Define and execute a calculation on a ParquetTable
48 
49  The `__call__` method accepts a `ParquetTable` object, and returns the
50  result of the calculation as a single column. Each functor defines what
51  columns are needed for the calculation, and only these columns are read
52  from the `ParquetTable`.
53 
54  The action of `__call__` consists of two steps: first, loading the
55  necessary columns from disk into memory as a `pandas.DataFrame` object;
56  and second, performing the computation on this dataframe and returning the
57  result.
58 
59 
60  To define a new `Functor`, a subclass must define a `_func` method,
61  that takes a `pandas.DataFrame` and returns result in a `pandas.Series`.
62  In addition, it must define the following attributes
63 
64  * `_columns`: The columns necessary to perform the calculation
65  * `name`: A name appropriate for a figure axis label
66  * `shortname`: A name appropriate for use as a dictionary key
67 
68  On initialization, a `Functor` should declare what filter (`filt` kwarg)
69  and dataset (e.g. `'ref'`, `'meas'`, `'forced_src'`) it is intended to be
70  applied to. This enables the `_get_cols` method to extract the proper
71  columns from the parquet file. If not specified, the dataset will fall back
72  on the `_defaultDataset`attribute. If filter is not specified and `dataset`
73  is anything other than `'ref'`, then an error will be raised when trying to
74  perform the calculation.
75 
76  As currently implemented, `Functor` is only set up to expect a
77  `ParquetTable` of the format of the `deepCoadd_obj` dataset; that is, a
78  `MultilevelParquetTable` with the levels of the column index being `filter`,
79  `dataset`, and `column`. This is defined in the `_columnLevels` attribute,
80  as well as being implicit in the role of the `filt` and `dataset` attributes
81  defined at initialization. In addition, the `_get_cols` method that reads
82  the dataframe from the `ParquetTable` will return a dataframe with column
83  index levels defined by the `_dfLevels` attribute; by default, this is
84  `column`.
85 
86  The `_columnLevels` and `_dfLevels` attributes should generally not need to
87  be changed, unless `_func` needs columns from multiple filters or datasets
88  to do the calculation.
89  An example of this is the `lsst.pipe.tasks.functors.Color` functor, for
90  which `_dfLevels = ('filter', 'column')`, and `_func` expects the dataframe
91  it gets to have those levels in the column index.
92 
93  Parameters
94  ----------
95  filt : str
96  Filter upon which to do the calculation
97 
98  dataset : str
99  Dataset upon which to do the calculation
100  (e.g., 'ref', 'meas', 'forced_src').
101 
102  """
103 
104  _defaultDataset = 'ref'
105  _columnLevels = ('filter', 'dataset', 'column')
106  _dfLevels = ('column',)
107  _defaultNoDup = False
108 
109  def __init__(self, filt=None, dataset=None, noDup=None):
110  self.filt = filt
111  self.dataset = dataset if dataset is not None else self._defaultDataset
112  self._noDup = noDup
113 
114  @property
115  def noDup(self):
116  if self._noDup is not None:
117  return self._noDup
118  else:
119  return self._defaultNoDup
120 
121  @property
122  def columns(self):
123  """Columns required to perform calculation
124  """
125  if not hasattr(self, '_columns'):
126  raise NotImplementedError('Must define columns property or _columns attribute')
127  return self._columns
128 
129  def multilevelColumns(self, parq):
130  if not set(parq.columnLevels) == set(self._columnLevels):
131  raise ValueError('ParquetTable does not have the expected column levels. ' +
132  'Got {0}; expected {1}.'.format(parq.columnLevels, self._columnLevels))
133 
134  columnDict = {'column': self.columns,
135  'dataset': self.dataset}
136  if self.filt is None:
137  if 'filter' in parq.columnLevels:
138  if self.dataset == 'ref':
139  columnDict['filter'] = parq.columnLevelNames['filter'][0]
140  else:
141  raise ValueError("'filt' not set for functor {}".format(self.name) +
142  "(dataset {}) ".format(self.dataset) +
143  "and ParquetTable " +
144  "contains multiple filters in column index. " +
145  "Set 'filt' or set 'dataset' to 'ref'.")
146  else:
147  columnDict['filter'] = self.filt
148 
149  return parq._colsFromDict(columnDict)
150 
151  def _func(self, df, dropna=True):
152  raise NotImplementedError('Must define calculation on dataframe')
153 
154  def _get_cols(self, parq):
155  """Retrieve dataframe necessary for calculation.
156 
157  Returns dataframe upon which `self._func` can act.
158  """
159  if isinstance(parq, MultilevelParquetTable):
160  columns = self.multilevelColumns(parq)
161  df = parq.toDataFrame(columns=columns, droplevels=False)
162  df = self._setLevels(df)
163  else:
164  columns = self.columns
165  df = parq.toDataFrame(columns=columns)
166 
167  return df
168 
169  def _setLevels(self, df):
170  levelsToDrop = [n for n in df.columns.names if n not in self._dfLevels]
171  df.columns = df.columns.droplevel(levelsToDrop)
172  return df
173 
174  def _dropna(self, vals):
175  return vals.dropna()
176 
177  def __call__(self, parq, dropna=False):
178  try:
179  df = self._get_cols(parq)
180  vals = self._func(df)
181  except Exception:
182  vals = self.fail(df)
183  if dropna:
184  vals = self._dropna(vals)
185 
186  return vals
187 
188  def fail(self, df):
189  return pd.Series(np.full(len(df), np.nan), index=df.index)
190 
191  @property
192  def name(self):
193  """Full name of functor (suitable for figure labels)
194  """
195  return NotImplementedError
196 
197  @property
198  def shortname(self):
199  """Short name of functor (suitable for column name/dict key)
200  """
201  return self.name
202 
203 
205  """Perform multiple calculations at once on a catalog
206 
207  The role of a `CompositeFunctor` is to group together computations from
208  multiple functors. Instead of returning `pandas.Series` a
209  `CompositeFunctor` returns a `pandas.Dataframe`, with the column names
210  being the keys of `funcDict`.
211 
212  The `columns` attribute of a `CompositeFunctor` is the union of all columns
213  in all the component functors.
214 
215  A `CompositeFunctor` does not use a `_func` method itself; rather,
216  when a `CompositeFunctor` is called, all its columns are loaded
217  at once, and the resulting dataframe is passed to the `_func` method of each component
218  functor. This has the advantage of only doing I/O (reading from parquet file) once,
219  and works because each individual `_func` method of each component functor does not
220  care if there are *extra* columns in the dataframe being passed; only that it must contain
221  *at least* the `columns` it expects.
222 
223  An important and useful class method is `from_yaml`, which takes as argument the path to a YAML
224  file specifying a collection of functors.
225 
226  Parameters
227  ----------
228  funcs : `dict` or `list`
229  Dictionary or list of functors. If a list, then it will be converted
230  into a dictonary according to the `.shortname` attribute of each functor.
231 
232  """
233  dataset = None
234 
235  def __init__(self, funcs, **kwargs):
236 
237  if type(funcs) == dict:
238  self.funcDict = funcs
239  else:
240  self.funcDict = {f.shortname: f for f in funcs}
241 
242  self._filt = None
243 
244  super().__init__(**kwargs)
245 
246  @property
247  def filt(self):
248  return self._filt
249 
250  @filt.setter
251  def filt(self, filt):
252  if filt is not None:
253  for _, f in self.funcDict.items():
254  f.filt = filt
255  self._filt = filt
256 
257  def update(self, new):
258  if isinstance(new, dict):
259  self.funcDict.update(new)
260  elif isinstance(new, CompositeFunctor):
261  self.funcDict.update(new.funcDict)
262  else:
263  raise TypeError('Can only update with dictionary or CompositeFunctor.')
264 
265  # Make sure new functors have the same 'filt' set
266  if self.filt is not None:
267  self.filt = self.filt
268 
269  @property
270  def columns(self):
271  return list(set([x for y in [f.columns for f in self.funcDict.values()] for x in y]))
272 
273  def multilevelColumns(self, parq):
274  return list(set([x for y in [f.multilevelColumns(parq)
275  for f in self.funcDict.values()] for x in y]))
276 
277  def __call__(self, parq, **kwargs):
278  if isinstance(parq, MultilevelParquetTable):
279  columns = self.multilevelColumns(parq)
280  df = parq.toDataFrame(columns=columns, droplevels=False)
281  valDict = {}
282  for k, f in self.funcDict.items():
283  try:
284  subdf = f._setLevels(df[f.multilevelColumns(parq)])
285  valDict[k] = f._func(subdf)
286  except Exception:
287  valDict[k] = f.fail(subdf)
288  else:
289  columns = self.columns
290  df = parq.toDataFrame(columns=columns)
291  valDict = {k: f._func(df) for k, f in self.funcDict.items()}
292 
293  try:
294  valDf = pd.concat(valDict, axis=1)
295  except TypeError:
296  print([(k, type(v)) for k, v in valDict.items()])
297  raise
298 
299  if kwargs.get('dropna', False):
300  valDf = valDf.dropna(how='any')
301 
302  return valDf
303 
304  @classmethod
305  def renameCol(cls, col, renameRules):
306  if renameRules is None:
307  return col
308  for old, new in renameRules:
309  if col.startswith(old):
310  col = col.replace(old, new)
311  return col
312 
313  @classmethod
314  def from_file(cls, filename, **kwargs):
315  with open(filename) as f:
316  translationDefinition = yaml.safe_load(f)
317 
318  return cls.from_yaml(translationDefinition, **kwargs)
319 
320  @classmethod
321  def from_yaml(cls, translationDefinition, **kwargs):
322  funcs = {}
323  for func, val in translationDefinition['funcs'].items():
324  funcs[func] = init_fromDict(val)
325 
326  if 'flag_rename_rules' in translationDefinition:
327  renameRules = translationDefinition['flag_rename_rules']
328  else:
329  renameRules = None
330 
331  if 'flags' in translationDefinition:
332  for flag in translationDefinition['flags']:
333  funcs[cls.renameCol(flag, renameRules)] = Column(flag, dataset='ref')
334 
335  return cls(funcs, **kwargs)
336 
337 
338 def mag_aware_eval(df, expr):
339  """Evaluate an expression on a DataFrame, knowing what the 'mag' function means
340 
341  Builds on `pandas.DataFrame.eval`, which parses and executes math on dataframes.
342 
343  Parameters
344  ----------
345  df : pandas.DataFrame
346  Dataframe on which to evaluate expression.
347 
348  expr : str
349  Expression.
350  """
351  try:
352  expr_new = re.sub(r'mag\((\w+)\)', r'-2.5*log(\g<1>)/log(10)', expr)
353  val = df.eval(expr_new, truediv=True)
354  except Exception: # Should check what actually gets raised
355  expr_new = re.sub(r'mag\((\w+)\)', r'-2.5*log(\g<1>_instFlux)/log(10)', expr)
356  val = df.eval(expr_new, truediv=True)
357  return val
358 
359 
361  """Arbitrary computation on a catalog
362 
363  Column names (and thus the columns to be loaded from catalog) are found
364  by finding all words and trying to ignore all "math-y" words.
365 
366  Parameters
367  ----------
368  expr : str
369  Expression to evaluate, to be parsed and executed by `mag_aware_eval`.
370  """
371  _ignore_words = ('mag', 'sin', 'cos', 'exp', 'log', 'sqrt')
372 
373  def __init__(self, expr, **kwargs):
374  self.expr = expr
375  super().__init__(**kwargs)
376 
377  @property
378  def name(self):
379  return self.expr
380 
381  @property
382  def columns(self):
383  flux_cols = re.findall(r'mag\(\s*(\w+)\s*\)', self.expr)
384 
385  cols = [c for c in re.findall(r'[a-zA-Z_]+', self.expr) if c not in self._ignore_words]
386  not_a_col = []
387  for c in flux_cols:
388  if not re.search('_instFlux$', c):
389  cols.append('{}_instFlux'.format(c))
390  not_a_col.append(c)
391  else:
392  cols.append(c)
393 
394  return list(set([c for c in cols if c not in not_a_col]))
395 
396  def _func(self, df):
397  return mag_aware_eval(df, self.expr)
398 
399 
401  """Get column with specified name
402  """
403 
404  def __init__(self, col, **kwargs):
405  self.col = col
406  super().__init__(**kwargs)
407 
408  @property
409  def name(self):
410  return self.col
411 
412  @property
413  def columns(self):
414  return [self.col]
415 
416  def _func(self, df):
417  return df[self.col]
418 
419 
420 class Index(Functor):
421  """Return the value of the index for each object
422  """
423 
424  columns = ['coord_ra'] # just a dummy; something has to be here
425  _defaultDataset = 'ref'
426  _defaultNoDup = True
427 
428  def _func(self, df):
429  return pd.Series(df.index, index=df.index)
430 
431 
433  col = 'id'
434  _allow_difference = False
435  _defaultNoDup = True
436 
437  def _func(self, df):
438  return pd.Series(df.index, index=df.index)
439 
440 
442  col = 'base_Footprint_nPix'
443 
444 
446  """Base class for coordinate column, in degrees
447  """
448  _allow_difference = False
449  _radians = True
450  _defaultNoDup = True
451 
452  def __init__(self, col, calculate=False, **kwargs):
453  self.calculate = calculate
454  super().__init__(col, **kwargs)
455 
456  def _func(self, df):
457  res = df[self.col]
458  if self._radians:
459  res *= 180 / np.pi
460  return res
461 
462 
464  """Right Ascension, in degrees
465  """
466  name = 'RA'
467 
468  def __init__(self, **kwargs):
469  super().__init__('coord_ra', **kwargs)
470 
471  def __call__(self, catalog, **kwargs):
472  return super().__call__(catalog, **kwargs)
473 
474 
476  """Declination, in degrees
477  """
478  name = 'Dec'
479 
480  def __init__(self, **kwargs):
481  super().__init__('coord_dec', **kwargs)
482 
483  def __call__(self, catalog, **kwargs):
484  return super().__call__(catalog, **kwargs)
485 
486 
487 def fluxName(col):
488  if not col.endswith('_instFlux'):
489  col += '_instFlux'
490  return col
491 
492 
493 def fluxErrName(col):
494  if not col.endswith('_instFluxErr'):
495  col += '_instFluxErr'
496  return col
497 
498 
499 class Mag(Functor):
500  """Compute calibrated magnitude
501 
502  Takes a `calib` argument, which returns the flux at mag=0
503  as `calib.getFluxMag0()`. If not provided, then the default
504  `fluxMag0` is 63095734448.0194, which is default for HSC.
505  This default should be removed in DM-21955
506 
507  This calculation hides warnings about invalid values and dividing by zero.
508 
509  As for all functors, a `dataset` and `filt` kwarg should be provided upon
510  initialization. Unlike the default `Functor`, however, the default dataset
511  for a `Mag` is `'meas'`, rather than `'ref'`.
512 
513  Parameters
514  ----------
515  col : `str`
516  Name of flux column from which to compute magnitude. Can be parseable
517  by `lsst.pipe.tasks.functors.fluxName` function---that is, you can pass
518  `'modelfit_CModel'` instead of `'modelfit_CModel_instFlux'`) and it will
519  understand.
520  calib : `lsst.afw.image.calib.Calib` (optional)
521  Object that knows zero point.
522  """
523  _defaultDataset = 'meas'
524 
525  def __init__(self, col, calib=None, **kwargs):
526  self.col = fluxName(col)
527  self.calib = calib
528  if calib is not None:
529  self.fluxMag0 = calib.getFluxMag0()[0]
530  else:
531  # TO DO: DM-21955 Replace hard coded photometic calibration values
532  self.fluxMag0 = 63095734448.0194
533 
534  super().__init__(**kwargs)
535 
536  @property
537  def columns(self):
538  return [self.col]
539 
540  def _func(self, df):
541  with np.warnings.catch_warnings():
542  np.warnings.filterwarnings('ignore', r'invalid value encountered')
543  np.warnings.filterwarnings('ignore', r'divide by zero')
544  return -2.5*np.log10(df[self.col] / self.fluxMag0)
545 
546  @property
547  def name(self):
548  return 'mag_{0}'.format(self.col)
549 
550 
551 class MagErr(Mag):
552  """Compute calibrated magnitude uncertainty
553 
554  Takes the same `calib` object as `lsst.pipe.tasks.functors.Mag`.
555 
556  Parameters
557  col : `str`
558  Name of flux column
559  calib : `lsst.afw.image.calib.Calib` (optional)
560  Object that knows zero point.
561  """
562 
563  def __init__(self, *args, **kwargs):
564  super().__init__(*args, **kwargs)
565  if self.calib is not None:
566  self.fluxMag0Err = self.calib.getFluxMag0()[1]
567  else:
568  self.fluxMag0Err = 0.
569 
570  @property
571  def columns(self):
572  return [self.col, self.col + 'Err']
573 
574  def _func(self, df):
575  with np.warnings.catch_warnings():
576  np.warnings.filterwarnings('ignore', r'invalid value encountered')
577  np.warnings.filterwarnings('ignore', r'divide by zero')
578  fluxCol, fluxErrCol = self.columns
579  x = df[fluxErrCol] / df[fluxCol]
580  y = self.fluxMag0Err / self.fluxMag0
581  magErr = (2.5 / np.log(10.)) * np.sqrt(x*x + y*y)
582  return magErr
583 
584  @property
585  def name(self):
586  return super().name + '_err'
587 
588 
590  """
591  """
592 
593  def _func(self, df):
594  return (df[self.col] / self.fluxMag0) * 1e9
595 
596 
598  _defaultDataset = 'meas'
599 
600  """Functor to calculate magnitude difference"""
601 
602  def __init__(self, col1, col2, **kwargs):
603  self.col1 = fluxName(col1)
604  self.col2 = fluxName(col2)
605  super().__init__(**kwargs)
606 
607  @property
608  def columns(self):
609  return [self.col1, self.col2]
610 
611  def _func(self, df):
612  with np.warnings.catch_warnings():
613  np.warnings.filterwarnings('ignore', r'invalid value encountered')
614  np.warnings.filterwarnings('ignore', r'divide by zero')
615  return -2.5*np.log10(df[self.col1]/df[self.col2])
616 
617  @property
618  def name(self):
619  return '(mag_{0} - mag_{1})'.format(self.col1, self.col2)
620 
621  @property
622  def shortname(self):
623  return 'magDiff_{0}_{1}'.format(self.col1, self.col2)
624 
625 
626 class Color(Functor):
627  """Compute the color between two filters
628 
629  Computes color by initializing two different `Mag`
630  functors based on the `col` and filters provided, and
631  then returning the difference.
632 
633  This is enabled by the `_func` expecting a dataframe with a
634  multilevel column index, with both `'filter'` and `'column'`,
635  instead of just `'column'`, which is the `Functor` default.
636  This is controlled by the `_dfLevels` attribute.
637 
638  Also of note, the default dataset for `Color` is `forced_src'`,
639  whereas for `Mag` it is `'meas'`.
640 
641  Parameters
642  ----------
643  col : str
644  Name of flux column from which to compute; same as would be passed to
645  `lsst.pipe.tasks.functors.Mag`.
646 
647  filt2, filt1 : str
648  Filters from which to compute magnitude difference.
649  Color computed is `Mag(filt2) - Mag(filt1)`.
650  """
651  _defaultDataset = 'forced_src'
652  _dfLevels = ('filter', 'column')
653  _defaultNoDup = True
654 
655  def __init__(self, col, filt2, filt1, **kwargs):
656  self.col = fluxName(col)
657  if filt2 == filt1:
658  raise RuntimeError("Cannot compute Color for %s: %s - %s " % (col, filt2, filt1))
659  self.filt2 = filt2
660  self.filt1 = filt1
661 
662  self.mag2 = Mag(col, filt=filt2, **kwargs)
663  self.mag1 = Mag(col, filt=filt1, **kwargs)
664 
665  super().__init__(**kwargs)
666 
667  @property
668  def filt(self):
669  return None
670 
671  @filt.setter
672  def filt(self, filt):
673  pass
674 
675  def _func(self, df):
676  mag2 = self.mag2._func(df[self.filt2])
677  mag1 = self.mag1._func(df[self.filt1])
678  return mag2 - mag1
679 
680  @property
681  def columns(self):
682  return [self.mag1.col, self.mag2.col]
683 
684  def multilevelColumns(self, parq):
685  return [(self.dataset, self.filt1, self.col),
686  (self.dataset, self.filt2, self.col)]
687 
688  @property
689  def name(self):
690  return '{0} - {1} ({2})'.format(self.filt2, self.filt1, self.col)
691 
692  @property
693  def shortname(self):
694  return '{0}_{1}m{2}'.format(self.col, self.filt2.replace('-', ''),
695  self.filt1.replace('-', ''))
696 
697 
699  """Main function of this subclass is to override the dropna=True
700  """
701  _null_label = 'null'
702  _allow_difference = False
703  name = 'label'
704  _force_str = False
705 
706  def __call__(self, parq, dropna=False, **kwargs):
707  return super().__call__(parq, dropna=False, **kwargs)
708 
709 
711  _columns = ["base_ClassificationExtendedness_value"]
712  _column = "base_ClassificationExtendedness_value"
713 
714  def _func(self, df):
715  x = df[self._columns][self._column]
716  mask = x.isnull()
717  test = (x < 0.5).astype(int)
718  test = test.mask(mask, 2)
719 
720  # TODO: DM-21954 Look into veracity of inline comment below
721  # are these backwards?
722  categories = ['galaxy', 'star', self._null_label]
723  label = pd.Series(pd.Categorical.from_codes(test, categories=categories),
724  index=x.index, name='label')
725  if self._force_str:
726  label = label.astype(str)
727  return label
728 
729 
731  _columns = ['numStarFlags']
732  labels = {"star": 0, "maybe": 1, "notStar": 2}
733 
734  def _func(self, df):
735  x = df[self._columns][self._columns[0]]
736 
737  # Number of filters
738  n = len(x.unique()) - 1
739 
740  labels = ['noStar', 'maybe', 'star']
741  label = pd.Series(pd.cut(x, [-1, 0, n-1, n], labels=labels),
742  index=x.index, name='label')
743 
744  if self._force_str:
745  label = label.astype(str)
746 
747  return label
748 
749 
751  name = 'Deconvolved Moments'
752  shortname = 'deconvolvedMoments'
753  _columns = ("ext_shapeHSM_HsmSourceMoments_xx",
754  "ext_shapeHSM_HsmSourceMoments_yy",
755  "base_SdssShape_xx", "base_SdssShape_yy",
756  "ext_shapeHSM_HsmPsfMoments_xx",
757  "ext_shapeHSM_HsmPsfMoments_yy")
758 
759  def _func(self, df):
760  """Calculate deconvolved moments"""
761  if "ext_shapeHSM_HsmSourceMoments_xx" in df.columns: # _xx added by tdm
762  hsm = df["ext_shapeHSM_HsmSourceMoments_xx"] + df["ext_shapeHSM_HsmSourceMoments_yy"]
763  else:
764  hsm = np.ones(len(df))*np.nan
765  sdss = df["base_SdssShape_xx"] + df["base_SdssShape_yy"]
766  if "ext_shapeHSM_HsmPsfMoments_xx" in df.columns:
767  psf = df["ext_shapeHSM_HsmPsfMoments_xx"] + df["ext_shapeHSM_HsmPsfMoments_yy"]
768  else:
769  # LSST does not have shape.sdss.psf. Could instead add base_PsfShape to catalog using
770  # exposure.getPsf().computeShape(s.getCentroid()).getIxx()
771  # raise TaskError("No psf shape parameter found in catalog")
772  raise RuntimeError('No psf shape parameter found in catalog')
773 
774  return hsm.where(np.isfinite(hsm), sdss) - psf
775 
776 
778  """Functor to calculate SDSS trace radius size for sources"""
779  name = "SDSS Trace Size"
780  shortname = 'sdssTrace'
781  _columns = ("base_SdssShape_xx", "base_SdssShape_yy")
782 
783  def _func(self, df):
784  srcSize = np.sqrt(0.5*(df["base_SdssShape_xx"] + df["base_SdssShape_yy"]))
785  return srcSize
786 
787 
789  """Functor to calculate SDSS trace radius size difference (%) between object and psf model"""
790  name = "PSF - SDSS Trace Size"
791  shortname = 'psf_sdssTrace'
792  _columns = ("base_SdssShape_xx", "base_SdssShape_yy",
793  "base_SdssShape_psf_xx", "base_SdssShape_psf_yy")
794 
795  def _func(self, df):
796  srcSize = np.sqrt(0.5*(df["base_SdssShape_xx"] + df["base_SdssShape_yy"]))
797  psfSize = np.sqrt(0.5*(df["base_SdssShape_psf_xx"] + df["base_SdssShape_psf_yy"]))
798  sizeDiff = 100*(srcSize - psfSize)/(0.5*(srcSize + psfSize))
799  return sizeDiff
800 
801 
803  """Functor to calculate HSM trace radius size for sources"""
804  name = 'HSM Trace Size'
805  shortname = 'hsmTrace'
806  _columns = ("ext_shapeHSM_HsmSourceMoments_xx",
807  "ext_shapeHSM_HsmSourceMoments_yy")
808 
809  def _func(self, df):
810  srcSize = np.sqrt(0.5*(df["ext_shapeHSM_HsmSourceMoments_xx"] +
811  df["ext_shapeHSM_HsmSourceMoments_yy"]))
812  return srcSize
813 
814 
816  """Functor to calculate HSM trace radius size difference (%) between object and psf model"""
817  name = 'PSF - HSM Trace Size'
818  shortname = 'psf_HsmTrace'
819  _columns = ("ext_shapeHSM_HsmSourceMoments_xx",
820  "ext_shapeHSM_HsmSourceMoments_yy",
821  "ext_shapeHSM_HsmPsfMoments_xx",
822  "ext_shapeHSM_HsmPsfMoments_yy")
823 
824  def _func(self, df):
825  srcSize = np.sqrt(0.5*(df["ext_shapeHSM_HsmSourceMoments_xx"] +
826  df["ext_shapeHSM_HsmSourceMoments_yy"]))
827  psfSize = np.sqrt(0.5*(df["ext_shapeHSM_HsmPsfMoments_xx"] +
828  df["ext_shapeHSM_HsmPsfMoments_yy"]))
829  sizeDiff = 100*(srcSize - psfSize)/(0.5*(srcSize + psfSize))
830  return sizeDiff
831 
832 
834  name = 'HSM Psf FWHM'
835  _columns = ('ext_shapeHSM_HsmPsfMoments_xx', 'ext_shapeHSM_HsmPsfMoments_yy')
836  # TODO: DM-21403 pixel scale should be computed from the CD matrix or transform matrix
837  pixelScale = 0.168
838  SIGMA2FWHM = 2*np.sqrt(2*np.log(2))
839 
840  def _func(self, df):
841  return self.pixelScale*self.SIGMA2FWHM*np.sqrt(
842  0.5*(df['ext_shapeHSM_HsmPsfMoments_xx'] + df['ext_shapeHSM_HsmPsfMoments_yy']))
843 
844 
845 class E1(Functor):
846  name = "Distortion Ellipticity (e1)"
847  shortname = "Distortion"
848 
849  def __init__(self, colXX, colXY, colYY, **kwargs):
850  self.colXX = colXX
851  self.colXY = colXY
852  self.colYY = colYY
853  self._columns = [self.colXX, self.colXY, self.colYY]
854  super().__init__(**kwargs)
855 
856  @property
857  def columns(self):
858  return [self.colXX, self.colXY, self.colYY]
859 
860  def _func(self, df):
861  return df[self.colXX] - df[self.colYY] / (df[self.colXX] + df[self.colYY])
862 
863 
864 class E2(Functor):
865  name = "Ellipticity e2"
866 
867  def __init__(self, colXX, colXY, colYY, **kwargs):
868  self.colXX = colXX
869  self.colXY = colXY
870  self.colYY = colYY
871  super().__init__(**kwargs)
872 
873  @property
874  def columns(self):
875  return [self.colXX, self.colXY, self.colYY]
876 
877  def _func(self, df):
878  return 2*df[self.colXY] / (df[self.colXX] + df[self.colYY])
879 
880 
882 
883  def __init__(self, colXX, colXY, colYY, **kwargs):
884  self.colXX = colXX
885  self.colXY = colXY
886  self.colYY = colYY
887  super().__init__(**kwargs)
888 
889  @property
890  def columns(self):
891  return [self.colXX, self.colXY, self.colYY]
892 
893  def _func(self, df):
894  return (df[self.colXX]*df[self.colYY] - df[self.colXY]**2)**0.25
895 
896 
898  name = 'Reference Band'
899  shortname = 'refBand'
900 
901  @property
902  def columns(self):
903  return ["merge_measurement_i",
904  "merge_measurement_r",
905  "merge_measurement_z",
906  "merge_measurement_y",
907  "merge_measurement_g"]
908 
909  def _func(self, df):
910  def getFilterAliasName(row):
911  # get column name with the max value (True > False)
912  colName = row.idxmax()
913  return colName.replace('merge_measurement_', '')
914 
915  return df[self.columns].apply(getFilterAliasName, axis=1)
916 
917 
919  # AB to NanoJansky (3631 Jansky)
920  AB_FLUX_SCALE = (0 * u.ABmag).to_value(u.nJy)
921  LOG_AB_FLUX_SCALE = 12.56
922  FIVE_OVER_2LOG10 = 1.085736204758129569
923  # TO DO: DM-21955 Replace hard coded photometic calibration values
924  COADD_ZP = 27
925 
926  def __init__(self, colFlux, colFluxErr=None, calib=None, **kwargs):
927  self.vhypot = np.vectorize(self.hypot)
928  self.col = colFlux
929  self.colFluxErr = colFluxErr
930 
931  self.calib = calib
932  if calib is not None:
933  self.fluxMag0, self.fluxMag0Err = calib.getFluxMag0()
934  else:
935  self.fluxMag0 = 1./np.power(10, -0.4*self.COADD_ZP)
936  self.fluxMag0Err = 0.
937 
938  super().__init__(**kwargs)
939 
940  @property
941  def columns(self):
942  return [self.col]
943 
944  @property
945  def name(self):
946  return 'mag_{0}'.format(self.col)
947 
948  @classmethod
949  def hypot(cls, a, b):
950  if np.abs(a) < np.abs(b):
951  a, b = b, a
952  if a == 0.:
953  return 0.
954  q = b/a
955  return np.abs(a) * np.sqrt(1. + q*q)
956 
957  def dn2flux(self, dn, fluxMag0):
958  return self.AB_FLUX_SCALE * dn / fluxMag0
959 
960  def dn2mag(self, dn, fluxMag0):
961  with np.warnings.catch_warnings():
962  np.warnings.filterwarnings('ignore', r'invalid value encountered')
963  np.warnings.filterwarnings('ignore', r'divide by zero')
964  return -2.5 * np.log10(dn/fluxMag0)
965 
966  def dn2fluxErr(self, dn, dnErr, fluxMag0, fluxMag0Err):
967  retVal = self.vhypot(dn * fluxMag0Err, dnErr * fluxMag0)
968  retVal *= self.AB_FLUX_SCALE / fluxMag0 / fluxMag0
969  return retVal
970 
971  def dn2MagErr(self, dn, dnErr, fluxMag0, fluxMag0Err):
972  retVal = self.dn2fluxErr(dn, dnErr, fluxMag0, fluxMag0Err) / self.dn2flux(dn, fluxMag0)
973  return self.FIVE_OVER_2LOG10 * retVal
974 
975 
977  def _func(self, df):
978  return self.dn2flux(df[self.col], self.fluxMag0)
979 
980 
982  @property
983  def columns(self):
984  return [self.col, self.colFluxErr]
985 
986  def _func(self, df):
987  retArr = self.dn2fluxErr(df[self.col], df[self.colFluxErr], self.fluxMag0, self.fluxMag0Err)
988  return pd.Series(retArr, index=df.index)
989 
990 
992  def _func(self, df):
993  return self.dn2mag(df[self.col], self.fluxMag0)
994 
995 
997  @property
998  def columns(self):
999  return [self.col, self.colFluxErr]
1000 
1001  def _func(self, df):
1002  retArr = self.dn2MagErr(df[self.col], df[self.colFluxErr], self.fluxMag0, self.fluxMag0Err)
1003  return pd.Series(retArr, index=df.index)
def format(config, name=None, writeSourceLine=True, prefix="", verbose=False)
Definition: history.py:174
def __init__(self, expr, kwargs)
Definition: functors.py:373
def __init__(self, col, calculate=False, kwargs)
Definition: functors.py:452
def __call__(self, parq, dropna=False)
Definition: functors.py:177
std::vector< SchemaItem< Flag > > * items
def __init__(self, col, kwargs)
Definition: functors.py:404
def dn2MagErr(self, dn, dnErr, fluxMag0, fluxMag0Err)
Definition: functors.py:971
def __call__(self, catalog, kwargs)
Definition: functors.py:471
def _func(self, df, dropna=True)
Definition: functors.py:151
def __call__(self, parq, kwargs)
Definition: functors.py:277
daf::base::PropertySet * set
Definition: fits.cc:902
def __call__(self, catalog, kwargs)
Definition: functors.py:483
def __init__(self, colXX, colXY, colYY, kwargs)
Definition: functors.py:883
def __init__(self, col1, col2, kwargs)
Definition: functors.py:602
def multilevelColumns(self, parq)
Definition: functors.py:684
def __init__(self, col, filt2, filt1, kwargs)
Definition: functors.py:655
def __call__(self, parq, dropna=False, kwargs)
Definition: functors.py:706
def mag_aware_eval(df, expr)
Definition: functors.py:338
def renameCol(cls, col, renameRules)
Definition: functors.py:305
def __init__(self, filt=None, dataset=None, noDup=None)
Definition: functors.py:109
def __init__(self, colXX, colXY, colYY, kwargs)
Definition: functors.py:849
table::Key< int > type
Definition: Detector.cc:163
def from_yaml(cls, translationDefinition, kwargs)
Definition: functors.py:321
def doImport(pythonType)
Definition: utils.py:104
def from_file(cls, filename, kwargs)
Definition: functors.py:314
def __init__(self, colFlux, colFluxErr=None, calib=None, kwargs)
Definition: functors.py:926
def __init__(self, kwargs)
Definition: functors.py:468
def dn2mag(self, dn, fluxMag0)
Definition: functors.py:960
def __init__(self, col, calib=None, kwargs)
Definition: functors.py:525
def __init__(self, args, kwargs)
Definition: functors.py:563
def dn2fluxErr(self, dn, dnErr, fluxMag0, fluxMag0Err)
Definition: functors.py:966
def multilevelColumns(self, parq)
Definition: functors.py:129
def dn2flux(self, dn, fluxMag0)
Definition: functors.py:957
def __init__(self, funcs, kwargs)
Definition: functors.py:235
def init_fromDict(initDict, basePath='lsst.pipe.tasks.functors', typeKey='functor')
Definition: functors.py:12
def __init__(self, colXX, colXY, colYY, kwargs)
Definition: functors.py:867
daf::base::PropertyList * list
Definition: fits.cc:903