22"""Plugins for use in DiaSource summary statistics.
25as defined in the schema of the Apdb both in name and units.
31from astropy.stats
import median_absolute_deviation
34from scipy.optimize
import lsq_linear
39from astropy.timeseries
import LombScargle
40from astropy.timeseries
import LombScargleMultiband
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")
72 """Decorator for generically catching numpy warnings.
74 def decoratorCatchWarnings(func):
75 @functools.wraps(func)
76 def wrapperCatchWarnings(*args, **kwargs):
77 with warnings.catch_warnings():
79 warnings.filterwarnings(
"ignore", val)
80 return func(*args, **kwargs)
81 return wrapperCatchWarnings
84 return decoratorCatchWarnings
86 return decoratorCatchWarnings(_func)
91 Computes an optimized periodogram frequency grid for a given time series.
97 oversampling_factor : `int`, optional
98 The oversampling factor for frequency grid.
99 nyquist_factor : `int`, optional
100 The Nyquist factor for frequency grid.
104 frequencies : `array`
105 The computed optimized periodogram frequency grid.
109 baseline = np.max(x0) - np.min(x0)
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)
126@
register(
"ap_lombScarglePeriodogram")
128 """Compute the single-band period of a DiaObject given a set of DiaSources.
130 ConfigClass = LombScarglePeriodogramConfig
133 outputCols = [
"period",
"power"]
140 @catchWarnings(warns=["All-NaN slice encountered"])
146 """Compute the periodogram.
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.
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.
167 df : `pandas.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.
180 pd_tab : `pandas.Series`
181 The output DataFrame with the Lomb-Scargle parameters.
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)
195 time, oversampling_factor=oversampling_factor, nyquist_factor=nyquist_factor)
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)
210@
register(
"ap_lombScarglePeriodogramMulti")
212 """Compute the multi-band LombScargle periodogram of a DiaObject given a set of DiaSources.
214 ConfigClass = LombScarglePeriodogramMultiConfig
217 outputCols = [
"multiPeriod",
"multiPower",
218 "multiFap",
"multiAmp",
"multiPhase"]
227 """Calculate the False-Alarm probability using the Baluev approximation.
234 The number of detections.
236 The maximum period in the grid.
238 The maximum power in the grid.
242 fap_estimate : `float`
243 The False-Alarm probability Baluev approximation.
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
253 gam_ratio = math.factorial(int((n - 1)/2)) / math.factorial(int((n - 2)/2))
255 return gam_ratio * np.sqrt(
256 4*np.pi*statistics.variance(time)
257 ) * fu * (1-zmax)**((n-4)/2) * np.sqrt(zmax)
261 """Generate the Lomb-Scargle parameters.
264 lsp_model : `astropy.timeseries.LombScargleMultiband`
265 The Lomb-Scargle model.
269 The bands of the time series.
274 The amplitude of the time series.
276 The phase of the time series.
280 .. [1] VanderPlas, J. T., & Ivezic, Z. 2015, ApJ, 812, 18
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]
302 @catchWarnings(warns=["All-NaN slice encountered"])
307 """Compute the multi-band LombScargle periodogram of a DiaObject given
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.
317 Unused kwargs that are always passed to a plugin.
319 n_bands = len(diaSources[
"band"].unique())
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.
337 df : `pandas.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.
348 pd_tab : `pandas.Series`
349 The output DataFrame with the Lomb-Scargle parameters.
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,
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)
370 time, oversampling_factor=oversampling_factor, nyquist_factor=nyquist_factor)
372 power = lsp.power(f_grid)
375 time, len(time), period[np.argmax(power)], np.max(power))
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]
388 diaObjects.loc[:, [periodCol, powerCol, fapCol, ampCol, phaseCol]
389 ] = diaSources.apply(_calculate_period_multi)
398 """Compute the mean position of a DiaObject given a set of DiaSources.
401 ConfigClass = MeanDiaPositionConfig
405 outputCols = [
"ra",
"dec",
"radecMjdTai"]
413 """Compute the mean ra/dec position of the diaObject given the
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.
423 Any additional keyword arguments that may be passed to the plugin.
426 if outCol
not in diaObjects.columns:
427 diaObjects[outCol] = np.nan
429 def _computeMeanPos(df):
430 aveCoord = geom.averageSpherePoint(
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):
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
450 htmLevel = pexConfig.Field(
452 doc=
"Level of the HTM pixelization.",
457@register("ap_HTMIndex")
459 """Compute the mean position of a DiaObject given a set of DiaSources.
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.
468 ConfigClass = HTMIndexDiaPositionConfig
472 inputCols = [
"ra",
"dec"]
473 outputCols = [
"pixelId"]
477 DiaObjectCalculationPlugin.__init__(self, config, name, metadata)
485 """Compute the mean position of a DiaObject given a set of DiaSources
489 diaObjects : `pandas.dataFrame`
490 Summary objects to store values in and read ra/dec from.
492 Id of the diaObject to update.
494 Any additional keyword arguments that may be passed to the plugin.
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())
509 """Compute the total number of DiaSources associated with this DiaObject.
512 ConfigClass = NumDiaSourcesDiaPluginConfig
513 outputCols = [
"nDiaSources"]
522 """Compute the total number of DiaSources associated with this DiaObject.
527 Summary object to store values in and read ra/dec from.
529 Any additional keyword arguments that may be passed to the plugin.
531 dtype = diaObjects[
"nDiaSources"].dtype
532 diaObjects.loc[:,
"nDiaSources"] = diaSources.diaObjectId.count().astype(dtype)
541 """Find if any DiaSource is flagged.
543 Set the DiaObject flag if any DiaSource is flagged.
546 ConfigClass = NumDiaSourcesDiaPluginConfig
547 outputCols = [
"flags"]
556 """Find if any DiaSource is flagged.
558 Set the DiaObject flag if any DiaSource is flagged.
563 Summary object to store values in and read ra/dec from.
565 Any additional keyword arguments that may be passed to the plugin.
567 dtype = diaObjects[
"flags"].dtype
568 diaObjects.loc[:,
"flags"] = diaSources.flags.any().astype(dtype)
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.
583 ConfigClass = WeightedMeanDiaPsfFluxConfig
584 outputCols = [
"psfFluxMean",
"psfFluxMeanErr",
"psfFluxNdata"]
592 @catchWarnings(warns=[
"invalid value encountered",
600 """Compute the weighted mean and mean error of the point source flux.
605 Summary object to store values in.
606 diaSources : `pandas.DataFrame`
607 DataFrame representing all diaSources associated with this
609 filterDiaSources : `pandas.DataFrame`
610 DataFrame representing diaSources associated with this
611 diaObject that are observed in the band pass ``band``.
613 Simple, string name of the filter for the flux being calculated.
615 Any additional keyword arguments that may be passed to the plugin.
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
635 fluxMeanErr = np.sqrt(1 / tot_weight)
638 nFluxData = len(tmpDf)
640 return pd.Series({meanName: fluxMean,
641 errName: fluxMeanErr,
642 nDataName: nFluxData},
644 df = filterDiaSources.apply(_weightedMean).astype(diaObjects.dtypes[[meanName, errName, nDataName]])
646 diaObjects.loc[:, [meanName, errName, nDataName]] = df
650 percentiles = pexConfig.ListField(
652 default=[5, 25, 50, 75, 95],
653 doc=
"Percentiles to calculate to compute values for. Should be "
658@register("ap_percentileFlux")
660 """Compute percentiles of diaSource fluxes.
663 ConfigClass = PercentileDiaPsfFluxConfig
669 def __init__(self, config, name, metadata, **kwargs):
670 DiaObjectCalculationPlugin.__init__(self,
675 self.
outputCols = [
"psfFluxPercentile{:02d}".format(percent)
676 for percent
in self.
config.percentiles]
682 @catchWarnings(warns=["All-NaN slice encountered"])
689 """Compute the percentile fluxes of the point source flux.
694 Summary object to store values in.
695 diaSources : `pandas.DataFrame`
696 DataFrame representing all diaSources associated with this
698 filterDiaSources : `pandas.DataFrame`
699 DataFrame representing diaSources associated with this
700 diaObject that are observed in the band pass ``band``.
702 Simple, string name of the filter for the flux being calculated.
704 Any additional keyword arguments that may be passed to the plugin.
708 for tilePercent
in self.
config.percentiles:
709 pTileName =
"{}_psfFluxPercentile{:02d}".format(band,
711 pTileNames.append(pTileName)
712 if pTileName
not in diaObjects.columns:
713 diaObjects[pTileName] = np.nan
715 dtype = diaObjects[pTileName].dtype
717 def _fluxPercentiles(df):
718 pTiles = np.nanpercentile(df[
"psfFlux"], self.
config.percentiles)
720 dict((tileName, pTile)
721 for tileName, pTile
in zip(pTileNames, pTiles)))
723 diaObjects.loc[:, pTileNames] = filterDiaSources.apply(_fluxPercentiles)
725 diaObjects.loc[:, pTileNames] = filterDiaSources.apply(_fluxPercentiles).astype(dtype)
734 """Compute scatter of diaSource fluxes.
737 ConfigClass = SigmaDiaPsfFluxConfig
739 outputCols = [
"psfFluxSigma"]
753 """Compute the sigma fluxes of the point source flux.
758 Summary object to store values in.
759 diaSources : `pandas.DataFrame`
760 DataFrame representing all diaSources associated with this
762 filterDiaSources : `pandas.DataFrame`
763 DataFrame representing diaSources associated with this
764 diaObject that are observed in the band pass ``band``.
766 Simple, string name of the filter for the flux being calculated.
768 Any additional keyword arguments that may be passed to the plugin.
772 column =
"{}_psfFluxSigma".format(band)
773 if column
in diaObjects:
774 dtype = diaObjects[column].dtype
775 diaObjects.loc[:, column] = filterDiaSources.psfFlux.std().astype(dtype)
777 diaObjects.loc[:, column] = filterDiaSources.psfFlux.std()
786 """Compute chi2 of diaSource fluxes.
789 ConfigClass = Chi2DiaPsfFluxConfig
792 inputCols = [
"psfFluxMean"]
794 outputCols = [
"psfFluxChi2"]
802 @catchWarnings(warns=["All-NaN slice encountered"])
809 """Compute the chi2 of the point source fluxes.
814 Summary object to store values in.
815 diaSources : `pandas.DataFrame`
816 DataFrame representing all diaSources associated with this
818 filterDiaSources : `pandas.DataFrame`
819 DataFrame representing diaSources associated with this
820 diaObject that are observed in the band pass ``band``.
822 Simple, string name of the filter for the flux being calculated.
824 Any additional keyword arguments that may be passed to the plugin.
826 meanName =
"{}_psfFluxMean".format(band)
827 column =
"{}_psfFluxChi2".format(band)
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)
838 diaObjects.loc[:, column] = filterDiaSources.apply(_chi2)
847 """Compute median absolute deviation of diaSource fluxes.
850 ConfigClass = MadDiaPsfFluxConfig
854 outputCols = [
"psfFluxMAD"]
862 @catchWarnings(warns=["All-NaN slice encountered"])
869 """Compute the median absolute deviation of the point source fluxes.
874 Summary object to store values in.
875 diaSources : `pandas.DataFrame`
876 DataFrame representing all diaSources associated with this
878 filterDiaSources : `pandas.DataFrame`
879 DataFrame representing diaSources associated with this
880 diaObject that are observed in the band pass ``band``.
882 Simple, string name of the filter for the flux being calculated.
884 Any additional keyword arguments that may be passed to the plugin.
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)
893 diaObjects.loc[:, column] = \
894 filterDiaSources.psfFlux.apply(median_absolute_deviation,
904 """Compute the skew of diaSource fluxes.
907 ConfigClass = SkewDiaPsfFluxConfig
911 outputCols = [
"psfFluxSkew"]
925 """Compute the skew of the point source fluxes.
930 Summary object to store values in.
931 diaSources : `pandas.DataFrame`
932 DataFrame representing all diaSources associated with this
934 filterDiaSources : `pandas.DataFrame`
935 DataFrame representing diaSources associated with this
936 diaObject that are observed in the band pass ``band``.
938 Simple, string name of the filter for the flux being calculated.
940 Any additional keyword arguments that may be passed to the plugin.
942 column =
"{}_psfFluxSkew".format(band)
943 if column
in diaObjects:
944 dtype = diaObjects[column].dtype
945 diaObjects.loc[:, column] = filterDiaSources.psfFlux.skew().astype(dtype)
947 diaObjects.loc[:, column] = filterDiaSources.psfFlux.skew()
956 """Compute min/max of diaSource fluxes.
959 ConfigClass = MinMaxDiaPsfFluxConfig
963 outputCols = [
"psfFluxMin",
"psfFluxMax"]
977 """Compute min/max of the point source fluxes.
982 Summary object to store values in.
983 diaSources : `pandas.DataFrame`
984 DataFrame representing all diaSources associated with this
986 filterDiaSources : `pandas.DataFrame`
987 DataFrame representing diaSources associated with this
988 diaObject that are observed in the band pass ``band``.
990 Simple, string name of the filter for the flux being calculated.
992 Any additional keyword arguments that may be passed to the plugin.
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)
1012 """Compute the maximum ratio time ordered deltaFlux / deltaTime.
1015 ConfigClass = MinMaxDiaPsfFluxConfig
1019 outputCols = [
"psfFluxMaxSlope"]
1033 """Compute the maximum ratio time ordered deltaFlux / deltaTime.
1038 Summary object to store values in.
1039 diaSources : `pandas.DataFrame`
1040 DataFrame representing all diaSources associated with this
1042 filterDiaSources : `pandas.DataFrame`
1043 DataFrame representing diaSources associated with this
1044 diaObject that are observed in the band pass ``band``.
1046 Simple, string name of the filter for the flux being calculated.
1048 Any additional keyword arguments that may be passed to the plugin.
1052 tmpDf = df[~np.logical_or(np.isnan(df[
"psfFlux"]),
1053 np.isnan(df[
"midpointMjdTai"]))]
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)
1067 diaObjects.loc[:, column] = filterDiaSources.apply(_maxSlope)
1076 """Compute the mean of the dia source errors.
1079 ConfigClass = ErrMeanDiaPsfFluxConfig
1083 outputCols = [
"psfFluxErrMean"]
1097 """Compute the mean of the dia source errors.
1102 Summary object to store values in.
1103 diaSources : `pandas.DataFrame`
1104 DataFrame representing all diaSources associated with this
1106 filterDiaSources : `pandas.DataFrame`
1107 DataFrame representing diaSources associated with this
1108 diaObject that are observed in the band pass ``band``.
1110 Simple, string name of the filter for the flux being calculated.
1112 Any additional keyword arguments that may be passed to the plugin.
1114 column =
"{}_psfFluxErrMean".format(band)
1115 if column
in diaObjects:
1116 dtype = diaObjects[column].dtype
1117 diaObjects.loc[:, column] = filterDiaSources.psfFluxErr.mean().astype(dtype)
1119 diaObjects.loc[:, column] = filterDiaSources.psfFluxErr.mean()
1128 """Compute fit a linear model to flux vs time.
1131 ConfigClass = LinearFitDiaPsfFluxConfig
1135 outputCols = [
"psfFluxLinearSlope",
"psfFluxLinearIntercept"]
1149 """Compute fit a linear model to flux vs time.
1154 Summary object to store values in.
1155 diaSources : `pandas.DataFrame`
1156 DataFrame representing all diaSources associated with this
1158 filterDiaSources : `pandas.DataFrame`
1159 DataFrame representing diaSources associated with this
1160 diaObject that are observed in the band pass ``band``.
1162 Simple, string name of the filter for the flux being calculated.
1164 Any additional keyword arguments that may be passed to the plugin.
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
1176 tmpDf = df[~np.logical_or(
1177 np.isnan(df[
"psfFlux"]),
1178 np.logical_or(np.isnan(df[
"psfFluxErr"]),
1179 np.isnan(df[
"midpointMjdTai"])))]
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)
1198 """Compute the StetsonJ statistic on the DIA point source fluxes.
1201 ConfigClass = LinearFitDiaPsfFluxConfig
1204 inputCols = [
"psfFluxMean"]
1206 outputCols = [
"psfFluxStetsonJ"]
1220 """Compute the StetsonJ statistic on the DIA point source fluxes.
1225 Summary object to store values in.
1226 diaSources : `pandas.DataFrame`
1227 DataFrame representing all diaSources associated with this
1229 filterDiaSources : `pandas.DataFrame`
1230 DataFrame representing diaSources associated with this
1231 diaObject that are observed in the band pass ``band``.
1233 Simple, string name of the filter for the flux being calculated.
1235 Any additional keyword arguments that may be passed to the plugin.
1237 meanName =
"{}_psfFluxMean".format(band)
1240 tmpDf = df[~np.logical_or(np.isnan(df[
"psfFlux"]),
1241 np.isnan(df[
"psfFluxErr"]))]
1244 fluxes = tmpDf[
"psfFlux"].to_numpy()
1245 errors = tmpDf[
"psfFluxErr"].to_numpy()
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)
1257 diaObjects.loc[:, column] = filterDiaSources.apply(_stetsonJ)
1260 """Compute the single band stetsonJ statistic.
1264 fluxes : `numpy.ndarray` (N,)
1265 Calibrated lightcurve flux values.
1266 errors : `numpy.ndarray` (N,)
1267 Errors on the calibrated lightcurve fluxes.
1269 Starting mean from previous plugin.
1274 stetsonJ statistic for the input fluxes and errors.
1278 .. [1] Stetson, P. B., "On the Automatic Determination of Light-Curve
1279 Parameters for Cepheid Variables", PASP, 108, 851S, 1996
1281 n_points = len(fluxes)
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)))
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.
1306 values : `numpy.dnarray`, (N,)
1307 Input values to compute the mean of.
1308 errors : `numpy.ndarray`, (N,)
1309 Errors on the input values.
1311 Starting mean value or None.
1313 Scalar down-weighting of the fractional difference. lower->more
1314 clipping. (Default value is 2.)
1316 Power law slope of the used to down-weight outliers. higher->more
1317 clipping. (Default value is 2.)
1319 Number of iterations of clipping.
1321 Fractional and absolute tolerance goal on the change in the mean
1322 before exiting early. (Default value is 1e-6)
1327 Weighted stetson mean result.
1331 .. [1] Stetson, P. B., "On the Automatic Determination of Light-Curve
1332 Parameters for Cepheid Variables", PASP, 108, 851S, 1996
1334 n_points = len(values)
1335 n_factor = np.sqrt(n_points / (n_points - 1))
1336 inv_var = 1 / errors ** 2
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(
1344 weights=inv_var / (1 + (chi / alpha) ** beta))
1345 diff = np.fabs(tmp_mean - mean)
1347 if diff / mean < tol
and diff < tol:
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.
1364 ConfigClass = WeightedMeanDiaPsfFluxConfig
1365 outputCols = [
"scienceFluxMean",
"scienceFluxMeanErr"]
1373 @catchWarnings(warns=[
"invalid value encountered",
1381 """Compute the weighted mean and mean error of the point source flux.
1386 Summary object to store values in.
1387 diaSources : `pandas.DataFrame`
1388 DataFrame representing all diaSources associated with this
1390 filterDiaSources : `pandas.DataFrame`
1391 DataFrame representing diaSources associated with this
1392 diaObject that are observed in the band pass ``band``.
1394 Simple, string name of the filter for the flux being calculated.
1396 Any additional keyword arguments that may be passed to the plugin.
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
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
1427 """Compute scatter of diaSource fluxes.
1430 ConfigClass = SigmaDiaPsfFluxConfig
1432 outputCols = [
"scienceFluxSigma"]
1446 """Compute the sigma fluxes of the point source flux measured on the
1452 Summary object to store values in.
1453 diaSources : `pandas.DataFrame`
1454 DataFrame representing all diaSources associated with this
1456 filterDiaSources : `pandas.DataFrame`
1457 DataFrame representing diaSources associated with this
1458 diaObject that are observed in the band pass ``band``.
1460 Simple, string name of the filter for the flux being calculated.
1462 Any additional keyword arguments that may be passed to the plugin.
1466 column =
"{}_scienceFluxSigma".format(band)
1467 if column
in diaObjects:
1468 dtype = diaObjects[column].dtype
1469 diaObjects.loc[:, column] = filterDiaSources.scienceFlux.std().astype(dtype)
1472 diaObjects.loc[:, column] = filterDiaSources.scienceFlux.std()
float FLUX_MOMENTS_CALCULATED
calculate(self, diaObjects, diaSources, filterDiaSources, band, **kwargs)
calculate(self, diaObjects, diaSources, filterDiaSources, band, **kwargs)
calculate(self, diaObjects, diaObjectId, **kwargs)
__init__(self, config, name, metadata)
calculate(self, diaObjects, diaSources, filterDiaSources, band, **kwargs)
calculate(self, diaObjects, diaSources, filterDiaSources, band)
calculate_baluev_fap(time, n, maxPeriod, zmax)
generate_lsp_params(lsp_model, fbest, bands)
calculate(self, diaObjects, diaSources, **kwargs)
calculate(self, diaObjects, diaSources, filterDiaSources, band, **kwargs)
calculate(self, diaObjects, diaSources, filterDiaSources, band, **kwargs)
calculate(self, diaObjects, diaSources, **kwargs)
calculate(self, diaObjects, diaSources, filterDiaSources, band, **kwargs)
calculate(self, diaObjects, diaSources, **kwargs)
__init__(self, config, name, metadata, **kwargs)
calculate(self, diaObjects, diaSources, filterDiaSources, band, **kwargs)
calculate(self, diaObjects, diaSources, filterDiaSources, band, **kwargs)
calculate(self, diaObjects, diaSources, filterDiaSources, band, **kwargs)
calculate(self, diaObjects, diaSources, **kwargs)
calculate(self, diaObjects, diaSources, filterDiaSources, band, **kwargs)
calculate(self, diaObjects, diaSources, filterDiaSources, band, **kwargs)
_stetson_J(self, fluxes, errors, mean=None)
_stetson_mean(self, values, errors, mean=None, alpha=2., beta=2., n_iter=20, tol=1e-6)
calculate(self, diaObjects, diaSources, filterDiaSources, band, **kwargs)
calculate(self, diaObjects, diaSources, filterDiaSources, band, **kwargs)
float DEFAULT_CATALOGCALCULATION
compute_optimized_periodogram_grid(x0, oversampling_factor=5, nyquist_factor=100)
catchWarnings(_func=None, *, warns=[])
register(name, shouldApCorr=False, apCorrList=())