Coverage for spectractor/fit/fitter.py: 5%
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
1from iminuit import Minuit
2from scipy import optimize
3from schwimmbad import MPIPool
4import emcee
5import time
6import matplotlib.pyplot as plt
7from matplotlib.ticker import MaxNLocator
8import numpy as np
9import sys
10import os
11import multiprocessing
13from spectractor import parameters
14from spectractor.config import set_logger
15from spectractor.tools import formatting_numbers, compute_correlation_matrix, plot_correlation_matrix_simple
16from spectractor.fit.statistics import Likelihood
19class FitWorkspace:
21 def __init__(self, file_name="", nwalkers=18, nsteps=1000, burnin=100, nbins=10,
22 verbose=0, plot=False, live_fit=False, truth=None):
23 """Generic class to create a fit workspace with parameters, bounds and general fitting methods.
25 Parameters
26 ----------
27 file_name: str, optional
28 The generic file name to save results. If file_name=="", nothing is saved ond disk (default: "").
29 nwalkers: int, optional
30 Number of walkers for MCMC exploration (default: 18).
31 nsteps: int, optional
32 Number of steps for MCMC exploration (default: 1000).
33 burnin: int, optional
34 Number of burn-in steps for MCMC exploration (default: 100).
35 nbins: int, optional
36 Number of bins to make histograms after MCMC exploration (default: 10).
37 verbose: int, optional
38 Level of verbosity (default: 0).
39 plot: bool, optional
40 Level of plotting (default: False).
41 live_fit: bool, optional, optional
42 If True, model, data and residuals plots are made along the fitting procedure (default: False).
43 truth: array_like, optional
44 Array of true parameters (default: None).
46 Examples
47 --------
48 >>> w = FitWorkspace()
49 >>> w.ndim
50 0
51 """
52 self.my_logger = set_logger(self.__class__.__name__)
53 self.filename = file_name
54 self.truth = truth
55 self.verbose = verbose
56 self.plot = plot
57 self.live_fit = live_fit
58 self.p = np.array([])
59 self.cov = np.array([[]])
60 self.rho = np.array([[]])
61 self.data = None
62 self.err = None
63 self.data_cov = None
64 self.W = None
65 self.x = None
66 self.outliers = []
67 self.sigma_clip = 5
68 self.model = None
69 self.model_err = None
70 self.model_noconv = None
71 self.input_labels = []
72 self.axis_names = []
73 self.input_labels = []
74 self.bounds = ((), ())
75 self.fixed = []
76 self.nwalkers = max(2 * self.ndim, nwalkers)
77 self.nsteps = nsteps
78 self.nbins = nbins
79 self.burnin = burnin
80 self.start = []
81 self.likelihood = np.array([[]])
82 self.gelmans = np.array([])
83 self.chains = np.array([[]])
84 self.lnprobs = np.array([[]])
85 self.costs = np.array([[]])
86 self.params_table = None
87 self.flat_chains = np.array([[]])
88 self.valid_chains = [False] * self.nwalkers
89 self.global_average = None
90 self.global_std = None
91 self.title = ""
92 self.use_grid = False
93 if self.filename != "":
94 if "." in self.filename:
95 self.emcee_filename = os.path.splitext(self.filename)[0] + "_emcee.h5"
96 else:
97 self.my_logger.warning("\n\tFile name must have an extension.")
98 else:
99 self.emcee_filename = "emcee.h5"
101 @property
102 def ndim(self):
103 """Number of parameters of the model.
105 Returns
106 -------
107 ndim: int
109 Examples
110 --------
111 >>> from spectractor.fit.fitter import FitWorkspace
112 >>> import numpy as np
113 >>> w = FitWorkspace()
114 >>> w.p = np.ones(5)
115 >>> w.ndim
116 5
117 """
118 return len(self.p)
120 def get_bad_indices(self):
121 """List of indices that are outliers rejected by a sigma-clipping method or other masking method.
123 Returns
124 -------
125 not_outliers: list
127 Examples
128 --------
129 >>> from spectractor.fit.fitter import FitWorkspace
130 >>> import numpy as np
131 >>> w = FitWorkspace()
132 >>> w.data = np.array([np.array([1,2,3]), np.array([1,2,3,4])])
133 >>> w.outliers = [2, 6]
134 >>> w.get_bad_indices()
135 [array([2]), array([3])]
136 """
137 bad_indices = np.asarray(self.outliers, dtype=int)
138 if self.data.dtype == np.object:
139 if len(self.outliers) > 0:
140 bad_indices = []
141 start_index = 0
142 for k in range(self.data.shape[0]):
143 mask = np.zeros(self.data[k].size, dtype=bool)
144 outliers = np.asarray(self.outliers)[np.logical_and(np.asarray(self.outliers) > start_index,
145 np.asarray(self.outliers) < start_index +
146 self.data[k].size)]
147 mask[outliers - start_index] = True
148 bad_indices.append(np.arange(self.data[k].size)[mask])
149 start_index += self.data[k].size
150 else:
151 bad_indices = [[] for _ in range(self.data.shape[0])]
152 return bad_indices
154 def set_start(self, percent=0.02, a_random=1e-5):
155 """Set the random starting points for MCMC exploration.
157 A set of parameters are drawn with a uniform distribution between +/- percent times the starting guess.
158 For null guess parameters, starting points are drawn from a uniform distribution between +/- a_random.
160 Parameters
161 ----------
162 percent: float, optional
163 Percent of the guess parameters to set the uniform interval to draw random points (default: 0.02).
164 a_random: float, optional
165 Absolute value to set the +/- uniform interval to draw random points
166 for null guess parameters (default: 1e-5).
168 Returns
169 -------
170 start: np.array
171 Array of starting points of shape (ndim, nwalkers).
173 """
174 self.start = np.array(
175 [np.random.uniform(self.p[i] - percent * self.p[i], self.p[i] + percent * self.p[i], self.nwalkers)
176 for i in range(self.ndim)]).T
177 self.start[self.start == 0] = a_random * np.random.uniform(-1, 1)
178 return self.start
180 def load_chains(self):
181 """Load the MCMC chains from a hdf5 file. The burn-in points are not rejected at this stage.
183 Returns
184 -------
185 chains: np.array
186 Array of the chains.
187 lnprobs: np.array
188 Array of the logarithmic posterior probability.
190 """
191 self.chains = [[]]
192 self.lnprobs = [[]]
193 self.nsteps = 0
194 # tau = -1
195 reader = emcee.backends.HDFBackend(self.emcee_filename)
196 try:
197 tau = reader.get_autocorr_time()
198 except emcee.autocorr.AutocorrError:
199 tau = -1
200 self.chains = reader.get_chain(discard=0, flat=False, thin=1)
201 self.lnprobs = reader.get_log_prob(discard=0, flat=False, thin=1)
202 self.nsteps = self.chains.shape[0]
203 self.nwalkers = self.chains.shape[1]
204 print(f"Auto-correlation time: {tau}")
205 print(f"Burn-in: {self.burnin}")
206 print(f"Chains shape: {self.chains.shape}")
207 print(f"Log prob shape: {self.lnprobs.shape}")
208 return self.chains, self.lnprobs
210 def build_flat_chains(self):
211 """Flatten the chains array and apply burn-in.
213 Returns
214 -------
215 flat_chains: np.array
216 Flat chains.
218 """
219 self.flat_chains = self.chains[self.burnin:, self.valid_chains, :].reshape((-1, self.ndim))
220 return self.flat_chains
222 def simulate(self, *p):
223 """Compute the model prediction given a set of parameters.
225 Parameters
226 ----------
227 p: array_like
228 Array of parameters for the computation of the model.
230 Returns
231 -------
232 x: array_like
233 The abscisse of the model prediction.
234 model: array_like
235 The model prediction.
236 model_err: array_like
237 The uncertainty on the model prediction.
239 Examples
240 --------
241 >>> w = FitWorkspace()
242 >>> p = np.zeros(3)
243 >>> x, model, model_err = w.simulate(*p)
245 .. doctest::
246 :hide:
247 >>> assert x is not None
249 """
250 self.x = np.array([])
251 self.model = np.array([])
252 self.model_err = np.array([])
253 return self.x, self.model, self.model_err
255 def analyze_chains(self):
256 """Load the chains, build the probability densities for the parameters, compute the best fitting values
257 and the uncertainties and covariance matrices, and plot.
259 """
260 self.load_chains()
261 self.set_chain_validity()
262 self.convergence_tests()
263 self.build_flat_chains()
264 self.likelihood = self.chain2likelihood()
265 self.cov = self.likelihood.cov_matrix
266 self.rho = self.likelihood.rho_matrix
267 self.p = self.likelihood.mean_vec
268 self.simulate(*self.p)
269 self.plot_fit()
270 figure_name = os.path.splitext(self.emcee_filename)[0] + '_triangle.pdf'
271 self.likelihood.triangle_plots(output_filename=figure_name)
273 def plot_fit(self):
274 """Generic function to plot the result of the fit for 1D curves.
276 Returns
277 -------
278 fig: plt.FigureClass
279 The figure.
281 """
282 fig = plt.figure()
283 plt.errorbar(self.x, self.data, yerr=self.err, fmt='ko', label='Data')
284 if self.truth is not None:
285 x, truth, truth_err = self.simulate(*self.truth)
286 plt.plot(self.x, truth, label="Truth")
287 plt.plot(self.x, self.model, label='Best fitting model')
288 plt.xlabel('$x$')
289 plt.ylabel('$y$')
290 title = ""
291 for i, label in enumerate(self.input_labels):
292 if self.cov.size > 0:
293 err = np.sqrt(self.cov[i, i])
294 formatting_numbers(self.p[i], err, err)
295 _, par, err, _ = formatting_numbers(self.p[i], err, err, label=label)
296 title += rf"{label} = {par} $\pm$ {err}"
297 else:
298 title += f"{label} = {self.p[i]:.3g}"
299 if i < len(self.input_labels) - 1:
300 title += ", "
301 plt.title(title)
302 plt.legend()
303 plt.grid()
304 if parameters.DISPLAY: # pragma: no cover
305 plt.show()
306 if parameters.PdfPages:
307 parameters.PdfPages.savefig()
308 return fig
310 def chain2likelihood(self, pdfonly=False, walker_index=-1):
311 """Convert the chains to a psoterior probability density function via histograms.
313 Parameters
314 ----------
315 pdfonly: bool, optional
316 If True, do not compute the covariances and the 2D correlation plots (default: False).
317 walker_index: int, optional
318 The walker index to plot. If -1, all walkers are selected (default: -1).
320 Returns
321 -------
322 likelihood: np.array
323 Posterior density function.
325 """
326 if walker_index >= 0:
327 chains = self.chains[self.burnin:, walker_index, :]
328 else:
329 chains = self.flat_chains
330 rangedim = range(chains.shape[1])
331 centers = []
332 for i in rangedim:
333 centers.append(np.linspace(np.min(chains[:, i]), np.max(chains[:, i]), self.nbins - 1))
334 likelihood = Likelihood(centers, labels=self.input_labels, axis_names=self.axis_names, truth=self.truth)
335 if walker_index < 0:
336 for i in rangedim:
337 likelihood.pdfs[i].fill_histogram(chains[:, i], weights=None)
338 if not pdfonly:
339 for j in rangedim:
340 if i != j:
341 likelihood.contours[i][j].fill_histogram(chains[:, i], chains[:, j], weights=None)
342 output_file = ""
343 if self.filename != "":
344 output_file = os.path.splitext(self.filename)[0] + "_bestfit.txt"
345 likelihood.stats(output=output_file)
346 else:
347 for i in rangedim:
348 likelihood.pdfs[i].fill_histogram(chains[:, i], weights=None)
349 return likelihood
351 def compute_local_acceptance_rate(self, start_index, last_index, walker_index):
352 """Compute the local acceptance rate in a chain.
354 Parameters
355 ----------
356 start_index: int
357 Beginning index.
358 last_index: int
359 End index.
360 walker_index: int
361 Index of the walker.
363 Returns
364 -------
365 freq: float
366 The acceptance rate.
368 """
369 frequences = []
370 test = -2 * self.lnprobs[start_index, walker_index]
371 counts = 1
372 for index in range(start_index + 1, last_index):
373 chi2 = -2 * self.lnprobs[index, walker_index]
374 if np.isclose(chi2, test):
375 counts += 1
376 else:
377 frequences.append(float(counts))
378 counts = 1
379 test = chi2
380 frequences.append(counts)
381 return 1.0 / np.mean(frequences)
383 def set_chain_validity(self):
384 """Test the validity of a chain: reject chains whose chi2 is far from the mean of the others.
386 Returns
387 -------
388 valid_chains: list
389 List of boolean values, True if the chain is valid, or False if invalid.
391 """
392 nchains = [k for k in range(self.nwalkers)]
393 chisq_averages = []
394 chisq_std = []
395 for k in nchains:
396 chisqs = -2 * self.lnprobs[self.burnin:, k]
397 # if np.mean(chisqs) < 1e5:
398 chisq_averages.append(np.mean(chisqs))
399 chisq_std.append(np.std(chisqs))
400 self.global_average = np.mean(chisq_averages)
401 self.global_std = np.mean(chisq_std)
402 self.valid_chains = [False] * self.nwalkers
403 for k in nchains:
404 chisqs = -2 * self.lnprobs[self.burnin:, k]
405 chisq_average = np.mean(chisqs)
406 chisq_std = np.std(chisqs)
407 if 3 * self.global_std + self.global_average < chisq_average < 1e5:
408 self.valid_chains[k] = False
409 elif chisq_std < 0.1 * self.global_std:
410 self.valid_chains[k] = False
411 else:
412 self.valid_chains[k] = True
413 return self.valid_chains
415 def convergence_tests(self):
416 """Compute the convergence tests (Gelman-Rubin, acceptance rate).
418 """
419 chains = self.chains[self.burnin:, :, :] # .reshape((-1, self.ndim))
420 nchains = [k for k in range(self.nwalkers)]
421 fig, ax = plt.subplots(self.ndim + 1, 2, figsize=(16, 7), sharex='all')
422 fontsize = 8
423 steps = np.arange(self.burnin, self.nsteps)
424 # Chi2 vs Index
425 print("Chisq statistics:")
426 for k in nchains:
427 chisqs = -2 * self.lnprobs[self.burnin:, k]
428 text = f"\tWalker {k:d}: {float(np.mean(chisqs)):.3f} +/- {float(np.std(chisqs)):.3f}"
429 if not self.valid_chains[k]:
430 text += " -> excluded"
431 ax[self.ndim, 0].plot(steps, chisqs, c='0.5', linestyle='--')
432 else:
433 ax[self.ndim, 0].plot(steps, chisqs)
434 print(text)
435 # global_average = np.mean(-2*self.lnprobs[self.valid_chains, self.burnin:])
436 # global_std = np.std(-2*self.lnprobs[self.valid_chains, self.burnin:])
437 ax[self.ndim, 0].set_ylim(
438 [self.global_average - 5 * self.global_std, self.global_average + 5 * self.global_std])
439 # Parameter vs Index
440 print("Computing Parameter vs Index plots...")
441 for i in range(self.ndim):
442 ax[i, 0].set_ylabel(self.axis_names[i], fontsize=fontsize)
443 for k in nchains:
444 if self.valid_chains[k]:
445 ax[i, 0].plot(steps, chains[:, k, i])
446 else:
447 ax[i, 0].plot(steps, chains[:, k, i], c='0.5', linestyle='--')
448 ax[i, 0].get_yaxis().set_label_coords(-0.05, 0.5)
449 ax[self.ndim, 0].set_ylabel(r'$\chi^2$', fontsize=fontsize)
450 ax[self.ndim, 0].set_xlabel('Steps', fontsize=fontsize)
451 ax[self.ndim, 0].get_yaxis().set_label_coords(-0.05, 0.5)
452 # Acceptance rate vs Index
453 print("Computing acceptance rate...")
454 min_len = self.nsteps
455 window = 100
456 if min_len > window:
457 for k in nchains:
458 ARs = []
459 indices = []
460 for pos in range(self.burnin + window, self.nsteps, window):
461 ARs.append(self.compute_local_acceptance_rate(pos - window, pos, k))
462 indices.append(pos)
463 if self.valid_chains[k]:
464 ax[self.ndim, 1].plot(indices, ARs, label=f'Walker {k:d}')
465 else:
466 ax[self.ndim, 1].plot(indices, ARs, label=f'Walker {k:d}', c='gray', linestyle='--')
467 ax[self.ndim, 1].set_xlabel('Steps', fontsize=fontsize)
468 ax[self.ndim, 1].set_ylabel('Aceptance rate', fontsize=fontsize)
469 # ax[self.dim + 1, 2].legend(loc='upper left', ncol=2, fontsize=10)
470 # Parameter PDFs by chain
471 print("Computing chain by chain PDFs...")
472 for k in nchains:
473 likelihood = self.chain2likelihood(pdfonly=True, walker_index=k)
474 likelihood.stats(pdfonly=True, verbose=False)
475 # for i in range(self.dim):
476 # ax[i, 1].plot(likelihood.pdfs[i].axe.axis, likelihood.pdfs[i].grid, lw=var.LINEWIDTH,
477 # label=f'Walker {k:d}')
478 # ax[i, 1].set_xlabel(self.axis_names[i])
479 # ax[i, 1].set_ylabel('PDF')
480 # ax[i, 1].legend(loc='upper right', ncol=2, fontsize=10)
481 # Gelman-Rubin test.py
482 if len(nchains) > 1:
483 step = max(1, (self.nsteps - self.burnin) // 20)
484 self.gelmans = []
485 print(f'Gelman-Rubin tests (burnin={self.burnin:d}, step={step:d}, nsteps={self.nsteps:d}):')
486 for i in range(self.ndim):
487 Rs = []
488 lens = []
489 for pos in range(self.burnin + step, self.nsteps, step):
490 chain_averages = []
491 chain_variances = []
492 global_average = np.mean(self.chains[self.burnin:pos, self.valid_chains, i])
493 for k in nchains:
494 if not self.valid_chains[k]:
495 continue
496 chain_averages.append(np.mean(self.chains[self.burnin:pos, k, i]))
497 chain_variances.append(np.var(self.chains[self.burnin:pos, k, i], ddof=1))
498 W = np.mean(chain_variances)
499 B = 0
500 for n in range(len(chain_averages)):
501 B += (chain_averages[n] - global_average) ** 2
502 B *= ((pos + 1) / (len(chain_averages) - 1))
503 R = (W * pos / (pos + 1) + B / (pos + 1) * (len(chain_averages) + 1) / len(chain_averages)) / W
504 Rs.append(R - 1)
505 lens.append(pos)
506 print(f'\t{self.input_labels[i]}: R-1 = {Rs[-1]:.3f} (l = {lens[-1] - 1:d})')
507 self.gelmans.append(Rs[-1])
508 ax[i, 1].plot(lens, Rs, lw=1, label=self.axis_names[i])
509 ax[i, 1].axhline(0.03, c='k', linestyle='--')
510 ax[i, 1].set_xlabel('Walker length', fontsize=fontsize)
511 ax[i, 1].set_ylabel('$R-1$', fontsize=fontsize)
512 ax[i, 1].set_ylim(0, 0.6)
513 # ax[self.dim, 3].legend(loc='best', ncol=2, fontsize=10)
514 self.gelmans = np.array(self.gelmans)
515 fig.tight_layout()
516 plt.subplots_adjust(hspace=0)
517 if parameters.DISPLAY: # pragma: no cover
518 plt.show()
519 if parameters.PdfPages:
520 parameters.PdfPages.savefig()
521 figure_name = self.emcee_filename.replace('.h5', '_convergence.pdf')
522 print(f'Save figure: {figure_name}')
523 fig.savefig(figure_name, dpi=100)
525 def print_settings(self):
526 """Print the main settings of the FitWorkspace.
528 """
529 print('************************************')
530 print(f"Input file: {self.filename}\nWalkers: {self.nwalkers}\t Steps: {self.nsteps}")
531 print(f"Output file: {self.emcee_filename}")
532 print('************************************')
534 def save_parameters_summary(self, ipar, header=""):
535 """Save the best fitting parameter summary in a text file.
537 The file name is build from self.file_name, adding the suffix _bestfit.txt.
539 Parameters
540 ----------
541 ipar: list
542 The list of parameter indices to save.
543 header: str, optional
544 A header to add to the file (default: "").
545 """
546 output_filename = os.path.splitext(self.filename)[0] + "_bestfit.txt"
547 f = open(output_filename, 'w')
548 txt = self.filename + "\n"
549 if header != "":
550 txt += header + "\n"
551 for k, ip in enumerate(ipar):
552 txt += "%s: %s +%s -%s\n" % formatting_numbers(self.p[ip], np.sqrt(self.cov[k, k]),
553 np.sqrt(self.cov[k, k]),
554 label=self.input_labels[ip])
555 for row in self.cov:
556 txt += np.array_str(row, max_line_width=20 * self.cov.shape[0]) + '\n'
557 self.my_logger.info(f"\n\tSave best fit parameters in {output_filename}.")
558 f.write(txt)
559 f.close()
561 def plot_correlation_matrix(self, ipar=None):
562 """Compute and plot a correlation matrix.
564 Save the plot if parameters.SAVE is True. The output file name is build from self.file_name,
565 adding the suffix _correlation.pdf.
567 Parameters
568 ----------
569 ipar: list, optional
570 The list of parameter indices to include in the matrix.
572 Examples
573 --------
574 >>> w = FitWorkspace()
575 >>> w.axis_names = ["x", "y", "z"]
576 >>> w.cov = np.array([[1,-0.5,0],[-0.5,1,-1],[0,-1,1]])
577 >>> w.plot_correlation_matrix()
578 """
579 if ipar is None:
580 ipar = np.arange(self.cov.shape[0]).astype(int)
581 fig = plt.figure()
582 self.rho = compute_correlation_matrix(self.cov)
583 plot_correlation_matrix_simple(plt.gca(), self.rho, axis_names=[self.axis_names[i] for i in ipar])
584 if parameters.SAVE and self.filename != "": # pragma: no cover
585 figname = os.path.splitext(self.filename)[0] + "_correlation.pdf"
586 self.my_logger.info(f"Save figure {figname}.")
587 fig.savefig(figname, dpi=100, bbox_inches='tight')
588 if parameters.PdfPages:
589 parameters.PdfPages.savefig() # args from the above here MFL
590 if parameters.DISPLAY: # pragma: no cover
591 if self.live_fit:
592 plt.draw()
593 plt.pause(1e-8)
594 else:
595 plt.show()
597 def weighted_residuals(self, p): # pragma: nocover
598 """Compute the weighted residuals array for a set of model parameters p.
600 Parameters
601 ----------
602 p: array_like
603 The array of model parameters.
605 Returns
606 -------
607 residuals: np.array
608 The array of weighted residuals.
610 """
611 x, model, model_err = self.simulate(*p)
612 if self.data_cov is None:
613 if len(self.outliers) > 0:
614 model_err = model_err.flatten()
615 err = self.err.flatten()
616 res = (model.flatten() - self.data.flatten()) / np.sqrt(model_err * model_err + err * err)
617 else:
618 res = ((model - self.data) / np.sqrt(model_err * model_err + self.err * self.err)).flatten()
619 else:
620 if self.data_cov.ndim > 2:
621 K = self.data_cov.shape[0]
622 if np.any(model_err > 0):
623 cov = [self.data_cov[k] + np.diag(model_err[k] ** 2) for k in range(K)]
624 L = [np.linalg.inv(np.linalg.cholesky(cov[k])) for k in range(K)]
625 else:
626 L = [np.linalg.cholesky(self.W[k]) for k in range(K)]
627 res = [L[k] @ (model[k] - self.data[k]) for k in range(K)]
628 res = np.concatenate(res).ravel()
629 else:
630 if np.any(model_err > 0):
631 cov = self.data_cov + np.diag(model_err * model_err)
632 L = np.linalg.inv(np.linalg.cholesky(cov))
633 else:
634 if self.W.ndim == 1 and self.W.dtype != np.object:
635 L = np.sqrt(self.W)
636 elif self.W.ndim == 2 and self.W.dtype != np.object:
637 L = np.linalg.cholesky(self.W)
638 else:
639 raise ValueError(f"Case not implemented with self.W.ndim={self.W.ndim} "
640 f"and self.W.dtype={self.W.dtype}")
641 res = L @ (model - self.data)
642 return res
644 def chisq(self, p, model_output=False):
645 """Compute the chi square for a set of model parameters p.
647 Four cases are implemented: diagonal W, 2D W, array of diagonal Ws, array of 2D Ws. The two latter cases
648 are for multiple independent data vectors with W being block diagonal.
650 Parameters
651 ----------
652 p: array_like
653 The array of model parameters.
654 model_output: bool, optional
655 If true, the simulated model is output.
657 Returns
658 -------
659 chisq: float
660 The chi square value.
662 """
663 # check data format
664 if (self.data.dtype != np.object and self.data.ndim > 1) or (self.err.dtype != np.object and self.err.ndim > 1):
665 raise ValueError("Fitworkspace.data and Fitworkspace.err must be a flat 1D array,"
666 " or an array of flat arrays of unequal lengths.")
667 # prepare weight matrices in case they have not been built before
668 self.prepare_weight_matrices()
669 x, model, model_err = self.simulate(*p)
670 if self.W.ndim == 1 and self.W.dtype != np.object:
671 if np.any(model_err > 0):
672 W = 1 / (self.data_cov + model_err * model_err)
673 else:
674 W = self.W
675 res = (model - self.data)
676 chisq = res @ (W * res)
677 # fit_workspace.my_logger.warning(f"ll {tmp_params}")
678 # fit_workspace.my_logger.warning(f"yyyy {np.sum(residuals)} {np.sum(W)} {np.sum(W*residuals)}")
679 # fit_workspace.my_logger.warning(f"yoooo {np.sum(residuals)} {np.sum(W*residuals)} ")
680 # fit_workspace.my_logger.warning(f"yiiii {np.sum(tmp_model.flatten()[fit_workspace.not_outliers])} {np.sum(fit_workspace.data.flatten()[fit_workspace.not_outliers])} ")
681 # self.my_logger.warning(f"ll {p}")
682 # self.my_logger.warning(f"yyyy {np.sum(res)} {np.sum(W)} {np.sum(W*res)}")
683 # self.my_logger.warning(f"yoooo {np.sum(res[self.not_outliers])} {np.sum(W[self.not_outliers]*res[self.not_outliers])} ")
684 # self.my_logger.warning(f"yiiii {np.sum(model[self.not_outliers])} {np.sum(self.data[self.not_outliers])} ")
685 elif self.W.dtype == np.object:
686 K = len(self.W)
687 if self.W[0].ndim == 1:
688 if np.any(model_err > 0):
689 W = [1 / (self.data_cov[k] + model_err * model_err) for k in range(K)]
690 else:
691 W = self.W
692 res = [model[k] - self.data[k] for k in range(K)]
693 chisq = np.sum([res[k] @ (W[k] * res[k]) for k in range(K)])
694 elif self.W[0].ndim == 2:
695 K = len(self.W)
696 if np.any(model_err > 0):
697 cov = [self.data_cov[k] + np.diag(model_err[k] ** 2) for k in range(K)]
698 L = [np.linalg.inv(np.linalg.cholesky(cov[k])) for k in range(K)]
699 W = [L[k].T @ L[k] for k in range(K)]
700 else:
701 W = self.W
702 res = [model[k] - self.data[k] for k in range(K)]
703 chisq = np.sum([res[k] @ W[k] @ res[k] for k in range(K)])
704 else:
705 raise ValueError(f"First element of fitworkspace.W has no ndim attribute or has a dimension above 2. "
706 f"I get W[0]={self.W[0]}")
707 elif self.W.ndim == 2 and self.W.dtype != np.object:
708 if np.any(model_err > 0):
709 cov = self.data_cov + np.diag(model_err * model_err)
710 L = np.linalg.inv(np.linalg.cholesky(cov))
711 W = L.T @ L
712 else:
713 W = self.W
714 res = (model - self.data)
715 chisq = res @ W @ res
716 else:
717 raise ValueError(
718 f"Data inverse covariance matrix must be a np.ndarray of dimension 1 or 2,"
719 f"either made of 1D or 2D arrays of equal lengths or not for block diagonal matrices."
720 f"\nHere W type is {type(self.W)}, shape is {self.W.shape} and W is {self.W}.")
721 if model_output:
722 return chisq, x, model, model_err
723 else:
724 return chisq
726 def prepare_weight_matrices(self):
727 # Prepare covariance matrix for data
728 if self.data_cov is None:
729 self.data_cov = np.asarray(self.err.flatten() ** 2)
730 # Prepare inverse covariance matrix for data
731 if self.W is None:
732 if self.data_cov.ndim == 1 and self.data_cov.dtype != np.object:
733 self.W = 1 / self.data_cov
734 elif self.data_cov.ndim == 2 and self.data_cov.dtype != np.object:
735 L = np.linalg.inv(np.linalg.cholesky(self.data_cov))
736 self.W = L.T @ L
737 elif self.data_cov.dtype is np.object:
738 if self.data_cov[0].ndim == 1:
739 self.W = np.array([1 / self.data_cov[k] for k in range(self.data_cov.shape[0])])
740 else:
741 self.W = []
742 for k in range(len(self.data_cov)):
743 L = np.linalg.inv(np.linalg.cholesky(self.data_cov[k]))
744 self.W[k] = L.T @ L
745 self.W = np.asarray(self.W)
746 if len(self.outliers) > 0:
747 bad_indices = self.get_bad_indices()
748 if self.W.ndim == 1 and self.W.dtype != np.object:
749 self.W[bad_indices] = 0
750 elif self.W.ndim == 2 and self.W.dtype != np.object:
751 self.W[:, bad_indices] = 0
752 self.W[bad_indices, :] = 0
753 elif self.W.dtype == np.object:
754 if self.data_cov[0].ndim == 1:
755 for k in range(len(self.W)):
756 self.W[k][bad_indices[k]] = 0
757 else:
758 for k in range(len(self.W)):
759 self.W[k][:, bad_indices[k]] = 0
760 self.W[k][bad_indices[k], :] = 0
761 else:
762 raise ValueError(
763 f"Data inverse covariance matrix must be a np.ndarray of dimension 1 or 2,"
764 f"either made of 1D or 2D arrays of equal lengths or not for block diagonal matrices."
765 f"\nHere W type is {type(self.W)}, shape is {self.W.shape} and W is {self.W}.")
767 def lnlike(self, p):
768 """Compute the logarithmic likelihood for a set of model parameters p as -0.5*chisq.
770 Parameters
771 ----------
772 p: array_like
773 The array of model parameters.
775 Returns
776 -------
777 lnlike: float
778 The logarithmic likelihood value.
780 """
781 return -0.5 * self.chisq(p)
783 def lnprior(self, p):
784 """Compute the logarithmic prior for a set of model parameters p.
786 The function returns 0 for good parameters, and -np.inf for parameters out of their boundaries.
788 Parameters
789 ----------
790 p: array_like
791 The array of model parameters.
793 Returns
794 -------
795 lnprior: float
796 The logarithmic value fo the prior.
798 """
799 in_bounds = True
800 for npar, par in enumerate(p):
801 if par < self.bounds[npar][0] or par > self.bounds[npar][1]:
802 in_bounds = False
803 break
804 if in_bounds:
805 return 0.0
806 else:
807 return -np.inf
809 def jacobian(self, params, epsilon, fixed_params=None, model_input=None):
810 """Generic function to compute the Jacobian matrix of a model, with numerical derivatives.
812 Parameters
813 ----------
814 params: array_like
815 The array of model parameters.
816 epsilon: array_like
817 The array of small steps to compute the partial derivatives of the model.
818 fixed_params: array_like
819 List of boolean values. If True, the parameter is considered fixed and no derivative are computed.
820 model_input: array_like, optional
821 A model input as a list with (x, model, model_err) to avoid an additional call to simulate().
823 Returns
824 -------
825 J: np.array
826 The Jacobian matrix.
828 """
829 if model_input:
830 x, model, model_err = model_input
831 else:
832 x, model, model_err = self.simulate(*params)
833 if self.W.dtype == np.object and self.W[0].ndim == 2:
834 J = [[] for _ in range(params.size)]
835 else:
836 model = model.flatten()
837 J = np.zeros((params.size, model.size))
838 for ip, p in enumerate(params):
839 if fixed_params[ip]:
840 continue
841 tmp_p = np.copy(params)
842 if tmp_p[ip] + epsilon[ip] < self.bounds[ip][0] or tmp_p[ip] + epsilon[ip] > self.bounds[ip][1]:
843 epsilon[ip] = - epsilon[ip]
844 tmp_p[ip] += epsilon[ip]
845 tmp_x, tmp_model, tmp_model_err = self.simulate(*tmp_p)
846 if self.W.dtype == np.object and self.W[0].ndim == 2:
847 for k in range(model.shape[0]):
848 J[ip].append((tmp_model[k] - model[k]) / epsilon[ip])
849 else:
850 J[ip] = (tmp_model.flatten() - model) / epsilon[ip]
851 return np.asarray(J)
853 def hessian(self, params, epsilon, fixed_params=None): # pragma: nocover
854 """Experimental function to compute the hessian of a model.
856 Parameters
857 ----------
858 params: array_like
859 The array of model parameters.
860 epsilon: array_like
861 The array of small steps to compute the partial derivatives of the model.
862 fixed_params: array_like
863 List of boolean values. If True, the parameter is considered fixed and no derivative are computed.
865 Returns
866 -------
868 """
869 x, model, model_err = self.simulate(*params)
870 model = model.flatten()
871 J = self.jacobian(params, epsilon, fixed_params=fixed_params)
872 H = np.zeros((params.size, params.size, model.size))
873 tmp_p = np.copy(params)
874 for ip, p1 in enumerate(params):
875 print(ip, p1, params[ip], tmp_p[ip], self.bounds[ip], epsilon[ip], tmp_p[ip] + epsilon[ip])
876 if fixed_params[ip]:
877 continue
878 if tmp_p[ip] + epsilon[ip] < self.bounds[ip][0] or tmp_p[ip] + epsilon[ip] > self.bounds[ip][1]:
879 epsilon[ip] = - epsilon[ip]
880 tmp_p[ip] += epsilon[ip]
881 print(tmp_p)
882 # tmp_x, tmp_model, tmp_model_err = self.simulate(*tmp_p)
883 # J[ip] = (tmp_model.flatten() - model) / epsilon[ip]
884 tmp_J = self.jacobian(tmp_p, epsilon, fixed_params=fixed_params)
885 for ip, p1 in enumerate(params):
886 if fixed_params[ip]:
887 continue
888 for jp, p2 in enumerate(params):
889 if fixed_params[jp]:
890 continue
891 x, modelplus, model_err = self.simulate(params + epsilon)
892 x, modelmoins, model_err = self.simulate(params - epsilon)
893 model = model.flatten()
895 print("hh", ip, jp, tmp_J[ip], J[jp], tmp_p[ip], params, (tmp_J[ip] - J[jp]) / epsilon)
896 print((modelplus + modelmoins - 2 * model) / (np.asarray(epsilon) ** 2))
897 H[ip, jp] = (tmp_J[ip] - J[jp]) / epsilon
898 H[ip, jp] = (modelplus + modelmoins - 2 * model) / (np.asarray(epsilon) ** 2)
899 return H
902def lnprob(p): # pragma: no cover
903 global fit_workspace
904 lp = fit_workspace.lnprior(p)
905 if not np.isfinite(lp):
906 return -1e20
907 return lp + fit_workspace.lnlike(p)
910def gradient_descent(fit_workspace, params, epsilon, niter=10, fixed_params=None, xtol=1e-3, ftol=1e-3,
911 with_line_search=True):
912 """
914 Four cases are implemented: diagonal W, 2D W, array of diagonal Ws, array of 2D Ws. The two latter cases
915 are for multiple independent data vectors with W being block diagonal.
917 Parameters
918 ----------
919 fit_workspace: FitWorkspace
920 params
921 epsilon
922 niter
923 fixed_params
924 xtol
925 ftol
926 with_line_search
928 Returns
929 -------
931 """
932 my_logger = set_logger(__name__)
933 tmp_params = np.copy(params)
934 fit_workspace.prepare_weight_matrices()
935 W = fit_workspace.W
936 ipar = np.arange(params.size)
937 if fixed_params is not None:
938 ipar = np.array(np.where(np.array(fixed_params).astype(int) == 0)[0])
939 costs = []
940 params_table = []
941 inv_JT_W_J = np.zeros((len(ipar), len(ipar)))
942 for i in range(niter):
943 start = time.time()
944 cost, tmp_lambdas, tmp_model, tmp_model_err = fit_workspace.chisq(tmp_params, model_output=True)
945 if isinstance(fit_workspace.W, np.ndarray) and fit_workspace.W.dtype != np.object:
946 residuals = (tmp_model - fit_workspace.data).flatten()
947 elif isinstance(fit_workspace.W, np.ndarray) and fit_workspace.W.dtype == np.object:
948 residuals = [(tmp_model[k] - fit_workspace.data[k]) for k in range(len(fit_workspace.W))]
949 else:
950 raise TypeError(f"Type of fit_workspace.W is {type(fit_workspace.W)}. It must be a np.ndarray.")
951 # Jacobian
952 J = fit_workspace.jacobian(tmp_params, epsilon, fixed_params=fixed_params,
953 model_input=[tmp_lambdas, tmp_model, tmp_model_err])
954 # remove parameters with unexpected null Jacobian vectors
955 for ip in range(J.shape[0]):
956 if ip not in ipar:
957 continue
958 if np.all(np.array(J[ip]).flatten() == np.zeros(np.array(J[ip]).size)):
959 ipar = np.delete(ipar, list(ipar).index(ip))
960 fixed_params[ip] = True
961 # tmp_params[ip] = 0
962 my_logger.warning(
963 f"\n\tStep {i}: {fit_workspace.input_labels[ip]} has a null Jacobian; parameter is fixed "
964 f"at its last known current value ({tmp_params[ip]}).")
965 # remove fixed parameters
966 J = J[ipar].T
967 # algebra
968 if fit_workspace.W.ndim == 1 and fit_workspace.W.dtype != np.object:
969 JT_W = J.T * W
970 JT_W_J = JT_W @ J
971 elif fit_workspace.W.ndim == 2 and fit_workspace.W.dtype != np.object:
972 JT_W = J.T @ W
973 JT_W_J = JT_W @ J
974 else:
975 if fit_workspace.W[0].ndim == 1:
976 JT_W = J.T * np.concatenate(W).ravel()
977 JT_W_J = JT_W @ J
978 else:
979 # warning ! here the data arrays indexed by k can have different lengths because outliers
980 # because W inverse covariance is block diagonal and blocks can have different sizes
981 # the philosophy is to temporarily flatten the data arrays
982 JT_W = [np.concatenate([J[ip][k].T @ W[k]
983 for k in range(fit_workspace.W.shape[0])]).ravel()
984 for ip in range(len(J))]
985 JT_W_J = np.array([[JT_W[ip2] @ np.concatenate(J[ip1][:]).ravel() for ip1 in range(len(J))]
986 for ip2 in range(len(J))])
987 try:
988 L = np.linalg.inv(np.linalg.cholesky(JT_W_J)) # cholesky is too sensible to the numerical precision
989 inv_JT_W_J = L.T @ L
990 except np.linalg.LinAlgError:
991 inv_JT_W_J = np.linalg.inv(JT_W_J)
992 if fit_workspace.W.dtype != np.object:
993 JT_W_R0 = JT_W @ residuals
994 else:
995 JT_W_R0 = JT_W @ np.concatenate(residuals).ravel()
996 dparams = - inv_JT_W_J @ JT_W_R0
998 if with_line_search:
999 def line_search(alpha):
1000 tmp_params_2 = np.copy(tmp_params)
1001 tmp_params_2[ipar] = tmp_params[ipar] + alpha * dparams
1002 for ipp, pp in enumerate(tmp_params_2):
1003 if pp < fit_workspace.bounds[ipp][0]:
1004 tmp_params_2[ipp] = fit_workspace.bounds[ipp][0]
1005 if pp > fit_workspace.bounds[ipp][1]:
1006 tmp_params_2[ipp] = fit_workspace.bounds[ipp][1]
1007 return fit_workspace.chisq(tmp_params_2)
1009 # tol parameter acts on alpha (not func)
1010 alpha_min, fval, iter, funcalls = optimize.brent(line_search, full_output=True, tol=5e-1, brack=(0, 1))
1011 else:
1012 alpha_min = 1
1013 fval = np.copy(cost)
1014 funcalls = 0
1015 iter = 0
1017 tmp_params[ipar] += alpha_min * dparams
1018 # check bounds
1019 for ip, p in enumerate(tmp_params):
1020 if p < fit_workspace.bounds[ip][0]:
1021 tmp_params[ip] = fit_workspace.bounds[ip][0]
1022 if p > fit_workspace.bounds[ip][1]:
1023 tmp_params[ip] = fit_workspace.bounds[ip][1]
1025 # prepare outputs
1026 costs.append(fval)
1027 params_table.append(np.copy(tmp_params))
1028 fit_workspace.p = tmp_params
1029 if fit_workspace.verbose:
1030 my_logger.info(f"\n\tIteration={i}: initial cost={cost:.5g} initial chisq_red={cost / tmp_model.size:.5g}"
1031 f"\n\t\t Line search: alpha_min={alpha_min:.3g} iter={iter} funcalls={funcalls}"
1032 f"\n\tParameter shifts: {alpha_min * dparams}"
1033 f"\n\tNew parameters: {tmp_params[ipar]}"
1034 f"\n\tFinal cost={fval:.5g} final chisq_red={fval / tmp_model.size:.5g} "
1035 f"computed in {time.time() - start:.2f}s")
1036 if fit_workspace.live_fit: # pragma: no cover
1037 fit_workspace.simulate(*tmp_params)
1038 fit_workspace.plot_fit()
1039 fit_workspace.cov = inv_JT_W_J
1040 # fit_workspace.plot_correlation_matrix(ipar)
1041 if len(ipar) == 0:
1042 my_logger.warning(f"\n\tGradient descent terminated in {i} iterations because all parameters "
1043 f"have null Jacobian.")
1044 break
1045 if fit_workspace.verbose or parameters.DEBUG:
1046 if np.sum(np.abs(alpha_min * dparams)) / np.sum(np.abs(tmp_params[ipar])) < xtol:
1047 my_logger.info(f"\n\tGradient descent terminated in {i} iterations because the sum of parameter shift "
1048 f"relative to the sum of the parameters is below xtol={xtol}.")
1049 break
1050 if len(costs) > 1 and np.abs(costs[-2] - fval) / np.max([np.abs(fval), np.abs(costs[-2])]) < ftol:
1051 my_logger.info(f"\n\tGradient descent terminated in {i} iterations because the "
1052 f"relative change of cost is below ftol={ftol}.")
1053 break
1054 plt.close()
1055 return tmp_params, inv_JT_W_J, np.array(costs), np.array(params_table)
1058def simple_newton_minimisation(fit_workspace, params, epsilon, niter=10, fixed_params=None,
1059 xtol=1e-3, ftol=1e-3): # pragma: no cover
1060 """Experimental function to minimize a function.
1062 Parameters
1063 ----------
1064 fit_workspace: FitWorkspace
1065 params
1066 epsilon
1067 niter
1068 fixed_params
1069 xtol
1070 ftol
1072 Returns
1073 -------
1075 """
1076 my_logger = set_logger(__name__)
1077 tmp_params = np.copy(params)
1078 ipar = np.arange(params.size)
1079 if fixed_params is not None:
1080 ipar = np.array(np.where(np.array(fixed_params).astype(int) == 0)[0])
1081 funcs = []
1082 params_table = []
1083 inv_H = np.zeros((len(ipar), len(ipar)))
1084 for i in range(niter):
1085 start = time.time()
1086 tmp_lambdas, tmp_model, tmp_model_err = fit_workspace.simulate(*tmp_params)
1087 # if fit_workspace.live_fit:
1088 # fit_workspace.plot_fit()
1089 J = fit_workspace.jacobian(tmp_params, epsilon, fixed_params=fixed_params)
1090 # remove parameters with unexpected null Jacobian vectors
1091 for ip in range(J.shape[0]):
1092 if ip not in ipar:
1093 continue
1094 if np.all(J[ip] == np.zeros(J.shape[1])):
1095 ipar = np.delete(ipar, list(ipar).index(ip))
1096 # tmp_params[ip] = 0
1097 my_logger.warning(
1098 f"\n\tStep {i}: {fit_workspace.input_labels[ip]} has a null Jacobian; parameter is fixed "
1099 f"at its last known current value ({tmp_params[ip]}).")
1100 # remove fixed parameters
1101 J = J[ipar].T
1102 # hessian
1103 H = fit_workspace.hessian(tmp_params, epsilon, fixed_params=fixed_params)
1104 try:
1105 L = np.linalg.inv(np.linalg.cholesky(H)) # cholesky is too sensible to the numerical precision
1106 inv_H = L.T @ L
1107 except np.linalg.LinAlgError:
1108 inv_H = np.linalg.inv(H)
1109 dparams = - inv_H[:, :, 0] @ J[:, 0]
1110 print("dparams", dparams, inv_H, J, H)
1111 tmp_params[ipar] += dparams
1113 # check bounds
1114 print("tmp_params", tmp_params, dparams, inv_H, J)
1115 for ip, p in enumerate(tmp_params):
1116 if p < fit_workspace.bounds[ip][0]:
1117 tmp_params[ip] = fit_workspace.bounds[ip][0]
1118 if p > fit_workspace.bounds[ip][1]:
1119 tmp_params[ip] = fit_workspace.bounds[ip][1]
1121 tmp_lambdas, new_model, tmp_model_err = fit_workspace.simulate(*tmp_params)
1122 new_func = new_model[0]
1123 funcs.append(new_func)
1125 r = np.log10(fit_workspace.regs)
1126 js = [fit_workspace.jacobian(np.asarray([rr]), epsilon, fixed_params=fixed_params)[0] for rr in np.array(r)]
1127 plt.plot(r, js, label="J")
1128 plt.grid()
1129 plt.legend()
1130 plt.show()
1132 if parameters.DISPLAY:
1133 fig = plt.figure()
1134 plt.plot(r, js, label="prior")
1135 mod = tmp_model + J[0] * (r - (tmp_params - dparams)[0])
1136 plt.plot(r, mod)
1137 plt.axvline(tmp_params)
1138 plt.axhline(tmp_model)
1139 plt.grid()
1140 plt.legend()
1141 plt.draw()
1142 plt.pause(1e-8)
1143 plt.close(fig)
1145 # prepare outputs
1146 params_table.append(np.copy(tmp_params))
1147 if fit_workspace.verbose:
1148 my_logger.info(f"\n\tIteration={i}: initial func={tmp_model[0]:.5g}"
1149 f"\n\tParameter shifts: {dparams}"
1150 f"\n\tNew parameters: {tmp_params[ipar]}"
1151 f"\n\tFinal func={new_func:.5g}"
1152 f" computed in {time.time() - start:.2f}s")
1153 if fit_workspace.live_fit:
1154 fit_workspace.simulate(*tmp_params)
1155 fit_workspace.plot_fit()
1156 fit_workspace.cov = inv_H[:, :, 0]
1157 print("shape", fit_workspace.cov.shape)
1158 # fit_workspace.plot_correlation_matrix(ipar)
1159 if len(ipar) == 0:
1160 my_logger.warning(f"\n\tGradient descent terminated in {i} iterations because all parameters "
1161 f"have null Jacobian.")
1162 break
1163 if fit_workspace.verbose or parameters.DEBUG:
1164 if np.sum(np.abs(dparams)) / np.sum(np.abs(tmp_params[ipar])) < xtol:
1165 my_logger.info(f"\n\tGradient descent terminated in {i} iterations because the sum of parameter shift "
1166 f"relative to the sum of the parameters is below xtol={xtol}.")
1167 break
1168 if len(funcs) > 1 and np.abs(funcs[-2] - new_func) / np.max([np.abs(new_func), np.abs(funcs[-2])]) < ftol:
1169 my_logger.info(f"\n\tGradient descent terminated in {i} iterations because the "
1170 f"relative change of cost is below ftol={ftol}.")
1171 break
1172 plt.close()
1173 return tmp_params, inv_H[:, :, 0], np.array(funcs), np.array(params_table)
1176def print_parameter_summary(params, cov, labels):
1177 """Print the best fitting parameters on screen.
1179 Parameters
1180 ----------
1181 params: array_like
1182 The best fitting parameter values.
1183 cov: array_like
1184 The associated covariance matrix.
1185 labels: array_like
1186 The list of associated parameter labels.
1187 """
1188 my_logger = set_logger(__name__)
1189 txt = ""
1190 for ip in np.arange(0, cov.shape[0]).astype(int):
1191 txt += "%s: %s +%s -%s\n\t" % formatting_numbers(params[ip], np.sqrt(cov[ip, ip]), np.sqrt(cov[ip, ip]),
1192 label=labels[ip])
1193 my_logger.info(f"\n\t{txt}")
1196def plot_gradient_descent(fit_workspace, costs, params_table):
1197 fig, ax = plt.subplots(2, 1, figsize=(10, 6), sharex="all")
1198 iterations = np.arange(params_table.shape[0])
1199 ax[0].plot(iterations, costs, lw=2)
1200 for ip in range(params_table.shape[1]):
1201 ax[1].plot(iterations, params_table[:, ip], label=f"{fit_workspace.axis_names[ip]}")
1202 ax[1].set_yscale("symlog")
1203 ax[1].legend(ncol=6, loc=9)
1204 ax[1].grid()
1205 ax[0].set_yscale("log")
1206 ax[0].set_ylabel(r"$\chi^2$")
1207 ax[1].set_ylabel("Parameters")
1208 ax[0].grid()
1209 ax[1].set_xlabel("Iterations")
1210 ax[0].xaxis.set_major_locator(MaxNLocator(integer=True))
1211 fig.tight_layout()
1212 plt.subplots_adjust(wspace=0, hspace=0)
1213 if parameters.SAVE and fit_workspace.filename != "": # pragma: no cover
1214 figname = os.path.splitext(fit_workspace.filename)[0] + "_fitting.pdf"
1215 fit_workspace.my_logger.info(f"\n\tSave figure {figname}.")
1216 fig.savefig(figname, dpi=100, bbox_inches='tight')
1217 if parameters.DISPLAY: # pragma: no cover
1218 plt.show()
1219 if parameters.PdfPages: # args from the above? MFL
1220 parameters.PdfPages.savefig()
1222 fit_workspace.simulate(*fit_workspace.p)
1223 fit_workspace.live_fit = False
1224 fit_workspace.plot_fit()
1227def save_gradient_descent(fit_workspace, costs, params_table):
1228 iterations = np.arange(params_table.shape[0]).astype(int)
1229 t = np.zeros((params_table.shape[1] + 2, params_table.shape[0]))
1230 t[0] = iterations
1231 t[1] = costs
1232 t[2:] = params_table.T
1233 h = 'iter,costs,' + ','.join(fit_workspace.input_labels)
1234 output_filename = os.path.splitext(fit_workspace.filename)[0] + "_fitting.txt"
1235 np.savetxt(output_filename, t.T, header=h, delimiter=",")
1236 fit_workspace.my_logger.info(f"\n\tSave gradient descent log {output_filename}.")
1239def run_gradient_descent(fit_workspace, guess, epsilon, params_table, costs, fix, xtol, ftol, niter, verbose=False,
1240 with_line_search=True):
1241 fit_workspace.p, fit_workspace.cov, tmp_costs, tmp_params_table = gradient_descent(fit_workspace, guess,
1242 epsilon, niter=niter,
1243 fixed_params=fix,
1244 xtol=xtol, ftol=ftol,
1245 with_line_search=with_line_search)
1246 params_table = np.concatenate([params_table, tmp_params_table])
1247 costs = np.concatenate([costs, tmp_costs])
1248 ipar = np.array(np.where(np.array(fix).astype(int) == 0)[0])
1249 if verbose or fit_workspace.verbose:
1250 print_parameter_summary(fit_workspace.p[ipar], fit_workspace.cov,
1251 [fit_workspace.input_labels[ip] for ip in ipar])
1252 if parameters.DEBUG and (verbose or fit_workspace.verbose):
1253 # plot_psf_poly_params(fit_workspace.p[fit_workspace.psf_params_start_index:])
1254 # fit_workspace.plot_fit()
1255 plot_gradient_descent(fit_workspace, costs, params_table)
1256 if len(ipar) > 1:
1257 fit_workspace.plot_correlation_matrix(ipar=ipar)
1258 return params_table, costs
1261def run_simple_newton_minimisation(fit_workspace, guess, epsilon, fix=None, xtol=1e-8, ftol=1e-8,
1262 niter=50, verbose=False): # pragma: no cover
1263 if fix is None:
1264 fix = [False] * guess.size
1265 fit_workspace.p, fit_workspace.cov, funcs, params_table = simple_newton_minimisation(fit_workspace, guess,
1266 epsilon, niter=niter,
1267 fixed_params=fix,
1268 xtol=xtol, ftol=ftol)
1269 ipar = np.array(np.where(np.array(fix).astype(int) == 0)[0])
1270 if verbose or fit_workspace.verbose:
1271 print_parameter_summary(fit_workspace.p[ipar], fit_workspace.cov,
1272 [fit_workspace.input_labels[ip] for ip in ipar])
1273 if parameters.DEBUG and (verbose or fit_workspace.verbose):
1274 # plot_psf_poly_params(fit_workspace.p[fit_workspace.psf_params_start_index:])
1275 # fit_workspace.plot_fit()
1276 plot_gradient_descent(fit_workspace, funcs, params_table)
1277 if len(ipar) > 1:
1278 fit_workspace.plot_correlation_matrix(ipar=ipar)
1279 return params_table, funcs
1282def run_minimisation(fit_workspace, method="newton", epsilon=None, fix=None, xtol=1e-4, ftol=1e-4, niter=50,
1283 verbose=False, with_line_search=True, minimizer_method="L-BFGS-B"):
1284 my_logger = set_logger(__name__)
1286 bounds = fit_workspace.bounds
1288 nll = lambda params: -fit_workspace.lnlike(params)
1290 guess = fit_workspace.p.astype('float64')
1291 if verbose:
1292 my_logger.debug(f"\n\tStart guess: {guess}")
1294 if method == "minimize":
1295 start = time.time()
1296 result = optimize.minimize(nll, fit_workspace.p, method=minimizer_method,
1297 options={'ftol': ftol, 'gtol': 1e-20,
1298 'maxiter': 100000, 'maxls': 50, 'maxcor': 30},
1299 bounds=bounds)
1300 fit_workspace.p = result['x']
1301 if verbose:
1302 my_logger.debug(f"\n\t{result}")
1303 my_logger.debug(f"\n\tMinimize: total computation time: {time.time() - start}s")
1304 fit_workspace.plot_fit()
1305 elif method == 'basinhopping':
1306 start = time.time()
1307 minimizer_kwargs = dict(method=minimizer_method, bounds=bounds)
1308 result = optimize.basinhopping(nll, guess, minimizer_kwargs=minimizer_kwargs)
1309 fit_workspace.p = result['x']
1310 if verbose:
1311 my_logger.debug(f"\n\t{result}")
1312 my_logger.debug(f"\n\tBasin-hopping: total computation time: {time.time() - start}s")
1313 fit_workspace.plot_fit()
1314 elif method == "least_squares": # pragma: no cover
1315 fit_workspace.my_logger.warning("least_squares might not work, use with caution... "
1316 "or repair carefully the function weighted_residuals()")
1317 start = time.time()
1318 x_scale = np.abs(guess)
1319 x_scale[x_scale == 0] = 0.1
1320 p = optimize.least_squares(fit_workspace.weighted_residuals, guess, verbose=2, ftol=1e-6, x_scale=x_scale,
1321 diff_step=0.001, bounds=bounds.T)
1322 fit_workspace.p = p.x # m.np_values()
1323 if verbose:
1324 my_logger.debug(f"\n\t{p}")
1325 my_logger.debug(f"\n\tLeast_squares: total computation time: {time.time() - start}s")
1326 fit_workspace.plot_fit()
1327 elif method == "minuit":
1328 start = time.time()
1329 # fit_workspace.simulation.fix_psf_cube = False
1330 error = 0.1 * np.abs(guess) * np.ones_like(guess)
1331 error[2:5] = 0.3 * np.abs(guess[2:5]) * np.ones_like(guess[2:5])
1332 z = np.where(np.isclose(error, 0.0, 1e-6))
1333 error[z] = 1.
1334 if fix is None:
1335 fix = [False] * guess.size
1336 # noinspection PyArgumentList
1337 # m = Minuit(fcn=nll, values=guess, error=error, errordef=1, fix=fix, print_level=verbose, limit=bounds)
1338 m = Minuit(nll, np.copy(guess))
1339 m.errors = error
1340 m.errordef = 1
1341 m.fixed = fix
1342 m.print_level = verbose
1343 m.limits = bounds
1344 m.tol = 10
1345 m.migrad()
1346 fit_workspace.p = np.array(m.values[:])
1347 if verbose:
1348 my_logger.debug(f"\n\t{m}")
1349 my_logger.debug(f"\n\tMinuit: total computation time: {time.time() - start}s")
1350 fit_workspace.plot_fit()
1351 elif method == "newton":
1352 if fit_workspace.costs.size == 0:
1353 costs = np.array([fit_workspace.chisq(guess)])
1354 params_table = np.array([guess])
1355 else:
1356 costs = np.concatenate([fit_workspace.costs, np.array([fit_workspace.chisq(guess)])])
1357 params_table = np.concatenate([fit_workspace.params_table, np.array([guess])])
1358 if epsilon is None:
1359 epsilon = 1e-4 * guess
1360 epsilon[epsilon == 0] = 1e-4
1361 if fix is None:
1362 fix = [False] * guess.size
1364 start = time.time()
1365 params_table, costs = run_gradient_descent(fit_workspace, guess, epsilon, params_table, costs,
1366 fix=fix, xtol=xtol, ftol=ftol, niter=niter, verbose=verbose,
1367 with_line_search=with_line_search)
1368 fit_workspace.costs = costs
1369 fit_workspace.params_table = params_table
1370 if verbose:
1371 my_logger.debug(f"\n\tNewton: total computation time: {time.time() - start}s")
1372 if fit_workspace.filename != "":
1373 ipar = np.array(np.where(np.array(fit_workspace.fixed).astype(int) == 0)[0])
1374 fit_workspace.save_parameters_summary(ipar)
1375 save_gradient_descent(fit_workspace, costs, params_table)
1378def run_minimisation_sigma_clipping(fit_workspace, method="newton", epsilon=None, fix=None, xtol=1e-4, ftol=1e-4,
1379 niter=50, sigma_clip=5.0, niter_clip=3, verbose=False):
1380 my_logger = set_logger(__name__)
1381 fit_workspace.sigma_clip = sigma_clip
1382 for step in range(niter_clip):
1383 if verbose:
1384 my_logger.info(f"\n\tSigma-clipping step {step}/{niter_clip} (sigma={sigma_clip})")
1385 run_minimisation(fit_workspace, method=method, epsilon=epsilon, fix=fix, xtol=xtol, ftol=ftol, niter=niter)
1386 # remove outliers
1387 if fit_workspace.data.dtype == np.object:
1388 # indices_no_nan = ~np.isnan(np.concatenate(fit_workspace.data).ravel())
1389 data = np.concatenate(fit_workspace.data).ravel() # [indices_no_nan]
1390 model = np.concatenate(fit_workspace.model).ravel() # [indices_no_nan]
1391 err = np.concatenate(fit_workspace.err).ravel() # [indices_no_nan]
1392 else:
1393 # indices_no_nan = ~np.isnan(fit_workspace.data.flatten())
1394 data = fit_workspace.data.flatten() # [indices_no_nan]
1395 model = fit_workspace.model.flatten() # [indices_no_nan]
1396 err = fit_workspace.err.flatten() # [indices_no_nan]
1397 residuals = np.abs(data - model) / err
1398 outliers = residuals > sigma_clip
1399 outliers = [i for i in range(data.size) if outliers[i]]
1400 outliers.sort()
1401 if len(outliers) > 0:
1402 my_logger.debug(f'\n\tOutliers flat index list: {outliers}')
1403 my_logger.info(f'\n\tOutliers: {len(outliers)} / {data.size} data points '
1404 f'({100 * len(outliers) / data.size:.2f}%) '
1405 f'at more than {sigma_clip}-sigma from best-fit model.')
1406 if np.all(fit_workspace.outliers == outliers):
1407 my_logger.info(f'\n\tOutliers flat index list unchanged since last iteration: '
1408 f'break the sigma clipping iterations.')
1409 break
1410 else:
1411 fit_workspace.outliers = outliers
1412 else:
1413 my_logger.info(f'\n\tNo outliers detected at first iteration: break the sigma clipping iterations.')
1414 break
1417def run_emcee(fit_workspace, ln=lnprob):
1418 my_logger = set_logger(__name__)
1419 fit_workspace.print_settings()
1420 nsamples = fit_workspace.nsteps
1421 p0 = fit_workspace.set_start()
1422 filename = fit_workspace.emcee_filename
1423 backend = emcee.backends.HDFBackend(filename)
1424 try: # pragma: no cover
1425 pool = MPIPool()
1426 if not pool.is_master():
1427 pool.wait()
1428 sys.exit(0)
1429 sampler = emcee.EnsembleSampler(fit_workspace.nwalkers, fit_workspace.ndim, ln, args=(),
1430 pool=pool, backend=backend)
1431 my_logger.info(f"\n\tInitial size: {backend.iteration}")
1432 if backend.iteration > 0:
1433 p0 = backend.get_last_sample()
1434 if nsamples - backend.iteration > 0:
1435 sampler.run_mcmc(p0, nsteps=max(0, nsamples - backend.iteration), progress=True)
1436 pool.close()
1437 except ValueError:
1438 sampler = emcee.EnsembleSampler(fit_workspace.nwalkers, fit_workspace.ndim, ln, args=(),
1439 threads=multiprocessing.cpu_count(), backend=backend)
1440 my_logger.info(f"\n\tInitial size: {backend.iteration}")
1441 if backend.iteration > 0:
1442 p0 = sampler.get_last_sample()
1443 for _ in sampler.sample(p0, iterations=max(0, nsamples - backend.iteration), progress=True, store=True):
1444 continue
1445 fit_workspace.chains = sampler.chain
1446 fit_workspace.lnprobs = sampler.lnprobability
1449class RegFitWorkspace(FitWorkspace):
1451 def __init__(self, w, opt_reg=parameters.PSF_FIT_REG_PARAM, verbose=False, live_fit=False):
1452 """
1454 Parameters
1455 ----------
1456 w: ChromaticPSFFitWorkspace
1457 """
1458 FitWorkspace.__init__(self, verbose=verbose, live_fit=live_fit)
1459 self.x = np.array([0])
1460 self.data = np.array([0])
1461 self.err = np.array([1])
1462 self.w = w
1463 self.p = np.asarray([np.log10(opt_reg)])
1464 self.bounds = [(-20, np.log10(self.w.amplitude_priors.size) + 2)]
1465 self.input_labels = ["log10_reg"]
1466 self.axis_names = [r"$\log_{10} r$"]
1467 self.fixed = [False] * self.p.size
1468 self.opt_reg = opt_reg
1469 self.resolution = np.zeros_like((self.w.amplitude_params.size, self.w.amplitude_params.size))
1470 self.G = 0
1471 self.chisquare = -1
1473 def simulate(self, log10_r):
1474 reg = 10 ** log10_r
1475 M_dot_W_dot_M_plus_Q = self.w.M_dot_W_dot_M + reg * self.w.Q
1476 try:
1477 L = np.linalg.inv(np.linalg.cholesky(M_dot_W_dot_M_plus_Q))
1478 cov = L.T @ L
1479 except np.linalg.LinAlgError:
1480 cov = np.linalg.inv(M_dot_W_dot_M_plus_Q)
1481 if self.w.W.ndim == 1:
1482 A = cov @ (self.w.M.T @ (self.w.W * self.w.data) + reg * self.w.Q_dot_A0)
1483 else:
1484 A = cov @ (self.w.M.T @ (self.w.W @ self.w.data) + reg * self.w.Q_dot_A0)
1485 self.resolution = np.eye(A.size) - reg * cov @ self.w.Q
1486 diff = self.w.data - self.w.M @ A
1487 if self.w.W.ndim == 1:
1488 self.chisquare = diff @ (self.w.W * diff)
1489 else:
1490 self.chisquare = diff @ self.w.W @ diff
1491 self.w.amplitude_params = A
1492 self.w.amplitude_cov_matrix = cov
1493 self.w.amplitude_params_err = np.array([np.sqrt(cov[x, x]) for x in range(cov.shape[0])])
1494 self.G = self.chisquare / (self.w.data.size - np.trace(self.resolution)) ** 2
1495 return np.asarray([log10_r]), np.asarray([self.G]), np.zeros_like(self.data)
1497 def plot_fit(self):
1498 log10_opt_reg = self.p[0]
1499 opt_reg = 10 ** log10_opt_reg
1500 regs = 10 ** np.linspace(min(-10, 0.9 * log10_opt_reg), max(3, 1.2 * log10_opt_reg), 50)
1501 Gs = []
1502 chisqs = []
1503 resolutions = []
1504 x = np.arange(len(self.w.amplitude_priors))
1505 for r in regs:
1506 self.simulate(np.log10(r))
1507 if parameters.DISPLAY and False: # pragma: no cover
1508 fig = plt.figure()
1509 plt.errorbar(x, self.w.amplitude_params, yerr=[np.sqrt(self.w.amplitude_cov_matrix[i, i]) for i in x],
1510 label=f"fit r={r:.2g}")
1511 plt.plot(x, self.w.amplitude_priors, label="prior")
1512 plt.grid()
1513 plt.legend()
1514 plt.draw()
1515 plt.pause(1e-8)
1516 plt.close(fig)
1517 Gs.append(self.G)
1518 chisqs.append(self.chisquare)
1519 resolutions.append(np.trace(self.resolution))
1520 fig, ax = plt.subplots(3, 1, figsize=(7, 5), sharex="all")
1521 ax[0].plot(regs, Gs)
1522 ax[0].axvline(opt_reg, color="k")
1523 ax[1].axvline(opt_reg, color="k")
1524 ax[2].axvline(opt_reg, color="k")
1525 ax[0].set_ylabel(r"$G(r)$")
1526 ax[0].set_xlabel("Regularisation hyper-parameter $r$")
1527 ax[0].grid()
1528 ax[0].set_title(f"Optimal regularisation parameter: {opt_reg:.3g}")
1529 ax[1].plot(regs, chisqs)
1530 ax[1].set_ylabel(r"$\chi^2(\mathbf{A}(r) \vert \mathbf{\theta})$")
1531 ax[1].set_xlabel("Regularisation hyper-parameter $r$")
1532 ax[1].grid()
1533 ax[1].set_xscale("log")
1534 ax[2].set_xscale("log")
1535 ax[2].plot(regs, resolutions)
1536 ax[2].set_ylabel(r"$\mathrm{Tr}\,\mathbf{R}$")
1537 ax[2].set_xlabel("Regularisation hyper-parameter $r$")
1538 ax[2].grid()
1539 fig.tight_layout()
1540 plt.subplots_adjust(hspace=0)
1541 if parameters.DISPLAY:
1542 plt.show()
1543 if parameters.LSST_SAVEFIGPATH:
1544 fig.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'regularisation.pdf'))
1546 fig = plt.figure(figsize=(7, 5))
1547 rho = compute_correlation_matrix(self.w.amplitude_cov_matrix)
1548 plot_correlation_matrix_simple(plt.gca(), rho, axis_names=[''] * len(self.w.amplitude_params))
1549 # ipar=np.arange(10, 20))
1550 plt.gca().set_title(r"Correlation matrix $\mathbf{\rho}$")
1551 if parameters.LSST_SAVEFIGPATH:
1552 fig.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'amplitude_correlation_matrix.pdf'))
1553 if parameters.DISPLAY:
1554 plt.show()
1557if __name__ == "__main__": 1557 ↛ 1558line 1557 didn't jump to line 1558, because the condition on line 1557 was never true
1558 import doctest
1560 doctest.testmod()