Coverage for spectractor/fit/statistics.py: 8%
Shortcuts 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
Shortcuts 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 matplotlib.pyplot as plt
2from matplotlib.ticker import MaxNLocator
3from scipy import interpolate
4import numpy as np
5import sys
8from spectractor import parameters
9from spectractor.tools import formatting_numbers
12class Axis(object):
13 def __init__(self, axis, axisname):
14 self.axisname = axisname
15 self.axis = []
16 self.bins = []
17 self.min = 0
18 self.max = 0
19 self.step = 0
20 self.set_axis(axis)
21 self.size = len(axis)
22 self.txt = ''
24 def getAxisVal(self, index):
25 return self.axis[index]
27 def getAxisIndex(self, x):
28 # optimized for sorted array
29 index = np.searchsorted(self.axis, x)
30 return index
32 def set_axis(self, axis):
33 if isinstance(axis, float):
34 axis = [axis]
35 else:
36 if len(axis) == 1:
37 axis = [axis[0]]
38 self.axis = np.sort(axis)
39 self.min = np.min(self.axis)
40 self.max = np.max(self.axis)
41 self.size = len(self.axis)
42 if len(self.axis) > 1:
43 self.step = np.gradient(self.axis)
44 else:
45 self.step = [0]
46 self.bins = np.zeros(self.size + 1)
47 self.bins[0] = self.axis[0] - self.step[0] / 2
48 self.bins[1:] = self.axis[:] + self.step / 2
51class Grid:
52 def __init__(self, dim, ranges, axis_names):
53 self.dim = dim
54 self.axis_names = axis_names
55 self.grid = np.zeros_like(1)
56 self.max = 0
57 self.max_index = -1
58 self.total = 0
59 self.rangedim = list(range(dim))
60 if dim == 1 and len(ranges) != dim:
61 ranges = [ranges]
62 if dim == 1 and len(axis_names) != dim:
63 self.axis_names = [axis_names]
64 self.axes = [Axis(ranges[i], self.axis_names[i]) for i in self.rangedim]
66 def getAxisVal(self, axis_index, index):
67 return self.axes[axis_index].getAxisVal(index)
69 def getAxisIndex(self, axis_index, value):
70 return self.axes[axis_index].getAxisIndex(value)
72 def getAxisIndices(self, values):
73 return [self.getAxisIndex(i, values[i]) for i in self.rangedim]
75 def getMaximum(self):
76 self.max = np.max(self.grid.flatten())
77 self.max_index = np.argmax(self.grid)
78 return self.max
80 def getTotal(self):
81 if len(self.axes[-1].axis) > 1:
82 self.total = np.trapz(y=self.grid, x=self.axes[-1].axis, axis=self.rangedim[-1])
83 else:
84 self.total = np.sum(self.grid)
85 if self.dim > 1:
86 for i in reversed(self.rangedim[:-1]):
87 if len(self.axes[i].axis) > 1:
88 self.total = np.trapz(y=self.total, x=self.axes[i].axis, axis=i)
89 else:
90 self.total = np.sum(self.total, axis=i)
91 return self.total
93 def normalize(self):
94 self.total = self.getTotal()
95 if self.total == 0:
96 sys.exit('Warning! Sum of likelihood is zero: can not normalize grid {}.'.format(self.axis_names))
97 else:
98 self.grid = self.grid / self.total
99 return self.total
101 def marginalizeAlongAxis(self, axis_index):
102 # return(np.sum(self.grid,axis=axis_index))
103 return np.trapz(self.grid, self.axes[axis_index].axis, axis=axis_index)
106class PDF(Grid):
107 def __init__(self, ticks, label='', axis_name=''):
108 Grid.__init__(self, 1, ticks, axis_name)
109 self.axe = Axis(ticks, axis_name)
110 self.label = label
111 self.axis_name = axis_name
112 self.grid = np.zeros_like(ticks)
113 self.mean = None
114 self.max_pdf = None
115 self.error_low = None
116 self.error_high = None
117 self.probability_levels = [0.682690, 0.954500] # [ 0.682690, 0.954500, 0.9973 ]
118 self.variance = None
119 self.title = ""
121 def fill(self, pdf):
122 self.grid = pdf
123 self.normalize()
124 return pdf
126 def fill_histogram(self, data, weights=None):
127 self.grid = np.histogram(data, bins=self.axe.bins, normed=False, weights=weights)[0]
128 self.normalize()
130 def plot(self, truth=None):
131 """
133 Returns:
134 :
135 """
136 x = self.axe.axis
137 y = self.grid
138 tck = interpolate.splrep(self.axe.axis, self.grid, s=0)
139 if parameters.PAPER:
140 x = np.linspace(self.axe.min, self.axe.max, num=101, endpoint=True)
141 y = interpolate.splev(x, tck, der=0)
142 plt.plot(x, y, lw=parameters.LINEWIDTH)
143 # shaded 1 sigma band
144 if self.error_low is not None and self.error_high is not None:
145 x1s = np.linspace(self.mean - self.error_low, self.mean + self.error_high, num=101, endpoint=True)
146 y1s = interpolate.splev(x1s, tck, der=0)
147 plt.fill_between(x1s, y1s, 0, alpha=0.5, color='cornflowerblue')
148 plt.plot([self.mean, self.mean], [0, np.interp(self.mean, x, y)], 'b--', lw=parameters.LINEWIDTH)
149 # truth
150 if truth is not None:
151 plt.plot([truth, truth], [0, 1.2 * max(self.grid)], 'r-', lw=parameters.LINEWIDTH)
152 plt.xlabel(self.axis_name)
153 plt.gca().axes.get_yaxis().set_visible(False)
154 plt.ylim(0, 1.2 * max(self.grid))
155 plt.xlim(self.axe.min, self.axe.max)
156 # delete last and first tick labels
157 xticks = plt.gca().axes.get_xticks()
158 # if xticks[-1] > 1: xticks = xticks[:-1]
159 xticks = xticks[:-1]
160 plt.gca().axes.set_xticks(xticks[1:])
161 if self.title != "":
162 plt.title(self.title)
164 def stats(self, verbose=True):
165 self.getMaximum()
166 self.max_pdf = self.axe.axis[self.max_index]
167 # self.mean = np.average(self.axe.axis,weights=self.grid)
168 xprod = np.zeros_like(self.grid)
169 for xindex, x in enumerate(self.axe.axis):
170 xprod[xindex] = x * self.grid[xindex]
171 self.mean = np.trapz(xprod, x=self.axe.axis)
172 # cumprob = np.cumsum(self.grid)
173 cumprob = np.zeros_like(self.grid)
174 cumprob[0] = self.grid[0]
175 for xindex in range(len(self.axe.axis))[1:]:
176 cumprob[xindex] = cumprob[xindex - 1] + 0.5 * (self.grid[xindex] + self.grid[xindex - 1]) * (
177 self.axe.axis[xindex] - self.axe.axis[xindex - 1])
178 cumbest = np.interp(self.mean, self.axe.axis, cumprob)
179 if cumbest > 1 - self.probability_levels[0] / 2.0:
180 if verbose > 2:
181 print('\tWarning! {{}} estimate is too close to cumulative prob upper limit of 1. '
182 'Errors may not be accurate.'.format(self.label))
183 if cumbest < self.probability_levels[0] / 2.0:
184 if verbose > 2:
185 print('\tWarning! {{}} estimate is too close to cumulative prob lower limit of 0. '
186 'Errors may not be accurate.'.format(self.label))
187 upcum = cumbest + self.probability_levels[0] / 2.0
188 if upcum > 1.0:
189 uplimit = np.interp(1, cumprob, self.axe.axis)
190 else:
191 uplimit = np.interp(upcum, cumprob, self.axe.axis)
192 self.error_high = uplimit - self.mean
193 botcum = cumbest - self.probability_levels[0] / 2.0
194 if botcum < 0.0:
195 lowlimit = np.interp(0, cumprob, self.axe.axis)
196 else:
197 lowlimit = np.interp(botcum, cumprob, self.axe.axis)
198 self.error_low = self.mean - lowlimit
199 # MCI interval
200 # print 'Warning! MCI disabled'
201 for y in np.linspace(0, self.max, num=1000)[::-1][1:-1]:
202 limits = np.where(self.grid > y)[0]
203 if len(limits) > 1:
204 if limits[0] > 0:
205 lowx = np.interp(y, self.grid[limits[0] - 1:limits[0] + 1],
206 self.axe.axis[limits[0] - 1:limits[0] + 1])
207 else:
208 lowx = self.axe.axis[limits[0]]
209 if limits[-1] < len(self.axe.axis) - 1:
210 upx = np.interp(y, self.grid[limits[-1]:limits[-1] + 2][::-1],
211 self.axe.axis[limits[-1]:limits[-1] + 2][::-1])
212 else:
213 upx = self.axe.axis[limits[-1]]
214 prob = np.interp(upx, self.axe.axis, cumprob) - np.interp(lowx, self.axe.axis, cumprob)
215 if prob > self.probability_levels[0]:
216 break
217 self.error_high = upx - self.mean
218 self.error_low = -(lowx - self.mean)
219 # Estimate variance
220 xxprod = np.zeros_like(self.grid)
221 for xindex, x in enumerate(self.axe.axis):
222 xxprod[xindex] = self.grid[xindex] * (x - self.mean) ** 2
223 self.variance = np.trapz(xxprod, self.axe.axis)
224 txt = "%s: %s +%s -%s (std: %s)" % formatting_numbers(self.mean, self.error_high, self.error_low,
225 std=np.sqrt(self.variance), label=self.label)
226 self.title = '$%s^{+%s}_{-%s}$' % formatting_numbers(self.mean, self.error_high, self.error_low)
227 self.txt = txt
228 self.txt_long = f"{self.label}: {self.mean} +{self.error_high} -{self.error_low} (std: {np.sqrt(self.variance)})"
229 if verbose:
230 print('\t'+txt)
233class Contours(Grid):
234 def __init__(self, list0, list1, labels, axisnames):
235 Grid.__init__(self, 2, [list0, list1], axisnames)
236 self.grid = np.zeros([len(list0), len(list1)])
237 self.axes = [Axis(list0, axisnames[0]), Axis(list1, axisnames[1])]
238 self.pdfs = [PDF(list0, labels[0], axisnames[0]), PDF(list1, labels[1], axisnames[1])]
239 self.problevels = [0.682690, 0.954500] # [ 0.682690, 0.954500, 0.9973 ]
240 self.labels = labels
241 self.cov = 0
242 self.rho = 0
244 def fill_histogram(self, data1, data2, weights=None):
245 self.grid = (np.histogram2d(data1, data2, bins=[list(self.axes[1].bins), list(self.axes[0].bins)], normed=False,
246 weights=weights)[0]).T
247 self.normalize()
249 def covariance(self):
250 self.normalize()
251 pdf = np.trapz(y=self.grid, x=self.axes[1].axis, axis=1)
252 self.pdfs[0].fill(pdf)
253 pdf = np.trapz(y=self.grid, x=self.axes[0].axis, axis=0)
254 self.pdfs[1].fill(pdf)
255 if self.pdfs[0].max_pdf is None:
256 self.pdfs[0].stats(verbose=False)
257 if self.pdfs[1].max_pdf is None:
258 self.pdfs[1].stats(verbose=False)
259 self.cov = 0
260 # for xindex,x in enumerate(self.axes[0].axis):
261 # for yindex,y in enumerate(self.axes[1].axis):
262 # self.cov += (x-self.pdfs[0].mean)*(y-self.pdfs[1].mean)*self.grid[xindex][yindex]
263 xyprod = np.zeros_like(self.grid)
264 for xindex, x in enumerate(self.axes[0].axis):
265 for yindex, y in enumerate(self.axes[1].axis):
266 xyprod[xindex][yindex] = (x - self.pdfs[0].mean) * (y - self.pdfs[1].mean) * self.grid[xindex][yindex]
267 self.cov = np.trapz(np.trapz(y=xyprod, x=self.axes[1].axis, axis=1), self.axes[0].axis, axis=0)
268 self.rho = self.cov / (np.sqrt(self.pdfs[0].variance * self.pdfs[1].variance))
269 return self.cov
271 def plot(self, plot=False, truth=None):
272 """
274 Returns:
275 :
276 """
277 self.normalize()
278 dxdyprod = np.zeros_like(self.grid)
279 sortgrid = []
280 # Trapezoidal 2D integration with irregular axes
281 for xindex, x in enumerate(self.axes[0].axis[:-1]):
282 for yindex, y in enumerate(self.axes[1].axis[:-1]):
283 val = 0.25 * (
284 self.grid[xindex][yindex] + self.grid[xindex + 1][yindex] + self.grid[xindex][yindex + 1] +
285 self.grid[xindex + 1][yindex + 1])
286 dxdyprod[xindex][yindex] = val * (self.axes[0].axis[xindex + 1] - x) * (
287 self.axes[1].axis[yindex + 1] - y)
288 # dxdyprod[xindex][yindex] =
289 # (self.grid[xindex][yindex])*(self.axes[0].axis[xindex+1]-x)*(self.axes[1].axis[yindex+1]-y)
290 sortgrid.append((dxdyprod[xindex][yindex], val))
291 # Sort dxdyprod keeping a trace of grid sorting
292 sortgrid = np.array(sortgrid, dtype=[('dxdyprod', float), ('grid', float)])
293 sortprob = np.sort(sortgrid, order='dxdyprod')
294 dxdyprod, sortgrid = list(zip(*sortprob))
295 # Cumulative integration
296 totprob = np.zeros_like(dxdyprod)
297 totprob[0] = dxdyprod[0]
298 for i in range(1, len(dxdyprod)):
299 totprob[i] = totprob[i - 1] + dxdyprod[i]
300 totprob = 1.0 - totprob
301 # Contour levels
302 ilevels = []
303 for i in range(len(self.problevels)):
304 levels = np.where(totprob > self.problevels[i])
305 if len(levels[0]) != 0:
306 ilevels.append(levels[0][-1])
307 contlevels = np.sort(np.array(sortgrid)[ilevels])
308 # if var.PAPER:
309 # f = interpolate.interp2d(self.axes[0].axis,self.axes[1].axis,self.grid.T, kind='linear')
310 # x = np.linspace(self.axes[0].min,self.axes[0].max,2*self.axes[0].size)
311 # y = np.linspace(self.axes[1].min,self.axes[1].max,2*self.axes[1].size)
312 # z = f(x,y)
313 # c = plt.contourf(x,y,z,levels=np.sort(list(contlevels) + [0,np.max(self.grid)]),
314 # colors=('w','cornflowerblue','b'),origin='lower')
315 # c2 = plt.contour(c,levels=contlevels,linewidths=[var.LINEWIDTH,var.LINEWIDTH],colors='b',origin='lower')
316 # else:
317 plt.contourf(self.axes[0].axis, self.axes[1].axis, self.grid.T,
318 levels=np.sort(list(contlevels) + [0, np.max(self.grid)]), colors=('w', 'cornflowerblue', 'b'),
319 origin='lower')
320 plt.contour(self.axes[0].axis, self.axes[1].axis, self.grid.T, levels=contlevels,
321 linewidths=[parameters.LINEWIDTH, parameters.LINEWIDTH], colors='b', origin='lower')
322 # plot mean values and truth
323 plt.plot([self.pdfs[0].mean], [self.pdfs[1].mean], 'k*', markersize=10)
324 if truth is not None:
325 plt.plot([truth[0]], [truth[1]], 'ro', markersize=10)
326 plt.axhline(truth[1], color='r', linewidth=parameters.LINEWIDTH)
327 plt.axvline(truth[0], color='r', linewidth=parameters.LINEWIDTH)
328 # set axes
329 plt.xlim(self.axes[0].min, self.axes[0].max)
330 plt.ylim(self.axes[1].min, self.axes[1].max)
331 # delete last and first tick labels
332 yticks = plt.gca().axes.get_yticks()
333 # if yticks[-1] > 1: yticks = yticks[:-1]
334 yticks = yticks[:-1]
335 plt.gca().axes.set_yticks(yticks[1:])
336 xticks = plt.gca().axes.get_xticks()
337 # if xticks[-1] > 1: xticks = xticks[:-1]
338 xticks = xticks[:-1]
339 plt.gca().axes.set_xticks(xticks[1:])
340 if plot:
341 plt.xlabel(self.axis_names[0])
342 plt.ylabel(self.axis_names[1])
343 plt.show()
344 if parameters.PdfPages:
345 parameters.PdfPages.savefig()
348class Likelihood(Grid):
350 def __init__(self, ranges, labels=[], axis_names=[], truth=None):
351 Grid.__init__(self, len(ranges), ranges, axis_names)
352 self.ranges = ranges
353 self.axes = [Axis(self.ranges[i], axis_names[i]) for i in self.rangedim]
354 self.pdfs = [PDF(self.ranges[i], labels[i], axis_names[i]) for i in self.rangedim]
355 self.contours = [
356 [Contours(self.ranges[i], self.ranges[j], [labels[i], labels[j]], [axis_names[i], axis_names[j]]) for i in
357 self.rangedim] for j in self.rangedim]
358 self.grid = None
359 if self.dim <= 6:
360 self.grid = np.zeros(list(map(len, ranges)))
361 self.labels = labels
362 self.best_chisq = 1e20
363 self.truth = truth
364 self.cov_matrix = None
365 self.rho_matrix = None
366 self.mean_vec = None
368 def setValue(self, indices, value):
369 if self.dim == 4:
370 self.grid[indices[0]][indices[1]][indices[2]][indices[3]] = value
371 elif self.dim == 5:
372 self.grid[indices[0]][indices[1]][indices[2]][indices[3]][indices[4]] = value
373 elif self.dim == 6:
374 self.grid[indices[0]][indices[1]][indices[2]][indices[3]][indices[4]][indices[5]] = value
375 elif self.dim == 7:
376 self.grid[indices[0]][indices[1]][indices[2]][indices[3]][indices[4]][indices[5]][indices[6]] = value
377 else:
378 sys.exit('Warning! In setValue, unsupported grid dimension.')
380 def marginalize(self, pdfonly=False):
381 for i in self.rangedim:
382 for j in self.rangedim:
383 axes = [n for n in self.rangedim if n not in [i, j]]
384 if i == j:
385 if j > i:
386 continue
387 if self.dim > 1:
388 if len(self.axes[axes[-1]].axis) == 1:
389 pdf = np.sum(self.grid, axis=axes[-1])
390 else:
391 pdf = np.trapz(y=self.grid, x=self.axes[axes[-1]].axis, axis=axes[-1])
392 for axe in reversed(axes[:-1]):
393 if len(self.axes[axe].axis) == 1:
394 pdf = np.sum(pdf, axis=axe)
395 else:
396 pdf = np.trapz(y=pdf, x=self.axes[axe].axis, axis=axe)
397 self.pdfs[i].fill(pdf)
398 else:
399 self.pdfs[i].fill(self.grid)
400 else:
401 if not pdfonly:
402 if self.dim > 2:
403 if len(self.axes[axes[-1]].axis) == 1:
404 self.contours[i][j].grid = np.sum(self.grid, axis=axes[-1])
405 else:
406 self.contours[i][j].grid = np.trapz(y=self.grid, x=self.axes[axes[-1]].axis,
407 axis=axes[-1])
408 for axe in reversed(axes[:-1]):
409 if len(self.axes[axe].axis) == 1:
410 self.contours[i][j].grid = np.sum(self.contours[i][j].grid, axis=axe)
411 else:
412 self.contours[i][j].grid = np.trapz(y=self.contours[i][j].grid,
413 x=self.axes[axe].axis, axis=axe)
414 if i < j:
415 self.contours[i][j].grid = self.contours[i][j].grid.T
416 else:
417 if i < j:
418 self.contours[i][j].grid = self.grid.T
419 if j < i:
420 self.contours[i][j].grid = self.grid
422 def triangle_plots(self, output_filename=''):
423 n = self.dim
424 fig = plt.figure(1, figsize=(16, 9))
425 if parameters.PAPER:
426 fig.set_size_inches(18, 13)
427 fig.clf()
428 for i in range(n):
429 fig.add_subplot(n, n, i + i * n + 1)
430 truth = None
431 if self.truth is not None:
432 truth = self.truth[i]
433 self.pdfs[i].plot(truth=truth)
434 plt.gca().axes.get_xaxis().set_major_locator(MaxNLocator(4, prune='upper'))
435 if i == n - 1:
436 plt.xlabel(self.axis_names[i])
437 plt.gca().axes.get_xaxis().set_label_coords(0.5, -0.3)
438 else:
439 plt.gca().axes.get_xaxis().set_ticklabels([])
440 # print 'hist ',n1
441 for j in range(i):
442 n1 = self.axis_names[i]
443 n2 = self.axis_names[j]
444 # print 'plot ',n1,' vs. ',n2
445 fig.add_subplot(n, n, i * n + j + 1)
446 truth = None
447 if self.truth is not None:
448 truth = [self.truth[j], self.truth[i]]
449 self.contours[i][j].plot(plot=False, truth=truth)
450 plt.gca().axes.get_xaxis().set_major_locator(MaxNLocator(4, prune='upper'))
451 plt.gca().axes.get_yaxis().set_major_locator(MaxNLocator(4, prune='upper'))
452 if i == n - 1:
453 plt.xlabel(n2)
454 plt.gca().axes.get_xaxis().set_label_coords(0.5, -0.3)
455 # formatter = mpl.ticker.ScalarFormatter(useOffset=False)
456 # plt.gca().axes.get_xaxis().set_major_formatter(formatter)
457 # tick_params(axis='both', which='major')
458 if j == 0:
459 plt.ylabel(n1)
460 plt.gca().axes.get_yaxis().set_label_coords(-0.32, 0.5)
461 else:
462 plt.gca().axes.get_yaxis().set_ticklabels([])
463 fig.tight_layout()
464 # embed correlation matrix plot
465 plt.axes([0.65, 0.65, 0.3, 0.3]) # This defines the inset
466 cax = plt.imshow(self.rho_matrix, interpolation="nearest", cmap='bwr', vmin=-1, vmax=1)
467 plt.title('Correlation matrix')
468 plt.xticks(list(range(self.dim)), self.axis_names, rotation='vertical', fontsize=11)
469 plt.yticks(list(range(self.dim)), self.axis_names, fontsize=11)
470 cbar = fig.colorbar(cax)
471 cbar.ax.tick_params(labelsize=9)
472 # plot the triangle
473 fig.subplots_adjust(hspace=0, wspace=0)
474 if parameters.DISPLAY:
475 plt.show()
476 if output_filename != '':
477 print(f'Save figure: {output_filename}')
478 fig.savefig(output_filename, dpi=100, bbox_inches='tight')
479 if parameters.PdfPages:
480 parameters.PdfPages.savefig()
481 return fig
483 def max_likelihood_stats(self):
484 self.getMaximum()
485 if self.best_chisq > 1e6:
486 self.best_chisq = -2.0 * np.log(self.total * self.getMaximum())
487 print('Maximum likelihood position: chi2={:.3g}'.format(self.best_chisq))
488 for i in self.rangedim:
489 print("\t" + self.labels[i] + ": " + str(self.getAxisVal(i, self.max_index)))
491 def stats(self, output='', pdfonly=False, verbose=True):
492 #self.max_likelihood_stats()
493 if verbose:
494 print('Marginalised best fit values (Mean and MCI):')
495 self.mean_vec = np.zeros(self.dim)
496 for i in self.rangedim:
497 self.pdfs[i].stats(verbose=verbose)
498 self.mean_vec[i] = self.pdfs[i].mean
499 if not pdfonly:
500 # Estimate covariance
501 self.cov_matrix = np.zeros([self.dim, self.dim])
502 self.rho_matrix = np.zeros([self.dim, self.dim])
503 for i in self.rangedim:
504 for j in self.rangedim:
505 if i == j:
506 self.cov_matrix[i][j] = self.pdfs[i].variance
507 self.rho_matrix[i][j] = 1.0
508 else:
509 self.cov_matrix[i][j] = self.contours[i][j].covariance()
510 self.rho_matrix[i][j] = self.contours[i][j].rho
511 if verbose:
512 print('Correlation matrix:')
513 if verbose:
514 print(('\n'.join([''.join(['\t{0:4.3f}'.format(item) for item in row]) for row in self.rho_matrix])))
515 # Output results
516 if output != '':
517 txt = ''
518 for i in self.rangedim:
519 txt += f'{self.pdfs[i].txt_long}\n'
520 cov = '\n'.join([''.join(['\t{0:8.6f}'.format(item) for item in row]) for row in self.cov_matrix])
521 print(f'Save best fit parameters in {output}')
522 f = open(output, 'w')
523 f.write(txt + cov)
524 f.close()