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)[source]

Bases: object

A model fit component.

class Components[source]

Bases: dict

The dictionary of model fit components.

property components

Return the model fit components.

Type:

list[models]

class Fit(y, config, logger, x=None, mask=None)[source]

Bases: object

Wrapper class for scipy/lmfit.

add_model(model)[source]

Add a model component to the fit model.

Parameters:

model (models) – A fit model class (make sure its prefix is specified in model.prefix for duplicative model names).

add_parameter(parameter)[source]

Add a fit parameter to the fit model.

Parameters:

parameter (dict) – 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 –

    Additional key, value pairs to pass on directly to the core fit routine.

static guess_init_peak(x, y, target_centers, centers_range, centers_range_fraction, min_height=None, min_width=None)[source]

Return guesses for the initial height, center and fwhm for peak-like models.

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(x=None, 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:
  • x (array-like, optional) – x-coordinates.

  • 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) – Visually distinguish the masked from the unmasked data, defaults to True.

  • **kwargs –

    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 y

Return the input y-coordinates.

Type:

numpy.ndarray

class FitMap(y, config, logger, x=None, mask=None)[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 (int or 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 –

    Additional key, value pairs to pass on directly to the core fit routine.

freemem()[source]

Free memory allocated for parallel processing.

init_parameters(dims=None)[source]

Return the initial fit parameters.

Parameters:

dims (int or list or tuple, optional) – Map indices of the initial 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:

Initial fit parameters.

Return type:

list[str] or dict

property init_values

Return init values of the fit parameters.

Type:

numpy.ndarray

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(x=None, dims=None, *, y_title=None, plot_comp_legends=False, plot_residual=False, plot_masked_data=True, **kwargs)[source]

Plot the best fits.

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

  • 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) – Visually distinguish the masked from the unmasked data, defaults to True.

  • **kwargs –

    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.

Variables:

config (dict, optional) – Initialization parameters for an instance of FitConfig.

config: FitConfig | None
static create_multipeak_model(model)[source]

Create a multipeak model.

Parameters:

model (MultipeakModel) – 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.

pipeline_fields: dict
process(data)[source]

Fit the data and return a Fit or FitMap object depending on the dimensionality of the input data. The input data should be a list of PipelineData items containing either one with a data field of type Fit or FitMap (to refit or continue a previous fit), or one with the name of signal and an array-like data field. In the latter case, optional x-coordinates can be supplied by a second PipelineData item with the name of coordinates and again an array-like data field.

Parameters:

data (list[PipelineData]) – Input data.

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 (FitParameter) – The fit parameter to add to the dictionary.

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

class SetupProcessor(*, 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

Processor to set up an empty results container for FitProcessor.

Creates a Zarr store whose structure is determined by the fit configuration and the scan / signal dimensions.

Variables:
  • config (dict, optional) – Initialization parameters for an instance of FitConfig.

  • dataset_shape (list[int], optional) – Shape of the map (scan) dimensions of the output datasets, defaults to [0].

  • dataset_chunks (list[int] or 'auto', optional) – Chunk shape along the scan dimensions, or 'auto' to let Zarr choose, defaults to 'auto'.

  • signal_shape (list[int]) – Shape of one frame of the 1-D signal being fit (the signal dimension).

config: FitConfig | None
dataset_chunks: Literal['auto'] | Annotated[list[Annotated[int, None, Interval(gt=0, ge=None, lt=None, le=None), None]], Len(min_length=1, max_length=None)] | None
dataset_shape: Annotated[list[Annotated[int, None, Interval(gt=None, ge=0, lt=None, le=None), None]], Len(min_length=1, max_length=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.

pipeline_fields: dict
process(data)[source]

Create and return an empty Zarr store whose group hierarchy mirrors the output of FitProcessor for the configured fit model.

The store structure is produced by zarr_tree() and populated into an in-memory zarr.Group so that a downstream writer can write fit results into it incrementally.

Parameters:

data (list[PipelineData]) – Input pipeline data; may supply a FitConfig to populate config when one is not already set.

Returns:

In-memory Zarr root group pre-structured for fit results.

Return type:

zarr.Group

signal_shape: Annotated[list[Annotated[int, None, Interval(gt=None, ge=0, lt=None, le=None), None]], Len(min_length=1, max_length=None)]
class UpdateValuesProcessor(*, 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

Processor to extract fit results from a Fit (or FitMap) object and format them as a list of path-keyed value dicts suitable for a downstream NexusValuesWriter.

This processor is the write-side complement of SetupProcessor: the paths it emits correspond to the Zarr dataset layout defined by zarr_tree().

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)[source]

Extract fit results from a Fit or FitMap object and return them as a flat list of path-keyed value dicts.

The paths in the returned dicts match the dataset layout defined by zarr_tree() and the container created by SetupProcessor.

Parameters:

data (list[PipelineData]) – Input pipeline data; must include a 'FitProcessor'-tagged item whose data field is a Fit or FitMap instance.

Returns:

List of dicts, each with keys 'path' (str) and 'data' (scalar or array), for use with a downstream NexusValuesWriter.

Return type:

list[dict]

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, merge_source_only=True, 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 –

    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 –

    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[[int, int]], optional) – List of preselected index ranges to mask, lower bounds are inclusive, upper bounds not.

  • 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[[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 ConstantModel[source]

Bases: FitModel

Class representing a Constant model component.

Variables:

model_type (Literal['constant']) – Model component type.

LINEAR_PARAMETERS: ClassVar[list[str]] = ['c']
LMFITMODEL

alias of ConstantModel

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.

model_type: Literal['constant']
class ExponentialModel[source]

Bases: FitModel

Class representing an Exponential model component.

Variables:

model_type (Literal['exponential']) – Model component type.

LINEAR_PARAMETERS: ClassVar[list[str]] = ['amplitude']
LMFITMODEL

alias of ExponentialModel

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.

model_type: Literal['exponential']
class ExpressionModel[source]

Bases: FitModel

Class representing an Expression model component.

Variables:
  • model_type (Literal['expression']) – Model component type.

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

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)]
property expr_parameters

Return the parameter expr_parameters.

Type:

str or None

lmfit_model(prefix=None, parameters=None)[source]

Return the corresponding lmfit model.

Parameters:
  • prefix (str, optional) – Model prefix.

  • parameters (lmfit.Parameters) – Current model parameters.

Returns:

Corresponding lmfit model.

Return type:

lmfit.models.ExpressionModel

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.

model_type: Literal['expression']
validate_expressionmodel_after()[source]

Parse expr for free variable names and append a FitParameter for each one not already present in parameters and not a built-in asteval symbol or the independent variable x.

Returns:

Validated and updated model instance.

Return type:

ExpressionModel

class FitConfig[source]

Bases: CHAPBaseModel

Class representing the configuration for the fit processor.

Variables:
  • abs_height_cutoff (int, optional) – Absolute peak height cutoff for peak fitting (any peak with a height smaller than abs_height_cutoff gets removed from the fit model).

  • 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’.

  • max_nfev (int, optional) – Maximum number of function evaluations in the the strain analysis peak fitting routine.

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

  • method (Literal[ 'leastsq', 'trf', 'dogbox', 'lm', 'least_squares']) – SciPy non-linear fit method, defaults to “leastsq”.

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

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

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

  • 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.

  • 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).

abs_height_cutoff: Annotated[int, None, Interval(gt=0, ge=None, lt=None, le=None), None] | None
code: Literal['lmfit', 'scipy']
max_nfev: Annotated[int, None, Interval(gt=0, ge=None, lt=None, le=None), None] | None
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[Annotated[ConstantModel | LinearModel | QuadraticModel | ExponentialModel | GaussianModel | LorentzianModel | PseudoVoigtModel | RectangleModel | ExpressionModel, FieldInfo(annotation=NoneType, required=True, discriminator='model_type')] | MultipeakModel], 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, 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

zarr_tree(dataset_shape, dataset_chunks, signal_shape, nxlinks=None)[source]

Return a nested dict representing the Zarr group tree for this fit’s output container.

The tree contains a data group with global fit statistics (best_fit, num_func_eval, redchi, residual, success) and a components group with one sub-tree per model component, structured by zarr_tree(). The paths in this tree correspond to those emitted by UpdateValuesProcessor.

Parameters:
  • dataset_shape (tuple[int, ...]) – Shape of the measurement (scan) dimensions of the output dataset, excluding the signal dimensions.

  • dataset_chunks (list[int] or str) – Chunk shape along the scan dimensions, or 'auto'.

  • signal_shape (tuple[int, ...]) – Shape of one frame of the 1-D signal being fit (the signal dimension).

  • nxlinks (str or list[str], optional) – NeXus path(s) to link into the data group. When the zarr tree is written to a .zarr file and converted to .nxs with ZarrToNexusProcessor, each path produces an NXlink whose name is os.path.basename(path). Accepts a single path string or a list of path strings. All links must be explicit; none are auto-generated.

Returns:

Nested dict representing the zarr group tree for this fit.

Return type:

dict

class FitModel[source]

Bases: CHAPBaseModel

Abstract base class representing a generic model component.

Variables:
  • model_type – Model component type.

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

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

LINEAR_PARAMETERS: ClassVar[list[str]] = []
MODEL_IDENTIFIERS: ClassVar[list[str]] = []
MODEL_PARAMETERS: ClassVar[list[str]] = []
eval(x, **kwargs)[source]
property func

Return the model function

Type:

function

property func_args

Return the model function arguments

Type:

list[str]

property long_name

Return the fully-qualified model name, combining the model prefix (if any) with model_type.

Type:

str

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.

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

Validate the model configuration and initialize the appropriate parameters from the model function signature.

Returns:

Validated and initialized configuration.

Return type:

Model

zarr_tree(dataset_shape, dataset_chunks, signal_shape, nxlinks=None)[source]

Return a nested dict representing the Zarr group tree for this model component’s output container.

The group contains a parameters sub-group (one entry per parameter, structured by zarr_tree()) and a data sub-group with a best_fit dataset shaped to hold the component’s fitted curve for every point in the scan map.

Parameters:
  • dataset_shape (tuple[int, ...]) – Shape of the measurement (scan) dimensions of the output dataset, excluding the signal dimensions.

  • dataset_chunks (list[int] or str) – Chunk shape along the scan dimensions, or 'auto'.

  • signal_shape (tuple[int, ...]) – Shape of one frame of the 1-D signal being fit (the signal dimension).

  • nxlinks (str or list[str], optional) – NeXus path(s) to link into the data group. When the zarr tree is written to a .zarr file and converted to .nxs with ZarrToNexusProcessor, each path produces an NXlink whose name is os.path.basename(path). Accepts a single path string or a list of path strings. All links must be explicit; none are auto-generated.

Returns:

Nested dict representing the zarr group tree for this model component.

Return type:

dict

class FitParameter[source]

Bases: CHAPBaseModel

Class representing a specific fit parameter for the fit processor.

Variables:
  • name (str) – Parameter name (always includes the component prefix if belonging to a model component)

  • 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.

  • description (str, optional) – Free-text description of the parameter, defaults to “unspecified”.

  • units (str, optional) – Units of the parameter, defaults to “unspecified”.

property default

Return the default parameter value.

Type:

float or None

description: str | 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)]
set(value=None, min=None, max=None, vary=None, expr=None, is_init_value=True)[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.

  • is_init_value (bool, optional) – Whether to set the intial value when setting the parameter value, default to True.

property stderr

Return the parameter’s uncertainty value.

Type:

float or None

units: str | 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)]
zarr_tree(dataset_shape, dataset_chunks, nxlinks=None)[source]

Return a nested dict representing the Zarr group tree for this fit parameter’s output container.

The group contains one dataset per parameter attribute (value, error, initial, min, max, vary, expression), each shaped to hold one scalar per point in the scan map.

Parameters:
  • dataset_shape (tuple[int, ...]) – Shape of the measurement (scan) dimensions of the output dataset, excluding the signal dimensions.

  • dataset_chunks (list[int] or str) – Chunk shape along the scan dimensions, or 'auto'.

  • nxlinks (str or list[str], optional) – NeXus path(s) to link into the data group. When the zarr tree is written to a .zarr file and converted to .nxs with ZarrToNexusProcessor, each path produces an NXlink whose name is os.path.basename(path). Accepts a single path string or a list of path strings. All links must be explicit; none are auto-generated.

Returns:

Nested dict representing the zarr group tree for this parameter.

Return type:

dict

class GaussianModel[source]

Bases: FitModel

Class representing a Gaussian model component.

Variables:

model_type (Literal['gaussian']) – Model component type.

LINEAR_PARAMETERS: ClassVar[list[str]] = ['amplitude']
LMFITMODEL

alias of GaussianModel

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.

model_type: Literal['gaussian']
class LinearModel[source]

Bases: FitModel

Class representing a Linear model component.

Variables:

model_type (Literal['linear']) – Model component type.

LINEAR_PARAMETERS: ClassVar[list[str]] = ['slope', 'intercept']
LMFITMODEL

alias of LinearModel

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.

model_type: Literal['linear']
class LorentzianModel[source]

Bases: FitModel

Class representing a Lorentzian model component.

Variables:

model_type (Literal['lorentzian']) – Model component type.

LINEAR_PARAMETERS: ClassVar[list[str]] = ['amplitude']
LMFITMODEL

alias of LorentzianModel

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.

model_type: Literal['lorentzian']
class MultipeakModel[source]

Bases: CHAPBaseModel

Class representing a multipeak model.

Variables:
  • model_type (Literal['expression']) – Model component type.

  • centers – Peak centers.

  • centers_range (float, optional) – Range of peak centers around their centers, defaults to 0.0 in which case it is ignored. The actual values used are the larger of the ones determined from centers_range and centers_range_fraction.

  • centers_range_fraction (float, optional) – Range of peak centers around their centers as a fraction of their position, defaults to 0.05. The actual values used are the larger of the ones determined from centers_range and centers_range_fraction.

  • 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=0, lt=None, le=None), None, AllowInfNan(allow_inf_nan=False)] | None
centers_range_fraction: Annotated[float, None, Interval(gt=None, ge=0, 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_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

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

model_type: Literal['multipeak']
peak_models: Literal['gaussian', 'lorentzian', 'pvoigt']
class PseudoVoigtModel[source]

Bases: FitModel

Class representing a PseudoVoigt model component.

Variables:

model_type (Literal['pvoigt']) – Model component type.

LINEAR_PARAMETERS: ClassVar[list[str]] = ['amplitude']
LMFITMODEL

alias of PseudoVoigtModel

MODEL_PARAMETERS: ClassVar[list[str]] = ['fraction']
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.

model_type: Literal['pvoigt']
class QuadraticModel[source]

Bases: FitModel

Class representing a Quadratic model component.

Variables:

model_type (Literal['parabolic']) – Model component type.

LINEAR_PARAMETERS: ClassVar[list[str]] = ['a', 'b', 'c']
LMFITMODEL

alias of QuadraticModel

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.

model_type: Literal['parabolic']
class RectangleModel[source]

Bases: FitModel

Class representing a Rectangle model component.

Variables:
  • form (Literal[ 'linear', 'atan', 'arctan', 'erf', 'logistic'], optional) – Shape type of the transition edges, defaults to ‘linear’.

  • model_type (Literal['rectangle']) – Model component type.

LINEAR_PARAMETERS: ClassVar[list[str]] = ['amplitude']
LMFITMODEL

alias of RectangleModel

MODEL_IDENTIFIERS: ClassVar[list[str]] = ['form']
form: Literal['linear', 'atan', 'arctan', 'erf', 'logistic']
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.

model_type: Literal['rectangle']
constant(x, c=0.0)[source]

Return a linear function.

Parameters:

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

Returns:

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:

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:

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:

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:

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)\).

parabolic(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:

Function evaluations.

Return type:

numpy.ndarray

\[f(x; a, b, c) = a x^2 + b x + c\]
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:

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)\).

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:

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}\)

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