CHAP.utils package

This subpackage contains generic utilities for fitting, parsing CHESS scan data, collecting interactive user input, and finding lattice properties of materials (among others).

Submodules summary

converters

Functions for converting between some commonly used data formats.

fit

Generic curve fitting module.

general

A collection of generic functions for use in any CHAP Processor, Reader or Writer.

material

Module defining the Material class.

models

Utils Pydantic model classes.

parfile

Utilities for interacting with scans using an SMB-style par file as input.

Submodules

CHAP.utils.converters module

Functions for converting between some commonly used data formats.

convert_sparse_dense(data)[source]

Converts between dense and sparse representations for NumPy arrays, xarray DataArrays, and xarray Datasets.

  • If input is a NumPy array, converts to a SciPy sparse CSR matrix.

  • If input is a SciPy sparse matrix, converts to a dense NumPy array.

  • If input is an xarray DataArray or Dataset containing sparse arrays, converts to dense.

  • If input is an xarray DataArray or Dataset containing dense arrays, converts to sparse.

Parameters:

data (numpy.ndarray or scipy.sparse.spmatrix or xarray.DataArray, xarray.Dataset) – Imput data.

Returns:

Converted object – sparse if input is dense, dense if input is sparse.

Return type:

numpy.ndarray or scipy.sparse.spmatrix or xarray.DataArray, xarray.Dataset

convert_structured_unstructured(data)[source]

Convert a NeXus style NXdata object from unstructured to structured data.

Parameters:

data (nexusformat.nexus.NXdata) – Input data.

Returns:

Converted data.

Return type:

nexusformat.nexus.NXdata

convert_xarray_nexus(data)[source]

Convert a xarray DataArray or Dataset into a NeXus style NXdata data object or vice versa.

Parameters:

data (xarray.DataArray or xarray.Dataset or nexusformat.nexus.NXdata) – Input data.

Returns:

Conveted data.

Return type:

xarray.DataArray or xarray.Dataset or nexusformat.nexus.NXdata

CHAP.utils.fit module

Generic curve fitting module.

class Component(model, prefix='')[source]

Bases: object

A model fit component.

class Components[source]

Bases: dict

The dictionary of model fit components.

add(model, prefix='')[source]

Add a model to the model fit components dictionary.

Parameters:
  • model (models) – A fit model class.

  • prefix (str, optional) – Model prefix.

property components

Return the model fit components.

Type:

list[models]

class Fit(nxdata, config, logger)[source]

Bases: object

Wrapper class for scipy/lmfit.

add_model(model, prefix)[source]

Add a model component to the fit model.

Parameters:
  • model (models) – A fit model class.

  • prefix (str) – Model prefix.

add_parameter(parameter)[source]

Add a fit parameter to the fit model.

Parameters:

parameter (FitParameter) – A new parameter to be added to the fit model.

property best_errors

Return errors in the best fit parameters.

Type:

dict

property best_fit

Return the best fit.

Type:

numpy.ndarray

property best_parameters

Return the best fit parameters.

Type:

dict

property best_values

Return values for the best fit parameters.

Type:

dict

property best_vary

Return vary parameters for the best fit parameters.

Type:

dict

property chisqr

Return chisqr values for the best fit parameters.

Type:

numpy.ndarray

property components

Return fit model components info.

Type:

dict

property covar

Return the covarience matrix for the best fit parameters.

Type:

numpy.ndarray

eval(x, result=None)[source]

Evaluate the best fit.

Parameters:
  • x (array-like, optional) – x-coordinates.

  • result (ModelResult or lmfit.model.ModelResult, optional) – Model result, defaults to the self._result class attribute.

fit(config=None, **kwargs)[source]

Fit the model to the input data.

Parameters:
  • config (CHAP.utils.models.FitConfig, optional) – Fit configuration.

  • kwargs (dict) – Additional key, value pairs to pass on directly to the core fit routine.

static guess_init_peak(x, y, *args, center_guess=None, use_max_for_center=True)[source]

Return a guess for the initial height, center and fwhm for a single peak.

property init_parameters

Return the initial parameters for the fit model.

Type:

dict

property init_values

Return the initial values for the fit parameters.

Type:

dict

property normalization_offset

Return the normalization_offset value for the fit model.

Type:

float

property num_func_eval

Return the number of function evaluations for the best fit.

Type:

int

property parameters

Return the fit parameters info.

Type:

dict

plot(y=None, *, y_title=None, title=None, result=None, skip_init=False, plot_comp=True, plot_comp_legends=False, plot_residual=False, plot_masked_data=True, **kwargs)[source]

Plot the best fit.

Parameters:
  • y (array-like, optional) – y-coordinates.

  • y_title (str, optional) – y-axis label.

  • title (str, optional) – Graph title.

  • result (ModelResult or lmfit.model.ModelResult, optional) – Model result, defaults to the self._result class attribute.

  • skip_init (bool, optional) – Skip plotting the initial guess, defaults to False.

  • plot_comp (bool, optional) – Plot the individual model components, defaults to True.

  • plot_comp_legends (bool, optional) – Add a legend for the individual model components, defaults to False.

  • plot_residual (bool, optional) – Plot the residual, defaults to False.

  • plot_masked_data (bool, optional)

  • kwargs (dict) – Additional key, value pairs to pass on directly to the Matplotlib plot function.

print_fit_report(result=None, show_correl=False)[source]

Print a fit report.

Parameters:
  • result (ModelResult or lmfit.model.ModelResult, optional) – Model result, defaults to the self._result class attribute.

  • show_correl (bool, optional) – Whether to show list of correlations, defaults to False.

property redchi

Return redchi for the best fit.

Type:

dict

property residual

Return the residual in the best fit.

Type:

numpy.ndarray

property success

Return the success value for the fit.

Type:

bool

property var_names

Return the variable names for the covarience matrix property.

Type:

list[str]

property x

Return the input x-coordinates.

Type:

numpy.ndarray

property y

Return the input y-coordinates.

Type:

numpy.ndarray

class FitMap(nxdata, config, logger)[source]

Bases: Fit

Wrapper to the Fit class to fit data on a N-dimensional map.

property best_errors

Return errors in the best fit parameters.

Type:

numpy.ndarray

property best_fit

Return the best fits.

Type:

numpy.ndarray

best_parameters(dims=None)[source]

Return the best fit parameters.

Parameters:

dims (list or tuple, optional) – Map indices of the best fit parameters to return, defaults to None which will return the list of the best parameter names in the correct order for the results.

Returns:

Best fit parameters.

Return type:

list[str] or dict

property best_values

Return values for the best fit parameters.

Type:

numpy.ndarray

property best_vary

Return vary parameters for the best fit parameters.

Type:

numpy.ndarray

property chisqr

Return the chisqr value for each best fit.

Type:

numpy.ndarray

property components

Return the fit model components info.

Type:

dict

property covar

Return the covarience matrices for the best fit parameters.

Type:

numpy.ndarray

fit(config=None, **kwargs)[source]

Fit the model to the input data.

Parameters:
  • config (CHAP.utils.models.FitConfig, optional) – Fit configuration.

  • kwargs (dict) – Additional key, value pairs to pass on directly to the core fit routine.

freemem()[source]

Free memory allocated for parallel processing.

property max_nfev

Return if the maximum number of function evaluations is reached for each fit.

Type:

numpy.ndarray

property num_func_eval

Return the number of function evaluations for each best fit.

Type:

numpy.ndarray

property out_of_bounds

Return the out_of_bounds flag values for each best fit.

Type:

numpy.ndarray

plot(dims=None, *, y_title=None, plot_comp_legends=False, plot_residual=False, plot_masked_data=True, **kwargs)[source]

Plot the best fits.

Parameters:
  • dims (list or tuple, optional) – Map indices of the data point to plot, defaults to None which will plot the first data point.

  • y_title (str, optional) – y-axis label.

  • plot_comp_legends (bool, optional) – Add a legend for the individual model components, defaults to False.

  • plot_residual (bool, optional) – Plot the residual, defaults to False.

  • plot_masked_data (bool, optional)

  • kwargs (dict) – Additional key, value pairs to pass on directly to the Matplotlib plot function.

property redchi

Return the redchi value for each best fit.

Type:

numpy.ndarray

property residual

Return the residual in each best fit.

Type:

numpy.ndarray

property success

Return the success value for each fit.

Type:

bool

property var_names

Return the variable names for the covarience matrix property.

Type:

list[str]

property y

Return the input y-coordinates.

Type:

numpy.ndarray

property ymap

Return the input y-coordinates map.

Type:

numpy.ndarray

class FitProcessor(*, root: Annotated[Path, PathType(path_type=dir)] | None = '/home/runner/work/ChessAnalysisPipeline/ChessAnalysisPipeline/docs', inputdir: Annotated[Path, PathType(path_type=dir)] | None = None, outputdir: Annotated[Path, PathType(path_type=dir)] | None = None, interactive: bool | None = False, log_level: Literal['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'] | None = 'INFO')[source]

Bases: Processor

A processor to perform a fit on a data set or data map.

static create_multipeak_model(model_config)[source]

Create a multipeak model.

Parameters:

model_config (Multipeak) – A Multipeak fit model class.

Returns:

The fit parameters and fit model classes.

Return type:

list[FitParameter], list[models]

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context: Any, /) None

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Args:

self: The BaseModel instance. context: The context.

process(data, config=None)[source]

Fit the data and return a Fit or FitMap object depending on the dimensionality of the input data. The input data should be or contain a NeXus style NXdata object, with properly defined signal and axis, or a Fit or FitMap object from a previous fit.

Parameters:
  • data (list[PipelineData] or Fit or FitMap or nexusformat.nexus.NXdata) – Input data containing the nexusformat.nexus.NXdata object to fit.

  • config (dict, optional) – Fit configuration.

Raises:

ValueError – Invalid input or configuration parameter.

Returns:

The fitted data object.

Return type:

Fit or FitMap

class ModelResult(model, parameters, x=None, y=None, method=None, ast=None, res_par_exprs=None, res_par_indices=None, res_par_names=None, result=None)[source]

Bases: object

The result of a model fit, mimicking the functionality of a similarly named class in the lmfit library.

eval_components(x=None, parameters=None)[source]

Evaluate each component of a composite model function.

Parameters:
  • x (array-like, optional) – Independent variable, defaults to None, in which case the class variable x is used.

  • parameters (Parameters or lmfit.parameter.Parameter, optional) – Composite model parameters, defaults to None, in which case the class variable params is used.

Returns:

A dictionary with component name and evaluated function values key, value pairs.

Return type:

dict

fit_report(show_correl=False)[source]

Generates a report of the fitting results with their best parameter values and uncertainties.

Parameters:

show_correl (bool, optional) – Whether to show list of correlations, defaults to False.

class Parameters[source]

Bases: dict

A dictionary of FitParameter objects, mimicking the functionality of a similarly named class in the lmfit library.

add(parameter, prefix='')[source]

Add a fit parameter.

Parameters:
  • parameter (str or FitParameter) – The fit parameter to add to the dictionary.

  • prefix (str, optional) – Prefix of the model to which this parameter belongs, defaults to ‘’.

CHAP.utils.general module

A collection of generic functions for use in any CHAP Processor, Reader or Writer.

all_any(l, key)[source]

Check for a common key in a list of dictionaries, looping at maximum only once over the entire list.

Parameters:
  • l (list[dict]) – Input list.

  • key (Any) – Common dictionary key.

Returns:

1 if all(l, key), 0 if not any(l, key), or -1 otherwise. Return None for a zero length input list.

Return type:

None or int

almost_equal(value1, value2, sig_figs)[source]

Check if equal to within a certain number of significant digits.

Parameters:
  • value1 (float) – Input value.

  • value2 (float) – Input value.

  • sig_figs (int) – Number of sig figs.

Returns:

True is inputs are equal within sig_figs sig figs, False if not.

Return type:

bool

assert_no_duplicate_attr_in_list_of_objs(l, attr, raise_error=False)[source]

Assert that there are no duplicate attributes in a list of objects.

Parameters:
  • l (list) – Input list.

  • key (str) – Attribute.

  • raise_error (bool, optional) – Raise an exception upon any error, defaults to False.

assert_no_duplicate_key_in_list_of_dicts(l, key, raise_error=False)[source]

Assert that there are no duplicate keys in a list of dictionaries.

Parameters:
  • l (list[dict]) – Input list.

  • key (str) – Dictionary key.

  • raise_error (bool, optional) – Raise an exception upon any error, defaults to False.

assert_no_duplicates_in_list_of_dicts(l, raise_error=False)[source]

Assert that there are no duplicates in a list of dictionaries.

Parameters:
  • l (list[dict]) – Input list.

  • raise_error (bool, optional) – Raise an exception upon any error, defaults to False.

baseline_arPLS(y, mask=None, w=None, tol=1e-08, lam=1000000.0, max_iter=20, full_output=False)[source]

Returns the smoothed baseline estimate of a spectrum.

Based on S.-J. Baek, A. Park, Y.-J Ahn, and J. Choo, “Baseline correction using asymmetrically reweighted penalized least squares smoothing”, Analyst, 2015,140, 250-257

Parameters:
  • y (array-like) – Spectrum.

  • mask (array-like, optional) – Mask to apply to the spectrum before baseline construction.

  • w (numpy.array, optional) – Weights (allows restart for additional iterations).

  • tol (float, optional) – Convergence tolerence, defaults to 1.e-8.

  • lam (float, optional) – &lambda (smoothness) parameter (the balance between the residual of the data and the baseline and the smoothness of the baseline). The suggested range is between 100 and 10^8, defaults to 10^6.

  • max_iter (int, optional) – Maximum number of iterations, defaults to 20.

  • full_output (bool, optional) – Whether or not to also output the baseline corrected spectrum, the number of iterations and error in the returned result, defaults to False.

Returns:

Smoothed baseline, with optionally the baseline corrected spectrum, the weights, the number of iterations and the error in the returned result.

Return type:

numpy.array [, numpy.array, int, float]

depth_list(l)[source]

Return the depth of a list.

Parameters:

l (list) – Input list.

Returns:

Depth of a list.

Return type:

int

depth_tuple(t)[source]

Return the depth of a tuple.

Parameters:

t (tuple) – Input tuple.

Returns:

Depth of a tuple.

Return type:

int

dictionary_update(target, source, merge_key_paths=None, sort=False)[source]

Recursively updates a target dictionary with values from a source dictionary. Source values superseed target values for identical keys unless both values are lists of dictionaries in which case they are merged according to the merge_key_paths parameter.

Parameters:
  • target (collections.abc.Mapping) – Target dictionary.

  • source – Source dictionary.

  • merge_key_paths (str or list[str]) – List key paths to merge dictionary lists, only used if items in the target and source dictionary trees are lists of dictionaries.

  • sort (bool, optional) – Sort dictionary lists on the key.

Returns:

Updated target directory.

Return type:

collections.abc.Mapping

fig_to_iobuf(fig, fileformat=None)[source]

Return an in-memory object as a byte stream represention of a Matplotlib figure.

Parameters:
  • fig (matplotlib.figure.Figure) – Matplotlib figure object.

  • fileformat (str, optional) – Valid Matplotlib saved figure file format, defaults to ‘png’.

Returns:

Byte stream representation of the Matplotlib figure and the associated file format.

Return type:

tuple[_io.BytesIO, str]

file_exists_and_readable(filename)[source]

Check if a file exists and is readable.

Parameters:

f (str) – File name.

Raises:

ValueError – Invalid file or inaccessible for reading.

Returns:

File name.

Return type:

str

get_consecutive_int_range(a)[source]

Return a list of pairs of integers marking consecutive ranges of integers.

Parameters:

a (array-like) – Input array.

Returns:

Pairs of integers marking consecutive ranges of integers.

Return type:

list

get_default_path(nxobject)[source]

Return the relative path to the default plottable NeXus style NXdata object within the parent NXobject provided.

Parameters:

nxobject (nexusformat.nexus.NXobject) – Parent NXobject containing plottable NXdata.

Returns:

Path to default NXdata group.

Return type:

str

get_trailing_int(s)[source]

Get the trailing integer in a string.

Parameters:

s (str) – Input value

Returns:

Trailing integer in a string.

Return type:

int

getfloat_attr(obj, attr, length=11)[source]

Format an attribute of an object for printing.

Parameters:
  • obj (str) – Object that the attr belongs to.

  • attr (str) – Attribute.

  • length (int, optional) – Length of the number field, defaults to 11.

Returns:

Representation of the attribute.

Return type:

str

gformat(value, length=11)[source]
Format a number with ‘%g’-like format, while:
  • the length of the output string will be of the requested length

  • positive numbers will have a leading blank

  • the precision will be as high as possible

  • trailing zeros will not be trimmed

Parameters:
  • value (float) – Input value.

  • length (int, optional) – Length of the number field, defaults to 11.

Returns:

Formatted number.

Return type:

str

illegal_combination(value1, name1, value2, name2, location=None, raise_error=False, log=True)[source]

Print illegal combination message and/or raise error.

Parameters:
  • value1 – Input value.

  • name1 (str) – Value name.

  • value2 – Input value.

  • name2 (str) – Value name.

  • location (str, optional) – Input location.

  • raise_error (bool, optional) – Raise an error, defaults to False.

  • log (bool, optional) – Write error message to the logger, defaults to True.

Raise:

ValueError when raise_error is set to True.

illegal_value(value, name, location=None, raise_error=False, log=True)[source]

Print illegal value message and/or raise error.

Parameters:
  • value – Input value.

  • name (str) – Value name.

  • location (str, optional) – Input location.

  • raise_error (bool, optional) – Raise an error, defaults to False.

  • log (bool, optional) – Write error message to the logger, defaults to True.

Raise:

ValueError when raise_error is set to True.

index_nearest(a, value)[source]

Return index of nearest array value.

Parameters:
  • a (array-like) – Input array.

  • value (int or float) – Input value.

Returns:

Index or array value nearest to input value.

Return type:

int

index_nearest_down(a, value)[source]

Return index of nearest array value, rounded down.

Parameters:
  • a (array-like) – Input array.

  • value (int or float) – Input value.

Returns:

Index or array value nearest to input value, rounded down.

Return type:

int

index_nearest_up(a, value)[source]

Return index of nearest array value, rounded up.

Parameters:
  • a (array-like) – Input array.

  • value (int or float) – Input value.

Returns:

Index or array value nearest to input value, rounded up.

Return type:

int

input_int(s=None, ge=None, gt=None, le=None, lt=None, default=None, inset=None, raise_error=False, log=True)[source]

Interactively prompt the user to enter an integer.

Parameters:
  • s (str, optional) – Interactive user prompt, defaults to “Enter an integer” with an optional range.

  • ge (int, optional) – Greater or equal to.

  • gt (int, optional) – Greater than.

  • le (int, optional) – Smaller or equal to.

  • lt (int, optional) – Smaller than.

  • default (int, optional) – Default value to return.

  • inset (list[int], optional) – Valid values to choose from.

  • raise_error (bool, optional) – Raise an error, defaults to False.

  • log (bool, optional) – Write error message to the logger, defaults to True.

Returns:

Entered value.

Return type:

int

input_int_list(s=None, num_max=None, ge=None, le=None, split_on_dash=True, remove_duplicates=True, sort=True, raise_error=False, log=True)[source]

Prompt the user to input a list of integers and split the entered string on any combination of commas, whitespaces, or dashes (when split_on_dash is True). e.g: ‘1 3,5-8 , 12 ‘ -> [1, 3, 5, 6, 7, 8, 12]

Parameters:
  • s (str, optional) – Interactive user prompt.

  • num_max (int, optional) – Maximum number of inputs in list.

  • ge (int, optional) – Minimum value of inputs in list.

  • le (int, optional) – Minimum value of inputs in list.

  • split_on_dash (bool, optional) – Allow dashes in input string, defaults to True.

  • remove_duplicates (bool, optional) – Removes duplicates (may also change the order), defaults to True.

  • sort (bool, optional) – Sort in ascending order, defaults to True.

  • raise_error (bool, optional) – Raise an exception upon any error, defaults to False.

  • log (bool, optional) – Print an error message upon any error, defaults to True.

Returns:

Input list or None upon an illegal input.

Return type:

list

input_menu(items, default=None, header=None)[source]

Interactively prompt the user to select from a menu.

Parameters:
  • items – Menu items.

  • default (str) – Default value to return.

Returns:

Choosen entry.

Return type:

str

input_num(s=None, ge=None, gt=None, le=None, lt=None, default=None, raise_error=False, log=True)[source]

Interactively prompt the user to enter a number.

Parameters:
  • s (str, optional) – Interactive user prompt, defaults to “Enter a value” with an optional range.

  • ge (int or float, optional) – Greater or equal to.

  • gt (int or float, optional) – Greater than.

  • le (int or float, optional) – Smaller or equal to.

  • lt (int or float, optional) – Smaller than.

  • default (int or float, optional) – Default value to return.

  • raise_error (bool, optional) – Raise an error, defaults to False.

  • log (bool, optional) – Write error message to the logger, defaults to True.

Returns:

Entered value.

Return type:

int or float

input_num_list(s=None, num_max=None, ge=None, le=None, remove_duplicates=True, sort=True, raise_error=False, log=True)[source]

Prompt the user to input a list of numbers and split the entered string on any combination of commas or whitespaces. e.g: ‘1.0, 3, 5.8, 12 ‘ -> [1.0, 3.0, 5.8, 12.0]

Parameters:
  • s (str, optional) – Interactive user prompt.

  • num_max (int, optional) – Maximum number of inputs in list.

  • ge (float, optional) – Minimum value of inputs in list.

  • le (float, optional) – Minimum value of inputs in list.

  • remove_duplicates (bool, optional) – Removes duplicates (may also change the order), defaults to True.

  • sort (bool, optional) – Sort in ascending order, defaults to True.

  • raise_error (bool, optional) – Raise an exception upon any error, defaults to False.

  • log (bool, optional) – Print an error message upon any error, defaults to True.

Returns:

Input list or None upon an illegal input.

Return type:

list

input_yesno(s=None, default=None)[source]

Interactively prompt the user to enter a y/n question.

Parameters:
  • s (str, optional) – Interactive user prompt, defaults to “Enter yes or no”.

  • default (int or float, optional) – Default value to return.

Returns:

True if “yes”, False if “no”.

Return type:

bool

is_dict_nums(d, raise_error=False, log=True)[source]

Value is a dictionary with single number values.

Parameters:
  • t_or_l (dict[str, int]) – Input values.

  • raise_error (bool, optional) – Raise an error, defaults to False.

  • log (bool, optional) – Write error message to the logger, defaults to True.

Returns:

True if input value is valid or False if not.

Return type:

bool

is_dict_series(t_or_l, raise_error=False, log=True)[source]

Value is a tuple or list of dictionaries.

Parameters:
  • t_or_l (tuple[dict] or list[dict]) – Input values.

  • raise_error (bool, optional) – Raise an error, defaults to False.

  • log (bool, optional) – Write error message to the logger, defaults to True.

Returns:

True if input value is valid or False if not.

Return type:

bool

is_dict_strings(d, raise_error=False, log=True)[source]

Value is a dictionary with single string values.

Parameters:
  • t_or_l (dict[str, str]) – Input values.

  • raise_error (bool, optional) – Raise an error, defaults to False.

  • log (bool, optional) – Write error message to the logger, defaults to True.

Returns:

True if input value is valid or False if not.

Return type:

bool

is_index(value, ge=0, lt=None, raise_error=False, log=True)[source]

Value is an array index in range ge <= value < lt.

Note

The value for lt IS NOT included!

Parameters:
  • value (int) – Input value.

  • ge (int, optional) – Greater or equal to, defaults to 0.

  • lt (int, optional) – Smaller than.

  • raise_error (bool, optional) – Raise an error, defaults to False.

  • log (bool, optional) – Write error message to the logger, defaults to True.

Returns:

True if input value is a valid array index or False if not.

Return type:

bool

is_index_range(value, ge=0, le=None, lt=None, raise_error=False, log=True)[source]

Value is an array index range in range ge <= value[0] <= value[1] <= le or ge <= value[0] <= value[1] < lt.

Note

The value for le IS included!

Parameters:
  • value (list[int, int]) – Input value.

  • ge (int, optional) – Greater or equal to, defaults to 0.

  • le (int, optional) – Smaller or equal to.

  • lt (int, optional) – Smaller than.

  • raise_error (bool, optional) – Raise an error, defaults to False.

  • log (bool, optional) – Write error message to the logger, defaults to True.

Returns:

True if input value is a valid array index range or False if not.

Return type:

bool

is_int(value, ge=None, gt=None, le=None, lt=None, raise_error=False, log=True)[source]

Value is an integer in range ge <= value <= le or gt < value < lt or some combination.

Parameters:
  • value (int) – Input value.

  • ge (int, optional) – Greater or equal to.

  • gt (int, optional) – Greater than.

  • le (int, optional) – Smaller or equal to.

  • lt (int, optional) – Smaller than.

  • raise_error (bool, optional) – Raise an error, defaults to False.

  • log (bool, optional) – Write error message to the logger, defaults to True.

Returns:

True if input value is in valid range or False if not.

Return type:

bool

is_int_pair(values, ge=None, gt=None, le=None, lt=None, raise_error=False, log=True)[source]

Value is an integer pair, each in range ge <= values[i] <= le or gt < values[i] < lt or ge[i] <= values[i] <= le[i] or gt[i] < values[i] < lt[i] or some combination.

Parameters:
  • values (list[int, int]) – Input values.

  • ge (int, optional) – Greater or equal to.

  • gt (int, optional) – Greater than.

  • le (int, optional) – Smaller or equal to.

  • lt (int, optional) – Smaller than.

  • raise_error (bool, optional) – Raise an error, defaults to False.

  • log (bool, optional) – Write error message to the logger, defaults to True.

Returns:

True if input value is a valid pair in the valid range or False if not.

Return type:

bool

is_int_series(t_or_l, ge=None, gt=None, le=None, lt=None, raise_error=False, log=True)[source]

Value is a tuple or list of integers, each in range ge <= l[i] <= le or gt < l[i] < lt or some combination.

Parameters:
  • t_or_l (list[int]) – Input values.

  • ge (int, optional) – Greater or equal to.

  • gt (int, optional) – Greater than.

  • le (int, optional) – Smaller or equal to.

  • lt (int, optional) – Smaller than.

  • raise_error (bool, optional) – Raise an error, defaults to False.

  • log (bool, optional) – Write error message to the logger, defaults to True.

Returns:

True if input value is a valid list or False if not.

Return type:

bool

is_num(value, ge=None, gt=None, le=None, lt=None, raise_error=False, log=True)[source]

Value is a number in range ge <= value <= le or gt < value < lt or some combination.

Parameters:
  • value (int or float) – Input value.

  • ge (int or float, optional) – Greater or equal to.

  • gt (int or float, optional) – Greater than.

  • le (int or float, optional) – Smaller or equal to.

  • lt (int or float, optional) – Smaller than.

  • raise_error (bool, optional) – Raise an error, defaults to False.

  • log (bool, optional) – Write error message to the logger, defaults to True.

Returns:

True if input value is in valid range or False if not.

Return type:

bool

is_num_pair(values, ge=None, gt=None, le=None, lt=None, raise_error=False, log=True)[source]

Value is a number pair, each in range ge <= values[i] <= le or gt < values[i] < lt or ge[i] <= values[i] <= le[i] or gt[i] < values[i] < lt[i] or some combination.

Parameters:
  • values (list[int, int] or list[float, float]) – Input values.

  • ge (int or float, optional) – Greater or equal to.

  • gt (int or float, optional) – Greater than.

  • le (int or float, optional) – Smaller or equal to.

  • lt (int or float, optional) – Smaller than.

  • raise_error (bool, optional) – Raise an error, defaults to False.

  • log (bool, optional) – Write error message to the logger, defaults to True.

Returns:

True if input value is a valid pair in the valid range or False if not.

Return type:

bool

is_num_series(t_or_l, ge=None, gt=None, le=None, lt=None, raise_error=False, log=True)[source]

Value is a tuple or list of numbers, each in range ge <= l[i] <= le or gt < l[i] < lt or some combination.

Parameters:
  • t_or_l (list[int] or list[float]) – Input values.

  • ge (int or float, optional) – Greater or equal to.

  • gt (int or float, optional) – Greater than.

  • le (int or float, optional) – Smaller or equal to.

  • lt (int or float, optional) – Smaller than.

  • raise_error (bool, optional) – Raise an error, defaults to False.

  • log (bool, optional) – Write error message to the logger, defaults to True.

Returns:

True if input value is a valid list or False if not.

Return type:

bool

is_str_or_str_series(t_or_l, raise_error=False, log=True)[source]

Value is a string ot a tuple or list of strings.

Parameters:
  • t_or_l (str or tuple[str] or list[str]) – Input values.

  • raise_error (bool, optional) – Raise an error, defaults to False.

  • log (bool, optional) – Write error message to the logger, defaults to True.

Returns:

True if input value is valid or False if not.

Return type:

bool

is_str_series(t_or_l, raise_error=False, log=True)[source]

Value is a tuple or list of strings.

Parameters:
  • t_or_l (tuple[str] or list[str]) – Input values.

  • raise_error (bool, optional) – Raise an error, defaults to False.

  • log (bool, optional) – Write error message to the logger, defaults to True.

Returns:

True if input value is a valid False if not.

Return type:

bool

list_dictionary_update(target, source, key=None, key_type=None, sort=False)[source]

Recursively updates a target list of dictionaries with values from a source list of dictionaries. Each list item is updated item by item based on the key if given and equal to a key that is shared among all sets of source and target list item keys. Otherwise the target list appended to the source list is returned.

Parameters:
  • target (list) – Target list.

  • source (list) – Source list.

  • key (str, optional) – Selected key to merge the lists of dictionaries.

  • key_type (type, optional) – Key type to enforce.

  • sort (bool, optional) – Sort the returned list on the key.

Returns:

Updated list.

Return type:

list

list_to_string(a)[source]

Return an array index list of integers in string notation. e.g: [1, 3, 5, 6, 7, 8, 12] -> ‘1, 3, 5-8, 12’

Parameters:

a (array-like) – Input array.

Returns:

Index list in string notation.

Return type:

str

not_zero(value)[source]

Return value with a minimal absolute size of tiny, (numpy.finfo(numpy.float64).resolution) preserving the sign.

Parameters:

value (float) – Input value.

Returns:

Minimum of input value and tiny, preserving sign.

nxcopy(nxobject, exclude_nxpaths=None, nxpath_prefix=None, nxpathabs_prefix=None, nxpath_copy_abspath=None, nxgroup_to_nxdata=False)[source]

Function that returns a copy of a NeXus style NXobject optionally exluding certain child items.

Parameters:
  • nxobject (nexusformat.nexus.NXobject) – Input nexus object to “copy”.

  • exlude_nxpaths – List of relative paths to child nexus objects that should be excluded from the returned “copy”.

  • nxpath_prefix (str, optional) – For use in recursive calls from inside this function only.

  • nxpathabs_prefix (str, optional) – For use in recursive calls from inside this function only.

  • nxpath_copy_abspath (str, optional) – For use in recursive calls from inside this function only.

Returns:

Copy of the input nxobject with some children optionally exluded.

Return type:

nexusformat.nexus.NXobject

quick_imshow(a, title=None, row_label='row index', column_label='column index', path=None, name=None, show_fig=True, save_fig=False, return_fig=False, block=None, extent=None, show_grid=False, grid_color='w', grid_linewidth=1, colorbar=False, **kwargs)[source]

Display and or save a 2D Matplotlib image and or return an in-memory object as a byte stream represention.

Parameters:
  • a (array-like) – Input array.

  • title (str, optional) – Graph title.

  • row_label (str, optional) – Row label title.

  • column_label (str, optional) – Column label title.

  • path (str, optional) – File path to save image to (ignored if save_fig is False).

  • name (str, optional) – File name of image (ignored if save_fig is False).

  • show_fig (bool, optional) – Display image, defaults to True.

  • save_fig (bool, optional) – Save image to file, defaults to False.

  • return_fig (bool, optional) – Return an in-memory object as a byte stream represention of the Matplotlib image, defaults to False.

  • block (bool, optional) – Wait for the image to be closed before returning.

  • extent (floats (left, right, bottom, top), optional) – Bounding box in data coordinates that the image will fill.

  • show_grid (bool, optional) – Show grid lines, defaults to False.

  • grid_color (str, optional) – Grid color, defaults to “w” or white.

  • grid_linewidth (int, optional) – Grid line width, defaults to 1.

  • colorbar (bool, optional) – Include a colorbar, defaults to False.

  • kwargs (dict, optional) – Any additional keyword parameters to pass on to matplotlib.pyplot.imshow.

Raise:

ValueError for invalid input data or parameters.

Returns:

In-memory object as a byte stream represention if return_fig is set.

Return type:

tuple[_io.BytesIO, str] or None

quick_plot(*args, xerr=None, yerr=None, vlines=None, title=None, xlim=None, ylim=None, xlabel=None, ylabel=None, legend=None, path=None, name=None, show_grid=False, save_fig=False, save_only=False, block=False, **kwargs)[source]

Display a 2D Matplotlib line plot.

Parameters:
  • args ([x], y, [fmt] [, [x2], y2, [fmt2], ...]) – Tuple or tuple of tuples of input x-coordinates (optional), y-coordinates, and optional line formatting parameters.

  • xerr – Errors in x-coordinates.

  • yerr – Errors in y-coordinates.

  • vlines (list[float], optional) – List of vertical lines to add to plot.

  • title (str, optional) – Graph title.

  • xlim (list[float, float], optional) – x-axis view limits.

  • ylim (list[float, float], optional) – y-axis view limits.

  • xlabel (str, optional) – x-axis label.

  • ylabel (str, optional) – y-axis label.

  • path (str, optional) – File path to save image to (ignored if save_fig is False).

  • name (str, optional) – File name of image (ignored if save_fig is False).

  • show_grid (bool, optional) – Show grid lines, defaults to False.

  • save_fig (bool, optional) – Save image to file, defaults to False.

  • save_only (bool, optional) – Don not display the figure, only save it to file, defaults to False.

  • block (bool, optional) – Wait for the image to be closed before returning.

  • kwargs (dict, optional) – Any additional keyword parameters to pass on to matplotlib.pyplot.plot

Type:

array-like or float, optional

Type:

array-like or float, optional

Raise:

ValueError for invalid input data or parameters.

range_string_ge_gt_le_lt(ge=None, gt=None, le=None, lt=None)[source]

Return a range string representation matching the ge, gt, le, lt qualifiers. Does not validate the inputs, do that as needed before calling.

Parameters:
  • ge (int or float, optional) – Greater or equal to.

  • gt (int or float, optional) – Greater than.

  • le (int or float, optional) – Smaller or equal to.

  • lt (int or float, optional) – Smaller than.

Returns:

Range string representation.

Return type:

str

rolling_average(y, x=None, dtype=None, start=0, end=None, width=None, stride=None, num=None, average=True, mode='valid', use_convolve=None)[source]

Returns the rolling sum or average of an array over the last dimension.

Parameters:
  • y (array-like) – Input data.

  • x (array-like, optional) – Independent dimension.

  • dtype (numpy.dtype) – Input data type, defaults to the type of y if average is True or numpy.float if not.

  • start (int, optional) – First array index, defaults to 0.

  • end (int, optional) – Last array index.

  • width (int, optional) – Number of elements in rolling sum or average.

  • stride (int, optional) – Stride in rolling sum or average.

  • num (int, optional) – Number of outputs of rolling sum or average.

  • average (bool) – Compute the rolling average if True or the rolling sum otherwise.

  • mode (Literal['valid', 'full'], optional) – Only return results for full sized windows if “valid”, include partial windows if “full”, defaults to “valid”.

  • use_convolve (bool, optional) – Use numpy.convolve if True.

Raises:

ValueError – Invalid input parameters.

Returns:

Rolling sum or average of the input array, optionally with their independent coordinates.

Return type:

numpy.ndarray or (numpy.ndarray, numpy.ndarray)

Note

Specify only one or two of width, stride, and num.

round_to_n(value, n=1)[source]

Round to a specific number of sig figs.

Parameters:
  • value (float) – Input value.

  • n (int, optional) – Number of sig figs, defaults to 1.

Returns:

Input value rounded to n sig figs.

Return type:

float

round_up_to_n(value, n=1)[source]

Round up to a specific number of sig figs.

Parameters:
  • value (float) – Input value.

  • n (int, optional) – Number of sig figs, defaults to 1.

Returns:

Input value rounded up to n sig figs.

Return type:

float

save_iobuf_fig(buf, filename, force_overwrite=False)[source]

Save a byte stream represention of a Matplotlib figure to file.

Parameters:
  • buf (_io.BytesIO) – Byte stream representation of the Matplotlib figure.

  • filename (str) – Filename (with a valid extension).

  • force_overwrite (bool, optional) – Flag to allow filename to be overwritten if it already exists, defaults to False.

Raises:

RuntimeError – If a file already exists and force_overwrite is False.

select_image_indices(a, axis, b=None, preselected_indices=None, axis_index_offset=0, min_range=None, min_num_indices=2, max_num_indices=2, title=None, title_a=None, title_b=None, row_label='row index', column_label='column index', interactive=True, return_buf=False)[source]

Display a 2D image and have the user select a set of image indices in either row or column direction.

Parameters:
  • a (array-like) – Two-dimensional image data array for which a region of interest will be selected.

  • axis (int) – Selection direction (0: row, 1: column)

  • b (array-like, optional) – Secondary two-dimensional image data array for which a shared region of interest will be selected.

  • preselected_indices (tuple(int), list(int), optional) – Preselected image indices.

  • axis_index_offset (int, optional) – Offset in axis index range and preselected indices, defaults to 0.

  • min_range (int, optional) – Minimal range spanned by the selected indices.

  • min_num_indices (int, optional) – Minimum number of selected indices.

  • max_num_indices (int, optional) – Maximum number of selected indices.

  • title (str, optional) – Title for the displayed figure.

  • title_a (str, optional) – Title for the image of a.

  • title_b (str, optional) – Title for the image of b.

  • row_label (str, optional) – Label for the y-axis of the displayed figure, defaults to row index.

  • column_label (str, optional) – Label for the x-axis of the displayed figure, defaults to column index.

  • interactive (bool, optional) – Show the plot and allow user interactions with the matplotlib figure, defaults to True.

  • return_buf (bool, optional) – Return an in-memory object as a byte stream represention of the Matplotlib figure instead of the matplotlib figure, defaults to False.

Returns:

Selected region of interest as array indices and a matplotlib figure.

Return type:

tuple[_io.BytesIO, str] or None, tuple(int, int, int, int) or None.

select_mask_1d(y, x=None, preselected_index_ranges=None, preselected_mask=None, title=None, xlabel=None, ylabel=None, min_num_index_ranges=None, max_num_index_ranges=None, interactive=True, filename=None, return_buf=False)[source]

Display a lineplot and have the user select a mask.

Parameters:
  • y (array-like) – One-dimensional data array for which a mask will be constructed.

  • x (array-like, optional) – x-coordinates of the reference data.

  • preselected_index_ranges (list[tuple(int, int)] or list[list[int]] or list[tuple(float, float)] or list[list[float]]), optional) – List of preselected index ranges to mask (bounds are inclusive).

  • preselected_mask (array-like, optional) – Preselected boolean mask array.

  • title (str, optional) – Title for the displayed figure.

  • xlabel (str, optional) – Label for the x-axis of the displayed figure.

  • ylabel (str, optional) – Label for the y-axis of the displayed figure.

  • min_num_index_ranges (int, optional) – Minimum number of selected index ranges.

  • max_num_index_ranges (int, optional) – Maximum number of selected index ranges.

  • interactive (bool, optional) – Show the plot and allow user interactions with the matplotlib figure, defaults to True.

  • filename (str, optional) – Save a .png of the plot to filename, defaults to None, in which case the plot is not saved.

  • return_buf (bool, optional) – Return an in-memory object as a byte stream represention of the Matplotlib figure, defaults to False.

Returns:

Byte stream represention of the Matplotlib figure if return_buf is True (None otherwise), a boolean mask array, and the list of selected index ranges.

Return type:

tuple[_io.BytesIO, str] or None, numpy.ndarray, list[list[int, int]]

select_roi_1d(y, x=None, preselected_roi=None, title=None, xlabel=None, ylabel=None, interactive=True, filename=None, return_buf=False)[source]

Display a 2D plot and have the user select a single region of interest.

Parameters:
  • y (array-like) – One-dimensional data array for which a for which a region of interest will be selected.

  • x (array-like, optional) – x-coordinates of the data

  • preselected_roi (tuple(int, int), optional) – Preselected region of interest.

  • title (str, optional) – Title for the displayed figure.

  • xlabel (str, optional) – Label for the x-axis of the displayed figure.

  • ylabel (str, optional) – Label for the y-axis of the displayed figure.

  • interactive (bool, optional) – Show the plot and allow user interactions with the matplotlib figure, defaults to True.

  • filename (str, optional) – Save a .png of the plot to filename, defaults to None, in which case the plot is not saved.

  • return_buf (bool, optional) – Return an in-memory object as a byte stream represention of the Matplotlib figure, defaults to False.

Returns:

Byte stream represention of the Matplotlib figure if return_buf is True (None otherwise), and the selected region of interest.

Return type:

io.BytesIO or None, tuple(int, int)

select_roi_2d(a, preselected_roi=None, title=None, title_a=None, row_label='row index', column_label='column index', interactive=True, filename=None, return_buf=False)[source]

Display a 2D image and have the user select a single rectangular region of interest.

Parameters:
  • a (array-like) – Two-dimensional image data array for which a region of interest will be selected.

  • preselected_roi (tuple(int, int, int, int), optional) – Preselected region of interest.

  • title (str, optional) – Title for the displayed figure.

  • title_a (str, optional) – Title for the image of a.

  • row_label (str, optional) – Label for the y-axis of the displayed figure, defaults to row index.

  • column_label (str, optional) – Label for the x-axis of the displayed figure, defaults to column index.

  • interactive (bool, optional) – Show the plot and allow user interactions with the matplotlib figure, defaults to True.

  • filename (str, optional) – Save a .png of the plot to filename, defaults to None, in which case the plot is not saved.

  • return_buf (bool, optional) – Return an in-memory object as a byte stream represention of the Matplotlib figure, defaults to False.

Returns:

Byte stream represention of the Matplotlib figure if return_buf is True (None otherwise), and the selected region of interest.

Return type:

tuple[_io.BytesIO, str] or None, tuple(int, int, int, int)

string_to_list(s, split_on_dash=True, remove_duplicates=True, sort=True, raise_error=False)[source]

Return a list of numbers by splitting/expanding a string on any combination of commas, whitespaces, or dashes (when split_on_dash=True). e.g: ‘1, 3, 5-8, 12 ‘ -> [1, 3, 5, 6, 7, 8, 12]

Parameters:
  • s (str) – Input string.

  • split_on_dash (bool, optional) – Allow dashes in input string, defaults to True.

  • remove_duplicates (bool, optional) – Removes duplicates (may also change the order), defaults to True.

  • sort (bool, optional) – Sort in ascending order, defaults to True.

  • raise_error (bool, optional) – Raise an exception upon any error, defaults to False.

Returns:

Input list or None upon an illegal input.

Return type:

list

test_ge_gt_le_lt(ge, gt, le, lt, func, location=None, raise_error=False, log=True)[source]

Check individual and mutual validity of ge, gt, le, lt qualifiers.

Parameters:
  • ge (int or float) – Greater or equal to.

  • gt (int or float) – Greater than.

  • le (int or float) – Smaller or equal to.

  • lt (int or float) – Smaller than.

  • func (callable: is_int, is_num) – Test for integers or numbers.

  • location (str, optional) – Input location.

  • raise_error (bool, optional) – Raise an error, defaults to False.

  • log (bool, optional) – Write error message to the logger, defaults to True.

Returns:

True upon success or False when mutually exlusive.

Return type:

bool

trunc_to_n(value, n=1)[source]

Truncate to a specific number of sig figs.

Parameters:
  • value (float) – Input value.

  • n (int, optional) – Number of sig figs, defaults to 1.

Returns:

Input value trunctated to n sig figs.

Return type:

float

unwrap_tuple(t)[source]

Unwrap a tuple.

Parameters:

t (tuple) – Input tuple.

Returns:

Unwrapped tupple.

Return type:

tuple

CHAP.utils.material module

Module defining the Material class.

class Material(material_name=None, material_file=None, sgnum=None, lattice_parameters_angstroms=None, atoms=None, pos=None, enrgy=None)[source]

Bases: object

Base class for materials in an sin2psi or EDD analysis. Right now it assumes a single material, extend its ability to do differently when test data is available.

add_material(material_name, material_file=None, sgnum=None, lattice_parameters_angstroms=None, atoms=None, pos=None, dmin_angstroms=0.35)[source]

Add a material to the internal list of materials.

Parameters:
  • material_name (str) – Material name.

  • material_file (str, optional) – Material file name in cif or hdf5 format.

  • sgnum (int, optional) – Space group number.

  • lattice_parameters_angstroms (float, optional) – Lattice parameters in angstrom.

  • atoms (list, optional) – Elements.

  • pos (list, optional) – Wyckoff atom positions in the unit cell.

  • dmin_angstroms (float, optional) – Minimum lattice spacing in angstrom, defaults to 0.35.

ds_unique(tth_tol=None, tth_max=None, round_sig=8)[source]

Return the unique lattice spacings.

Parameters:
  • tth_tol (float, optional) – Two-theta tolerance (in degrees).

  • tth_max (float, optional) – Maximum two-theta value (in degrees).

  • round_sig (int, optional) – Significant digits, passed to round() function, defaults to 8.

Returns:

Unique lattice spacings.

Return type:

list

get_ds_unique(tth_tol=None, tth_max=None, round_sig=8)[source]

Get the list of unique lattice spacings from material HKLs.

Parameters:
  • tth_tol (float, optional) – Two-theta tolerance (in degrees).

  • tth_max (float, optional) – Maximum two-theta value (in degrees).

  • round_sig (int, optional) – Significant digits, passed to round() function, defaults to 8.

Returns:

HKLs corresponding to the unique lattice spacings and the list of the unique lattice spacings.

Return type:

list, list

hkls_unique(tth_tol=None, tth_max=None, round_sig=8)[source]

Return the unique HKLs.

Parameters:
  • tth_tol (float, optional) – Two-theta tolerance (in degrees).

  • tth_max (float, optional) – Maximum two-theta value (in degrees).

  • round_sig (int, optional) – Significant digits, passed to round() function, defaults to 8.

Returns:

HKLs corresponding to the unique lattice spacings.

Return type:

list

lattice_parameters(index=0)[source]

Convert from internal nm units to angstrom.

Parameters:

index (int, optional) – List index of the material, defaults to 0.

Returns:

Lattice parameters in angstrom.

Return type:

list

static make_material(material_name, material_file=None, sgnum=None, lattice_parameters_angstroms=None, atoms=None, pos=None, dmin_angstroms=0.35)[source]

Use HeXRD to get material properties when a materials file is provided. Use xrayutilities otherwise.

Parameters:
  • material_name (str) – Material name.

  • material_file (str, optional) – Material file name in cif or hdf5 format.

  • sgnum (int, optional) – Space group number.

  • lattice_parameters_angstroms (float, optional) – Lattice parameters in angstrom.

  • atoms (list, optional) – Elements.

  • pos (list, optional) – Wyckoff atom positions in the unit cell.

  • dmin_angstroms (float, optional) – Minimum lattice spacing in angstrom, defaults to 0.35.

Returns:

Material properties.

Return type:

hexrd.material.Material or xrayutilities.materials.Crystal

CHAP.utils.models module

Utils Pydantic model classes.

class Constant[source]

Bases: CHAPBaseModel

Class representing a Constant model component.

Variables:
  • model (Literal['constant']) – The model component base name (a prefix will be added if multiple identical model components are added).

  • parameters (list[FitParameter], optional) – Function parameters, defaults to those auto generated from the function signature (excluding the independent variable).

  • prefix (str, optional) – The model prefix, defaults to ‘’.

model: Literal['constant']
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

parameters: Annotated[list[FitParameter], Len(min_length=0, max_length=None), FieldInfo(annotation=NoneType, required=True, validate_default=True)]
prefix: str | None
class Exponential[source]

Bases: CHAPBaseModel

Class representing an Exponential model component.

Variables:
  • model (Literal['exponential']) – The model component base name (a prefix will be added if multiple identical model components are added).

  • parameters (list[FitParameter], optional) – Function parameters, defaults to those auto generated from the function signature (excluding the independent variable).

  • prefix (str, optional) – The model prefix, defaults to ‘’.

model: Literal['exponential']
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

parameters: Annotated[list[FitParameter], Len(min_length=0, max_length=None), FieldInfo(annotation=NoneType, required=True, validate_default=True)]
prefix: str | None
class Expression[source]

Bases: CHAPBaseModel

Class representing an Expression model component.

Variables:
  • model (Literal['expression']) – The model component base name (a prefix will be added if multiple identical model components are added).

  • expr (str) – Mathematical expression to represent the model component.

  • parameters (list[FitParameter], optional) – Function parameters, defaults to those auto generated from the model expression (excluding the independent variable).

  • prefix (str, optional) – The model prefix, defaults to ‘’.

expr: Annotated[str, StringConstraints(strip_whitespace=True, to_upper=None, to_lower=None, strict=None, min_length=1, max_length=None, pattern=None, ascii_only=None)]
model: Literal['expression']
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

parameters: Annotated[list[FitParameter], Len(min_length=0, max_length=None), FieldInfo(annotation=NoneType, required=True, validate_default=True)]
prefix: str | None
class FitConfig[source]

Bases: CHAPBaseModel

Class representing the configuration for the fit processor.

Variables:
  • code (Literal['lmfit', 'scipy'], optional) – Specifies is lmfit is used to perform the fit or if the scipy fit method is called directly, default to ‘lmfit’.

  • parameters (list[FitParameter], optional) – Fit model parameters in addition to those implicitly defined through the build-in model functions, defaults to []

  • models (list[models]) – The component(s) of the (composite) fit model.

  • rel_height_cutoff (float, optional) – Relative peak height cutoff for peak fitting (any peak with a height smaller than rel_height_cutoff times the maximum height of all peaks gets removed from the fit model).

  • num_proc (int, optional) – The number of processors used in fitting a map of data, defaults to 1.

  • plot (bool, optional.) – Whether a plot of the fit result is generated, defaults to False.

  • print_report (bool, optional.) – Whether to generate a fit result printout, defaults to False.

  • memfolder (str, optional) – Folder name for the temporary memory map if multiple processors are used, defaults to ‘joblib_memmap’.

code: Literal['lmfit', 'scipy']
memfolder: str
method: Literal['leastsq', 'trf', 'dogbox', 'lm', 'least_squares']
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

models: Annotated[list[Constant | Linear | Quadratic | Exponential | Gaussian | Lorentzian | PseudoVoigt | Rectangle | Expression | Multipeak], Len(min_length=1, max_length=None)]
num_proc: Annotated[int, None, Interval(gt=0, ge=None, lt=None, le=None), None]
parameters: Annotated[list[FitParameter], Len(min_length=0, max_length=None)]
plot: Annotated[bool, Strict(strict=True)]
print_report: Annotated[bool, Strict(strict=True)]
rel_height_cutoff: Annotated[float, None, Interval(gt=0, ge=None, lt=1.0, le=None), None, AllowInfNan(allow_inf_nan=False)] | None
classmethod validate_method(method, info)[source]

Validate the specified method.

Parameters:
  • method (str) – The value of method to validate.

  • info (pydantic.ValidationInfo) – Model parameter validation information.

Returns:

Fit method.

Return type:

str

class FitParameter[source]

Bases: CHAPBaseModel

Class representing a specific fit parameter for the fit processor.

Variables:
  • name (str) – Parameter name.

  • value (float, optional) – Parameter value.

  • min (bool, optional) – Lower Parameter value bound, defaults to -numpy.inf.

  • max (bool, optional) – Upper Parameter value bound. defaults to numpy.inf.

  • vary (bool, optional) – Whether the Parameter is varied during a fit, defaults to True.

  • expr (str, optional) – Mathematical expression used to constrain the value during the fit. To remove a constraint you must supply an empty string.

property default

Return the default parameter value.

Type:

float or None

expr: Annotated[str, StringConstraints(strip_whitespace=True, to_upper=None, to_lower=None, strict=None, min_length=1, max_length=None, pattern=None, ascii_only=None)] | None
property init_value

Return the initial parameter value.

Type:

float or None

max: Annotated[float, None, Interval(gt=None, ge=None, lt=None, le=None), None, None] | None
min: Annotated[float, None, Interval(gt=None, ge=None, lt=None, le=None), None, None] | None
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context: Any, /) None

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Args:

self: The BaseModel instance. context: The context.

name: Annotated[str, StringConstraints(strip_whitespace=True, to_upper=None, to_lower=None, strict=None, min_length=1, max_length=None, pattern=None, ascii_only=None)]
property prefix

Return the parametr prefix.

Type:

str or None

set(value=None, min=None, max=None, vary=None, expr=None)[source]

Set or update FitParameter attributes.

Parameters:
  • value (float, optional) – Parameter value.

  • min (bool, optional) – Lower Parameter value bound. To remove the lower bound you must set min to numpy.inf.

  • max (bool, optional) – Upper Parameter value bound. To remove the lower bound you must set max to numpy.inf.

  • vary (bool, optional) – Whether the Parameter is varied during a fit.

  • expr (str, optional) – Mathematical expression used to constrain the value during the fit. To remove a constraint you must supply an empty string.

property stderr

Return the parameter’s uncertainty value.

Type:

float or None

classmethod validate_max(value)[source]

Validate the specified max.

Parameters:

value (float or None) – Field value to validate (max).

Returns:

Upper bound of fit parameter.

Return type:

float

classmethod validate_min(value)[source]

Validate the specified min.

Parameters:

value (float or None) – Field value to validate (min).

Returns:

Lower bound of fit parameter.

Return type:

float

value: Annotated[float, None, Interval(gt=None, ge=None, lt=None, le=None), None, AllowInfNan(allow_inf_nan=False)] | None
vary: Annotated[bool, Strict(strict=True)]
class Gaussian[source]

Bases: CHAPBaseModel

Class representing a Gaussian model component.

Variables:
  • model (Literal['gaussian']) – The model component base name (a prefix will be added if multiple identical model components are added).

  • parameters (list[FitParameter], optional) – Function parameters, defaults to those auto generated from the function signature (excluding the independent variable).

  • prefix (str, optional) – The model prefix, defaults to ‘’.

model: Literal['gaussian']
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

parameters: Annotated[list[FitParameter], Len(min_length=0, max_length=None), FieldInfo(annotation=NoneType, required=True, validate_default=True)]
prefix: str | None
class Linear[source]

Bases: CHAPBaseModel

Class representing a Linear model component.

Variables:
  • model (Literal['linear']) – The model component base name (a prefix will be added if multiple identical model components are added).

  • parameters (list[FitParameter], optional) – Function parameters, defaults to those auto generated from the function signature (excluding the independent variable).

  • prefix (str, optional) – The model prefix, defaults to ‘’.

model: Literal['linear']
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

parameters: Annotated[list[FitParameter], Len(min_length=0, max_length=None), FieldInfo(annotation=NoneType, required=True, validate_default=True)]
prefix: str | None
class Lorentzian[source]

Bases: CHAPBaseModel

Class representing a Lorentzian model component.

Variables:
  • model (Literal['lorentzian']) – The model component base name (a prefix will be added if multiple identical model components are added).

  • parameters (list[FitParameter], optional) – Function parameters, defaults to those auto generated from the function signature (excluding the independent variable).

  • prefix (str, optional) – The model prefix, defaults to ‘’.

model: Literal['lorentzian']
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

parameters: Annotated[list[FitParameter], Len(min_length=0, max_length=None), FieldInfo(annotation=NoneType, required=True, validate_default=True)]
prefix: str | None
class Multipeak[source]

Bases: CHAPBaseModel

Class representing a multipeak model.

Variables:
  • model (Literal['expression']) – The model component base name (a prefix will be added if multiple identical model components are added).

  • centers – Peak centers.

  • centers_range (float, optional) – Range of peak centers around their centers.

  • fit_type (Literal['uniform', 'unconstrained'], optional.) – Type of fit, defaults to ‘unconstrained’.

  • fwhm_min (float, optional) – Lower limit of the fwhm of the peaks.

  • fwhm_max (float, optional) – Upper limit of the fwhm of the peaks.

  • peak_models (Literal['gaussian', 'lorentzian', 'pvoigt'], optional.) – Type of peaks, defaults to ‘gaussian’.

centers: Annotated[list[Annotated[float, None, Interval(gt=None, ge=None, lt=None, le=None), None, AllowInfNan(allow_inf_nan=False)]], Len(min_length=1, max_length=None)]
centers_range: Annotated[float, None, Interval(gt=None, ge=None, lt=None, le=None), None, AllowInfNan(allow_inf_nan=False)] | None
fit_type: Literal['uniform', 'unconstrained'] | None
fwhm_max: Annotated[float, None, Interval(gt=None, ge=None, lt=None, le=None), None, AllowInfNan(allow_inf_nan=False)] | None
fwhm_min: Annotated[float, None, Interval(gt=None, ge=None, lt=None, le=None), None, AllowInfNan(allow_inf_nan=False)] | None
model: Literal['multipeak']
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

peak_models: Literal['gaussian', 'lorentzian', 'pvoigt']
class PseudoVoigt[source]

Bases: CHAPBaseModel

Class representing a PseudoVoigt model component.

Variables:
  • model (Literal['pvoigt']) – The model component base name (a prefix will be added if multiple identical model components are added).

  • parameters (list[FitParameter], optional) – Function parameters, defaults to those auto generated from the function signature (excluding the independent variable).

  • prefix (str, optional) – The model prefix, defaults to ‘’.

model: Literal['pvoigt']
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

parameters: Annotated[list[FitParameter], Len(min_length=0, max_length=None), FieldInfo(annotation=NoneType, required=True, validate_default=True)]
prefix: str | None
class Quadratic[source]

Bases: CHAPBaseModel

Class representing a Quadratic model component.

Variables:
  • model (Literal['quadratic']) – The model component base name (a prefix will be added if multiple identical model components are added).

  • parameters (list[FitParameter], optional) – Function parameters, defaults to those auto generated from the function signature (excluding the independent variable).

  • prefix (str, optional) – The model prefix, defaults to ‘’.

model: Literal['quadratic']
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

parameters: Annotated[list[FitParameter], Len(min_length=0, max_length=None), FieldInfo(annotation=NoneType, required=True, validate_default=True)]
prefix: str | None
class Rectangle[source]

Bases: CHAPBaseModel

Class representing a Rectangle model component.

Variables:
  • model (Literal['rectangle']) – The model component base name (a prefix will be added if multiple identical model components are added).

  • parameters (list[FitParameter], optional) – Function parameters, defaults to those auto generated from the function signature (excluding the independent variable).

  • prefix (str, optional) – The model prefix, defaults to ‘’.

model: Literal['rectangle']
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

parameters: Annotated[list[FitParameter], Len(min_length=0, max_length=None), FieldInfo(annotation=NoneType, required=True, validate_default=True)]
prefix: str | None
constant(x, c=0.0)[source]

Return a linear function.

Parameters:

c (float, optional) – Constant, defaults to 0.

Returns:

The function evaluations.

Return type:

numpy.ndarray

\[f(x; c) = c\]
exponential(x, amplitude=1.0, decay=1.0)[source]

Return an exponential function.

Parameters:
  • amplitude (float, optional) – Amplitude, defaults to 1.

  • decay (float, optional) – Exponential decay, defaults to 1.

Returns:

The function evaluations.

Return type:

numpy.ndarray

\[f(x; A, \tau) = A exp(-x/\tau)\]

with amplitude for \(A\) and decay for \(\tau\).

gaussian(x, amplitude=1.0, center=0.0, sigma=1.0)[source]

Return a 1-dimensional Gaussian function.

Parameters:
  • amplitude (float, optional) – amplitude, defaults to 1.

  • center (float, optional) – Center, defaults to 0.

  • sigma (float, optional) – Standard deviation, defaults to 1.

Returns:

The function evaluations.

Return type:

numpy.ndarray

\[f(x; A, \mu, \sigma) = frac{A}{\sigma\sqrt{2\pi}} e^{[{-{(x-\mu)^2}/{{2\sigma}^2}}]}\]

where the parameter amplitude corresponds to \(A\), center to \(\mu\), and sigma to \(\sigma\). The full width at half maximum is \(2\sigma\sqrt{2\ln{2}}\), approximately \(2.3548\sigma\).where the parameter amplitude corresponds to \(A\), center to \(\mu\), and sigma to \(\sigma\). The full width at half maximum is \(2\sigma\sqrt{2\ln{2}}\), and the peak height is \(A/(\sigma\sqrt{2\pi})\)

linear(x, slope=1.0, intercept=0.0)[source]

Return a linear function.

Parameters:
  • slope (float, optional) – Slope, defaults to 0.

  • intercept (float, optional) – Intercept, defaults to 0.

Returns:

The function evaluations.

Return type:

numpy.ndarray

\[f(x; m, b) = m x + b\]

with slope for \(m\) and intercept for \(b\).

lorentzian(x, amplitude=1.0, center=0.0, sigma=1.0)[source]

Return a 1-dimensional Lorentzian function.

Parameters:
  • amplitude (float, optional) – amplitude, defaults to 1.

  • center (float, optional) – Center, defaults to 0.

  • sigma (float, optional) – Standard deviation, defaults to 1.

Returns:

The function evaluations.

Return type:

numpy.ndarray

\[f(x; A, \mu, \sigma) = \frac{A}{\pi} \big[ \frac{\sigma}{(x - \mu)^2 + \sigma^2} \big]\]

where the parameter amplitude corresponds to \(A\), center to \(\mu\), and sigma to \(\sigma\). The full width at half maximum is \(2\sigma\), and the peak height is \(A/(\sigma\pi)\).

pvoigt(x, amplitude=1.0, center=0.0, sigma=1.0, fraction=0.5)[source]

Return a 1-dimensional pseudo-Voigt distribution.

This is an approximation of the Voigt function, a weighted sum of a Gaussian and Lorentzian distribution, with the parameter fraction setting the relative weight of the Gaussian and Lorentzian components.

Parameters:
  • amplitude (float, optional) – amplitude, defaults to 1.

  • center (float, optional) – Center, defaults to 0.

  • sigma (float, optional) – Standard deviation, defaults to 1.

  • fraction (float, optional) – Relative weight of the Gaussian and Lorentzian components, defaults to 0.5.

Returns:

The function evaluations.

Return type:

numpy.ndarray

\[f(x; A, \mu, \sigma) = frac{(1-\alpha)A}{\sigma_g\sqrt{2\pi}} e^{[{-{(x-\mu)^2}/{{2\sigma_g}^2}}]} + \frac{\alpha A}{\pi} \big[ \frac{\sigma}{(x - \mu)^2 + \sigma^2} \big]\]

where the parameter amplitude corresponds to \(A\), center to \(\mu\), and sigma to \(\sigma\). Here \(\sigma_g = {\sigma}/{\sqrt{2\ln{2}}}\) so that the full width at half maximum is \(2\sigma\) and the peak height is approximately \(A/(2.536\sigma)\).

quadratic(x, a=0.0, b=0.0, c=0.0)[source]

Return a parabolic function.

Parameters:
  • a (float, optional) – Quadratic polynomial coefficient, defaults to an initial value of 0.

  • b (float, optional) – Linear polynomial coefficient, defaults to an initial value of 0.

  • c (float, optional) – Constant polynomial coefficient, defaults to an initial value of 0.

Returns:

The function evaluations.

Return type:

numpy.ndarray

\[f(x; a, b, c) = a x^2 + b x + c\]
rectangle(x, amplitude=1.0, center1=0.0, sigma1=1.0, center2=1.0, sigma2=1.0, form='linear')[source]

Return a rectangle function.

Starts at 0.0, rises to amplitude (at center1 with width sigma1), then drops to 0.0 (at center2 with width sigma2)

Parameters:
  • x (float or numpy.ndarray) – Input values where the function is evaluated.

  • amplitude (float, optional) – Maximum height of the rectangle, defaults to 1.0.

  • center1 (float, optional) – Location of the rising edge, defaults to 0.0.

  • sigma1 (float, optional) – Width or smoothness of the rising edge, defaults to 1.0.

  • center2 (float, optional) – Location of the falling edge, defaults to 1.0.

  • sigma2 (float, optional) – Width or smoothness of the falling edge, defaults to 1.0.

  • form (str, optional) –

    Shape type of the transition edges:

    • 'linear': Simple ramp-up and ramp-down.

    • 'atan' or 'arctan': Inverse tangent transitions.

    • 'erf': Error function (Gaussian-like) transitions.

    • 'logistic': Sigmoidal (logistic function) transitions.

Returns:

The evaluated rectangle function values.

Return type:

float or numpy.ndarray

Note

The output is calculated based on the selected form:

  • atan: \(\frac{A}{\pi} [ \arctan(arg_1) + \arctan(arg_2) ]\)

  • erf: \(\frac{1}{2} A [ \text{erf}(arg_1) + \text{erf}(arg_2) ]\)

  • logistic: \(A [ \frac{1}{1 + \exp(-arg_1)} + \frac{1}{1 + \exp(-arg_2)} - 1 ]\)

The function is constructed using normalized arguments for the rising and falling edges: \(arg_1 = \frac{x - center_1}{\sigma_1}\) and \(arg_2 = \frac{center_2 - x}{\sigma_2}\)

validate_parameters(parameters, info)[source]

Validate the parameters.

Parameters:
  • parameters (list[FitParameter]) – Fit model parameters.

  • info (pydantic.ValidationInfo) – Model parameter validation information.

Returns:

List of fit model parameters.

Return type:

list[FitParameter]

CHAP.utils.parfile module

Utilities for interacting with scans using an SMB-style par file as input.

class ParFile(par_file, scan_numbers=None, scann_col_name='SCAN_N')[source]

Bases: object

Representation of a par file.

Variables:
  • column_names (list[str]) – List of the names of each column in the par file.

  • data (list[list]) – A 2D array of the data in this par file: 0th index: row, 1st index: column

  • json_file (str) – Name of the json file containing the keys for the column names of the par file.

  • par_file (str) – Name of the par file.

  • scann_i (int) – Column index for the scan number column in the par file.

  • scan_numbers (list[int]) – Scan numbers for which data is available in the par file.

  • spec_file (str) – Name of the SPEC data file associated with this par file.

get_map(experiment_type, station, par_dims, other_dims=None)[source]

Return a map configuration based on this par file.

Parameters:
  • experiment_type (Literal['EDD', 'GIWAXS', 'SAXSWAXS', 'TOMO', 'XRF']) – Experiment type name for the map that this par file represents.

  • station (Literal['id1a3','id3a','id3b']) – Station name at which the data were collected.

  • par_dims (list[dict[str, str]]) – List of dictionaries configuring the map’s independent dimensions.

  • other_dims (list[dict[str,str]], optional) – Other dimensions to include in the returned MapConfig’s independednt_dimensions. Use this if each scans in this par file captured more than one frame of data.

Returns:

Map configuration.

Return type:

MapConfig

get_values(column, scan_numbers=None)[source]

Return values from a single column of the par file.

Parameters:
  • column (str or int) – String name OR index of the column to return values for.

  • scan_numbers (list[int], optional) – Specific scan numbers to return values in the given column for (instead of the default behavior: return the entire column of values).

Raise:

ValueError: Unavailable column name. TypeError: Illegal column name type.

Returns:

Values from a single column in the par file.

Return type:

list[object]

good_scan_numbers(good_col_name='1/0')[source]

Return the numbers of scans marked with a “1” in the indicated “good” column of the par file.

Parameters:

good_col_name (str, optional) – Name of the “good” column of the par file, defaults to “1/0”

Raises:

ValueError – If this par file does not have a column with the same name as good_col_name.

Returns:

“good” scan numbers.

Return type:

list[int]

map_values(map_config, values)[source]

Return a reshaped array of the 1D list values so that it matches up with the coordinates of map_config.

Parameters:
  • map_config (MapConfig) – Map configuration according to which values will be reshaped.

  • values (list or numpy.ndarray) – 1D list of values to reshape.

Returns:

Reshaped array of values.

Return type:

numpy.ndarray