def test_report_ci(confidence_interval, capsys): """Verify that the CI report is printed when using report_ci.""" report_ci(confidence_interval) captured = capsys.readouterr() assert len(captured.out) > 250 for par in confidence_interval.keys(): assert par in captured.out for interval in ['99.73', '95.45', '68.27', '_BEST_']: assert interval in captured.out
def test_ci(): np.random.seed(1) p_true = Parameters() p_true.add('amp', value=14.0) p_true.add('period', value=5.33) p_true.add('shift', value=0.123) p_true.add('decay', value=0.010) def residual(pars, x, data=None): amp = pars['amp'] per = pars['period'] shift = pars['shift'] decay = pars['decay'] if abs(shift) > pi / 2: shift = shift - np.sign(shift) * pi model = amp * np.sin(shift + x / per) * np.exp(-x * x * decay * decay) if data is None: return model return model - data n = 2500 xmin = 0. xmax = 250.0 noise = np.random.normal(scale=0.7215, size=n) x = np.linspace(xmin, xmax, n) data = residual(p_true, x) + noise fit_params = Parameters() fit_params.add('amp', value=13.0) fit_params.add('period', value=4) fit_params.add('shift', value=0.1) fit_params.add('decay', value=0.02) out = minimize(residual, fit_params, args=(x,), kws={'data': data}) fit = residual(fit_params, x) print( ' N fev = ', out.nfev) print( out.chisqr, out.redchi, out.nfree) report_errors(fit_params) ci, tr = conf_interval(out, sigmas=[0.674], trace=True) report_ci(ci) for p in out.params: diff1 = ci[p][1][1] - ci[p][0][1] diff2 = ci[p][2][1] - ci[p][1][1] stderr = out.params[p].stderr assert(abs(diff1 - stderr) / stderr < 0.05) assert(abs(diff2 - stderr) / stderr < 0.05)
def confidence_intervals(self, p_names=None, sigmas=(1, 2, 3)): """Prints a confidence intervals. Parameters ---------- p_names : {list, None}, optional Names of the parameters for which the confidence intervals are calculated. If None (default), the confidence intervals are calculated for every parameter. sigmas : {list, tuple}, optional The sigma-levels to find (default is [1, 2, 3]). See Note below. Note ---- The values for sigma are taken as the number of standard deviations for a normal distribution and converted to probabilities. That is, the default sigma=[1, 2, 3] will use probabilities of 0.6827, 0.9545, and 0.9973. If any of the sigma values is less than 1, that will be interpreted as a probability. That is, a value of 1 and 0.6827 will give the same results, within precision. """ ci = conf_interval(self.minimizer, self.result, p_names=p_names, sigmas=sigmas) report_ci(ci)
fit_params.add('amp', value=13.0) fit_params.add('period', value=2) fit_params.add('shift', value=0.0) fit_params.add('decay', value=0.02) out = minimize(residual, fit_params, args=(x,), kws={'data':data}) fit = residual(fit_params, x) print( ' N fev = ', out.nfev) print( out.chisqr, out.redchi, out.nfree) report_fit(fit_params) #ci=calc_ci(out) ci, tr = conf_interval(out, trace=True) report_ci(ci) if HASPYLAB: names=fit_params.keys() i=0 gs=pylab.GridSpec(4,4) sx={} sy={} for fixed in names: j=0 for free in names: if j in sx and i in sy: ax=pylab.subplot(gs[i,j],sharex=sx[j],sharey=sy[i]) elif i in sy: ax=pylab.subplot(gs[i,j],sharey=sy[i]) sx[j]=ax
fit_params.add('decay', value=0.02) ############################################################################### # Set-up the minimizer and perform the fit using ``leastsq`` algorithm, and # show the report: mini = Minimizer(residual, fit_params, fcn_args=(x, ), fcn_kws={'data': data}) out = mini.leastsq() fit = residual(out.params, x) report_fit(out) ############################################################################### # Calculate the confidence intervals for parameters and display the results: ci, tr = conf_interval(mini, out, trace=True) report_ci(ci) names = out.params.keys() i = 0 gs = plt.GridSpec(4, 4) sx = {} sy = {} for fixed in names: j = 0 for free in names: if j in sx and i in sy: ax = plt.subplot(gs[i, j], sharex=sx[j], sharey=sy[i]) elif i in sy: ax = plt.subplot(gs[i, j], sharey=sy[i]) sx[j] = ax elif j in sx:
np.save('2014_04_13_freq.npy',y) ## assume quantum projection noise yerr = np.arcsin(1/np.sqrt(4*100)/0.35)/(2*np.pi*ramsey_time) params = lmfit.Parameters() params.add('A', value = 0, vary = True) ##cos ### -3 cXZ sin 2 chi: 7 +- 23 mHz params.add('B', value = 0, vary = True) ##sin ### -3 cYZ sin 2 chi: 32 +- 56 mHz params.add('C', value = 0, vary = True) ##cos2 ### -1.5 (cXX-cYY) sin^2 chi: 15 +- 22 mHz params.add('D', value = 0, vary = True) ##sin2 ### -3 cXY sin^2 chi: 8 +- 20 mHz params.add('offset', value = 0.069818) result = lmfit.minimize(cosine_fit, params, args = (x, y, yerr)) fit_values = y + result.residual lmfit.report_errors(params) print "Reduced chi-squared = ", result.redchi ci = lmfit.conf_interval(result) lmfit.report_ci(ci) x_plot = np.linspace(x.min(),x.max()+100000,1000) figure = pyplot.figure(1) figure.clf() pyplot.plot(x,y,'o') pyplot.plot(x_plot,cosine_model(params,x_plot),linewidth = 3.0) pyplot.show()
## assume quantum projection noise yerr = np.arcsin(1 / np.sqrt(4 * 100) / 0.35) / (2 * np.pi * ramsey_time) params = lmfit.Parameters() params.add('A', value=0, vary=True) ##cos ### -3 cXZ sin 2 chi: 7 +- 23 mHz params.add('B', value=0, vary=True) ##sin ### -3 cYZ sin 2 chi: 32 +- 56 mHz params.add('C', value=0, vary=True) ##cos2 ### -1.5 (cXX-cYY) sin^2 chi: 15 +- 22 mHz params.add('D', value=0, vary=True) ##sin2 ### -3 cXY sin^2 chi: 8 +- 20 mHz params.add('offset', value=0.069818) result = lmfit.minimize(cosine_fit, params, args=(x, y, yerr)) fit_values = y + result.residual lmfit.report_errors(params) print "Reduced chi-squared = ", result.redchi ci = lmfit.conf_interval(result) lmfit.report_ci(ci) x_plot = np.linspace(x.min(), x.max() + 100000, 1000) figure = pyplot.figure(1) figure.clf() pyplot.plot(x, y, 'o') pyplot.plot(x_plot, cosine_model(params, x_plot), linewidth=3.0) pyplot.show()