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

757 statements  

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 

12 

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 

17 

18 

19class FitWorkspace: 

20 

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. 

24 

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). 

45 

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.mask = [] 

68 self.sigma_clip = 5 

69 self.model = None 

70 self.model_err = None 

71 self.model_noconv = None 

72 self.input_labels = [] 

73 self.axis_names = [] 

74 self.input_labels = [] 

75 self.bounds = ((), ()) 

76 self.fixed = [] 

77 self.nwalkers = max(2 * self.ndim, nwalkers) 

78 self.nsteps = nsteps 

79 self.nbins = nbins 

80 self.burnin = burnin 

81 self.start = [] 

82 self.likelihood = np.array([[]]) 

83 self.gelmans = np.array([]) 

84 self.chains = np.array([[]]) 

85 self.lnprobs = np.array([[]]) 

86 self.costs = np.array([[]]) 

87 self.params_table = None 

88 self.flat_chains = np.array([[]]) 

89 self.valid_chains = [False] * self.nwalkers 

90 self.global_average = None 

91 self.global_std = None 

92 self.title = "" 

93 self.use_grid = False 

94 if self.filename != "": 

95 if "." in self.filename: 

96 self.emcee_filename = os.path.splitext(self.filename)[0] + "_emcee.h5" 

97 else: 

98 self.my_logger.warning("\n\tFile name must have an extension.") 

99 else: 

100 self.emcee_filename = "emcee.h5" 

101 

102 @property 

103 def ndim(self): 

104 """Number of parameters of the model. 

105 

106 Returns 

107 ------- 

108 ndim: int 

109 

110 Examples 

111 -------- 

112 >>> from spectractor.fit.fitter import FitWorkspace 

113 >>> import numpy as np 

114 >>> w = FitWorkspace() 

115 >>> w.p = np.ones(5) 

116 >>> w.ndim 

117 5 

118 """ 

119 return len(self.p) 

120 

121 def get_bad_indices(self): 

122 """List of indices that are outliers rejected by a sigma-clipping method or other masking method. 

123 

124 Returns 

125 ------- 

126 outliers: list 

127 

128 Examples 

129 -------- 

130 >>> from spectractor.fit.fitter import FitWorkspace 

131 >>> import numpy as np 

132 >>> w = FitWorkspace() 

133 >>> w.data = np.array([np.array([1,2,3]), np.array([1,2,3,4])]) 

134 >>> w.outliers = [2, 6] 

135 >>> w.get_bad_indices() 

136 [array([2]), array([3])] 

137 """ 

138 bad_indices = np.asarray(self.outliers, dtype=int) 

139 if self.data.dtype == np.object: 

140 if len(self.outliers) > 0: 

141 bad_indices = [] 

142 start_index = 0 

143 for k in range(self.data.shape[0]): 

144 mask = np.zeros(self.data[k].size, dtype=bool) 

145 outliers = np.asarray(self.outliers)[np.logical_and(np.asarray(self.outliers) > start_index, 

146 np.asarray(self.outliers) < start_index + 

147 self.data[k].size)] 

148 mask[outliers - start_index] = True 

149 bad_indices.append(np.arange(self.data[k].size)[mask]) 

150 start_index += self.data[k].size 

151 else: 

152 bad_indices = [[] for _ in range(self.data.shape[0])] 

153 return bad_indices 

154 

155 def set_start(self, percent=0.02, a_random=1e-5): 

156 """Set the random starting points for MCMC exploration. 

157 

158 A set of parameters are drawn with a uniform distribution between +/- percent times the starting guess. 

159 For null guess parameters, starting points are drawn from a uniform distribution between +/- a_random. 

160 

161 Parameters 

162 ---------- 

163 percent: float, optional 

164 Percent of the guess parameters to set the uniform interval to draw random points (default: 0.02). 

165 a_random: float, optional 

166 Absolute value to set the +/- uniform interval to draw random points 

167 for null guess parameters (default: 1e-5). 

168 

169 Returns 

170 ------- 

171 start: np.array 

172 Array of starting points of shape (ndim, nwalkers). 

173 

174 """ 

175 self.start = np.array( 

176 [np.random.uniform(self.p[i] - percent * self.p[i], self.p[i] + percent * self.p[i], self.nwalkers) 

177 for i in range(self.ndim)]).T 

178 self.start[self.start == 0] = a_random * np.random.uniform(-1, 1) 

179 return self.start 

180 

181 def load_chains(self): 

182 """Load the MCMC chains from a hdf5 file. The burn-in points are not rejected at this stage. 

183 

184 Returns 

185 ------- 

186 chains: np.array 

187 Array of the chains. 

188 lnprobs: np.array 

189 Array of the logarithmic posterior probability. 

190 

191 """ 

192 self.chains = [[]] 

193 self.lnprobs = [[]] 

194 self.nsteps = 0 

195 # tau = -1 

196 reader = emcee.backends.HDFBackend(self.emcee_filename) 

197 try: 

198 tau = reader.get_autocorr_time() 

199 except emcee.autocorr.AutocorrError: 

200 tau = -1 

201 self.chains = reader.get_chain(discard=0, flat=False, thin=1) 

202 self.lnprobs = reader.get_log_prob(discard=0, flat=False, thin=1) 

203 self.nsteps = self.chains.shape[0] 

204 self.nwalkers = self.chains.shape[1] 

205 print(f"Auto-correlation time: {tau}") 

206 print(f"Burn-in: {self.burnin}") 

207 print(f"Chains shape: {self.chains.shape}") 

208 print(f"Log prob shape: {self.lnprobs.shape}") 

209 return self.chains, self.lnprobs 

210 

211 def build_flat_chains(self): 

212 """Flatten the chains array and apply burn-in. 

213 

214 Returns 

215 ------- 

216 flat_chains: np.array 

217 Flat chains. 

218 

219 """ 

220 self.flat_chains = self.chains[self.burnin:, self.valid_chains, :].reshape((-1, self.ndim)) 

221 return self.flat_chains 

222 

223 def simulate(self, *p): 

224 """Compute the model prediction given a set of parameters. 

225 

226 Parameters 

227 ---------- 

228 p: array_like 

229 Array of parameters for the computation of the model. 

230 

231 Returns 

232 ------- 

233 x: array_like 

234 The abscisse of the model prediction. 

235 model: array_like 

236 The model prediction. 

237 model_err: array_like 

238 The uncertainty on the model prediction. 

239 

240 Examples 

241 -------- 

242 >>> w = FitWorkspace() 

243 >>> p = np.zeros(3) 

244 >>> x, model, model_err = w.simulate(*p) 

245 

246 .. doctest:: 

247 :hide: 

248 >>> assert x is not None 

249 

250 """ 

251 self.x = np.array([]) 

252 self.model = np.array([]) 

253 self.model_err = np.array([]) 

254 return self.x, self.model, self.model_err 

255 

256 def analyze_chains(self): 

257 """Load the chains, build the probability densities for the parameters, compute the best fitting values 

258 and the uncertainties and covariance matrices, and plot. 

259 

260 """ 

261 self.load_chains() 

262 self.set_chain_validity() 

263 self.convergence_tests() 

264 self.build_flat_chains() 

265 self.likelihood = self.chain2likelihood() 

266 self.cov = self.likelihood.cov_matrix 

267 self.rho = self.likelihood.rho_matrix 

268 self.p = self.likelihood.mean_vec 

269 self.simulate(*self.p) 

270 self.plot_fit() 

271 figure_name = os.path.splitext(self.emcee_filename)[0] + '_triangle.pdf' 

272 self.likelihood.triangle_plots(output_filename=figure_name) 

273 

274 def plot_fit(self): 

275 """Generic function to plot the result of the fit for 1D curves. 

276 

277 Returns 

278 ------- 

279 fig: plt.FigureClass 

280 The figure. 

281 

282 """ 

283 fig = plt.figure() 

284 plt.errorbar(self.x, self.data, yerr=self.err, fmt='ko', label='Data') 

285 if self.truth is not None: 

286 x, truth, truth_err = self.simulate(*self.truth) 

287 plt.plot(self.x, truth, label="Truth") 

288 plt.plot(self.x, self.model, label='Best fitting model') 

289 plt.xlabel('$x$') 

290 plt.ylabel('$y$') 

291 title = "" 

292 for i, label in enumerate(self.input_labels): 

293 if self.cov.size > 0: 

294 err = np.sqrt(self.cov[i, i]) 

295 formatting_numbers(self.p[i], err, err) 

296 _, par, err, _ = formatting_numbers(self.p[i], err, err, label=label) 

297 title += rf"{label} = {par} $\pm$ {err}" 

298 else: 

299 title += f"{label} = {self.p[i]:.3g}" 

300 if i < len(self.input_labels) - 1: 

301 title += ", " 

302 plt.title(title) 

303 plt.legend() 

304 plt.grid() 

305 if parameters.DISPLAY: # pragma: no cover 

306 plt.show() 

307 return fig 

308 

309 def chain2likelihood(self, pdfonly=False, walker_index=-1): 

310 """Convert the chains to a psoterior probability density function via histograms. 

311 

312 Parameters 

313 ---------- 

314 pdfonly: bool, optional 

315 If True, do not compute the covariances and the 2D correlation plots (default: False). 

316 walker_index: int, optional 

317 The walker index to plot. If -1, all walkers are selected (default: -1). 

318 

319 Returns 

320 ------- 

321 likelihood: np.array 

322 Posterior density function. 

323 

324 """ 

325 if walker_index >= 0: 

326 chains = self.chains[self.burnin:, walker_index, :] 

327 else: 

328 chains = self.flat_chains 

329 rangedim = range(chains.shape[1]) 

330 centers = [] 

331 for i in rangedim: 

332 centers.append(np.linspace(np.min(chains[:, i]), np.max(chains[:, i]), self.nbins - 1)) 

333 likelihood = Likelihood(centers, labels=self.input_labels, axis_names=self.axis_names, truth=self.truth) 

334 if walker_index < 0: 

335 for i in rangedim: 

336 likelihood.pdfs[i].fill_histogram(chains[:, i], weights=None) 

337 if not pdfonly: 

338 for j in rangedim: 

339 if i != j: 

340 likelihood.contours[i][j].fill_histogram(chains[:, i], chains[:, j], weights=None) 

341 output_file = "" 

342 if self.filename != "": 

343 output_file = os.path.splitext(self.filename)[0] + "_bestfit.txt" 

344 likelihood.stats(output=output_file) 

345 else: 

346 for i in rangedim: 

347 likelihood.pdfs[i].fill_histogram(chains[:, i], weights=None) 

348 return likelihood 

349 

350 def compute_local_acceptance_rate(self, start_index, last_index, walker_index): 

351 """Compute the local acceptance rate in a chain. 

352 

353 Parameters 

354 ---------- 

355 start_index: int 

356 Beginning index. 

357 last_index: int 

358 End index. 

359 walker_index: int 

360 Index of the walker. 

361 

362 Returns 

363 ------- 

364 freq: float 

365 The acceptance rate. 

366 

367 """ 

368 frequences = [] 

369 test = -2 * self.lnprobs[start_index, walker_index] 

370 counts = 1 

371 for index in range(start_index + 1, last_index): 

372 chi2 = -2 * self.lnprobs[index, walker_index] 

373 if np.isclose(chi2, test): 

374 counts += 1 

375 else: 

376 frequences.append(float(counts)) 

377 counts = 1 

378 test = chi2 

379 frequences.append(counts) 

380 return 1.0 / np.mean(frequences) 

381 

382 def set_chain_validity(self): 

383 """Test the validity of a chain: reject chains whose chi2 is far from the mean of the others. 

384 

385 Returns 

386 ------- 

387 valid_chains: list 

388 List of boolean values, True if the chain is valid, or False if invalid. 

389 

390 """ 

391 nchains = [k for k in range(self.nwalkers)] 

392 chisq_averages = [] 

393 chisq_std = [] 

394 for k in nchains: 

395 chisqs = -2 * self.lnprobs[self.burnin:, k] 

396 # if np.mean(chisqs) < 1e5: 

397 chisq_averages.append(np.mean(chisqs)) 

398 chisq_std.append(np.std(chisqs)) 

399 self.global_average = np.mean(chisq_averages) 

400 self.global_std = np.mean(chisq_std) 

401 self.valid_chains = [False] * self.nwalkers 

402 for k in nchains: 

403 chisqs = -2 * self.lnprobs[self.burnin:, k] 

404 chisq_average = np.mean(chisqs) 

405 chisq_std = np.std(chisqs) 

406 if 3 * self.global_std + self.global_average < chisq_average < 1e5: 

407 self.valid_chains[k] = False 

408 elif chisq_std < 0.1 * self.global_std: 

409 self.valid_chains[k] = False 

410 else: 

411 self.valid_chains[k] = True 

412 return self.valid_chains 

413 

414 def convergence_tests(self): 

415 """Compute the convergence tests (Gelman-Rubin, acceptance rate). 

416 

417 """ 

418 chains = self.chains[self.burnin:, :, :] # .reshape((-1, self.ndim)) 

419 nchains = [k for k in range(self.nwalkers)] 

420 fig, ax = plt.subplots(self.ndim + 1, 2, figsize=(16, 7), sharex='all') 

421 fontsize = 8 

422 steps = np.arange(self.burnin, self.nsteps) 

423 # Chi2 vs Index 

424 print("Chisq statistics:") 

425 for k in nchains: 

426 chisqs = -2 * self.lnprobs[self.burnin:, k] 

427 text = f"\tWalker {k:d}: {float(np.mean(chisqs)):.3f} +/- {float(np.std(chisqs)):.3f}" 

428 if not self.valid_chains[k]: 

429 text += " -> excluded" 

430 ax[self.ndim, 0].plot(steps, chisqs, c='0.5', linestyle='--') 

431 else: 

432 ax[self.ndim, 0].plot(steps, chisqs) 

433 print(text) 

434 # global_average = np.mean(-2*self.lnprobs[self.valid_chains, self.burnin:]) 

435 # global_std = np.std(-2*self.lnprobs[self.valid_chains, self.burnin:]) 

436 ax[self.ndim, 0].set_ylim( 

437 [self.global_average - 5 * self.global_std, self.global_average + 5 * self.global_std]) 

438 # Parameter vs Index 

439 print("Computing Parameter vs Index plots...") 

440 for i in range(self.ndim): 

441 ax[i, 0].set_ylabel(self.axis_names[i], fontsize=fontsize) 

442 for k in nchains: 

443 if self.valid_chains[k]: 

444 ax[i, 0].plot(steps, chains[:, k, i]) 

445 else: 

446 ax[i, 0].plot(steps, chains[:, k, i], c='0.5', linestyle='--') 

447 ax[i, 0].get_yaxis().set_label_coords(-0.05, 0.5) 

448 ax[self.ndim, 0].set_ylabel(r'$\chi^2$', fontsize=fontsize) 

449 ax[self.ndim, 0].set_xlabel('Steps', fontsize=fontsize) 

450 ax[self.ndim, 0].get_yaxis().set_label_coords(-0.05, 0.5) 

451 # Acceptance rate vs Index 

452 print("Computing acceptance rate...") 

453 min_len = self.nsteps 

454 window = 100 

455 if min_len > window: 

456 for k in nchains: 

457 ARs = [] 

458 indices = [] 

459 for pos in range(self.burnin + window, self.nsteps, window): 

460 ARs.append(self.compute_local_acceptance_rate(pos - window, pos, k)) 

461 indices.append(pos) 

462 if self.valid_chains[k]: 

463 ax[self.ndim, 1].plot(indices, ARs, label=f'Walker {k:d}') 

464 else: 

465 ax[self.ndim, 1].plot(indices, ARs, label=f'Walker {k:d}', c='gray', linestyle='--') 

466 ax[self.ndim, 1].set_xlabel('Steps', fontsize=fontsize) 

467 ax[self.ndim, 1].set_ylabel('Aceptance rate', fontsize=fontsize) 

468 # ax[self.dim + 1, 2].legend(loc='upper left', ncol=2, fontsize=10) 

469 # Parameter PDFs by chain 

470 print("Computing chain by chain PDFs...") 

471 for k in nchains: 

472 likelihood = self.chain2likelihood(pdfonly=True, walker_index=k) 

473 likelihood.stats(pdfonly=True, verbose=False) 

474 # for i in range(self.dim): 

475 # ax[i, 1].plot(likelihood.pdfs[i].axe.axis, likelihood.pdfs[i].grid, lw=var.LINEWIDTH, 

476 # label=f'Walker {k:d}') 

477 # ax[i, 1].set_xlabel(self.axis_names[i]) 

478 # ax[i, 1].set_ylabel('PDF') 

479 # ax[i, 1].legend(loc='upper right', ncol=2, fontsize=10) 

480 # Gelman-Rubin test.py 

481 if len(nchains) > 1: 

482 step = max(1, (self.nsteps - self.burnin) // 20) 

483 self.gelmans = [] 

484 print(f'Gelman-Rubin tests (burnin={self.burnin:d}, step={step:d}, nsteps={self.nsteps:d}):') 

485 for i in range(self.ndim): 

486 Rs = [] 

487 lens = [] 

488 for pos in range(self.burnin + step, self.nsteps, step): 

489 chain_averages = [] 

490 chain_variances = [] 

491 global_average = np.mean(self.chains[self.burnin:pos, self.valid_chains, i]) 

492 for k in nchains: 

493 if not self.valid_chains[k]: 

494 continue 

495 chain_averages.append(np.mean(self.chains[self.burnin:pos, k, i])) 

496 chain_variances.append(np.var(self.chains[self.burnin:pos, k, i], ddof=1)) 

497 W = np.mean(chain_variances) 

498 B = 0 

499 for n in range(len(chain_averages)): 

500 B += (chain_averages[n] - global_average) ** 2 

501 B *= ((pos + 1) / (len(chain_averages) - 1)) 

502 R = (W * pos / (pos + 1) + B / (pos + 1) * (len(chain_averages) + 1) / len(chain_averages)) / W 

503 Rs.append(R - 1) 

504 lens.append(pos) 

505 print(f'\t{self.input_labels[i]}: R-1 = {Rs[-1]:.3f} (l = {lens[-1] - 1:d})') 

506 self.gelmans.append(Rs[-1]) 

507 ax[i, 1].plot(lens, Rs, lw=1, label=self.axis_names[i]) 

508 ax[i, 1].axhline(0.03, c='k', linestyle='--') 

509 ax[i, 1].set_xlabel('Walker length', fontsize=fontsize) 

510 ax[i, 1].set_ylabel('$R-1$', fontsize=fontsize) 

511 ax[i, 1].set_ylim(0, 0.6) 

512 # ax[self.dim, 3].legend(loc='best', ncol=2, fontsize=10) 

513 self.gelmans = np.array(self.gelmans) 

514 fig.tight_layout() 

515 plt.subplots_adjust(hspace=0) 

516 if parameters.DISPLAY: # pragma: no cover 

517 plt.show() 

518 if parameters.PdfPages: 

519 parameters.PdfPages.savefig() 

520 figure_name = self.emcee_filename.replace('.h5', '_convergence.pdf') 

521 print(f'Save figure: {figure_name}') 

522 fig.savefig(figure_name, dpi=100) 

523 

524 def print_settings(self): 

525 """Print the main settings of the FitWorkspace. 

526 

527 """ 

528 print('************************************') 

529 print(f"Input file: {self.filename}\nWalkers: {self.nwalkers}\t Steps: {self.nsteps}") 

530 print(f"Output file: {self.emcee_filename}") 

531 print('************************************') 

532 

533 def save_parameters_summary(self, ipar, header=""): 

534 """Save the best fitting parameter summary in a text file. 

535 

536 The file name is build from self.file_name, adding the suffix _bestfit.txt. 

537 

538 Parameters 

539 ---------- 

540 ipar: list 

541 The list of parameter indices to save. 

542 header: str, optional 

543 A header to add to the file (default: ""). 

544 """ 

545 output_filename = os.path.splitext(self.filename)[0] + "_bestfit.txt" 

546 f = open(output_filename, 'w') 

547 txt = self.filename + "\n" 

548 if header != "": 

549 txt += header + "\n" 

550 for k, ip in enumerate(ipar): 

551 txt += "%s: %s +%s -%s\n" % formatting_numbers(self.p[ip], np.sqrt(self.cov[k, k]), 

552 np.sqrt(self.cov[k, k]), 

553 label=self.input_labels[ip]) 

554 for row in self.cov: 

555 txt += np.array_str(row, max_line_width=20 * self.cov.shape[0]) + '\n' 

556 self.my_logger.info(f"\n\tSave best fit parameters in {output_filename}.") 

557 f.write(txt) 

558 f.close() 

559 

560 def plot_correlation_matrix(self, ipar=None): 

561 """Compute and plot a correlation matrix. 

562 

563 Save the plot if parameters.SAVE is True. The output file name is build from self.file_name, 

564 adding the suffix _correlation.pdf. 

565 

566 Parameters 

567 ---------- 

568 ipar: list, optional 

569 The list of parameter indices to include in the matrix. 

570 

571 Examples 

572 -------- 

573 >>> w = FitWorkspace() 

574 >>> w.axis_names = ["x", "y", "z"] 

575 >>> w.cov = np.array([[1,-0.5,0],[-0.5,1,-1],[0,-1,1]]) 

576 >>> w.plot_correlation_matrix() 

577 """ 

578 if ipar is None: 

579 ipar = np.arange(self.cov.shape[0]).astype(int) 

580 fig = plt.figure() 

581 self.rho = compute_correlation_matrix(self.cov) 

582 plot_correlation_matrix_simple(plt.gca(), self.rho, axis_names=[self.axis_names[i] for i in ipar]) 

583 if parameters.SAVE and self.filename != "": # pragma: no cover 

584 figname = os.path.splitext(self.filename)[0] + "_correlation.pdf" 

585 self.my_logger.info(f"Save figure {figname}.") 

586 fig.savefig(figname, dpi=100, bbox_inches='tight') 

587 if parameters.DISPLAY: # pragma: no cover 

588 if self.live_fit: 

589 plt.draw() 

590 plt.pause(1e-8) 

591 else: 

592 plt.show() 

593 

594 def weighted_residuals(self, p): # pragma: nocover 

595 """Compute the weighted residuals array for a set of model parameters p. 

596 

597 Parameters 

598 ---------- 

599 p: array_like 

600 The array of model parameters. 

601 

602 Returns 

603 ------- 

604 residuals: np.array 

605 The array of weighted residuals. 

606 

607 """ 

608 x, model, model_err = self.simulate(*p) 

609 if self.data_cov is None: 

610 if len(self.outliers) > 0: 

611 model_err = model_err.flatten() 

612 err = self.err.flatten() 

613 res = (model.flatten() - self.data.flatten()) / np.sqrt(model_err * model_err + err * err) 

614 else: 

615 res = ((model - self.data) / np.sqrt(model_err * model_err + self.err * self.err)).flatten() 

616 else: 

617 if self.data_cov.ndim > 2: 

618 K = self.data_cov.shape[0] 

619 if np.any(model_err > 0): 

620 cov = [self.data_cov[k] + np.diag(model_err[k] ** 2) for k in range(K)] 

621 L = [np.linalg.inv(np.linalg.cholesky(cov[k])) for k in range(K)] 

622 else: 

623 L = [np.linalg.cholesky(self.W[k]) for k in range(K)] 

624 res = [L[k] @ (model[k] - self.data[k]) for k in range(K)] 

625 res = np.concatenate(res).ravel() 

626 else: 

627 if np.any(model_err > 0): 

628 cov = self.data_cov + np.diag(model_err * model_err) 

629 L = np.linalg.inv(np.linalg.cholesky(cov)) 

630 else: 

631 if self.W.ndim == 1 and self.W.dtype != np.object: 

632 L = np.sqrt(self.W) 

633 elif self.W.ndim == 2 and self.W.dtype != np.object: 

634 L = np.linalg.cholesky(self.W) 

635 else: 

636 raise ValueError(f"Case not implemented with self.W.ndim={self.W.ndim} " 

637 f"and self.W.dtype={self.W.dtype}") 

638 res = L @ (model - self.data) 

639 return res 

640 

641 def chisq(self, p, model_output=False): 

642 """Compute the chi square for a set of model parameters p. 

643 

644 Four cases are implemented: diagonal W, 2D W, array of diagonal Ws, array of 2D Ws. The two latter cases 

645 are for multiple independent data vectors with W being block diagonal. 

646 

647 Parameters 

648 ---------- 

649 p: array_like 

650 The array of model parameters. 

651 model_output: bool, optional 

652 If true, the simulated model is output. 

653 

654 Returns 

655 ------- 

656 chisq: float 

657 The chi square value. 

658 

659 """ 

660 # check data format 

661 if (self.data.dtype != np.object and self.data.ndim > 1) or (self.err.dtype != np.object and self.err.ndim > 1): 

662 raise ValueError("Fitworkspace.data and Fitworkspace.err must be a flat 1D array," 

663 " or an array of flat arrays of unequal lengths.") 

664 # prepare weight matrices in case they have not been built before 

665 self.prepare_weight_matrices() 

666 x, model, model_err = self.simulate(*p) 

667 if self.W.ndim == 1 and self.W.dtype != np.object: 

668 if np.any(model_err > 0): 

669 W = 1 / (self.data_cov + model_err * model_err) 

670 else: 

671 W = self.W 

672 res = (model - self.data) 

673 chisq = res @ (W * res) 

674 # fit_workspace.my_logger.warning(f"ll {tmp_params}") 

675 # fit_workspace.my_logger.warning(f"yyyy {np.sum(residuals)} {np.sum(W)} {np.sum(W*residuals)}") 

676 # fit_workspace.my_logger.warning(f"yoooo {np.sum(residuals)} {np.sum(W*residuals)} ") 

677 # 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])} ") 

678 # self.my_logger.warning(f"ll {p}") 

679 # self.my_logger.warning(f"yyyy {np.sum(res)} {np.sum(W)} {np.sum(W*res)}") 

680 # self.my_logger.warning(f"yoooo {np.sum(res[self.not_outliers])} {np.sum(W[self.not_outliers]*res[self.not_outliers])} ") 

681 # self.my_logger.warning(f"yiiii {np.sum(model[self.not_outliers])} {np.sum(self.data[self.not_outliers])} ") 

682 elif self.W.dtype == np.object: 

683 K = len(self.W) 

684 if self.W[0].ndim == 1: 

685 if np.any(model_err > 0): 

686 W = [1 / (self.data_cov[k] + model_err * model_err) for k in range(K)] 

687 else: 

688 W = self.W 

689 res = [model[k] - self.data[k] for k in range(K)] 

690 chisq = np.sum([res[k] @ (W[k] * res[k]) for k in range(K)]) 

691 elif self.W[0].ndim == 2: 

692 K = len(self.W) 

693 if np.any(model_err > 0): 

694 cov = [self.data_cov[k] + np.diag(model_err[k] ** 2) for k in range(K)] 

695 L = [np.linalg.inv(np.linalg.cholesky(cov[k])) for k in range(K)] 

696 W = [L[k].T @ L[k] for k in range(K)] 

697 else: 

698 W = self.W 

699 res = [model[k] - self.data[k] for k in range(K)] 

700 chisq = np.sum([res[k] @ W[k] @ res[k] for k in range(K)]) 

701 else: 

702 raise ValueError(f"First element of fitworkspace.W has no ndim attribute or has a dimension above 2. " 

703 f"I get W[0]={self.W[0]}") 

704 elif self.W.ndim == 2 and self.W.dtype != np.object: 

705 if np.any(model_err > 0): 

706 cov = self.data_cov + np.diag(model_err * model_err) 

707 L = np.linalg.inv(np.linalg.cholesky(cov)) 

708 W = L.T @ L 

709 else: 

710 W = self.W 

711 res = (model - self.data) 

712 chisq = res @ W @ res 

713 else: 

714 raise ValueError( 

715 f"Data inverse covariance matrix must be a np.ndarray of dimension 1 or 2," 

716 f"either made of 1D or 2D arrays of equal lengths or not for block diagonal matrices." 

717 f"\nHere W type is {type(self.W)}, shape is {self.W.shape} and W is {self.W}.") 

718 if model_output: 

719 return chisq, x, model, model_err 

720 else: 

721 return chisq 

722 

723 def prepare_weight_matrices(self): 

724 # Prepare covariance matrix for data 

725 if self.data_cov is None: 

726 self.data_cov = np.asarray(self.err.flatten() ** 2) 

727 # Prepare inverse covariance matrix for data 

728 if self.W is None: 

729 if self.data_cov.ndim == 1 and self.data_cov.dtype != np.object: 

730 self.W = 1 / self.data_cov 

731 elif self.data_cov.ndim == 2 and self.data_cov.dtype != np.object: 

732 L = np.linalg.inv(np.linalg.cholesky(self.data_cov)) 

733 self.W = L.T @ L 

734 elif self.data_cov.dtype is np.object: 

735 if self.data_cov[0].ndim == 1: 

736 self.W = np.array([1 / self.data_cov[k] for k in range(self.data_cov.shape[0])]) 

737 else: 

738 self.W = [] 

739 for k in range(len(self.data_cov)): 

740 L = np.linalg.inv(np.linalg.cholesky(self.data_cov[k])) 

741 self.W[k] = L.T @ L 

742 self.W = np.asarray(self.W) 

743 if len(self.outliers) > 0: 

744 bad_indices = self.get_bad_indices() 

745 if self.W.ndim == 1 and self.W.dtype != np.object: 

746 self.W[bad_indices] = 0 

747 elif self.W.ndim == 2 and self.W.dtype != np.object: 

748 self.W[:, bad_indices] = 0 

749 self.W[bad_indices, :] = 0 

750 elif self.W.dtype == np.object: 

751 if self.data_cov[0].ndim == 1: 

752 for k in range(len(self.W)): 

753 self.W[k][bad_indices[k]] = 0 

754 else: 

755 for k in range(len(self.W)): 

756 self.W[k][:, bad_indices[k]] = 0 

757 self.W[k][bad_indices[k], :] = 0 

758 else: 

759 raise ValueError( 

760 f"Data inverse covariance matrix must be a np.ndarray of dimension 1 or 2," 

761 f"either made of 1D or 2D arrays of equal lengths or not for block diagonal matrices." 

762 f"\nHere W type is {type(self.W)}, shape is {self.W.shape} and W is {self.W}.") 

763 

764 def lnlike(self, p): 

765 """Compute the logarithmic likelihood for a set of model parameters p as -0.5*chisq. 

766 

767 Parameters 

768 ---------- 

769 p: array_like 

770 The array of model parameters. 

771 

772 Returns 

773 ------- 

774 lnlike: float 

775 The logarithmic likelihood value. 

776 

777 """ 

778 return -0.5 * self.chisq(p) 

779 

780 def lnprior(self, p): 

781 """Compute the logarithmic prior for a set of model parameters p. 

782 

783 The function returns 0 for good parameters, and -np.inf for parameters out of their boundaries. 

784 

785 Parameters 

786 ---------- 

787 p: array_like 

788 The array of model parameters. 

789 

790 Returns 

791 ------- 

792 lnprior: float 

793 The logarithmic value fo the prior. 

794 

795 """ 

796 in_bounds = True 

797 for npar, par in enumerate(p): 

798 if par < self.bounds[npar][0] or par > self.bounds[npar][1]: 

799 in_bounds = False 

800 break 

801 if in_bounds: 

802 return 0.0 

803 else: 

804 return -np.inf 

805 

806 def jacobian(self, params, epsilon, fixed_params=None, model_input=None): 

807 """Generic function to compute the Jacobian matrix of a model, with numerical derivatives. 

808 

809 Parameters 

810 ---------- 

811 params: array_like 

812 The array of model parameters. 

813 epsilon: array_like 

814 The array of small steps to compute the partial derivatives of the model. 

815 fixed_params: array_like 

816 List of boolean values. If True, the parameter is considered fixed and no derivative are computed. 

817 model_input: array_like, optional 

818 A model input as a list with (x, model, model_err) to avoid an additional call to simulate(). 

819 

820 Returns 

821 ------- 

822 J: np.array 

823 The Jacobian matrix. 

824 

825 """ 

826 if model_input: 

827 x, model, model_err = model_input 

828 else: 

829 x, model, model_err = self.simulate(*params) 

830 if self.W.dtype == np.object and self.W[0].ndim == 2: 

831 J = [[] for _ in range(params.size)] 

832 else: 

833 model = model.flatten() 

834 J = np.zeros((params.size, model.size)) 

835 for ip, p in enumerate(params): 

836 if fixed_params[ip]: 

837 continue 

838 tmp_p = np.copy(params) 

839 if tmp_p[ip] + epsilon[ip] < self.bounds[ip][0] or tmp_p[ip] + epsilon[ip] > self.bounds[ip][1]: 

840 epsilon[ip] = - epsilon[ip] 

841 tmp_p[ip] += epsilon[ip] 

842 tmp_x, tmp_model, tmp_model_err = self.simulate(*tmp_p) 

843 if self.W.dtype == np.object and self.W[0].ndim == 2: 

844 for k in range(model.shape[0]): 

845 J[ip].append((tmp_model[k] - model[k]) / epsilon[ip]) 

846 else: 

847 J[ip] = (tmp_model.flatten() - model) / epsilon[ip] 

848 return np.asarray(J) 

849 

850 def hessian(self, params, epsilon, fixed_params=None): # pragma: nocover 

851 """Experimental function to compute the hessian of a model. 

852 

853 Parameters 

854 ---------- 

855 params: array_like 

856 The array of model parameters. 

857 epsilon: array_like 

858 The array of small steps to compute the partial derivatives of the model. 

859 fixed_params: array_like 

860 List of boolean values. If True, the parameter is considered fixed and no derivative are computed. 

861 

862 Returns 

863 ------- 

864 

865 """ 

866 x, model, model_err = self.simulate(*params) 

867 model = model.flatten() 

868 J = self.jacobian(params, epsilon, fixed_params=fixed_params) 

869 H = np.zeros((params.size, params.size, model.size)) 

870 tmp_p = np.copy(params) 

871 for ip, p1 in enumerate(params): 

872 print(ip, p1, params[ip], tmp_p[ip], self.bounds[ip], epsilon[ip], tmp_p[ip] + epsilon[ip]) 

873 if fixed_params[ip]: 

874 continue 

875 if tmp_p[ip] + epsilon[ip] < self.bounds[ip][0] or tmp_p[ip] + epsilon[ip] > self.bounds[ip][1]: 

876 epsilon[ip] = - epsilon[ip] 

877 tmp_p[ip] += epsilon[ip] 

878 print(tmp_p) 

879 # tmp_x, tmp_model, tmp_model_err = self.simulate(*tmp_p) 

880 # J[ip] = (tmp_model.flatten() - model) / epsilon[ip] 

881 tmp_J = self.jacobian(tmp_p, epsilon, fixed_params=fixed_params) 

882 for ip, p1 in enumerate(params): 

883 if fixed_params[ip]: 

884 continue 

885 for jp, p2 in enumerate(params): 

886 if fixed_params[jp]: 

887 continue 

888 x, modelplus, model_err = self.simulate(params + epsilon) 

889 x, modelmoins, model_err = self.simulate(params - epsilon) 

890 model = model.flatten() 

891 

892 print("hh", ip, jp, tmp_J[ip], J[jp], tmp_p[ip], params, (tmp_J[ip] - J[jp]) / epsilon) 

893 print((modelplus + modelmoins - 2 * model) / (np.asarray(epsilon) ** 2)) 

894 H[ip, jp] = (tmp_J[ip] - J[jp]) / epsilon 

895 H[ip, jp] = (modelplus + modelmoins - 2 * model) / (np.asarray(epsilon) ** 2) 

896 return H 

897 

898 

899def lnprob(p): # pragma: no cover 

900 global fit_workspace 

901 lp = fit_workspace.lnprior(p) 

902 if not np.isfinite(lp): 

903 return -1e20 

904 return lp + fit_workspace.lnlike(p) 

905 

906 

907def gradient_descent(fit_workspace, params, epsilon, niter=10, fixed_params=None, xtol=1e-3, ftol=1e-3, 

908 with_line_search=True): 

909 """ 

910 

911 Four cases are implemented: diagonal W, 2D W, array of diagonal Ws, array of 2D Ws. The two latter cases 

912 are for multiple independent data vectors with W being block diagonal. 

913 

914 Parameters 

915 ---------- 

916 fit_workspace: FitWorkspace 

917 params 

918 epsilon 

919 niter 

920 fixed_params 

921 xtol 

922 ftol 

923 with_line_search 

924 

925 Returns 

926 ------- 

927 

928 """ 

929 my_logger = set_logger(__name__) 

930 tmp_params = np.copy(params) 

931 fit_workspace.prepare_weight_matrices() 

932 W = fit_workspace.W 

933 ipar = np.arange(params.size) 

934 if fixed_params is not None: 

935 ipar = np.array(np.where(np.array(fixed_params).astype(int) == 0)[0]) 

936 costs = [] 

937 params_table = [] 

938 inv_JT_W_J = np.zeros((len(ipar), len(ipar))) 

939 for i in range(niter): 

940 start = time.time() 

941 cost, tmp_lambdas, tmp_model, tmp_model_err = fit_workspace.chisq(tmp_params, model_output=True) 

942 if isinstance(fit_workspace.W, np.ndarray) and fit_workspace.W.dtype != np.object: 

943 residuals = (tmp_model - fit_workspace.data).flatten() 

944 elif isinstance(fit_workspace.W, np.ndarray) and fit_workspace.W.dtype == np.object: 

945 residuals = [(tmp_model[k] - fit_workspace.data[k]) for k in range(len(fit_workspace.W))] 

946 else: 

947 raise TypeError(f"Type of fit_workspace.W is {type(fit_workspace.W)}. It must be a np.ndarray.") 

948 # Jacobian 

949 J = fit_workspace.jacobian(tmp_params, epsilon, fixed_params=fixed_params, 

950 model_input=[tmp_lambdas, tmp_model, tmp_model_err]) 

951 # remove parameters with unexpected null Jacobian vectors 

952 for ip in range(J.shape[0]): 

953 if ip not in ipar: 

954 continue 

955 if np.all(np.array(J[ip]).flatten() == np.zeros(np.array(J[ip]).size)): 

956 ipar = np.delete(ipar, list(ipar).index(ip)) 

957 fixed_params[ip] = True 

958 # tmp_params[ip] = 0 

959 my_logger.warning( 

960 f"\n\tStep {i}: {fit_workspace.input_labels[ip]} has a null Jacobian; parameter is fixed " 

961 f"at its last known current value ({tmp_params[ip]}).") 

962 # remove fixed parameters 

963 J = J[ipar].T 

964 # algebra 

965 if fit_workspace.W.ndim == 1 and fit_workspace.W.dtype != np.object: 

966 JT_W = J.T * W 

967 JT_W_J = JT_W @ J 

968 elif fit_workspace.W.ndim == 2 and fit_workspace.W.dtype != np.object: 

969 JT_W = J.T @ W 

970 JT_W_J = JT_W @ J 

971 else: 

972 if fit_workspace.W[0].ndim == 1: 

973 JT_W = J.T * np.concatenate(W).ravel() 

974 JT_W_J = JT_W @ J 

975 else: 

976 # warning ! here the data arrays indexed by k can have different lengths because outliers 

977 # because W inverse covariance is block diagonal and blocks can have different sizes 

978 # the philosophy is to temporarily flatten the data arrays 

979 JT_W = [np.concatenate([J[ip][k].T @ W[k] 

980 for k in range(fit_workspace.W.shape[0])]).ravel() 

981 for ip in range(len(J))] 

982 JT_W_J = np.array([[JT_W[ip2] @ np.concatenate(J[ip1][:]).ravel() for ip1 in range(len(J))] 

983 for ip2 in range(len(J))]) 

984 try: 

985 L = np.linalg.inv(np.linalg.cholesky(JT_W_J)) # cholesky is too sensible to the numerical precision 

986 inv_JT_W_J = L.T @ L 

987 except np.linalg.LinAlgError: 

988 inv_JT_W_J = np.linalg.inv(JT_W_J) 

989 if fit_workspace.W.dtype != np.object: 

990 JT_W_R0 = JT_W @ residuals 

991 else: 

992 JT_W_R0 = JT_W @ np.concatenate(residuals).ravel() 

993 dparams = - inv_JT_W_J @ JT_W_R0 

994 

995 if with_line_search: 

996 def line_search(alpha): 

997 tmp_params_2 = np.copy(tmp_params) 

998 tmp_params_2[ipar] = tmp_params[ipar] + alpha * dparams 

999 for ipp, pp in enumerate(tmp_params_2): 

1000 if pp < fit_workspace.bounds[ipp][0]: 

1001 tmp_params_2[ipp] = fit_workspace.bounds[ipp][0] 

1002 if pp > fit_workspace.bounds[ipp][1]: 

1003 tmp_params_2[ipp] = fit_workspace.bounds[ipp][1] 

1004 return fit_workspace.chisq(tmp_params_2) 

1005 

1006 # tol parameter acts on alpha (not func) 

1007 alpha_min, fval, iter, funcalls = optimize.brent(line_search, full_output=True, tol=5e-1, brack=(0, 1)) 

1008 else: 

1009 alpha_min = 1 

1010 fval = np.copy(cost) 

1011 funcalls = 0 

1012 iter = 0 

1013 

1014 tmp_params[ipar] += alpha_min * dparams 

1015 # check bounds 

1016 for ip, p in enumerate(tmp_params): 

1017 if p < fit_workspace.bounds[ip][0]: 

1018 tmp_params[ip] = fit_workspace.bounds[ip][0] 

1019 if p > fit_workspace.bounds[ip][1]: 

1020 tmp_params[ip] = fit_workspace.bounds[ip][1] 

1021 

1022 # prepare outputs 

1023 costs.append(fval) 

1024 params_table.append(np.copy(tmp_params)) 

1025 fit_workspace.p = tmp_params 

1026 if fit_workspace.verbose: 

1027 my_logger.info(f"\n\tIteration={i}: initial cost={cost:.5g} initial chisq_red={cost / (tmp_model.size - len(fit_workspace.mask)):.5g}" 

1028 f"\n\t\t Line search: alpha_min={alpha_min:.3g} iter={iter} funcalls={funcalls}" 

1029 f"\n\tParameter shifts: {alpha_min * dparams}" 

1030 f"\n\tNew parameters: {tmp_params[ipar]}" 

1031 f"\n\tFinal cost={fval:.5g} final chisq_red={fval / (tmp_model.size - len(fit_workspace.mask)):.5g} " 

1032 f"computed in {time.time() - start:.2f}s") 

1033 if fit_workspace.live_fit: # pragma: no cover 

1034 fit_workspace.simulate(*tmp_params) 

1035 fit_workspace.plot_fit() 

1036 fit_workspace.cov = inv_JT_W_J 

1037 # fit_workspace.plot_correlation_matrix(ipar) 

1038 if len(ipar) == 0: 

1039 my_logger.warning(f"\n\tGradient descent terminated in {i} iterations because all parameters " 

1040 f"have null Jacobian.") 

1041 break 

1042 if np.sum(np.abs(alpha_min * dparams)) / np.sum(np.abs(tmp_params[ipar])) < xtol: 

1043 my_logger.info(f"\n\tGradient descent terminated in {i} iterations because the sum of parameter shift " 

1044 f"relative to the sum of the parameters is below xtol={xtol}.") 

1045 break 

1046 if len(costs) > 1 and np.abs(costs[-2] - fval) / np.max([np.abs(fval), np.abs(costs[-2])]) < ftol: 

1047 my_logger.info(f"\n\tGradient descent terminated in {i} iterations because the " 

1048 f"relative change of cost is below ftol={ftol}.") 

1049 break 

1050 plt.close() 

1051 return tmp_params, inv_JT_W_J, np.array(costs), np.array(params_table) 

1052 

1053 

1054def simple_newton_minimisation(fit_workspace, params, epsilon, niter=10, fixed_params=None, 

1055 xtol=1e-3, ftol=1e-3): # pragma: no cover 

1056 """Experimental function to minimize a function. 

1057 

1058 Parameters 

1059 ---------- 

1060 fit_workspace: FitWorkspace 

1061 params 

1062 epsilon 

1063 niter 

1064 fixed_params 

1065 xtol 

1066 ftol 

1067 

1068 Returns 

1069 ------- 

1070 

1071 """ 

1072 my_logger = set_logger(__name__) 

1073 tmp_params = np.copy(params) 

1074 ipar = np.arange(params.size) 

1075 if fixed_params is not None: 

1076 ipar = np.array(np.where(np.array(fixed_params).astype(int) == 0)[0]) 

1077 funcs = [] 

1078 params_table = [] 

1079 inv_H = np.zeros((len(ipar), len(ipar))) 

1080 for i in range(niter): 

1081 start = time.time() 

1082 tmp_lambdas, tmp_model, tmp_model_err = fit_workspace.simulate(*tmp_params) 

1083 # if fit_workspace.live_fit: 

1084 # fit_workspace.plot_fit() 

1085 J = fit_workspace.jacobian(tmp_params, epsilon, fixed_params=fixed_params) 

1086 # remove parameters with unexpected null Jacobian vectors 

1087 for ip in range(J.shape[0]): 

1088 if ip not in ipar: 

1089 continue 

1090 if np.all(J[ip] == np.zeros(J.shape[1])): 

1091 ipar = np.delete(ipar, list(ipar).index(ip)) 

1092 # tmp_params[ip] = 0 

1093 my_logger.warning( 

1094 f"\n\tStep {i}: {fit_workspace.input_labels[ip]} has a null Jacobian; parameter is fixed " 

1095 f"at its last known current value ({tmp_params[ip]}).") 

1096 # remove fixed parameters 

1097 J = J[ipar].T 

1098 # hessian 

1099 H = fit_workspace.hessian(tmp_params, epsilon, fixed_params=fixed_params) 

1100 try: 

1101 L = np.linalg.inv(np.linalg.cholesky(H)) # cholesky is too sensible to the numerical precision 

1102 inv_H = L.T @ L 

1103 except np.linalg.LinAlgError: 

1104 inv_H = np.linalg.inv(H) 

1105 dparams = - inv_H[:, :, 0] @ J[:, 0] 

1106 print("dparams", dparams, inv_H, J, H) 

1107 tmp_params[ipar] += dparams 

1108 

1109 # check bounds 

1110 print("tmp_params", tmp_params, dparams, inv_H, J) 

1111 for ip, p in enumerate(tmp_params): 

1112 if p < fit_workspace.bounds[ip][0]: 

1113 tmp_params[ip] = fit_workspace.bounds[ip][0] 

1114 if p > fit_workspace.bounds[ip][1]: 

1115 tmp_params[ip] = fit_workspace.bounds[ip][1] 

1116 

1117 tmp_lambdas, new_model, tmp_model_err = fit_workspace.simulate(*tmp_params) 

1118 new_func = new_model[0] 

1119 funcs.append(new_func) 

1120 

1121 r = np.log10(fit_workspace.regs) 

1122 js = [fit_workspace.jacobian(np.asarray([rr]), epsilon, fixed_params=fixed_params)[0] for rr in np.array(r)] 

1123 plt.plot(r, js, label="J") 

1124 plt.grid() 

1125 plt.legend() 

1126 plt.show() 

1127 

1128 if parameters.DISPLAY: 

1129 fig = plt.figure() 

1130 plt.plot(r, js, label="prior") 

1131 mod = tmp_model + J[0] * (r - (tmp_params - dparams)[0]) 

1132 plt.plot(r, mod) 

1133 plt.axvline(tmp_params) 

1134 plt.axhline(tmp_model) 

1135 plt.grid() 

1136 plt.legend() 

1137 plt.draw() 

1138 plt.pause(1e-8) 

1139 plt.close(fig) 

1140 

1141 # prepare outputs 

1142 params_table.append(np.copy(tmp_params)) 

1143 if fit_workspace.verbose: 

1144 my_logger.info(f"\n\tIteration={i}: initial func={tmp_model[0]:.5g}" 

1145 f"\n\tParameter shifts: {dparams}" 

1146 f"\n\tNew parameters: {tmp_params[ipar]}" 

1147 f"\n\tFinal func={new_func:.5g}" 

1148 f" computed in {time.time() - start:.2f}s") 

1149 if fit_workspace.live_fit: 

1150 fit_workspace.simulate(*tmp_params) 

1151 fit_workspace.plot_fit() 

1152 fit_workspace.cov = inv_H[:, :, 0] 

1153 print("shape", fit_workspace.cov.shape) 

1154 # fit_workspace.plot_correlation_matrix(ipar) 

1155 if len(ipar) == 0: 

1156 my_logger.warning(f"\n\tGradient descent terminated in {i} iterations because all parameters " 

1157 f"have null Jacobian.") 

1158 break 

1159 if np.sum(np.abs(dparams)) / np.sum(np.abs(tmp_params[ipar])) < xtol: 

1160 my_logger.info(f"\n\tGradient descent terminated in {i} iterations because the sum of parameter shift " 

1161 f"relative to the sum of the parameters is below xtol={xtol}.") 

1162 break 

1163 if len(funcs) > 1 and np.abs(funcs[-2] - new_func) / np.max([np.abs(new_func), np.abs(funcs[-2])]) < ftol: 

1164 my_logger.info(f"\n\tGradient descent terminated in {i} iterations because the " 

1165 f"relative change of cost is below ftol={ftol}.") 

1166 break 

1167 plt.close() 

1168 return tmp_params, inv_H[:, :, 0], np.array(funcs), np.array(params_table) 

1169 

1170 

1171def print_parameter_summary(params, cov, labels): 

1172 """Print the best fitting parameters on screen. 

1173 

1174 Parameters 

1175 ---------- 

1176 params: array_like 

1177 The best fitting parameter values. 

1178 cov: array_like 

1179 The associated covariance matrix. 

1180 labels: array_like 

1181 The list of associated parameter labels. 

1182 """ 

1183 my_logger = set_logger(__name__) 

1184 txt = "" 

1185 for ip in np.arange(0, cov.shape[0]).astype(int): 

1186 txt += "%s: %s +%s -%s\n\t" % formatting_numbers(params[ip], np.sqrt(cov[ip, ip]), np.sqrt(cov[ip, ip]), 

1187 label=labels[ip]) 

1188 my_logger.info(f"\n\t{txt}") 

1189 

1190 

1191def plot_gradient_descent(fit_workspace, costs, params_table): 

1192 fig, ax = plt.subplots(2, 1, figsize=(10, 6), sharex="all") 

1193 iterations = np.arange(params_table.shape[0]) 

1194 ax[0].plot(iterations, costs, lw=2) 

1195 for ip in range(params_table.shape[1]): 

1196 ax[1].plot(iterations, params_table[:, ip], label=f"{fit_workspace.axis_names[ip]}") 

1197 ax[1].set_yscale("symlog") 

1198 ax[1].legend(ncol=6, loc=9) 

1199 ax[1].grid() 

1200 ax[0].set_yscale("log") 

1201 ax[0].set_ylabel(r"$\chi^2$") 

1202 ax[1].set_ylabel("Parameters") 

1203 ax[0].grid() 

1204 ax[1].set_xlabel("Iterations") 

1205 ax[0].xaxis.set_major_locator(MaxNLocator(integer=True)) 

1206 fig.tight_layout() 

1207 plt.subplots_adjust(wspace=0, hspace=0) 

1208 if parameters.SAVE and fit_workspace.filename != "": # pragma: no cover 

1209 figname = os.path.splitext(fit_workspace.filename)[0] + "_fitting.pdf" 

1210 fit_workspace.my_logger.info(f"\n\tSave figure {figname}.") 

1211 fig.savefig(figname, dpi=100, bbox_inches='tight') 

1212 if parameters.DISPLAY: # pragma: no cover 

1213 plt.show() 

1214 if parameters.PdfPages: # args from the above? MFL 

1215 parameters.PdfPages.savefig() 

1216 

1217 fit_workspace.simulate(*fit_workspace.p) 

1218 fit_workspace.live_fit = False 

1219 fit_workspace.plot_fit() 

1220 

1221 

1222def save_gradient_descent(fit_workspace, costs, params_table): 

1223 iterations = np.arange(params_table.shape[0]).astype(int) 

1224 t = np.zeros((params_table.shape[1] + 2, params_table.shape[0])) 

1225 t[0] = iterations 

1226 t[1] = costs 

1227 t[2:] = params_table.T 

1228 h = 'iter,costs,' + ','.join(fit_workspace.input_labels) 

1229 output_filename = os.path.splitext(fit_workspace.filename)[0] + "_fitting.txt" 

1230 np.savetxt(output_filename, t.T, header=h, delimiter=",") 

1231 fit_workspace.my_logger.info(f"\n\tSave gradient descent log {output_filename}.") 

1232 

1233 

1234def run_gradient_descent(fit_workspace, guess, epsilon, params_table, costs, fix, xtol, ftol, niter, verbose=False, 

1235 with_line_search=True): 

1236 fit_workspace.p, fit_workspace.cov, tmp_costs, tmp_params_table = gradient_descent(fit_workspace, guess, 

1237 epsilon, niter=niter, 

1238 fixed_params=fix, 

1239 xtol=xtol, ftol=ftol, 

1240 with_line_search=with_line_search) 

1241 params_table = np.concatenate([params_table, tmp_params_table]) 

1242 costs = np.concatenate([costs, tmp_costs]) 

1243 ipar = np.array(np.where(np.array(fix).astype(int) == 0)[0]) 

1244 if verbose or fit_workspace.verbose: 

1245 print_parameter_summary(fit_workspace.p[ipar], fit_workspace.cov, 

1246 [fit_workspace.input_labels[ip] for ip in ipar]) 

1247 if parameters.DEBUG and (verbose or fit_workspace.verbose): 

1248 # plot_psf_poly_params(fit_workspace.p[fit_workspace.psf_params_start_index:]) 

1249 # fit_workspace.plot_fit() 

1250 plot_gradient_descent(fit_workspace, costs, params_table) 

1251 if len(ipar) > 1: 

1252 fit_workspace.plot_correlation_matrix(ipar=ipar) 

1253 return params_table, costs 

1254 

1255 

1256def run_simple_newton_minimisation(fit_workspace, guess, epsilon, fix=None, xtol=1e-8, ftol=1e-8, 

1257 niter=50, verbose=False): # pragma: no cover 

1258 if fix is None: 

1259 fix = [False] * guess.size 

1260 fit_workspace.p, fit_workspace.cov, funcs, params_table = simple_newton_minimisation(fit_workspace, guess, 

1261 epsilon, niter=niter, 

1262 fixed_params=fix, 

1263 xtol=xtol, ftol=ftol) 

1264 ipar = np.array(np.where(np.array(fix).astype(int) == 0)[0]) 

1265 if verbose or fit_workspace.verbose: 

1266 print_parameter_summary(fit_workspace.p[ipar], fit_workspace.cov, 

1267 [fit_workspace.input_labels[ip] for ip in ipar]) 

1268 if parameters.DEBUG and (verbose or fit_workspace.verbose): 

1269 # plot_psf_poly_params(fit_workspace.p[fit_workspace.psf_params_start_index:]) 

1270 # fit_workspace.plot_fit() 

1271 plot_gradient_descent(fit_workspace, funcs, params_table) 

1272 if len(ipar) > 1: 

1273 fit_workspace.plot_correlation_matrix(ipar=ipar) 

1274 return params_table, funcs 

1275 

1276 

1277def run_minimisation(fit_workspace, method="newton", epsilon=None, fix=None, xtol=1e-4, ftol=1e-4, niter=50, 

1278 verbose=False, with_line_search=True, minimizer_method="L-BFGS-B"): 

1279 my_logger = set_logger(__name__) 

1280 

1281 bounds = fit_workspace.bounds 

1282 

1283 nll = lambda params: -fit_workspace.lnlike(params) 

1284 

1285 guess = fit_workspace.p.astype('float64') 

1286 if verbose: 

1287 my_logger.debug(f"\n\tStart guess: {guess}") 

1288 

1289 if method == "minimize": 

1290 start = time.time() 

1291 result = optimize.minimize(nll, fit_workspace.p, method=minimizer_method, 

1292 options={'ftol': ftol, 'maxiter': 100000}, bounds=bounds) 

1293 fit_workspace.p = result['x'] 

1294 if verbose: 

1295 my_logger.debug(f"\n\t{result}") 

1296 my_logger.debug(f"\n\tMinimize: total computation time: {time.time() - start}s") 

1297 fit_workspace.plot_fit() 

1298 elif method == 'basinhopping': 

1299 start = time.time() 

1300 minimizer_kwargs = dict(method=minimizer_method, bounds=bounds) 

1301 result = optimize.basinhopping(nll, guess, minimizer_kwargs=minimizer_kwargs) 

1302 fit_workspace.p = result['x'] 

1303 if verbose: 

1304 my_logger.debug(f"\n\t{result}") 

1305 my_logger.debug(f"\n\tBasin-hopping: total computation time: {time.time() - start}s") 

1306 fit_workspace.plot_fit() 

1307 elif method == "least_squares": # pragma: no cover 

1308 fit_workspace.my_logger.warning("least_squares might not work, use with caution... " 

1309 "or repair carefully the function weighted_residuals()") 

1310 start = time.time() 

1311 x_scale = np.abs(guess) 

1312 x_scale[x_scale == 0] = 0.1 

1313 p = optimize.least_squares(fit_workspace.weighted_residuals, guess, verbose=2, ftol=1e-6, x_scale=x_scale, 

1314 diff_step=0.001, bounds=bounds.T) 

1315 fit_workspace.p = p.x # m.np_values() 

1316 if verbose: 

1317 my_logger.debug(f"\n\t{p}") 

1318 my_logger.debug(f"\n\tLeast_squares: total computation time: {time.time() - start}s") 

1319 fit_workspace.plot_fit() 

1320 elif method == "minuit": 

1321 start = time.time() 

1322 # fit_workspace.simulation.fix_psf_cube = False 

1323 error = 0.1 * np.abs(guess) * np.ones_like(guess) 

1324 error[2:5] = 0.3 * np.abs(guess[2:5]) * np.ones_like(guess[2:5]) 

1325 z = np.where(np.isclose(error, 0.0, 1e-6)) 

1326 error[z] = 1. 

1327 if fix is None: 

1328 fix = [False] * guess.size 

1329 # noinspection PyArgumentList 

1330 # m = Minuit(fcn=nll, values=guess, error=error, errordef=1, fix=fix, print_level=verbose, limit=bounds) 

1331 m = Minuit(nll, np.copy(guess)) 

1332 m.errors = error 

1333 m.errordef = 1 

1334 m.fixed = fix 

1335 m.print_level = verbose 

1336 m.limits = bounds 

1337 m.tol = 10 

1338 m.migrad() 

1339 fit_workspace.p = np.array(m.values[:]) 

1340 if verbose: 

1341 my_logger.debug(f"\n\t{m}") 

1342 my_logger.debug(f"\n\tMinuit: total computation time: {time.time() - start}s") 

1343 fit_workspace.plot_fit() 

1344 elif method == "newton": 

1345 if fit_workspace.costs.size == 0: 

1346 costs = np.array([fit_workspace.chisq(guess)]) 

1347 params_table = np.array([guess]) 

1348 else: 

1349 costs = np.concatenate([fit_workspace.costs, np.array([fit_workspace.chisq(guess)])]) 

1350 params_table = np.concatenate([fit_workspace.params_table, np.array([guess])]) 

1351 if epsilon is None: 

1352 epsilon = 1e-4 * guess 

1353 epsilon[epsilon == 0] = 1e-4 

1354 if fix is None: 

1355 fix = [False] * guess.size 

1356 

1357 start = time.time() 

1358 params_table, costs = run_gradient_descent(fit_workspace, guess, epsilon, params_table, costs, 

1359 fix=fix, xtol=xtol, ftol=ftol, niter=niter, verbose=verbose, 

1360 with_line_search=with_line_search) 

1361 fit_workspace.costs = costs 

1362 fit_workspace.params_table = params_table 

1363 if verbose: 

1364 my_logger.debug(f"\n\tNewton: total computation time: {time.time() - start}s") 

1365 if fit_workspace.filename != "": 

1366 ipar = np.array(np.where(np.array(fit_workspace.fixed).astype(int) == 0)[0]) 

1367 fit_workspace.save_parameters_summary(ipar) 

1368 save_gradient_descent(fit_workspace, costs, params_table) 

1369 

1370 

1371def run_minimisation_sigma_clipping(fit_workspace, method="newton", epsilon=None, fix=None, xtol=1e-4, ftol=1e-4, 

1372 niter=50, sigma_clip=5.0, niter_clip=3, verbose=False): 

1373 my_logger = set_logger(__name__) 

1374 fit_workspace.sigma_clip = sigma_clip 

1375 for step in range(niter_clip): 

1376 if verbose: 

1377 my_logger.info(f"\n\tSigma-clipping step {step}/{niter_clip} (sigma={sigma_clip})") 

1378 run_minimisation(fit_workspace, method=method, epsilon=epsilon, fix=fix, xtol=xtol, ftol=ftol, niter=niter) 

1379 # remove outliers 

1380 if fit_workspace.data.dtype == np.object: 

1381 # indices_no_nan = ~np.isnan(np.concatenate(fit_workspace.data).ravel()) 

1382 data = np.concatenate(fit_workspace.data).ravel() # [indices_no_nan] 

1383 model = np.concatenate(fit_workspace.model).ravel() # [indices_no_nan] 

1384 err = np.concatenate(fit_workspace.err).ravel() # [indices_no_nan] 

1385 else: 

1386 # indices_no_nan = ~np.isnan(fit_workspace.data.flatten()) 

1387 data = fit_workspace.data.flatten() # [indices_no_nan] 

1388 model = fit_workspace.model.flatten() # [indices_no_nan] 

1389 err = fit_workspace.err.flatten() # [indices_no_nan] 

1390 residuals = np.abs(data - model) / err 

1391 outliers = residuals > sigma_clip 

1392 outliers = [i for i in range(data.size) if outliers[i]] 

1393 outliers.sort() 

1394 if len(outliers) > 0: 

1395 my_logger.debug(f'\n\tOutliers flat index list: {outliers}') 

1396 my_logger.info(f'\n\tOutliers: {len(outliers)} / {data.size} data points ' 

1397 f'({100 * len(outliers) / data.size:.2f}%) ' 

1398 f'at more than {sigma_clip}-sigma from best-fit model.') 

1399 if np.all(fit_workspace.outliers == outliers): 

1400 my_logger.info(f'\n\tOutliers flat index list unchanged since last iteration: ' 

1401 f'break the sigma clipping iterations.') 

1402 break 

1403 else: 

1404 fit_workspace.outliers = outliers 

1405 else: 

1406 my_logger.info(f'\n\tNo outliers detected at first iteration: break the sigma clipping iterations.') 

1407 break 

1408 

1409 

1410def run_emcee(fit_workspace, ln=lnprob): 

1411 my_logger = set_logger(__name__) 

1412 fit_workspace.print_settings() 

1413 nsamples = fit_workspace.nsteps 

1414 p0 = fit_workspace.set_start() 

1415 filename = fit_workspace.emcee_filename 

1416 backend = emcee.backends.HDFBackend(filename) 

1417 try: # pragma: no cover 

1418 pool = MPIPool() 

1419 if not pool.is_master(): 

1420 pool.wait() 

1421 sys.exit(0) 

1422 sampler = emcee.EnsembleSampler(fit_workspace.nwalkers, fit_workspace.ndim, ln, args=(), 

1423 pool=pool, backend=backend) 

1424 my_logger.info(f"\n\tInitial size: {backend.iteration}") 

1425 if backend.iteration > 0: 

1426 p0 = backend.get_last_sample() 

1427 if nsamples - backend.iteration > 0: 

1428 sampler.run_mcmc(p0, nsteps=max(0, nsamples - backend.iteration), progress=True) 

1429 pool.close() 

1430 except ValueError: 

1431 sampler = emcee.EnsembleSampler(fit_workspace.nwalkers, fit_workspace.ndim, ln, args=(), 

1432 threads=multiprocessing.cpu_count(), backend=backend) 

1433 my_logger.info(f"\n\tInitial size: {backend.iteration}") 

1434 if backend.iteration > 0: 

1435 p0 = sampler.get_last_sample() 

1436 for _ in sampler.sample(p0, iterations=max(0, nsamples - backend.iteration), progress=True, store=True): 

1437 continue 

1438 fit_workspace.chains = sampler.chain 

1439 fit_workspace.lnprobs = sampler.lnprobability 

1440 

1441 

1442class RegFitWorkspace(FitWorkspace): 

1443 

1444 def __init__(self, w, opt_reg=parameters.PSF_FIT_REG_PARAM, verbose=0, live_fit=False): 

1445 """ 

1446 

1447 Parameters 

1448 ---------- 

1449 w: ChromaticPSFFitWorkspace 

1450 """ 

1451 FitWorkspace.__init__(self, verbose=verbose, live_fit=live_fit) 

1452 self.x = np.array([0]) 

1453 self.data = np.array([0]) 

1454 self.err = np.array([1]) 

1455 self.w = w 

1456 self.p = np.asarray([np.log10(opt_reg)]) 

1457 self.bounds = [(-20, np.log10(self.w.amplitude_priors.size) + 2)] 

1458 self.input_labels = ["log10_reg"] 

1459 self.axis_names = [r"$\log_{10} r$"] 

1460 self.fixed = [False] * self.p.size 

1461 self.opt_reg = opt_reg 

1462 self.resolution = np.zeros_like((self.w.amplitude_params.size, self.w.amplitude_params.size)) 

1463 self.G = 0 

1464 self.chisquare = -1 

1465 

1466 def print_regularisation_summary(self): 

1467 self.my_logger.info(f"\n\tOptimal regularisation parameter: {self.opt_reg}" 

1468 f"\n\tTr(R) = {np.trace(self.resolution)}" 

1469 f"\n\tN_params = {len(self.w.amplitude_params)}" 

1470 f"\n\tN_data = {self.w.data.size - len(self.w.mask) - len(self.w.outliers)}" 

1471 f" (without mask and outliers)") 

1472 

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 if A.ndim == 2: # ndim == 2 when A comes from a sparse matrix computation 

1486 A = np.asarray(A).reshape(-1) 

1487 self.resolution = np.eye(A.size) - reg * cov @ self.w.Q 

1488 diff = self.w.data - self.w.M @ A 

1489 if self.w.W.ndim == 1: 

1490 self.chisquare = diff @ (self.w.W * diff) 

1491 else: 

1492 self.chisquare = diff @ self.w.W @ diff 

1493 self.w.amplitude_params = A 

1494 self.w.amplitude_cov_matrix = cov 

1495 self.w.amplitude_params_err = np.array([np.sqrt(cov[x, x]) for x in range(cov.shape[0])]) 

1496 self.G = self.chisquare / ((self.w.data.size - len(self.w.mask) - len(self.w.outliers)) - np.trace(self.resolution)) ** 2 

1497 return np.asarray([log10_r]), np.asarray([self.G]), np.zeros_like(self.data) 

1498 

1499 def plot_fit(self): 

1500 log10_opt_reg = self.p[0] 

1501 opt_reg = 10 ** log10_opt_reg 

1502 regs = 10 ** np.linspace(min(-10, 0.9 * log10_opt_reg), max(3, 1.2 * log10_opt_reg), 50) 

1503 Gs = [] 

1504 chisqs = [] 

1505 resolutions = [] 

1506 x = np.arange(len(self.w.amplitude_priors)) 

1507 for r in regs: 

1508 self.simulate(np.log10(r)) 

1509 if parameters.DISPLAY and False: # pragma: no cover 

1510 fig = plt.figure() 

1511 plt.errorbar(x, self.w.amplitude_params, yerr=[np.sqrt(self.w.amplitude_cov_matrix[i, i]) for i in x], 

1512 label=f"fit r={r:.2g}") 

1513 plt.plot(x, self.w.amplitude_priors, label="prior") 

1514 plt.grid() 

1515 plt.legend() 

1516 plt.draw() 

1517 plt.pause(1e-8) 

1518 plt.close(fig) 

1519 Gs.append(self.G) 

1520 chisqs.append(self.chisquare) 

1521 resolutions.append(np.trace(self.resolution)) 

1522 fig, ax = plt.subplots(3, 1, figsize=(7, 5), sharex="all") 

1523 ax[0].plot(regs, Gs) 

1524 ax[0].axvline(opt_reg, color="k") 

1525 ax[1].axvline(opt_reg, color="k") 

1526 ax[2].axvline(opt_reg, color="k") 

1527 ax[0].set_ylabel(r"$G(r)$") 

1528 ax[0].set_xlabel("Regularisation hyper-parameter $r$") 

1529 ax[0].grid() 

1530 ax[0].set_title(f"Optimal regularisation parameter: {opt_reg:.3g}") 

1531 ax[1].plot(regs, chisqs) 

1532 ax[1].set_ylabel(r"$\chi^2(\mathbf{A}(r) \vert \mathbf{\theta})$") 

1533 ax[1].set_xlabel("Regularisation hyper-parameter $r$") 

1534 ax[1].grid() 

1535 ax[1].set_xscale("log") 

1536 ax[2].set_xscale("log") 

1537 ax[2].plot(regs, resolutions) 

1538 ax[2].set_ylabel(r"$\mathrm{Tr}\,\mathbf{R}$") 

1539 ax[2].set_xlabel("Regularisation hyper-parameter $r$") 

1540 ax[2].grid() 

1541 fig.tight_layout() 

1542 plt.subplots_adjust(hspace=0) 

1543 if parameters.DISPLAY: 

1544 plt.show() 

1545 if parameters.LSST_SAVEFIGPATH: 

1546 fig.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'regularisation.pdf')) 

1547 

1548 fig = plt.figure(figsize=(7, 5)) 

1549 rho = compute_correlation_matrix(self.w.amplitude_cov_matrix) 

1550 plot_correlation_matrix_simple(plt.gca(), rho, axis_names=[''] * len(self.w.amplitude_params)) 

1551 # ipar=np.arange(10, 20)) 

1552 plt.gca().set_title(r"Correlation matrix $\mathbf{\rho}$") 

1553 if parameters.LSST_SAVEFIGPATH: 

1554 fig.savefig(os.path.join(parameters.LSST_SAVEFIGPATH, 'amplitude_correlation_matrix.pdf')) 

1555 if parameters.DISPLAY: 

1556 plt.show() 

1557 

1558 def run_regularisation(self): 

1559 run_minimisation(self, method="minimize", ftol=1e-4, xtol=1e-2, verbose=self.verbose, epsilon=[1e-1], 

1560 minimizer_method="Nelder-Mead") 

1561 self.opt_reg = 10 ** self.p[0] 

1562 self.simulate(np.log10(self.opt_reg)) 

1563 self.print_regularisation_summary() 

1564 

1565 

1566if __name__ == "__main__": 1566 ↛ 1567line 1566 didn't jump to line 1567, because the condition on line 1566 was never true

1567 import doctest 

1568 

1569 doctest.testmod()