Using ufit as a library¶
Full noninteractive usage¶
The ufit.lab module¶
This module is a combination of pylab and ufit imports. You can do
from ufit.lab import *
at the top of your script and have all pylab (numpy + plotting) and ufit API available.
Loading data¶
- ufit.set_datatemplate(template)¶
Set a new template for data file names.
Normally, data file names consist of a fixed part and a sequential number. Therefore ufit constructs file names from a data template, which should contain a placeholder like %06d (for a 6-digit sequential number), and the actual file number given in the read_data() function.
An example:
set_datatemplate('/data/exp/data2012n%06d.dat') d1 = read_data(100) d2 = read_data(101) # etc.
- ufit.set_dataformat(format)¶
Set the input data format.
Normally ufit autodetects file formats, but this can be overridden using this function. Data formats are:
- 'ill' - ILL TAS data format
- 'llb' - LLB binary TAS data format (known working for data from 1T and 4F unpolarized)
- 'nicos' - NICOS data format
- 'old nicos' - NICOS 1.0 data format
- 'trisp' - FRM-II TRISP data format
- 'taipan' - ANSTO Taipan data format
- 'simple' - simple whitespace-separated multi-column files
- 'simple comma-separated' - simple comma-separated multi-column files
- ufit.read_data(n, xcol='auto', ycol='auto', dycol=None, ncol=None, nscale=1)¶
Read a data file. Returns a Dataset object.
Parameters: - xcol – X column name (or 1-based index)
- ycol – Y column name (or 1-based index)
- ycol – Y errors column name (or 1-based index); the default is to take the square root of the Y column as appropriate for counts
- ncol – normalization column name (or 1-based index); typically a beam monitor column
- nscale – scale for the normalization column; the Y data is determined as y[i] = y_raw[i] / ncol[i] * nscale
- ufit.read_numors(nstring, binsize, xcol='auto', ycol='auto', dycol=None, ncol=None, nscale=1)¶
Read a number of data files. Returns a list of Datasets.
Parameters: - nstring – A string that gives file numbers, with the operators given below.
- binsize – Bin size when files need to be merged according to nstring.
Other parameters as in read_data().
nstring can contain these operators:
- , – loads multiple files
- - – loads multiple sequential files
- + – merges multiple files
- > – merges multiple sequential files
For example:
- '10-15,23' loads files 10 through 15 and 23 in 7 separate datasets.
- '10+11,23+24' loads two datasets consisting of files 10 and 11 merged into one set, as well as files 23 and 24.
- '10>15+23' merges files 10 through 15 and 23 into one single dataset.
- '10,11,12+13,14' loads four sets.
- class ufit.Dataset¶
- name¶
The name of the dataset, usually the file number.
- x¶
- y¶
- dy¶
The X, Y and Y error data as used for fitting. Normalization is already performed on these array.
- mask¶
A boolean array of the same size as the data. Data points for which this array is False are not used for fitting. This can be used to mask out “bad” datapoints.
- fitmin¶
- fitmax¶
If not None, these two attributes can be used to restrict the X range of the data that is used for fitting, similar to mask.
- plot(axes=None, symbols=True, lines=False, **kw)¶
Plot the dataset using matplotlib.
axes is a matplotlib Axes object, as returned by gca(). If no axes are given, the current figure is used.
symbols and lines control whether the data is plotted using symbols, lines or both.
- merge(binsize, *others, **settings)¶
Merge this dataset with others.
The X values are redistributed into bins according to the given bin size.
Constructing models¶
- class ufit.Model¶
- add_params(**params)¶
Add parameters that referenced by expressions in other parameters.
For example, in this model
m = Gauss('p1', pos='delta', ampl=5, fwhm=0.5) + \ Gauss('p2', pos='-delta', ampl='p1_ampl', fwhm='p1_fwhm')
the parameter “delta” is referenced by two parameter expressions, but does not appear as a parameter of any of the model functions. This parameter must be made known to the model by calling e.g.
m.add_params(delta=0)
- fit(data, **kw)¶
Fit the model to the data. data must be a Dataset object.
Any keywords will be passed to the raw fitting routine of the backend.
- global_fit(datas, **kw)¶
Fit the model to multiple datasets, given as a list by datas.
Any keywords will be passed to the raw fitting routine of the backend.
See Global fits.
- plot(data, axes=None, labels=True, pdict=None, **kw)¶
Plot the model and the data in the current figure.
- plot_components(data, axes=None, labels=True, pdict=None, **kw)¶
Plot subcomponents of the model in the current figure.
See Model components.
- ufit.fixed(p)¶
Mark the parameter value as fixed.
The fixed() wrapper can also be omitted; any string means that a parameter as a fixed value that can include references to other parameters.
- ufit.expr(e)¶
Mark the parameter value as an expression.
The expr() wrapper can also be omitted; any string means that a parameter as a fixed value that can include references to other parameters.
- ufit.overall(v)¶
Mark the parameter as an “overall” (global) parameter in a global fit.
The argument can be another parameter definition, e.g. overall(limited(0, 10, 2)).
- ufit.datapar(v)¶
Mark the parameter as coming from the data file’s metadata.
datapar('foo') is equivalent to expr('data.foo').
- ufit.limited(self, min, max, v)¶
Give parameter limits together with the initial value.
Example use:
Gauss('peak', pos=0, ampl=limited(0, 100, 50), fwhm=1)
Working with results¶
- class ufit.Result¶
- params¶
The final list of parameters, as Param objects.
- paramdict¶
The final parameters, keyed by name.
- paramvalues¶
A dictionary mapping parameter names to parameter values only.
- paramerrors¶
A dictionary mapping parameter names to parameter errors only.
- values¶
A list of values for each parameter.
- errors¶
A list of errors for each parameter.
- results¶
A list of values, then errors for each parameter and the chi-squared value.
- residuals¶
An array of the residuals.
- plot(axes=None, params=True, multi=False)¶
Plot the data and model together in the current figure.
If params is true, also plot parameter values as text.
- plotfull(axes=None, params=True)¶
Plot the data and model, including subcomponents, together in the current figure or the given axes.
If params is true, also plot parameter values as text.
- printout()¶
Print out a table of the fit result and the parameter values.
The chi-square value is also included in the table. Example output:
Fit results for 373 --------------------------------------------------------------------- bkgd = 5.5111 +/- 0.21427 slope = -1.0318 +/- 0.16187 inc_pos = -0.015615 +/- 0.00066617 inc_ampl = 547.21 +/- 8.0482 inc_fwhm = 0.12656 +/- 0.0012489 dho_center = -0.015615 +/- 0 (fixed: inc_pos) dho_pos = 0.41689 +/- 0.0086916 dho_ampl = 0.36347 +/- 0.034156 dho_gamma = 0.22186 +/- 0.025093 dho_tt = 16 +/- 0 (fixed: data.T) chi^2/NDF = 1.491 =====================================================================
Scripting usage with GUI assistance¶
For harder fitting problems, it is often impossible to select good initial parameter values that will make the fit succeed. For these cases, ufit provides the fitting part of the full GUI for a combination of noninteractive processing with interactive fitting.
- ufit.gui.start_fitter(model, data, fit=True)¶
Start the GUI fitter component with the given model and dataset. The user can start the fitting process and change parameter values iteratively. If fit is true, a first fitting pass is started automatically with the initial parameter values.
The function returns a Result object with the last fit result after the user clicks “Close”.
Usage example:
# ... (import ufit and load data) data = read_data(...) # create a model of a simple Gaussian peak with given initial guess model = Background() + Gauss('peak', pos=97.5, ampl=100, fwhm=0.5) # fit the model, then print and plot the result result = start_fitter(model, data) # now process the result further, e.g. print the result result.printout()
A similar method exists to let the user select the data file with a GUI, and then do further processing automatically (or call start_fitter() at some point):
- ufit.gui.start_loader()¶
Start the GUI data loader component. The user can preview data files and finally click “Open”, after which the function returns a list of datasets loaded.