qensfit.qensfit
Main API module
Functions
|
Loading function for Mantid data saved in ASCII format using SaveAscii. |
Classes
|
Object which takes in the target fit function, a list of |
|
Parameter List object. |
|
Object that basicaly reimplements a float (with all its implicit methods) with added attributes to make it fit-compatible. |
|
Dataset object which can be instantiated by itself, provided with suitable data, or it can be automatically created by the load_ascii function. |
|
Contains the results of the fit. |
- class qensfit.qensfit.Model(func: callable, parlist: list, datasets: dict = None, **kwargs)
Bases:
objectObject which takes in the target fit function, a list of
Parameter, and the input data in the form of a dictionary ofQENSDataset. A dictionary ofQENSResultis generated whenModel.run_fit()is called.- target
Target function to be used as a model to run the fit. Because of the way the arguments are parsed from the target’s signature, it is necessary to explicitly declare the independent variable as a positional-only argument (before the /), the parameters as positional or keyword arguments (between the / and the *), and q and/or other constants as keyword-only arguments (after the *). Example:
def fit_func(x, /, par1, par2, *, const1): return const1 + (par1 * x) + np.exp(x / par2)
- Type:
callable
- pnames
List of parameter names as inspected from the target function.
- Type:
list
- cnames
List of constant names as inspected from the target function.
- Type:
list
- ds
Dictionary containing the input QENSDatasets.
- Type:
dict
- constants
Dictionary containing constants that need to be passed to the fitting function (if any exists)
- Type:
dict
- res
Dictionary containing the output QENSResults.
- Type:
dict
- n_ds
Number of Datasets used in the fit.
- Type:
int
- _par_cycler
Plot cycler object, which needs to be stored in memory for the buttons to still work.
- Type:
- __init__(func: callable, parlist: list, datasets: dict = None, **kwargs)
Initialise the Model object.
- Parameters:
func (callable) – Target function to be used as a model to run the fit.
parlist (list) – List of Parameters. The order is not important, as the constructor fuction will inspect the target function’s signature, and then reorder the Parameters passed in this list as they appear in the target function. If a Parameter is missing from this list while it is present in the target function, an error will be raised.
datasets (dict, optional) – Dictionary containing the input QENSDatasets. The default is None.
**kwargs (TYPE) – Constants have to be passed as keyword arguments, so that they can be interpreted as a dictionary.
- Raises:
RuntimeError – An error is raised if no input data is provided.
- Return type:
None.
- plot_fits(data_only: bool = False, xlabel: str = 'E (meV)', ylabel: str = 'Scattering Intensity (A.U.)', **plt_kw)
Plots the input data and the fits together, with residuals, in a single window which can be cycled through.
- Parameters:
data_only (bool, optional) – Lets the user decide if they want to only plot the input data, or data and fit together. The default is False.
xlabel (str, optional) – Label for the x axis. The default is ‘E (meV)’.
ylabel (str, optional) – Label for the y axis. The default is ‘Scattering Intensity (A.U.)’.
**plt_kw (TYPE) – Keyword arguments passed to matplotlib.pyplot.errorbar (i.e. formatting styles, etc.). Refer to the matplotlib documentation for more details.
- Return type:
None.
- plot_fits_grouped(data_only: bool = False, xlabel: str = 'E (meV)', ylabel: str = 'Scattering Intensity (A.U.)', **plt_kw)
Plots the input data and the fits together, with residuals, in a single window which can be cycled through. Use this in case of many 1D datasets as opposed to few 2D datasets.
- Parameters:
data_only (bool, optional) – Lets the user decide if they want to only plot the input data, or data and fit together. The default is False.
xlabel (str, optional) – Label for the x axis. The default is ‘E (meV)’.
ylabel (str, optional) – Label for the y axis. The default is ‘Scattering Intensity (A.U.)’.
**plt_kw (TYPE) – Keyword arguments passed to matplotlib.pyplot.errorbar (i.e. formatting styles, etc.). Refer to the matplotlib documentation for more details.
- Return type:
None.
- plot_par(index: str = 'q', x_title: str = '$q\\ (\\AA^{-1})$', x_title_glob: str = '$T\\ (K)$', **pltpar_kw)
Plots the Parameter values, for both free and global parameters separately.
- Parameters:
index (str, optional) – Index to be used as the x axis to plot free parameters. The default is ‘q’, but it can be another string corresponding to any key in the constants dictionary (provided that it has the same number of entries as the number of fitted curves).
x_title (str, optional) – x axis label for the free parameters plot. The default is r’$q(AA^{-1})$’.
x_title_glob (str, optional) – x axis label for the global parameters plot. The default is r’$T(K)$’.
**pltpar_kw (TYPE) – Keyword arguments passed to matplotlib.pyplot.errorbar (i.e. formatting styles, etc.). Refer to the matplotlib documentation for more details.
- Return type:
None.
- plot_par_grouped(index: str = 'ds', x_title: str = '$q\\ (\\AA^{-1})$', **pltpar_kw)
Plots the Parameter values for all datasets in the same graph. Useful when fitting many datasets separately, as the standard plot_par would return graphs with only one point in them. This method does not plot global parameters as it assumes that only one curve is present in each dataset.
- Parameters:
index (str, optional) – Index to be used as the x axis to plot free parameters. The default is ‘ds’, which will use the keys in the dataset dictionary. A custom array can be provided.
x_title (str, optional) – x axis label for the free parameters plot. The default is r’$q(AA^{-1})$’.
**pltpar_kw (TYPE) – Keyword arguments passed to matplotlib.pyplot.errorbar (i.e. formatting styles, etc.). Refer to the matplotlib documentation for more details.
- Return type:
None.
- run_fit(plot: bool = False, autosave: bool = False)
Method that runs the fit, generates the QENSResult objects, and places them in a dictionary accessible as
Model.res.- Parameters:
plot (bool, optional) – Lets the user decide if they want to plot all the fits and parameters automatically without having to call the plot functions. For more customisation of the plots, set to False, then call the plot functions yourself to pass more arguments to plt.errorbar. The default is False.
autosave (bool, optional) – Lets the user decide if they want to save all the results (fits and parameters) automatically without having to call the save functions. To change the save directory from the default, set to False, and call the save functions separately, indicating the path explicitly. The default is False.
- Return type:
None.
- save_fits(folder: str = 'results/')
Saves fit data in a csv file for each dataset, in the same format as the input data from Mantid. The data is saved in blocks, each separated by a line containing the q value. Each block contains five columns separated by commas: X, Y, dY (uncertainties), X_fit and Y_fit. Filenames will be the same as the dataset names.
WARNING: X_fit and Y_fit have different dimensions than X, Y and dY, because the fit arrays are denser for plotting reasons.
- Parameters:
folder (str, optional) – Directory in which the files are saved. The default is ‘results/’.
- Return type:
None.
- save_par(index: str = 'q', x_title: str = 'q (A^-1)', x_title_glob: str = 'T (K)', folder: str = 'results/')
Saves files containing the values of the best fit parameters and their uncertainties. A file with the free parameters will be saved for each dataset (and named like the dataset), plus one file containing all the global parameters. The files are comma-separated and contain columns for each parameter and its uncertainty.
- Parameters:
index (str, optional) – Index to be used as the x axis to plot free parameters. The default is ‘q’, but it can be another string corresponding to any key in the constants dictionary (provided that it has the same number of entries as the number of fitted curves).
x_title (str, optional) – x axis label for the free parameters plot. The default is ‘q (A^-1)’.
x_title_glob (str, optional) – x axis label for the global parameters plot. The default is ‘T (K)’.
folder (str, optional) – Directory in which the files are saved. The default is ‘results/’.
- Return type:
None.
- class qensfit.qensfit.ParList(parlist: list = None, curves: int = 1)
Bases:
objectParameter List object. Contains the Parameters in both list and dictionary formats, a list of parameter names, number of free, fixed or global parameters.
The ParList object itself can be indexed both like an array (requires knowledge of the order of paramters), and like a dictionary (using parameter names as the key).
All the pack and unpack functions shouldn’t be needed, as they’re only used when curve_fit is called, as it only accepts 1D inputs.
- n_curves
Number of curves to be fitted simultaneously by the
Modelobject.- Type:
int
- dict
Contains the
Parameterobjects in dictionary form. The keys areParameter.name.- Type:
dict
- names
List containing the names of the Parameters.
- Type:
list of str
- n_free
Number of free Parameters that are being used in the fit (i.e. the Parameter has a different value for each fitted curve).
- Type:
int
- n_fixed
Number of fixed Parameters that are being used in the fit (i.e. the Parameter has a value that is fixed to its initial value by the user).
- Type:
int
- n_global
Number of global Parameters that are being used in the fit (i.e. the Parameter has the same value for all fitted curves, but it is allowed to change between the bounds).
- Type:
int
- n_total
Total number of Parameters that are being used in the fit (i.e. n_curves * (n_free + n_fixed) + n_global).
- Type:
int
- values
1D array containing the values of all parameters. WARNING: Use only in conjunction with curve_fit. The proper way of getting a parameter value should be by using the dict or list, so that the name can be checked.
- Type:
np.ndarray
- errors
1D array containing the uncertainties of all parameters. WARNING: Use only in conjunction with curve_fit. The proper way of getting a parameter uncertainty should be by using the dict or list, so that the name can be checked.
- Type:
np.ndarray
- __init__(parlist: list = None, curves: int = 1)
Initialize the ParList instance.
- Parameters:
parlist (list, optional) – List containing the Parameter objects to add. The default is None.
curves (int, optional) – Number of curves to be fitted simultaneously using those parameters. The default is 1.
- Return type:
None.
- add_par(par)
Adds a parameter to the ParList instance.
- Parameters:
par (TYPE) – Parameter object to be added (required).
- Return type:
None.
- all_to_df(index=None, index_title=None) DataFrame
Returns a pandas.DataFrame containing the values and uncertainties for all the parameters (free and global). The index and its title can be customised.
- Parameters:
index (TYPE, optional) – Index values for the DataFrame. The default is None.
index_title (TYPE, optional) – Index title for the DataFrame. The default is None.
- Returns:
df – DataFrame containing the values and uncertainties for all the parameters (free and global) as columns.
- Return type:
pandas.DataFrame
- all_to_df_noerr() DataFrame
Returns a pandas.DataFrame containing the values for all the parameters (free and global). No uncertainties are provided!
- Returns:
df – DataFrame containing the values for all the parameters (free and global) as columns. No uncertainties are provided!
- Return type:
pandas.DataFrame
- free_to_df(index=None, index_title=None) DataFrame
Returns a pandas.DataFrame containing the values and uncertainties for all the free parameters. The index and its title can be customised.
- Parameters:
index (TYPE, optional) – Index values for the DataFrame. The default is None.
index_title (TYPE, optional) – Index title for the DataFrame. The default is None.
- Returns:
df – DataFrame containing the values and uncertainties for all the free parameters as columns.
- Return type:
pandas.DataFrame
- global_to_df(index=[1], index_title=None) DataFrame
Returns a pandas.DataFrame containing the values and uncertainties for the global parameters. This will have different dimensions than the DataFrame returned by all_to_df() or free_to_df(), as each global parameter will correspond to multiple curves. The index and its title can be customised.
- Parameters:
index (TYPE, optional) – Index values for the DataFrame. The default is [1].
index_title (TYPE, optional) – Index title for the DataFrame. The default is None.
- Returns:
df – DataFrame containing the values and uncertainties for the global parameters as columns.
- Return type:
pandas.DataFrame
- pack_errors(vector: ndarray)
Packs the provided uncertaintiesinto the Parameter objects into the ParList. WARNING: don’t use if you don’t know EXACTLY the order of the parameters!
- Parameters:
vector (numpy.ndarray) – Array containing the uncertainties to be packed.
- Return type:
None.
- pack_values(vector: ndarray)
Packs the provided values into the Parameter objects into the ParList. WARNING: don’t use if you don’t know EXACTLY the order of the parameters!
- Parameters:
vector (numpy.ndarray) – Array containing the values to be packed.
- Return type:
None.
- unpack_bounds() -> (<class 'numpy.ndarray'>, <class 'numpy.ndarray'>)
Unpacks the bounds of all the parameters, and stores them in a tuple of two 1D numpy.ndarray
- Raises:
RuntimeError – The bounds must be int or float (for global parameters), list or numpy.ndarray (for free parameters).
- Returns:
tuple of two 1D arrays containing the upper and lower bounds.
- Return type:
(numpy.ndarray, numpy.ndarray)
- unpack_errors() ndarray
Unpacks the uncertainties of all the parameters, and stores them in a 1D numpy.ndarray. If no fitting has been attempted yet, all values will be None.
- Returns:
1D array containing all the uncertainties values.
- Return type:
numpy.ndarray
- unpack_pin() ndarray
Unpacks the initial values of all the parameters, and stores them in a 1D numpy.ndarray
- Raises:
RuntimeError – The initial value must be int or float (for global parameters), list or numpy.ndarray (for free parameters).
- Returns:
1D array containing all the initial values.
- Return type:
numpy.ndarray
- unpack_values() ndarray
Unpacks the values of all the parameters, and stores them in a 1D numpy.ndarray. If no fitting has been attempted yet, all values will be equal to the initial values.
- Returns:
1D array containing all the parameter values.
- Return type:
numpy.ndarray
- class qensfit.qensfit.Parameter(name: str, value_0: float, low_bound: float = None, high_bound: float = None, is_fixed: bool = False, is_global: bool = False, ax_name: str = None)
Bases:
objectObject that basicaly reimplements a float (with all its implicit methods) with added attributes to make it fit-compatible. That is, all the operations are defined to be applied on Parameter.value. Moreover, it supports indexing when the value is an array-like.
- name
Name of the
Parameter- Type:
str
- ax_name
Y axis label when the parameter is plotted. If None,
nameis used- Type:
str
- ini
Initial value(s) of the
Parameter- Type:
float or list or np.ndarray
- low
Lower bound(s) of the
Parameter.- Type:
float or list or np.ndarray
- high
Upper bound(s) of the
Parameter.- Type:
float or list or np.ndarray
- is_fixed
Whether the
Parameteris constrained toiniduring the fitting.- Type:
bool
- is_global
Whether the
Parameteris global or not, i.e. the same value will be shared to fit multiple curves.- Type:
bool
- is_free
Whether the
Parameteris free, i.e. not fixed and not global.- Type:
bool
- value
Value(s) of the
Parameter. It changes during the fitting procedure, and will be equal to the best fit value after it has converged.- Type:
float or np.ndarray
- error
Uncertainty(ies) on the
Parameter.value. It is calculated as3 * sqrt(diag(cov))wherecovis the covariance matrix returned bycurve_fit.- Type:
float or np.ndarray
- __init__(name: str, value_0: float, low_bound: float = None, high_bound: float = None, is_fixed: bool = False, is_global: bool = False, ax_name: str = None)
Initialises the Parameter instance
- Parameters:
name (str) – Name of the parameter.
value_0 (float or list or np.ndarray) – Initial value.
low_bound (float or list or np.ndarray, optional) – Lower bound. The default is None, which will imply an unbounded parameter
high_bound (float or list or np.ndarray, optional) – Upper bound. The default is None, which will imply an unbounded parameter
is_fixed (bool, optional) – Used to fix a parameter. The default is False.
is_global (bool, optional) – Used to make a parameter global. The default is False.
ax_name (str, optional) – String that will appear as axis label when the parameter is plotted, supports LaTeX. The default is None.
- Return type:
None.
- class qensfit.qensfit.QENSDataset(name: str = '_', x: list = None, y: list = None, dy: list = None, q: list = None)
Bases:
objectDataset object which can be instantiated by itself, provided with suitable data, or it can be automatically created by the load_ascii function. Data is checked automatically for dimension mismatches.
- name
Dataset name.
- Type:
str
- x
Dataset x axis, i.e. the Energy axis.
- Type:
np.ndarray
- y
Dataset y axis, i.e. the Scattering Intensity axis.
- Type:
np.ndarray
- dy
Dataset dy axis, i.e. the Errors axis.
- Type:
np.ndarray
- q
Dataset q axis, i.e. the Momentum Transfer axis.
- Type:
np.ndarray
- n_q
Number of spectra, i.e. number of q points.
- Type:
int
- n_e
Number of energy values, i.e. number of bins in the spectra.
- Type:
int
- __init__(name: str = '_', x: list = None, y: list = None, dy: list = None, q: list = None)
Initialise the QENSDataset instance.
- Parameters:
name (str, optional) – Dataset name. The default is ‘_’.
x (list or np.ndarray, optional) – Dataset x axis, i.e. the Energy axis. Has to have the same dimensions as y and dy. The default is None.
y (list or np.ndarray, optional) – Dataset y axis, i.e. the Scattering Intensity axis. Has to have the same dimensions as x and dy. The default is None.
dy (list or np.ndarray, optional) – Dataset dy axis, i.e. the Errors axis. Has to have the same dimensions as x and yy. The default is None.
q (list or np.ndarray, optional) – Dataset q axis, i.e. the Momentum Transfer axis. If x, y and dy have dimensions (N, M), then q has to be 1D and of length N. The default is None.
- Return type:
None.
- class qensfit.qensfit.QENSResult(name: str = '_', x: ndarray = None, y: ndarray = None, params: ParList = None, chisq: float = None, popt: ndarray = None, pcov: ndarray = None, infodict: dict = None, mesg: str = None, ier: int = None, residuals: ndarray = None)
Bases:
objectContains the results of the fit. It is instantiated bu Model.run_fit() when a dataset is fitted. WARNING: If this object is used outside its intended scope, the validate_result() method has to be called by hand!
- name
Result name. Usually the same as the QENSDataset it refers to.
- Type:
str
- x
Result x axis. This array is denser than the input data (i.e. QENSDataset.x) to make the plots look smoother.
- Type:
np.ndarray
- y
Result y axis, i.e. the model function evaluated at the best fit parameter values.
- Type:
np.ndarray
- chisq
Chi squared value for the global fit.
- Type:
float
- popt
1D vector containing the values of the best fit parameters. See scipy.optimize.curve_fit for more info.
- Type:
np.ndarray
- pcov
2D vector containing approximate covariance of popt. See scipy.optimize.curve_fit for more info.
- Type:
np.ndarray
- infodict
Dictionary containing the keys ‘nfev’ (number of function evaluations) and ‘fvec’ (Residuals evaluated at the solution in a 1D array). See scipy.optimize.curve_fit for more info.
- Type:
dict
- mesg
A string message giving information about the solution. See scipy.optimize.curve_fit for more info.
- Type:
str
- ier
An integer flag. If it is equal to 1, 2, 3 or 4, the solution was found. Otherwise, the solution was not found.. See scipy.optimize.curve_fit for more info.
- Type:
int
- residuals
Residuals (infodict[‘fvec’]) reshaped to have the same dimensions of the y axis.
- Type:
np.ndarray
- cycler
Plot cycler object, which needs to be stored in memory for the buttons to still work.
- Type:
- __init__(name: str = '_', x: ndarray = None, y: ndarray = None, params: ParList = None, chisq: float = None, popt: ndarray = None, pcov: ndarray = None, infodict: dict = None, mesg: str = None, ier: int = None, residuals: ndarray = None)
Initialise the QENSResult instance.
- Parameters:
name (str, optional) – Result name. Usually the same as the QENSDataset it refers to. The default is ‘_’.
x (np.ndarray, optional) – Result x axis. This array is denser than the input data (i.e. QENSDataset.x) to make the plots look smoother. The default is None.
y (np.ndarray, optional) – Result y axis, i.e. the model function evaluated at the best fit parameter values. The default is None.
params (ParList, optional) – ParList instance containing the best fit parameters. The default is None.
chisq (float, optional) – Chi squared value for the global fit. The default is None.
popt (np.ndarray, optional) – 1D vector containing the values of the best fit parameters. See scipy.optimize.curve_fit for more info. The default is None.
pcov (np.ndarray, optional) – 2D vector containing approximate covariance of popt. See scipy.optimize.curve_fit for more info. The default is None.
infodict (dict, optional) – Dictionary containing the keys ‘nfev’ (number of function evaluations) and ‘fvec’ (Residuals evaluated at the solution in a 1D array). See scipy.optimize.curve_fit for more info. The default is None.
mesg (str, optional) – A string message giving information about the solution. See scipy.optimize.curve_fit for more info. The default is None.
ier (int, optional) – An integer flag. If it is equal to 1, 2, 3 or 4, the solution was found. Otherwise, the solution was not found.. See scipy.optimize.curve_fit for more info. The default is None.
residuals (np.ndarray, optional) – Residuals (infodict[‘fvec’]) reshaped to have the same dimensions of the y axis. The default is None.
- Return type:
None.
- print_result(index: str = None, index_title: str = None)
Prints all the best fit parameters in a nice readable way, as a pandas.DataFrame. The index and its title can be customised.
- Parameters:
index (str, optional) – Index values for the DataFrame. The default is None.
index_title (str, optional) – Index title for the DataFrame. The default is None.
- Return type:
None.
- validate_result()
Checks if all the arguments have been passed properly to the Result instance after the fit has been run.
- Raises:
RuntimeError – If any argument for QENSResult is None, an error is raised.
- Return type:
None.
- qensfit.qensfit.load_ascii(filename: str, sep: str = ',', index_list: list = 'temp') dict
Loading function for Mantid data saved in ASCII format using SaveAscii.
- Parameters:
filename (str) – File name to be searched in the current working directory. Supports the use of wildcards and can open multiple files at once.
sep (str, optional) – Separator in the text file. The default is ‘,’.
index_list (list or str, optional) – List of keys to index the data. If None, range(len(filenames)) is used. If list, the list is used (has to be the same length as the number of files being opened). The default is ‘temp’, in which case the temperature values will be inferred from the filenames, and the values will be used as the keys for the output dictionary.
- Raises:
RuntimeError – Raises an error if: no files are found, the number of files is bigger than the length of the index list, the temperature could not be inferred from the file names.
- Returns:
out_dict – Dictionary containing the QENSDataset instances constructed from the files’ contents.
- Return type:
dict