Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1import numpy as np 

2import warnings 

3 

4from .moMetrics import BaseMoMetric 

5 

6__all__ = ['integrateOverH', 'ValueAtHMetric', 'MeanValueAtHMetric', 

7 'MoCompletenessMetric', 'MoCompletenessAtTimeMetric'] 

8 

9 

10def integrateOverH(Mvalues, Hvalues, Hindex = 0.33): 

11 """Function to calculate a metric value integrated over an Hrange, assuming a power-law distribution. 

12 

13 Parameters 

14 ---------- 

15 Mvalues : numpy.ndarray 

16 The metric values at each H value. 

17 Hvalues : numpy.ndarray 

18 The H values corresponding to each Mvalue (must be the same length). 

19 Hindex : float, opt 

20 The power-law index expected for the H value distribution. 

21 Default is 0.33 (dN/dH = 10^(Hindex * H) ). 

22 

23 Returns 

24 -------- 

25 numpy.ndarray 

26 The integrated or cumulative metric values. 

27 """ 

28 # Set expected H distribution. 

29 # dndh = differential size distribution (number in this bin) 

30 dndh = np.power(10., Hindex*(Hvalues-Hvalues.min())) 

31 # dn = cumulative size distribution (number in this bin and brighter) 

32 intVals = np.cumsum(Mvalues*dndh)/np.cumsum(dndh) 

33 return intVals 

34 

35 

36class ValueAtHMetric(BaseMoMetric): 

37 """Return the metric value at a given H value. 

38 

39 Requires the metric values to be one-dimensional (typically, completeness values). 

40 

41 Parameters 

42 ---------- 

43 Hmark : float, opt 

44 The H value at which to look up the metric value. Default = 22. 

45 """ 

46 def __init__(self, Hmark=22, **kwargs): 

47 metricName = 'Value At H=%.1f' %(Hmark) 

48 super(ValueAtHMetric, self).__init__(metricName=metricName, **kwargs) 

49 self.Hmark = Hmark 

50 

51 def run(self, metricVals, Hvals): 

52 # Check if desired H value is within range of H values. 

53 if (self.Hmark < Hvals.min()) or (self.Hmark > Hvals.max()): 

54 warnings.warn('Desired H value of metric outside range of provided H values.') 

55 return None 

56 if metricVals.shape[0] != 1: 

57 warnings.warn('This is not an appropriate summary statistic for this data - need 1d values.') 

58 return None 

59 value = np.interp(self.Hmark, Hvals, metricVals[0]) 

60 return value 

61 

62 

63class MeanValueAtHMetric(BaseMoMetric): 

64 """Return the mean value of a metric at a given H. 

65 

66 Allows the metric values to be multi-dimensional (i.e. use a cloned H distribution). 

67 

68 Parameters 

69 ---------- 

70 Hmark : float, opt 

71 The H value at which to look up the metric value. Default = 22. 

72 """ 

73 def __init__(self, Hmark=22, reduceFunc=np.mean, metricName=None, **kwargs): 

74 if metricName is None: 

75 metricName = 'Mean Value At H=%.1f' %(Hmark) 

76 super(MeanValueAtHMetric, self).__init__(metricName=metricName, **kwargs) 

77 self.Hmark = Hmark 

78 self.reduceFunc = reduceFunc 

79 

80 def run(self, metricVals, Hvals): 

81 # Check if desired H value is within range of H values. 

82 if (self.Hmark < Hvals.min()) or (self.Hmark > Hvals.max()): 

83 warnings.warn('Desired H value of metric outside range of provided H values.') 

84 return None 

85 value = np.interp(self.Hmark, Hvals, self.reduceFunc(metricVals.swapaxes(0, 1), axis=1)) 

86 return value 

87 

88 

89class MoCompletenessMetric(BaseMoMetric): 

90 """Calculate the fraction of the population that meets `threshold` value or higher. 

91 This is equivalent to calculating the completeness (relative to the entire population) given 

92 the output of a Discovery_N_Chances metric, or the fraction of the population that meets a given cutoff 

93 value for Color determination metrics. 

94 

95 Any moving object metric that outputs a float value can thus have the 'fraction of the population' 

96 with greater than X value calculated here, as a summary statistic. 

97 

98 Parameters 

99 ---------- 

100 threshold : int, opt 

101 Count the fraction of the population that exceeds this value. Default = 1. 

102 nbins : int, opt 

103 If the H values for the metric are not a cloned distribution, then split up H into this many bins. 

104 Default 20. 

105 minHrange : float, opt 

106 If the H values for the metric are not a cloned distribution, then split up H into at least this 

107 range (otherwise just use the min/max of the H values). Default 1.0 

108 cumulative : bool, opt 

109 If False, simply report the differential fractional value (or differential completeness). 

110 If True, integrate over the H distribution (using IntegrateOverH) to report a cumulative fraction. 

111 Default False. 

112 Hindex : float, opt 

113 Use Hindex as the power law to integrate over H, if cumulative is True. Default 0.3. 

114 """ 

115 def __init__(self, threshold=1, nbins=20, minHrange=1.0, cumulative=False, Hindex=0.33, **kwargs): 

116 if 'metricName' in kwargs: 

117 metricName = kwargs.pop('metricName') 

118 if metricName.startswith('Cumulative'): 

119 self.cumulative=True 

120 units = '<= H' 

121 else: 

122 self.cumulative=False 

123 units = '@ H' 

124 else: 

125 self.cumulative = cumulative 

126 if self.cumulative: 

127 metricName = 'CumulativeCompleteness' 

128 units = '<= H' 

129 else: 

130 metricName = 'DifferentialCompleteness' 

131 units = '@ H' 

132 super(MoCompletenessMetric, self).__init__(metricName=metricName, units=units, **kwargs) 

133 self.threshold = threshold 

134 # If H is not a cloned distribution, then we need to specify how to bin these values. 

135 self.nbins = nbins 

136 self.minHrange = minHrange 

137 self.Hindex = Hindex 

138 

139 def run(self, metricValues, Hvals): 

140 nSsos = metricValues.shape[0] 

141 nHval = len(Hvals) 

142 metricValH = metricValues.swapaxes(0, 1) 

143 if nHval == metricValues.shape[1]: 

144 # Hvals array is probably the same as the cloned H array. 

145 completeness = np.zeros(len(Hvals), float) 

146 for i, H in enumerate(Hvals): 

147 completeness[i] = np.where(metricValH[i].filled(0) >= self.threshold)[0].size 

148 completeness = completeness / float(nSsos) 

149 else: 

150 # The Hvals are spread more randomly among the objects (we probably used one per object). 

151 hrange = Hvals.max() - Hvals.min() 

152 minH = Hvals.min() 

153 if hrange < self.minHrange: 

154 hrange = self.minHrange 

155 minH = Hvals.min() - hrange/2.0 

156 stepsize = hrange / float(self.nbins) 

157 bins = np.arange(minH, minH + hrange + stepsize/2.0, stepsize) 

158 Hvals = bins[:-1] 

159 n_all, b = np.histogram(metricValH[0], bins) 

160 condition = np.where(metricValH[0] >= self.requiredChances)[0] 

161 n_found, b = np.histogram(metricValH[0][condition], bins) 

162 completeness = n_found.astype(float) / n_all.astype(float) 

163 completeness = np.where(n_all==0, 0, completeness) 

164 if self.cumulative: 

165 completenessInt = integrateOverH(completeness, Hvals, self.Hindex) 

166 summaryVal = np.empty(len(completenessInt), dtype=[('name', np.str_, 20), ('value', float)]) 

167 summaryVal['value'] = completenessInt 

168 for i, Hval in enumerate(Hvals): 

169 summaryVal['name'][i] = 'H <= %f' % (Hval) 

170 else: 

171 summaryVal = np.empty(len(completeness), dtype=[('name', np.str_, 20), ('value', float)]) 

172 summaryVal['value'] = completeness 

173 for i, Hval in enumerate(Hvals): 

174 summaryVal['name'][i] = 'H = %f' % (Hval) 

175 return summaryVal 

176 

177class MoCompletenessAtTimeMetric(BaseMoMetric): 

178 """Calculate the completeness (relative to the entire population) <= a given H as a function of time, 

179 given the times of each discovery. 

180 

181 Input values of the discovery times can come from the Discovery_Time (child) metric or the 

182 KnownObjects metric. 

183 

184 Parameters 

185 ---------- 

186 times : numpy.ndarray like 

187 The bins to distribute the discovery times into. Same units as the discovery time (typically MJD). 

188 Hval : float, opt 

189 The value of H to count completeness at (or cumulative completeness to). 

190 Default None, in which case a value halfway through Hvals (the slicer H range) will be chosen. 

191 cumulative : bool, opt 

192 If True, calculate the cumulative completeness (completeness <= H). 

193 If False, calculate the differential completeness (completeness @ H). 

194 Default True. 

195 Hindex : float, opt 

196 Use Hindex as the power law to integrate over H, if cumulative is True. Default 0.3. 

197 """ 

198 

199 def __init__(self, times, Hval=None, cumulative=True, Hindex=0.33, **kwargs): 

200 self.Hval = Hval 

201 self.times = times 

202 self.Hindex = Hindex 

203 if 'metricName' in kwargs: 

204 metricName = kwargs.pop('metricName') 

205 if metricName.startswith('Differential'): 

206 self.cumulative = False 

207 self.metricName = metricName 

208 else: 

209 self.cumulative = True 

210 self.metricName = metricName 

211 else: 

212 self.cumulative = cumulative 

213 if self.cumulative: 

214 self.metricName = 'CumulativeCompleteness@Time@H=%.2f' % self.Hval 

215 else: 

216 self.metricName = 'DifferentialCompleteness@Time@H=%.2f' % self.Hval 

217 self._setLabels() 

218 super(MoCompletenessAtTimeMetric, self).__init__(metricName=self.metricName, units=self.units, 

219 **kwargs) 

220 

221 def _setLabels(self): 

222 if self.Hval is not None: 

223 if self.cumulative: 

224 self.units = 'H <=%.1f' % (self.Hval) 

225 else: 

226 self.units = 'H = %.1f' % (self.Hval) 

227 else: 

228 self.units = 'H' 

229 

230 def run(self, discoveryTimes, Hvals): 

231 if len(Hvals) != discoveryTimes.shape[1]: 

232 warnings.warn("This summary metric expects cloned H distribution. Cannot calculate summary.") 

233 return 

234 nSsos = discoveryTimes.shape[0] 

235 timesinH = discoveryTimes.swapaxes(0, 1) 

236 completenessH = np.empty([len(Hvals), len(self.times)], float) 

237 for i, H in enumerate(Hvals): 

238 n, b = np.histogram(timesinH[i].compressed(), bins=self.times) 

239 completenessH[i][0] = 0 

240 completenessH[i][1:] = n.cumsum() 

241 completenessH = completenessH / float(nSsos) 

242 completeness = completenessH.swapaxes(0, 1) 

243 if self.cumulative: 

244 for i, t in enumerate(self.times): 

245 completeness[i] = integrateOverH(completeness[i], Hvals) 

246 # To save the summary statistic, we must pick out a given H value. 

247 if self.Hval is None: 

248 Hidx = len(Hvals) // 2 

249 self.Hval = Hvals[Hidx] 

250 self._setLabels() 

251 else: 

252 Hidx = np.where(np.abs(Hvals - self.Hval) == np.abs(Hvals - self.Hval).min())[0][0] 

253 self.Hval = Hvals[Hidx] 

254 self._setLabels() 

255 summaryVal = np.empty(len(self.times), dtype=[('name', np.str_, 20), ('value', float)]) 

256 summaryVal['value'] = completeness[:, Hidx] 

257 for i, time in enumerate(self.times): 

258 summaryVal['name'][i] = '%s @ %.2f' % (self.units, time) 

259 return summaryVal 

260 

261