Coverage for python/lsst/meas/base/diaCalculationPlugins.py: 42%
521 statements
« prev ^ index » next coverage.py v7.6.10, created at 2025-01-27 23:43 +0000
« prev ^ index » next coverage.py v7.6.10, created at 2025-01-27 23:43 +0000
1# This file is part of ap_association.
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/>.
22"""Plugins for use in DiaSource summary statistics.
24Output columns must be
25as defined in the schema of the Apdb both in name and units.
26"""
28import functools
29import warnings
31from astropy.stats import median_absolute_deviation
32import numpy as np
33import pandas as pd
34from scipy.optimize import lsq_linear
36import lsst.geom as geom
37import lsst.pex.config as pexConfig
38import lsst.sphgeom as sphgeom
39from astropy.timeseries import LombScargle
40from astropy.timeseries import LombScargleMultiband
41import math
42import statistics
44from .diaCalculation import (
45 DiaObjectCalculationPluginConfig,
46 DiaObjectCalculationPlugin)
47from .pluginRegistry import register
50__all__ = ("MeanDiaPositionConfig", "MeanDiaPosition",
51 "HTMIndexDiaPosition", "HTMIndexDiaPositionConfig",
52 "NumDiaSourcesDiaPlugin", "NumDiaSourcesDiaPluginConfig",
53 "SimpleSourceFlagDiaPlugin", "SimpleSourceFlagDiaPluginConfig",
54 "WeightedMeanDiaPsfFluxConfig", "WeightedMeanDiaPsfFlux",
55 "PercentileDiaPsfFlux", "PercentileDiaPsfFluxConfig",
56 "SigmaDiaPsfFlux", "SigmaDiaPsfFluxConfig",
57 "Chi2DiaPsfFlux", "Chi2DiaPsfFluxConfig",
58 "MadDiaPsfFlux", "MadDiaPsfFluxConfig",
59 "SkewDiaPsfFlux", "SkewDiaPsfFluxConfig",
60 "MinMaxDiaPsfFlux", "MinMaxDiaPsfFluxConfig",
61 "MaxSlopeDiaPsfFlux", "MaxSlopeDiaPsfFluxConfig",
62 "ErrMeanDiaPsfFlux", "ErrMeanDiaPsfFluxConfig",
63 "LinearFitDiaPsfFlux", "LinearFitDiaPsfFluxConfig",
64 "StetsonJDiaPsfFlux", "StetsonJDiaPsfFluxConfig",
65 "WeightedMeanDiaTotFlux", "WeightedMeanDiaTotFluxConfig",
66 "SigmaDiaTotFlux", "SigmaDiaTotFluxConfig",
67 "LombScarglePeriodogram", "LombScarglePeriodogramConfig",
68 "LombScarglePeriodogramMulti", "LombScarglePeriodogramMultiConfig")
71def catchWarnings(_func=None, *, warns=[]):
72 """Decorator for generically catching numpy warnings.
73 """
74 def decoratorCatchWarnings(func):
75 @functools.wraps(func)
76 def wrapperCatchWarnings(*args, **kwargs):
77 with warnings.catch_warnings():
78 for val in warns:
79 warnings.filterwarnings("ignore", val)
80 return func(*args, **kwargs)
81 return wrapperCatchWarnings
83 if _func is None: 83 ↛ 86line 83 didn't jump to line 86 because the condition on line 83 was always true
84 return decoratorCatchWarnings
85 else:
86 return decoratorCatchWarnings(_func)
89def compute_optimized_periodogram_grid(x0, oversampling_factor=5, nyquist_factor=100):
90 """
91 Computes an optimized periodogram frequency grid for a given time series.
93 Parameters
94 ----------
95 x0 : `array`
96 The input time axis.
97 oversampling_factor : `int`, optional
98 The oversampling factor for frequency grid.
99 nyquist_factor : `int`, optional
100 The Nyquist factor for frequency grid.
102 Returns
103 -------
104 frequencies : `array`
105 The computed optimized periodogram frequency grid.
106 """
108 num_points = len(x0)
109 baseline = np.max(x0) - np.min(x0)
111 # Calculate the frequency resolution based on oversampling factor and baseline
112 frequency_resolution = 1. / baseline / oversampling_factor
114 num_frequencies = int(
115 0.5 * oversampling_factor * nyquist_factor * num_points)
116 frequencies = frequency_resolution + \
117 frequency_resolution * np.arange(num_frequencies)
119 return frequencies
122class LombScarglePeriodogramConfig(DiaObjectCalculationPluginConfig):
123 pass
126@register("ap_lombScarglePeriodogram")
127class LombScarglePeriodogram(DiaObjectCalculationPlugin):
128 """Compute the single-band period of a DiaObject given a set of DiaSources.
129 """
130 ConfigClass = LombScarglePeriodogramConfig
132 plugType = "multi"
133 outputCols = ["period", "power"]
134 needsFilter = True
136 @classmethod
137 def getExecutionOrder(cls):
138 return cls.DEFAULT_CATALOGCALCULATION
140 @catchWarnings(warns=["All-NaN slice encountered"])
141 def calculate(self,
142 diaObjects,
143 diaSources,
144 filterDiaSources,
145 band):
146 """Compute the periodogram.
148 Parameters
149 ----------
150 diaObjects : `pandas.DataFrame`
151 Summary objects to store values in.
152 diaSources : `pandas.DataFrame` or `pandas.DataFrameGroupBy`
153 Catalog of DiaSources summarized by this DiaObject.
154 """
156 # Check and initialize output columns in diaObjects.
157 if (periodCol := f"{band}_period") not in diaObjects.columns:
158 diaObjects[periodCol] = np.nan
159 if (powerCol := f"{band}_power") not in diaObjects.columns:
160 diaObjects[powerCol] = np.nan
162 def _calculate_period(df, min_detections=5, nterms=1, oversampling_factor=5, nyquist_factor=100):
163 """Compute the Lomb-Scargle periodogram given a set of DiaSources.
165 Parameters
166 ----------
167 df : `pandas.DataFrame`
168 The input DataFrame.
169 min_detections : `int`, optional
170 The minimum number of detections.
171 nterms : `int`, optional
172 The number of terms in the Lomb-Scargle model.
173 oversampling_factor : `int`, optional
174 The oversampling factor for frequency grid.
175 nyquist_factor : `int`, optional
176 The Nyquist factor for frequency grid.
178 Returns
179 -------
180 pd_tab : `pandas.Series`
181 The output DataFrame with the Lomb-Scargle parameters.
182 """
183 tmpDf = df[~np.logical_or(np.isnan(df["psfFlux"]),
184 np.isnan(df["midpointMjdTai"]))]
186 if len(tmpDf) < min_detections:
187 return pd.Series({periodCol: np.nan, powerCol: np.nan})
189 time = tmpDf["midpointMjdTai"].to_numpy()
190 flux = tmpDf["psfFlux"].to_numpy()
191 flux_err = tmpDf["psfFluxErr"].to_numpy()
193 lsp = LombScargle(time, flux, dy=flux_err, nterms=nterms)
194 f_grid = compute_optimized_periodogram_grid(
195 time, oversampling_factor=oversampling_factor, nyquist_factor=nyquist_factor)
196 period = 1/f_grid
197 power = lsp.power(f_grid)
199 return pd.Series({periodCol: period[np.argmax(power)],
200 powerCol: np.max(power)})
202 diaObjects.loc[:, [periodCol, powerCol]
203 ] = filterDiaSources.apply(_calculate_period)
206class LombScarglePeriodogramMultiConfig(DiaObjectCalculationPluginConfig):
207 pass
210@register("ap_lombScarglePeriodogramMulti")
211class LombScarglePeriodogramMulti(DiaObjectCalculationPlugin):
212 """Compute the multi-band LombScargle periodogram of a DiaObject given a set of DiaSources.
213 """
214 ConfigClass = LombScarglePeriodogramMultiConfig
216 plugType = "multi"
217 outputCols = ["multiPeriod", "multiPower",
218 "multiFap", "multiAmp", "multiPhase"]
219 needsFilter = True
221 @classmethod
222 def getExecutionOrder(cls):
223 return cls.DEFAULT_CATALOGCALCULATION
225 @staticmethod
226 def calculate_baluev_fap(time, n, maxPeriod, zmax):
227 """Calculate the False-Alarm probability using the Baluev approximation.
229 Parameters
230 ----------
231 time : `array`
232 The input time axis.
233 n : `int`
234 The number of detections.
235 maxPeriod : `float`
236 The maximum period in the grid.
237 zmax : `float`
238 The maximum power in the grid.
240 Returns
241 -------
242 fap_estimate : `float`
243 The False-Alarm probability Baluev approximation.
245 Notes
246 ----------
247 .. [1] Baluev, R. V. 2008, MNRAS, 385, 1279
248 .. [2] Süveges, M., Guy, L.P., Eyer, L., et al. 2015, MNRAS, 450, 2052
249 """
250 if n <= 2:
251 return np.nan
253 gam_ratio = math.factorial(int((n - 1)/2)) / math.factorial(int((n - 2)/2))
254 fu = 1/maxPeriod
255 return gam_ratio * np.sqrt(
256 4*np.pi*statistics.variance(time)
257 ) * fu * (1-zmax)**((n-4)/2) * np.sqrt(zmax)
259 @staticmethod
260 def generate_lsp_params(lsp_model, fbest, bands):
261 """Generate the Lomb-Scargle parameters.
262 Parameters
263 ----------
264 lsp_model : `astropy.timeseries.LombScargleMultiband`
265 The Lomb-Scargle model.
266 fbest : `float`
267 The best period.
268 bands : `array`
269 The bands of the time series.
271 Returns
272 -------
273 Amp : `array`
274 The amplitude of the time series.
275 Ph : `array`
276 The phase of the time series.
278 Notes
279 ----------
280 .. [1] VanderPlas, J. T., & Ivezic, Z. 2015, ApJ, 812, 18
281 """
282 best_params = lsp_model.model_parameters(fbest, units=True)
284 name_params = [f"theta_base_{i}" for i in range(3)]
285 name_params += [f"theta_band_{band}_{i}" for band in np.unique(bands) for i in range(3)]
287 df_params = pd.DataFrame([best_params], columns=name_params)
289 unique_bands = np.unique(bands)
291 amplitude_band = [np.sqrt(df_params[f"theta_band_{band}_1"]**2
292 + df_params[f"theta_band_{band}_2"]**2)
293 for band in unique_bands]
294 phase_bands = [np.arctan2(df_params[f"theta_band_{band}_2"],
295 df_params[f"theta_band_{band}_1"]) for band in unique_bands]
297 amp = [a[0] for a in amplitude_band]
298 ph = [p[0] for p in phase_bands]
300 return amp, ph
302 @catchWarnings(warns=["All-NaN slice encountered"])
303 def calculate(self,
304 diaObjects,
305 diaSources,
306 **kwargs):
307 """Compute the multi-band LombScargle periodogram of a DiaObject given
308 a set of DiaSources.
310 Parameters
311 ----------
312 diaObjects : `pandas.DataFrame`
313 Summary objects to store values in.
314 diaSources : `pandas.DataFrame` or `pandas.DataFrameGroupBy`
315 Catalog of DiaSources summarized by this DiaObject.
316 **kwargs : `dict`
317 Unused kwargs that are always passed to a plugin.
318 """
319 n_bands = len(diaSources["band"].unique())
320 # Check and initialize output columns in diaObjects.
321 if (periodCol := "multiPeriod") not in diaObjects.columns:
322 diaObjects[periodCol] = np.nan
323 if (powerCol := "multiPower") not in diaObjects.columns:
324 diaObjects[powerCol] = np.nan
325 if (fapCol := "multiFap") not in diaObjects.columns:
326 diaObjects[fapCol] = np.nan
327 if (ampCol := "multiAmp") not in diaObjects.columns:
328 diaObjects[ampCol] = pd.Series([np.nan]*n_bands, dtype="object")
329 if (phaseCol := "multiPhase") not in diaObjects.columns:
330 diaObjects[phaseCol] = pd.Series([np.nan]*n_bands, dtype="object")
332 def _calculate_period_multi(df, min_detections=9, oversampling_factor=5, nyquist_factor=100):
333 """Calculate the multi-band Lomb-Scargle periodogram.
335 Parameters
336 ----------
337 df : `pandas.DataFrame`
338 The input DataFrame.
339 min_detections : `int`, optional
340 The minimum number of detections, including all bands.
341 oversampling_factor : `int`, optional
342 The oversampling factor for frequency grid.
343 nyquist_factor : `int`, optional
344 The Nyquist factor for frequency grid.
346 Returns
347 -------
348 pd_tab : `pandas.Series`
349 The output DataFrame with the Lomb-Scargle parameters.
350 """
351 tmpDf = df[~np.logical_or(np.isnan(df["psfFlux"]),
352 np.isnan(df["midpointMjdTai"]))]
354 if (len(tmpDf)) < min_detections:
355 return pd.Series({periodCol: np.nan,
356 powerCol: np.nan,
357 fapCol: np.nan,
358 ampCol: pd.Series([np.nan]*n_bands, dtype="object"),
359 phaseCol: pd.Series([np.nan]*n_bands, dtype="object")})
361 time = tmpDf["midpointMjdTai"].to_numpy()
362 flux = tmpDf["psfFlux"].to_numpy()
363 flux_err = tmpDf["psfFluxErr"].to_numpy()
364 bands = tmpDf["band"].to_numpy()
366 lsp = LombScargleMultiband(time, flux, bands, dy=flux_err,
367 nterms_base=1, nterms_band=1)
369 f_grid = compute_optimized_periodogram_grid(
370 time, oversampling_factor=oversampling_factor, nyquist_factor=nyquist_factor)
371 period = 1/f_grid
372 power = lsp.power(f_grid)
374 fap_estimate = self.calculate_baluev_fap(
375 time, len(time), period[np.argmax(power)], np.max(power))
377 params_table_new = self.generate_lsp_params(lsp, f_grid[np.argmax(power)], bands)
379 pd_tab = pd.Series({periodCol: period[np.argmax(power)],
380 powerCol: np.max(power),
381 fapCol: fap_estimate,
382 ampCol: params_table_new[0],
383 phaseCol: params_table_new[1]
384 })
386 return pd_tab
388 diaObjects.loc[:, [periodCol, powerCol, fapCol, ampCol, phaseCol]
389 ] = diaSources.apply(_calculate_period_multi)
392class MeanDiaPositionConfig(DiaObjectCalculationPluginConfig):
393 pass
396@register("ap_meanPosition")
397class MeanDiaPosition(DiaObjectCalculationPlugin):
398 """Compute the mean position of a DiaObject given a set of DiaSources.
399 """
401 ConfigClass = MeanDiaPositionConfig
403 plugType = 'multi'
405 outputCols = ["ra", "dec", "radecMjdTai"]
406 needsFilter = False
408 @classmethod
409 def getExecutionOrder(cls):
410 return cls.DEFAULT_CATALOGCALCULATION
412 def calculate(self, diaObjects, diaSources, **kwargs):
413 """Compute the mean ra/dec position of the diaObject given the
414 diaSource locations.
416 Parameters
417 ----------
418 diaObjects : `pandas.DataFrame`
419 Summary objects to store values in.
420 diaSources : `pandas.DataFrame` or `pandas.DataFrameGroupBy`
421 Catalog of DiaSources summarized by this DiaObject.
422 **kwargs
423 Any additional keyword arguments that may be passed to the plugin.
424 """
425 for outCol in self.outputCols:
426 if outCol not in diaObjects.columns:
427 diaObjects[outCol] = np.nan
429 def _computeMeanPos(df):
430 aveCoord = geom.averageSpherePoint(
431 list(geom.SpherePoint(src["ra"], src["dec"], geom.degrees)
432 for idx, src in df.iterrows()))
433 ra = aveCoord.getRa().asDegrees()
434 dec = aveCoord.getDec().asDegrees()
435 if np.isnan(ra) or np.isnan(dec):
436 radecMjdTai = np.nan
437 else:
438 radecMjdTai = df["midpointMjdTai"].max()
440 return pd.Series({"ra": aveCoord.getRa().asDegrees(),
441 "dec": aveCoord.getDec().asDegrees(),
442 "radecMjdTai": radecMjdTai})
444 ans = diaSources.apply(_computeMeanPos)
445 diaObjects.loc[:, ["ra", "dec", "radecMjdTai"]] = ans
448class HTMIndexDiaPositionConfig(DiaObjectCalculationPluginConfig):
450 htmLevel = pexConfig.Field(
451 dtype=int,
452 doc="Level of the HTM pixelization.",
453 default=20,
454 )
457@register("ap_HTMIndex")
458class HTMIndexDiaPosition(DiaObjectCalculationPlugin):
459 """Compute the mean position of a DiaObject given a set of DiaSources.
461 Notes
462 -----
463 This plugin was implemented to satisfy requirements of old APDB interface
464 which required ``pixelId`` column in DiaObject with HTM20 index. APDB
465 interface had migrated to not need that information, but we keep this
466 plugin in case it may be useful for something else.
467 """
468 ConfigClass = HTMIndexDiaPositionConfig
470 plugType = 'single'
472 inputCols = ["ra", "dec"]
473 outputCols = ["pixelId"]
474 needsFilter = False
476 def __init__(self, config, name, metadata):
477 DiaObjectCalculationPlugin.__init__(self, config, name, metadata)
478 self.pixelator = sphgeom.HtmPixelization(self.config.htmLevel)
480 @classmethod
481 def getExecutionOrder(cls):
482 return cls.FLUX_MOMENTS_CALCULATED
484 def calculate(self, diaObjects, diaObjectId, **kwargs):
485 """Compute the mean position of a DiaObject given a set of DiaSources
487 Parameters
488 ----------
489 diaObjects : `pandas.dataFrame`
490 Summary objects to store values in and read ra/dec from.
491 diaObjectId : `int`
492 Id of the diaObject to update.
493 **kwargs
494 Any additional keyword arguments that may be passed to the plugin.
495 """
496 sphPoint = geom.SpherePoint(
497 diaObjects.at[diaObjectId, "ra"] * geom.degrees,
498 diaObjects.at[diaObjectId, "dec"] * geom.degrees)
499 diaObjects.at[diaObjectId, "pixelId"] = self.pixelator.index(
500 sphPoint.getVector())
503class NumDiaSourcesDiaPluginConfig(DiaObjectCalculationPluginConfig):
504 pass
507@register("ap_nDiaSources")
508class NumDiaSourcesDiaPlugin(DiaObjectCalculationPlugin):
509 """Compute the total number of DiaSources associated with this DiaObject.
510 """
512 ConfigClass = NumDiaSourcesDiaPluginConfig
513 outputCols = ["nDiaSources"]
514 plugType = "multi"
515 needsFilter = False
517 @classmethod
518 def getExecutionOrder(cls):
519 return cls.DEFAULT_CATALOGCALCULATION
521 def calculate(self, diaObjects, diaSources, **kwargs):
522 """Compute the total number of DiaSources associated with this DiaObject.
524 Parameters
525 ----------
526 diaObject : `dict`
527 Summary object to store values in and read ra/dec from.
528 **kwargs
529 Any additional keyword arguments that may be passed to the plugin.
530 """
531 dtype = diaObjects["nDiaSources"].dtype
532 diaObjects.loc[:, "nDiaSources"] = diaSources.diaObjectId.count().astype(dtype)
535class SimpleSourceFlagDiaPluginConfig(DiaObjectCalculationPluginConfig):
536 pass
539@register("ap_diaObjectFlag")
540class SimpleSourceFlagDiaPlugin(DiaObjectCalculationPlugin):
541 """Find if any DiaSource is flagged.
543 Set the DiaObject flag if any DiaSource is flagged.
544 """
546 ConfigClass = NumDiaSourcesDiaPluginConfig
547 outputCols = ["flags"]
548 plugType = "multi"
549 needsFilter = False
551 @classmethod
552 def getExecutionOrder(cls):
553 return cls.DEFAULT_CATALOGCALCULATION
555 def calculate(self, diaObjects, diaSources, **kwargs):
556 """Find if any DiaSource is flagged.
558 Set the DiaObject flag if any DiaSource is flagged.
560 Parameters
561 ----------
562 diaObject : `dict`
563 Summary object to store values in and read ra/dec from.
564 **kwargs
565 Any additional keyword arguments that may be passed to the plugin.
566 """
567 dtype = diaObjects["flags"].dtype
568 diaObjects.loc[:, "flags"] = diaSources.flags.any().astype(dtype)
571class WeightedMeanDiaPsfFluxConfig(DiaObjectCalculationPluginConfig):
572 pass
575@register("ap_meanFlux")
576class WeightedMeanDiaPsfFlux(DiaObjectCalculationPlugin):
577 """Compute the weighted mean and mean error on the point source fluxes
578 of the DiaSource measured on the difference image.
580 Additionally store number of usable data points.
581 """
583 ConfigClass = WeightedMeanDiaPsfFluxConfig
584 outputCols = ["psfFluxMean", "psfFluxMeanErr", "psfFluxNdata"]
585 plugType = "multi"
586 needsFilter = True
588 @classmethod
589 def getExecutionOrder(cls):
590 return cls.DEFAULT_CATALOGCALCULATION
592 @catchWarnings(warns=["invalid value encountered",
593 "divide by zero"])
594 def calculate(self,
595 diaObjects,
596 diaSources,
597 filterDiaSources,
598 band,
599 **kwargs):
600 """Compute the weighted mean and mean error of the point source flux.
602 Parameters
603 ----------
604 diaObject : `dict`
605 Summary object to store values in.
606 diaSources : `pandas.DataFrame`
607 DataFrame representing all diaSources associated with this
608 diaObject.
609 filterDiaSources : `pandas.DataFrame`
610 DataFrame representing diaSources associated with this
611 diaObject that are observed in the band pass ``band``.
612 band : `str`
613 Simple, string name of the filter for the flux being calculated.
614 **kwargs
615 Any additional keyword arguments that may be passed to the plugin.
616 """
617 meanName = "{}_psfFluxMean".format(band)
618 errName = "{}_psfFluxMeanErr".format(band)
619 nDataName = "{}_psfFluxNdata".format(band)
620 if meanName not in diaObjects.columns:
621 diaObjects[meanName] = np.nan
622 if errName not in diaObjects.columns:
623 diaObjects[errName] = np.nan
624 if nDataName not in diaObjects.columns:
625 diaObjects[nDataName] = 0
627 def _weightedMean(df):
628 tmpDf = df[~np.logical_or(np.isnan(df["psfFlux"]),
629 np.isnan(df["psfFluxErr"]))]
630 tot_weight = np.nansum(1 / tmpDf["psfFluxErr"] ** 2)
631 fluxMean = np.nansum(tmpDf["psfFlux"]
632 / tmpDf["psfFluxErr"] ** 2)
633 fluxMean /= tot_weight
634 if tot_weight > 0:
635 fluxMeanErr = np.sqrt(1 / tot_weight)
636 else:
637 fluxMeanErr = np.nan
638 nFluxData = len(tmpDf)
640 return pd.Series({meanName: fluxMean,
641 errName: fluxMeanErr,
642 nDataName: nFluxData},
643 dtype="object")
644 df = filterDiaSources.apply(_weightedMean).astype(diaObjects.dtypes[[meanName, errName, nDataName]])
646 diaObjects.loc[:, [meanName, errName, nDataName]] = df
649class PercentileDiaPsfFluxConfig(DiaObjectCalculationPluginConfig):
650 percentiles = pexConfig.ListField(
651 dtype=int,
652 default=[5, 25, 50, 75, 95],
653 doc="Percentiles to calculate to compute values for. Should be "
654 "integer values."
655 )
658@register("ap_percentileFlux")
659class PercentileDiaPsfFlux(DiaObjectCalculationPlugin):
660 """Compute percentiles of diaSource fluxes.
661 """
663 ConfigClass = PercentileDiaPsfFluxConfig
664 # Output columns are created upon instantiation of the class.
665 outputCols = []
666 plugType = "multi"
667 needsFilter = True
669 def __init__(self, config, name, metadata, **kwargs):
670 DiaObjectCalculationPlugin.__init__(self,
671 config,
672 name,
673 metadata,
674 **kwargs)
675 self.outputCols = ["psfFluxPercentile{:02d}".format(percent)
676 for percent in self.config.percentiles]
678 @classmethod
679 def getExecutionOrder(cls):
680 return cls.DEFAULT_CATALOGCALCULATION
682 @catchWarnings(warns=["All-NaN slice encountered"])
683 def calculate(self,
684 diaObjects,
685 diaSources,
686 filterDiaSources,
687 band,
688 **kwargs):
689 """Compute the percentile fluxes of the point source flux.
691 Parameters
692 ----------
693 diaObject : `dict`
694 Summary object to store values in.
695 diaSources : `pandas.DataFrame`
696 DataFrame representing all diaSources associated with this
697 diaObject.
698 filterDiaSources : `pandas.DataFrame`
699 DataFrame representing diaSources associated with this
700 diaObject that are observed in the band pass ``band``.
701 band : `str`
702 Simple, string name of the filter for the flux being calculated.
703 **kwargs
704 Any additional keyword arguments that may be passed to the plugin.
705 """
706 pTileNames = []
707 dtype = None
708 for tilePercent in self.config.percentiles:
709 pTileName = "{}_psfFluxPercentile{:02d}".format(band,
710 tilePercent)
711 pTileNames.append(pTileName)
712 if pTileName not in diaObjects.columns:
713 diaObjects[pTileName] = np.nan
714 elif dtype is None:
715 dtype = diaObjects[pTileName].dtype
717 def _fluxPercentiles(df):
718 pTiles = np.nanpercentile(df["psfFlux"], self.config.percentiles)
719 return pd.Series(
720 dict((tileName, pTile)
721 for tileName, pTile in zip(pTileNames, pTiles)))
722 if dtype is None:
723 diaObjects.loc[:, pTileNames] = filterDiaSources.apply(_fluxPercentiles)
724 else:
725 diaObjects.loc[:, pTileNames] = filterDiaSources.apply(_fluxPercentiles).astype(dtype)
728class SigmaDiaPsfFluxConfig(DiaObjectCalculationPluginConfig):
729 pass
732@register("ap_sigmaFlux")
733class SigmaDiaPsfFlux(DiaObjectCalculationPlugin):
734 """Compute scatter of diaSource fluxes.
735 """
737 ConfigClass = SigmaDiaPsfFluxConfig
738 # Output columns are created upon instantiation of the class.
739 outputCols = ["psfFluxSigma"]
740 plugType = "multi"
741 needsFilter = True
743 @classmethod
744 def getExecutionOrder(cls):
745 return cls.DEFAULT_CATALOGCALCULATION
747 def calculate(self,
748 diaObjects,
749 diaSources,
750 filterDiaSources,
751 band,
752 **kwargs):
753 """Compute the sigma fluxes of the point source flux.
755 Parameters
756 ----------
757 diaObject : `dict`
758 Summary object to store values in.
759 diaSources : `pandas.DataFrame`
760 DataFrame representing all diaSources associated with this
761 diaObject.
762 filterDiaSources : `pandas.DataFrame`
763 DataFrame representing diaSources associated with this
764 diaObject that are observed in the band pass ``band``.
765 band : `str`
766 Simple, string name of the filter for the flux being calculated.
767 **kwargs
768 Any additional keyword arguments that may be passed to the plugin.
769 """
770 # Set "delta degrees of freedom (ddf)" to 1 to calculate the unbiased
771 # estimator of scatter (i.e. 'N - 1' instead of 'N').
772 column = "{}_psfFluxSigma".format(band)
773 if column in diaObjects:
774 dtype = diaObjects[column].dtype
775 diaObjects.loc[:, column] = filterDiaSources.psfFlux.std().astype(dtype)
776 else:
777 diaObjects.loc[:, column] = filterDiaSources.psfFlux.std()
780class Chi2DiaPsfFluxConfig(DiaObjectCalculationPluginConfig):
781 pass
784@register("ap_chi2Flux")
785class Chi2DiaPsfFlux(DiaObjectCalculationPlugin):
786 """Compute chi2 of diaSource fluxes.
787 """
789 ConfigClass = Chi2DiaPsfFluxConfig
791 # Required input Cols
792 inputCols = ["psfFluxMean"]
793 # Output columns are created upon instantiation of the class.
794 outputCols = ["psfFluxChi2"]
795 plugType = "multi"
796 needsFilter = True
798 @classmethod
799 def getExecutionOrder(cls):
800 return cls.FLUX_MOMENTS_CALCULATED
802 @catchWarnings(warns=["All-NaN slice encountered"])
803 def calculate(self,
804 diaObjects,
805 diaSources,
806 filterDiaSources,
807 band,
808 **kwargs):
809 """Compute the chi2 of the point source fluxes.
811 Parameters
812 ----------
813 diaObject : `dict`
814 Summary object to store values in.
815 diaSources : `pandas.DataFrame`
816 DataFrame representing all diaSources associated with this
817 diaObject.
818 filterDiaSources : `pandas.DataFrame`
819 DataFrame representing diaSources associated with this
820 diaObject that are observed in the band pass ``band``.
821 band : `str`
822 Simple, string name of the filter for the flux being calculated.
823 **kwargs
824 Any additional keyword arguments that may be passed to the plugin.
825 """
826 meanName = "{}_psfFluxMean".format(band)
827 column = "{}_psfFluxChi2".format(band)
829 def _chi2(df):
830 delta = (df["psfFlux"]
831 - diaObjects.at[df.diaObjectId.iat[0], meanName])
832 return np.nansum((delta / df["psfFluxErr"]) ** 2)
834 if column in diaObjects:
835 dtype = diaObjects[column].dtype
836 diaObjects.loc[:, column] = filterDiaSources.apply(_chi2).astype(dtype)
837 else:
838 diaObjects.loc[:, column] = filterDiaSources.apply(_chi2)
841class MadDiaPsfFluxConfig(DiaObjectCalculationPluginConfig):
842 pass
845@register("ap_madFlux")
846class MadDiaPsfFlux(DiaObjectCalculationPlugin):
847 """Compute median absolute deviation of diaSource fluxes.
848 """
850 ConfigClass = MadDiaPsfFluxConfig
852 # Required input Cols
853 # Output columns are created upon instantiation of the class.
854 outputCols = ["psfFluxMAD"]
855 plugType = "multi"
856 needsFilter = True
858 @classmethod
859 def getExecutionOrder(cls):
860 return cls.DEFAULT_CATALOGCALCULATION
862 @catchWarnings(warns=["All-NaN slice encountered"])
863 def calculate(self,
864 diaObjects,
865 diaSources,
866 filterDiaSources,
867 band,
868 **kwargs):
869 """Compute the median absolute deviation of the point source fluxes.
871 Parameters
872 ----------
873 diaObject : `dict`
874 Summary object to store values in.
875 diaSources : `pandas.DataFrame`
876 DataFrame representing all diaSources associated with this
877 diaObject.
878 filterDiaSources : `pandas.DataFrame`
879 DataFrame representing diaSources associated with this
880 diaObject that are observed in the band pass ``band``.
881 band : `str`
882 Simple, string name of the filter for the flux being calculated.
883 **kwargs
884 Any additional keyword arguments that may be passed to the plugin.
885 """
886 column = "{}_psfFluxMAD".format(band)
887 if column in diaObjects:
888 dtype = diaObjects[column].dtype
889 diaObjects.loc[:, column] = \
890 filterDiaSources.psfFlux.apply(median_absolute_deviation,
891 ignore_nan=True).astype(dtype)
892 else:
893 diaObjects.loc[:, column] = \
894 filterDiaSources.psfFlux.apply(median_absolute_deviation,
895 ignore_nan=True)
898class SkewDiaPsfFluxConfig(DiaObjectCalculationPluginConfig):
899 pass
902@register("ap_skewFlux")
903class SkewDiaPsfFlux(DiaObjectCalculationPlugin):
904 """Compute the skew of diaSource fluxes.
905 """
907 ConfigClass = SkewDiaPsfFluxConfig
909 # Required input Cols
910 # Output columns are created upon instantiation of the class.
911 outputCols = ["psfFluxSkew"]
912 plugType = "multi"
913 needsFilter = True
915 @classmethod
916 def getExecutionOrder(cls):
917 return cls.DEFAULT_CATALOGCALCULATION
919 def calculate(self,
920 diaObjects,
921 diaSources,
922 filterDiaSources,
923 band,
924 **kwargs):
925 """Compute the skew of the point source fluxes.
927 Parameters
928 ----------
929 diaObject : `dict`
930 Summary object to store values in.
931 diaSources : `pandas.DataFrame`
932 DataFrame representing all diaSources associated with this
933 diaObject.
934 filterDiaSources : `pandas.DataFrame`
935 DataFrame representing diaSources associated with this
936 diaObject that are observed in the band pass ``band``.
937 band : `str`
938 Simple, string name of the filter for the flux being calculated.
939 **kwargs
940 Any additional keyword arguments that may be passed to the plugin.
941 """
942 column = "{}_psfFluxSkew".format(band)
943 if column in diaObjects:
944 dtype = diaObjects[column].dtype
945 diaObjects.loc[:, column] = filterDiaSources.psfFlux.skew().astype(dtype)
946 else:
947 diaObjects.loc[:, column] = filterDiaSources.psfFlux.skew()
950class MinMaxDiaPsfFluxConfig(DiaObjectCalculationPluginConfig):
951 pass
954@register("ap_minMaxFlux")
955class MinMaxDiaPsfFlux(DiaObjectCalculationPlugin):
956 """Compute min/max of diaSource fluxes.
957 """
959 ConfigClass = MinMaxDiaPsfFluxConfig
961 # Required input Cols
962 # Output columns are created upon instantiation of the class.
963 outputCols = ["psfFluxMin", "psfFluxMax"]
964 plugType = "multi"
965 needsFilter = True
967 @classmethod
968 def getExecutionOrder(cls):
969 return cls.DEFAULT_CATALOGCALCULATION
971 def calculate(self,
972 diaObjects,
973 diaSources,
974 filterDiaSources,
975 band,
976 **kwargs):
977 """Compute min/max of the point source fluxes.
979 Parameters
980 ----------
981 diaObject : `dict`
982 Summary object to store values in.
983 diaSources : `pandas.DataFrame`
984 DataFrame representing all diaSources associated with this
985 diaObject.
986 filterDiaSources : `pandas.DataFrame`
987 DataFrame representing diaSources associated with this
988 diaObject that are observed in the band pass ``band``.
989 band : `str`
990 Simple, string name of the filter for the flux being calculated.
991 **kwargs
992 Any additional keyword arguments that may be passed to the plugin.
993 """
994 minName = "{}_psfFluxMin".format(band)
995 if minName not in diaObjects.columns:
996 diaObjects[minName] = np.nan
997 maxName = "{}_psfFluxMax".format(band)
998 if maxName not in diaObjects.columns:
999 diaObjects[maxName] = np.nan
1001 dtype = diaObjects[minName].dtype
1002 diaObjects.loc[:, minName] = filterDiaSources.psfFlux.min().astype(dtype)
1003 diaObjects.loc[:, maxName] = filterDiaSources.psfFlux.max().astype(dtype)
1006class MaxSlopeDiaPsfFluxConfig(DiaObjectCalculationPluginConfig):
1007 pass
1010@register("ap_maxSlopeFlux")
1011class MaxSlopeDiaPsfFlux(DiaObjectCalculationPlugin):
1012 """Compute the maximum ratio time ordered deltaFlux / deltaTime.
1013 """
1015 ConfigClass = MinMaxDiaPsfFluxConfig
1017 # Required input Cols
1018 # Output columns are created upon instantiation of the class.
1019 outputCols = ["psfFluxMaxSlope"]
1020 plugType = "multi"
1021 needsFilter = True
1023 @classmethod
1024 def getExecutionOrder(cls):
1025 return cls.DEFAULT_CATALOGCALCULATION
1027 def calculate(self,
1028 diaObjects,
1029 diaSources,
1030 filterDiaSources,
1031 band,
1032 **kwargs):
1033 """Compute the maximum ratio time ordered deltaFlux / deltaTime.
1035 Parameters
1036 ----------
1037 diaObject : `dict`
1038 Summary object to store values in.
1039 diaSources : `pandas.DataFrame`
1040 DataFrame representing all diaSources associated with this
1041 diaObject.
1042 filterDiaSources : `pandas.DataFrame`
1043 DataFrame representing diaSources associated with this
1044 diaObject that are observed in the band pass ``band``.
1045 band : `str`
1046 Simple, string name of the filter for the flux being calculated.
1047 **kwargs
1048 Any additional keyword arguments that may be passed to the plugin.
1049 """
1051 def _maxSlope(df):
1052 tmpDf = df[~np.logical_or(np.isnan(df["psfFlux"]),
1053 np.isnan(df["midpointMjdTai"]))]
1054 if len(tmpDf) < 2:
1055 return np.nan
1056 times = tmpDf["midpointMjdTai"].to_numpy()
1057 timeArgs = times.argsort()
1058 times = times[timeArgs]
1059 fluxes = tmpDf["psfFlux"].to_numpy()[timeArgs]
1060 return (np.diff(fluxes) / np.diff(times)).max()
1062 column = "{}_psfFluxMaxSlope".format(band)
1063 if column in diaObjects:
1064 dtype = diaObjects[column].dtype
1065 diaObjects.loc[:, column] = filterDiaSources.apply(_maxSlope).astype(dtype)
1066 else:
1067 diaObjects.loc[:, column] = filterDiaSources.apply(_maxSlope)
1070class ErrMeanDiaPsfFluxConfig(DiaObjectCalculationPluginConfig):
1071 pass
1074@register("ap_meanErrFlux")
1075class ErrMeanDiaPsfFlux(DiaObjectCalculationPlugin):
1076 """Compute the mean of the dia source errors.
1077 """
1079 ConfigClass = ErrMeanDiaPsfFluxConfig
1081 # Required input Cols
1082 # Output columns are created upon instantiation of the class.
1083 outputCols = ["psfFluxErrMean"]
1084 plugType = "multi"
1085 needsFilter = True
1087 @classmethod
1088 def getExecutionOrder(cls):
1089 return cls.DEFAULT_CATALOGCALCULATION
1091 def calculate(self,
1092 diaObjects,
1093 diaSources,
1094 filterDiaSources,
1095 band,
1096 **kwargs):
1097 """Compute the mean of the dia source errors.
1099 Parameters
1100 ----------
1101 diaObject : `dict`
1102 Summary object to store values in.
1103 diaSources : `pandas.DataFrame`
1104 DataFrame representing all diaSources associated with this
1105 diaObject.
1106 filterDiaSources : `pandas.DataFrame`
1107 DataFrame representing diaSources associated with this
1108 diaObject that are observed in the band pass ``band``.
1109 band : `str`
1110 Simple, string name of the filter for the flux being calculated.
1111 **kwargs
1112 Any additional keyword arguments that may be passed to the plugin.
1113 """
1114 column = "{}_psfFluxErrMean".format(band)
1115 if column in diaObjects:
1116 dtype = diaObjects[column].dtype
1117 diaObjects.loc[:, column] = filterDiaSources.psfFluxErr.mean().astype(dtype)
1118 else:
1119 diaObjects.loc[:, column] = filterDiaSources.psfFluxErr.mean()
1122class LinearFitDiaPsfFluxConfig(DiaObjectCalculationPluginConfig):
1123 pass
1126@register("ap_linearFit")
1127class LinearFitDiaPsfFlux(DiaObjectCalculationPlugin):
1128 """Compute fit a linear model to flux vs time.
1129 """
1131 ConfigClass = LinearFitDiaPsfFluxConfig
1133 # Required input Cols
1134 # Output columns are created upon instantiation of the class.
1135 outputCols = ["psfFluxLinearSlope", "psfFluxLinearIntercept"]
1136 plugType = "multi"
1137 needsFilter = True
1139 @classmethod
1140 def getExecutionOrder(cls):
1141 return cls.DEFAULT_CATALOGCALCULATION
1143 def calculate(self,
1144 diaObjects,
1145 diaSources,
1146 filterDiaSources,
1147 band,
1148 **kwargs):
1149 """Compute fit a linear model to flux vs time.
1151 Parameters
1152 ----------
1153 diaObject : `dict`
1154 Summary object to store values in.
1155 diaSources : `pandas.DataFrame`
1156 DataFrame representing all diaSources associated with this
1157 diaObject.
1158 filterDiaSources : `pandas.DataFrame`
1159 DataFrame representing diaSources associated with this
1160 diaObject that are observed in the band pass ``band``.
1161 band : `str`
1162 Simple, string name of the filter for the flux being calculated.
1163 **kwargs
1164 Any additional keyword arguments that may be passed to the plugin.
1165 """
1167 mName = "{}_psfFluxLinearSlope".format(band)
1168 if mName not in diaObjects.columns:
1169 diaObjects[mName] = np.nan
1170 bName = "{}_psfFluxLinearIntercept".format(band)
1171 if bName not in diaObjects.columns:
1172 diaObjects[bName] = np.nan
1173 dtype = diaObjects[mName].dtype
1175 def _linearFit(df):
1176 tmpDf = df[~np.logical_or(
1177 np.isnan(df["psfFlux"]),
1178 np.logical_or(np.isnan(df["psfFluxErr"]),
1179 np.isnan(df["midpointMjdTai"])))]
1180 if len(tmpDf) < 2:
1181 return pd.Series({mName: np.nan, bName: np.nan})
1182 fluxes = tmpDf["psfFlux"].to_numpy()
1183 errors = tmpDf["psfFluxErr"].to_numpy()
1184 times = tmpDf["midpointMjdTai"].to_numpy()
1185 A = np.array([times / errors, 1 / errors]).transpose()
1186 m, b = lsq_linear(A, fluxes / errors).x
1187 return pd.Series({mName: m, bName: b}, dtype=dtype)
1189 diaObjects.loc[:, [mName, bName]] = filterDiaSources.apply(_linearFit)
1192class StetsonJDiaPsfFluxConfig(DiaObjectCalculationPluginConfig):
1193 pass
1196@register("ap_stetsonJ")
1197class StetsonJDiaPsfFlux(DiaObjectCalculationPlugin):
1198 """Compute the StetsonJ statistic on the DIA point source fluxes.
1199 """
1201 ConfigClass = LinearFitDiaPsfFluxConfig
1203 # Required input Cols
1204 inputCols = ["psfFluxMean"]
1205 # Output columns are created upon instantiation of the class.
1206 outputCols = ["psfFluxStetsonJ"]
1207 plugType = "multi"
1208 needsFilter = True
1210 @classmethod
1211 def getExecutionOrder(cls):
1212 return cls.FLUX_MOMENTS_CALCULATED
1214 def calculate(self,
1215 diaObjects,
1216 diaSources,
1217 filterDiaSources,
1218 band,
1219 **kwargs):
1220 """Compute the StetsonJ statistic on the DIA point source fluxes.
1222 Parameters
1223 ----------
1224 diaObject : `dict`
1225 Summary object to store values in.
1226 diaSources : `pandas.DataFrame`
1227 DataFrame representing all diaSources associated with this
1228 diaObject.
1229 filterDiaSources : `pandas.DataFrame`
1230 DataFrame representing diaSources associated with this
1231 diaObject that are observed in the band pass ``band``.
1232 band : `str`
1233 Simple, string name of the filter for the flux being calculated.
1234 **kwargs
1235 Any additional keyword arguments that may be passed to the plugin.
1236 """
1237 meanName = "{}_psfFluxMean".format(band)
1239 def _stetsonJ(df):
1240 tmpDf = df[~np.logical_or(np.isnan(df["psfFlux"]),
1241 np.isnan(df["psfFluxErr"]))]
1242 if len(tmpDf) < 2:
1243 return np.nan
1244 fluxes = tmpDf["psfFlux"].to_numpy()
1245 errors = tmpDf["psfFluxErr"].to_numpy()
1247 return self._stetson_J(
1248 fluxes,
1249 errors,
1250 diaObjects.at[tmpDf.diaObjectId.iat[0], meanName])
1252 column = "{}_psfFluxStetsonJ".format(band)
1253 if column in diaObjects:
1254 dtype = diaObjects[column].dtype
1255 diaObjects.loc[:, column] = filterDiaSources.apply(_stetsonJ).astype(dtype)
1256 else:
1257 diaObjects.loc[:, column] = filterDiaSources.apply(_stetsonJ)
1259 def _stetson_J(self, fluxes, errors, mean=None):
1260 """Compute the single band stetsonJ statistic.
1262 Parameters
1263 ----------
1264 fluxes : `numpy.ndarray` (N,)
1265 Calibrated lightcurve flux values.
1266 errors : `numpy.ndarray` (N,)
1267 Errors on the calibrated lightcurve fluxes.
1268 mean : `float`
1269 Starting mean from previous plugin.
1271 Returns
1272 -------
1273 stetsonJ : `float`
1274 stetsonJ statistic for the input fluxes and errors.
1276 References
1277 ----------
1278 .. [1] Stetson, P. B., "On the Automatic Determination of Light-Curve
1279 Parameters for Cepheid Variables", PASP, 108, 851S, 1996
1280 """
1281 n_points = len(fluxes)
1282 flux_mean = self._stetson_mean(fluxes, errors, mean)
1283 delta_val = (
1284 np.sqrt(n_points / (n_points - 1)) * (fluxes - flux_mean) / errors)
1285 p_k = delta_val ** 2 - 1
1287 return np.mean(np.sign(p_k) * np.sqrt(np.fabs(p_k)))
1289 def _stetson_mean(self,
1290 values,
1291 errors,
1292 mean=None,
1293 alpha=2.,
1294 beta=2.,
1295 n_iter=20,
1296 tol=1e-6):
1297 """Compute the stetson mean of the fluxes which down-weights outliers.
1299 Weighted biased on an error weighted difference scaled by a constant
1300 (1/``a``) and raised to the power beta. Higher betas more harshly
1301 penalize outliers and ``a`` sets the number of sigma where a weighted
1302 difference of 1 occurs.
1304 Parameters
1305 ----------
1306 values : `numpy.dnarray`, (N,)
1307 Input values to compute the mean of.
1308 errors : `numpy.ndarray`, (N,)
1309 Errors on the input values.
1310 mean : `float`
1311 Starting mean value or None.
1312 alpha : `float`
1313 Scalar down-weighting of the fractional difference. lower->more
1314 clipping. (Default value is 2.)
1315 beta : `float`
1316 Power law slope of the used to down-weight outliers. higher->more
1317 clipping. (Default value is 2.)
1318 n_iter : `int`
1319 Number of iterations of clipping.
1320 tol : `float`
1321 Fractional and absolute tolerance goal on the change in the mean
1322 before exiting early. (Default value is 1e-6)
1324 Returns
1325 -------
1326 mean : `float`
1327 Weighted stetson mean result.
1329 References
1330 ----------
1331 .. [1] Stetson, P. B., "On the Automatic Determination of Light-Curve
1332 Parameters for Cepheid Variables", PASP, 108, 851S, 1996
1333 """
1334 n_points = len(values)
1335 n_factor = np.sqrt(n_points / (n_points - 1))
1336 inv_var = 1 / errors ** 2
1338 if mean is None:
1339 mean = np.average(values, weights=inv_var)
1340 for iter_idx in range(n_iter):
1341 chi = np.fabs(n_factor * (values - mean) / errors)
1342 tmp_mean = np.average(
1343 values,
1344 weights=inv_var / (1 + (chi / alpha) ** beta))
1345 diff = np.fabs(tmp_mean - mean)
1346 mean = tmp_mean
1347 if diff / mean < tol and diff < tol:
1348 break
1349 return mean
1352class WeightedMeanDiaTotFluxConfig(DiaObjectCalculationPluginConfig):
1353 pass
1356@register("ap_meanTotFlux")
1357class WeightedMeanDiaTotFlux(DiaObjectCalculationPlugin):
1358 """Compute the weighted mean and mean error on the point source fluxes
1359 forced photometered at the DiaSource location in the calibrated image.
1361 Additionally store number of usable data points.
1362 """
1364 ConfigClass = WeightedMeanDiaPsfFluxConfig
1365 outputCols = ["scienceFluxMean", "scienceFluxMeanErr"]
1366 plugType = "multi"
1367 needsFilter = True
1369 @classmethod
1370 def getExecutionOrder(cls):
1371 return cls.DEFAULT_CATALOGCALCULATION
1373 @catchWarnings(warns=["invalid value encountered",
1374 "divide by zero"])
1375 def calculate(self,
1376 diaObjects,
1377 diaSources,
1378 filterDiaSources,
1379 band,
1380 **kwargs):
1381 """Compute the weighted mean and mean error of the point source flux.
1383 Parameters
1384 ----------
1385 diaObject : `dict`
1386 Summary object to store values in.
1387 diaSources : `pandas.DataFrame`
1388 DataFrame representing all diaSources associated with this
1389 diaObject.
1390 filterDiaSources : `pandas.DataFrame`
1391 DataFrame representing diaSources associated with this
1392 diaObject that are observed in the band pass ``band``.
1393 band : `str`
1394 Simple, string name of the filter for the flux being calculated.
1395 **kwargs
1396 Any additional keyword arguments that may be passed to the plugin.
1397 """
1398 totMeanName = "{}_scienceFluxMean".format(band)
1399 if totMeanName not in diaObjects.columns:
1400 diaObjects[totMeanName] = np.nan
1401 totErrName = "{}_scienceFluxMeanErr".format(band)
1402 if totErrName not in diaObjects.columns:
1403 diaObjects[totErrName] = np.nan
1405 def _meanFlux(df):
1406 tmpDf = df[~np.logical_or(np.isnan(df["scienceFlux"]),
1407 np.isnan(df["scienceFluxErr"]))]
1408 tot_weight = np.nansum(1 / tmpDf["scienceFluxErr"] ** 2)
1409 fluxMean = np.nansum(tmpDf["scienceFlux"]
1410 / tmpDf["scienceFluxErr"] ** 2)
1411 fluxMean /= tot_weight
1412 fluxMeanErr = np.sqrt(1 / tot_weight)
1414 return pd.Series({totMeanName: fluxMean,
1415 totErrName: fluxMeanErr})
1417 df = filterDiaSources.apply(_meanFlux).astype(diaObjects.dtypes[[totMeanName, totErrName]])
1418 diaObjects.loc[:, [totMeanName, totErrName]] = df
1421class SigmaDiaTotFluxConfig(DiaObjectCalculationPluginConfig):
1422 pass
1425@register("ap_sigmaTotFlux")
1426class SigmaDiaTotFlux(DiaObjectCalculationPlugin):
1427 """Compute scatter of diaSource fluxes.
1428 """
1430 ConfigClass = SigmaDiaPsfFluxConfig
1431 # Output columns are created upon instantiation of the class.
1432 outputCols = ["scienceFluxSigma"]
1433 plugType = "multi"
1434 needsFilter = True
1436 @classmethod
1437 def getExecutionOrder(cls):
1438 return cls.DEFAULT_CATALOGCALCULATION
1440 def calculate(self,
1441 diaObjects,
1442 diaSources,
1443 filterDiaSources,
1444 band,
1445 **kwargs):
1446 """Compute the sigma fluxes of the point source flux measured on the
1447 calibrated image.
1449 Parameters
1450 ----------
1451 diaObject : `dict`
1452 Summary object to store values in.
1453 diaSources : `pandas.DataFrame`
1454 DataFrame representing all diaSources associated with this
1455 diaObject.
1456 filterDiaSources : `pandas.DataFrame`
1457 DataFrame representing diaSources associated with this
1458 diaObject that are observed in the band pass ``band``.
1459 band : `str`
1460 Simple, string name of the filter for the flux being calculated.
1461 **kwargs
1462 Any additional keyword arguments that may be passed to the plugin.
1463 """
1464 # Set "delta degrees of freedom (ddf)" to 1 to calculate the unbiased
1465 # estimator of scatter (i.e. 'N - 1' instead of 'N').
1466 column = "{}_scienceFluxSigma".format(band)
1467 if column in diaObjects:
1468 dtype = diaObjects[column].dtype
1469 diaObjects.loc[:, column] = filterDiaSources.scienceFlux.std().astype(dtype)
1470 else:
1472 diaObjects.loc[:, column] = filterDiaSources.scienceFlux.std()