def build_kafe_fit_and_plot_object( kafedataset, fitfunktion=kafe.function_library.linear_2par): kafefit = kafe.Fit(kafedataset, fitfunktion) kafefit.do_fit() kafeplot = kafe.Plot(kafefit) kafeplot.plot_all() return [kafefit, kafeplot]
def plot_calibration_line_kafe( x, y, y_err=0.0, x_err=0.0, directory=False, PdfPages=False, suffix='Calibration', xlabel='$\gamma$-peak position from literature [keV]', ylabel=r'$\Delta$VCAL'): hdataset = kafe.build_dataset(x, y, yabserr=y_err, xabserr=x_err, title="Data", axis_labels=[xlabel, ylabel]) hfit = kafe.Fit(hdataset, linear_2par) hfit.do_fit() hplot = kafe.Plot(hfit) hplot.plot_all() hplot.save(directory + "tdc_calibrated_data_kafe_%s.png" % suffix) PdfPages.savefig()
# kafe # last modified: 27-JUL-31 <initial version> # 06-AUG-14 changed to use buildFit_fromFile() # 09-OCT-14 added section to plot contour # 05-Dec-14 more comfortable contour plotting #--------------------------------------------------------------------- # import everything we need from kafe import kafe # import helper function to parse the input file from kafe.file_tools import buildFit_fromFile # import matplotlib.pyplot as plt # # --------------------------------------------------------- fname = 'LEP-Data.dat' # initialize fit object from file BWfit = buildFit_fromFile(fname) BWfit.do_fit() # BWplot = kafe.Plot(BWfit) BWplot.plot_all() BWplot.save("kafe_BreitWignerFit.pdf") # plot contours and profiles BWfit.plot_correlations() # show everything plt.show()
my_dataset[1].add_error_source('y', 'simple', 0.01) my_dataset[1].add_error_source('x', 'simple', 0.01) #my_dataset[0]=kafe.Dataset(data=data1) #my_dataset[1]=kafe.Dataset(data=data2) #my_dataset.add_error_source() my_fits = [ kafe.Fit(dataset, linear_2par, fit_label="Linear regression") for dataset in my_dataset ] for fit in my_fits: fit.do_fit() my_plot = kafe.Plot(my_fits[0], my_fits[1]) my_plot.axis_labels = ['Drehfrequenz$[Hz]$', 'Nutationsfrequenz$[Hz]$'] my_plot.axis_units = ['$Hz$', '$Hz$'] my_plot.plot_all() my_plot.save('kafe_nutation.pdf') my_plot.show() #plt.plot(time1,dF1,'r+',label = "Messung der Nutations") #plt.plot(time2,dF2,'b+') #plt.xlabel("Drehfrequenz(Hz)") #plt.ylabel("Nutationsfrequenz(Hz)") #plt.grid() #plt.show()
def __init__(self,Multifit): self.fits = [] self.subplots = [] for fit in Multifit.fit_list: self.fits.append(fit) self.subplots.append(kafe.Plot(fit))
def kFit(func, x, y, sx, sy, p0=None, p0e=None, xabscor=None, yabscor=None, xrelcor=None, yrelcor=None, title='Daten', axis_labels=['X', 'Y'], plot=True, quiet=False): """ fit function func with errors on x and y; uses package `kafe` Args: * func: function to fit * x: np-array, independent data * y: np-array, dependent data the following are single floats or arrays of length of x * sx: scalar or np-array, uncertainty(ies) on x * sy: scalar or np-array, uncertainty(ies) on y * p0: array-like, initial guess of parameters * p0e: array-like, initial guess of parameter uncertainties * xabscor: absolute, correlated error(s) on x * yabscor: absolute, correlated error(s) on y * xrelcor: relative, correlated error(s) on x * yrelcor: relative, correlated error(s) on y * title: string, title of gaph * axis_labels: List of strings, axis labels x and y * plot: flag to switch off graphical ouput * quiet: flag to suppress text and log output Returns: * np-array of float: parameter values * np-array of float: parameter errors * np-array: cor correlation matrix * float: chi2 \chi-square """ # regression with kafe import kafe # create a data set ... dat = kafe.Dataset(data=(x,y), title=title, axis_labels=axis_labels, basename='kRegression') # ... and add all error sources dat.add_error_source('x','simple',sx) dat.add_error_source('y','simple',sy) if xabscor != None: dat.add_error_source('x','simple', xabscor, correlated=True) if yabscor != None: dat.add_error_source('y','simple', yabscor, correlated=True) if xrelcor != None: dat.add_error_source('x','simple', xrelcor, relative=True, correlated=True) if yrelcor != None: dat.add_error_source('y','simple', yrelcor, relative=True, correlated=True) # set up and run fit fit = kafe.Fit(dat, func) if p0 is not None: fit.set_parameters(p0, p0e) fit.do_fit(quiet=quiet) # harvest results # par, perr, cov, chi2 = fit.get_results() # for kafe vers. > 1.1.0 par = np.array(fit.final_parameter_values) pare = np.array(fit.final_parameter_errors) cor = fit.par_cov_mat/np.outer(pare, pare) chi2 = fit.minimizer.get_fit_info('fcn') if(plot): kplot=kafe.Plot(fit) kplot.plot_all() kplot.show() return par, pare, cor, chi2
def kRegression(x, y, sx, sy, xabscor=None, yabscor=None, xrelcor=None, yrelcor=None, title='Daten', axis_labels=['X', 'Y'], plot=True, quiet=False): """ linear regression y(x) = ax + b with errors on x and y; uses package `kafe` Args: * x: np-array, independent data * y: np-array, dependent data the following are single floats or arrays of length of x * sx: scalar or np-array, uncertainty(ies) on x * sy: scalar or np-array, uncertainty(ies) on y * xabscor: absolute, correlated error(s) on x * yabscor: absolute, correlated error(s) on y * xrelcor: relative, correlated error(s) on x * yrelcor: relative, correlated error(s) on y * title: string, title of gaph * axis_labels: List of strings, axis labels x and y * plot: flag to switch off graphical ouput * quiet: flag to suppress text and log output Returns: * float: a slope * float: b constant * float: sa sigma on slope * float: sb sigma on constant * float: cor correlation * float: chi2 \chi-square """ # regression with kafe import kafe from kafe.function_library import linear_2par # create a data set ... dat = kafe.Dataset(data=(x,y), title=title, axis_labels=axis_labels, basename='kRegression') # ... and add all error sources dat.add_error_source('x', 'simple', sx) dat.add_error_source('y', 'simple', sy) if xabscor != None: dat.add_error_source('x', 'simple', xabscor, correlated=True) if yabscor != None: dat.add_error_source('y', 'simple', yabscor, correlated=True) if xrelcor != None: dat.add_error_source('x', 'simple', xrelcor, relative=True, correlated=True) if yrelcor != None: dat.add_error_source('y', 'simple', yrelcor, relative=True, correlated=True) # set up and run fit fit = kafe.Fit(dat, linear_2par) fit.do_fit(quiet=quiet) # harvest results # par, perr, cov, chi2 = fit.get_results() # for kafe vers. > 1.1.0 # a = par[0] # b = par[1] # sa = perr[0] # sb = perr[1] # cor = cov[1,0]/(sa*sb) a = fit.final_parameter_values[0] b = fit.final_parameter_values[1] sa = fit.final_parameter_errors[0] sb = fit.final_parameter_errors[1] cor = fit.par_cov_mat[1,0]/(sa*sb) chi2 = fit.minimizer.get_fit_info('fcn') if(plot): kplot=kafe.Plot(fit) kplot.plot_all() kplot.show() return a, b, sa, sb, cor, chi2
def plot_tdc_gamma_spectrum_kafe(self, cluster_hist=False, p0=None, scan_parameter_range=False, cols=[0], rows=[0], title=False, cluster_background=False, background=True, PdfPages=False, Directory=None): Delta_Vcal_max = scan_parameter_range[-1] Delta_Vcal_min = 0 # scan_parameter_range[0] bin_size = 1 tdc_data = au.get_pixel_data(cluster_hist, cols, rows, test="delta_vcal") hist_data, edges = np.histogram(tdc_data, bins=np.arange(Delta_Vcal_min, Delta_Vcal_max, bin_size)) x, y = edges[:-1], hist_data y_err = np.sqrt(y) hdataset = kafe.build_dataset(x, y, yabserr=y_err, title="Data for %s source" % title, axis_labels=['x', 'y']) # error for bins with zero contents is set to 1. covmat = hdataset.get_cov_mat("y") for i in range(0, len(covmat)): if covmat[i, i] == 0.: covmat[i, i] = 1. hdataset.set_cov_mat('y', covmat) # write it back # Create the Fit instance if len(p0) > 3: #hfit1 = kafe.Fit(hdataset, gauss, fit_label="Fit of a Gaussian to histogram data 1") # hfit1.set_parameters(mean=p0[2], sigma=p0[4], scale=p0[0], no_warning=True) hfit2 = kafe.Fit(hdataset, gauss, fit_label="Fit of a Gaussian to histogram data 2") hfit2.set_parameters(mean=p0[3], sigma=p0[5], scale=p0[1], no_warning=True) # hfit1.do_fit() hfit2.do_fit() hplot = kafe.Plot(hfit2) else: hfit = kafe.Fit(hdataset, gauss, fit_label="Fit of a Gaussian to histogram data") hfit.set_parameters(mean=p0[1], sigma=p0[2], scale=p0[0], no_warning=True) # perform an initial fit with temporary errors (minimal output) hfit.call_minimizer(final_fit=True, verbose=False) hfit.do_fit() hplot = kafe.Plot(hfit) hfit.get_parameter_values() # re-set errors using model at pre-fit parameter values: # sigma_i^2=cov[i, i]=n(x_i) #fdata = hfit.fit_function.evaluate(hfit.xdata, hfit.current_parameter_values) #np.fill_diagonal(covmat, fdata) # hfit.current_cov_mat = covmat # write back new covariance matrix # now do final fit with full output hplot.plot_all() hplot.save(Directory + "\h5_files" + "tdc_calibrated_data_kafe_%s.png" % title) PdfPages.savefig()
#generate_dataset('dataset.dat') # Initialize the Dataset my_dataset = kafe.Dataset(title="Example dataset", axis_labels=['t', 'A']) # Load the Dataset from the file my_dataset.read_from_file(input_file='dataset.dat') # Create the Fit my_fit = kafe.Fit(my_dataset, exponential) # Do the Fit my_fit.do_fit() # Create the plots my_plot = kafe.Plot(my_fit) # Draw the plots my_plot.plot_all() ############### # Plot output # ############### # Save the plots my_plot.save('kafe_example3.pdf') cor_fig = my_fit.plot_correlations() cor_fig.savefig('kafe_example3_correlations.pdf') # Show the plots
# GQ 27-JUL-14 <initial version> #--------------------------------------------------------------------- # import everything we need from kafe import kafe from kafe.function_library import constant_1par from kafe.file_tools import buildDataset_fromFile # # --------------------------------------------------------- # begin execution fname = 'WData.dat' # build a kafe Dataset from input file curDataset = buildDataset_fromFile(fname) # perform fit curFit = kafe.Fit(curDataset, constant_1par) curFit.do_fit() print "average:", curFit.get_parameter_values() print "error :", curFit.get_parameter_errors() myPlot = kafe.Plot(curFit) myPlot.plot_all() myPlot.save("kafe_example4.pdf") myPlot.show()
# Initialize the Dataset my_dataset = kafe.Dataset(title="Example Dataset", axis_labels=['t', 'A'] ) # Load the Dataset from the file my_dataset.read_from_file(input_file='dataset.dat') # Create the Fit my_fit = kafe.Fit(my_dataset, exponential) # Do the Fit my_fit.do_fit() # Create the plots my_plot = kafe.Plot(my_fit, yscale='log', yscalebase=10) #OR: #my_plot.set_axis_scale('y', 'log', basey=2) # Draw the plots my_plot.plot_all() ############### # Plot output # ############### # Save the plots my_plot.save('kafe_example3.pdf') cor_fig = my_fit.plot_correlations() cor_fig.savefig('kafe_example3_correlations.pdf')
# Generate y-axis data from model my_y_data = list(map(lambda x: gauss_2par(x, 0, 1), my_x_data)) # Construct the Datasets my_dataset = kafe.Dataset(data=(my_x_data, my_y_data), title="Standard-Normalverteilung") # Fit the model to the data my_fit = kafe.Fit(my_dataset, gauss_2par, fit_label='Standard-Normalverteilung') # Don't call do_fit for this Fit. # Plot the Fit my_plot = kafe.Plot(my_fit, show_legend=True) # Instruct LaTeX to use the EulerVM package (optional, uncomment if needed) #plt.rcParams.update({'text.latex.preamble': ['\\usepackage{eulervm}']}) # Draw the Plots my_plot.plot_all( show_info_for='all', # include every fit in the info box show_data_for=None) # don't show the points, just the curve ######################### # Further customization # ######################### # Use the axes property of Plot objects to do some # additional matplotlib things (annotations, etc.)
# ---- fit function definition in kafe style # (decorators for nice output not mandatory) @ASCII(expression='k * ( x - xO ) + c') @LaTeX(name='f', parameter_names=('k', 'c', 'xO'), expression=r'k\,(x+\tilde{x})\,+c') @FitFunction def lin(x, k=1.0, c=0.0): return k * (x + xO) + c # ---- begin of fit --- # set the function fitf = lin # own definition #fitf=quadratic_3par # or from kafe function library # --------- begin of workflow ---------------------- # set data kdata = kafe.Dataset(data=(m, s), basename='kData', title='example data') kdata.add_error_source('y', 'simple', 1.0) kfit = kafe.Fit(kdata, fitf) # create the fit kfit.do_fit() # perform fit print(kfit) kplot = kafe.Plot(kfit) # create plot object kplot.axis_labels = ['x', 'Daten und f(x)'] kplot.plot_all() # make plots kplot.save('Blatt6_b_fit.pdf') kplot.show()
kData_T_U.add_error_source('x', 'simple', sigU) kData_T_U.add_error_source('y', 'simple', sigT) # construct and do the fit using a quadratic model (parabola) kFit_T_U_empirical = kafe.Fit(kData_T_U, empirical_T_U_model, fit_name='u-t-fit-quadratic') kFit_T_U_empirical.do_fit() # store the fit results in variables for later use quadratic_par_values = kFit_T_U_empirical.get_parameter_values() quadratic_par_errors = kFit_T_U_empirical.get_parameter_errors() quadratic_par_covariance = kFit_T_U_empirical.get_error_matrix() # plot the results (optional) kPlot_T_U_empirical = kafe.Plot(kFit_T_U_empirical) kPlot_T_U_empirical.plot_all() kPlot_T_U_empirical.save("kafe_example11_TU.png") # Step 2: fit the relation I(U) using the empirical model # construct a kafe dataset kData_I_U = kafe.Dataset(data=(U, I), basename='u-i-data', title='Current vs. Voltage', axis_labels=['U [V]', 'I [A]']) # declare errors on U and I kData_I_U.add_error_source('x', 'simple', sigU) kData_I_U.add_error_source('y', 'simple', sigI)
hlines, data1 = ppk.readCSV("praezession.csv", nlhead=1) print(hlines) time, dF = data1 my_dataset = kafe.Dataset(data=data1, title="Praezession", axis_labels=['Drehfrequenz', 'Umlaufdauer'], axis_units=['$Hz$', '$s$']) my_dataset.add_error_source('x', 'simple', 0.01) my_dataset.add_error_source('y', 'simple', 0.99) #my_dataset=kafe.Dataset(data=data1) my_fits = [kafe.Fit(my_dataset, linear_2par)] for fit in my_fits: fit.do_fit() my_plot = kafe.Plot(my_fits[0]) my_plot.plot_all() my_plot.save('kafe_praezession.pdf') my_plot.show() #plt.plot(time,dF,'r+',label = "Messung der Daempfung") #plt.xlabel("t(min)") #plt.ylabel("Drehfrequenz(Hz)") #plt.grid() #plt.show()
dat.add_error_source('x','simple', sigx_abs) dat.add_error_source('x','simple', sxrelcor, relative=True, correlated=True) ey = np.absolute(sigy_rel* ydat * np.ones(nd)) # array of relative y errors dat.add_error_source('y','simple', ey) dat.add_error_source('y','simple', syabscor, correlated=True) # set-up the fit ... fit = kafe.Fit(dat, model) # ... run it ... fit.do_fit(quiet=False) # ... harvest results in local variables par, par_err, cov, chi2 = fit.get_results() # for kafe vers. > 1.1.0 cor = cov/np.outer(par_err, par_err) # produce plots kplot=kafe.Plot(fit) kplot.plot_all() #kplot.show() # plt.draw(); plt.pause(2.) # show plot for 2s. # save input data as table (in include-direcotory for LaTeX) data = np.array([xdat, sigx_abs*np.ones(nd), ydat, ey]) if writeTexTable('analysis/Table1.tex', data, cnames=['X', '$\\sigma_X$', 'Y', '$\\sigma_Y$' ], caption='ToyData; außer den in der Tabelle ' + 'angegbenen Unsicherheiten gibt es noch eine ' + 'gemeinsame Unsicherheit von ' + str(syabscor) + ' auf die Y-Werte und eine gemeinsame relative' + ' Unsicherheit von ' + str(sxrelcor*100) + '\\% auf die X-Werte.', fmt='%.4g' ) :