API Reference

datareduction

Tools for reducing data into 2D and 1D, and visualization functions for plotting and animating data.

nxs_analysis_tools.datareduction.load_data(path, print_tree=True)

Load data from a NeXus file at a specified path. It is assumed that the data follows the CHESS file structure (i.e., root/entry/data/counts, etc.).

Parameters:
  • path (str) – The path to the NeXus data file.

  • print_tree (bool, optional) – Whether to print the data tree upon loading. Default True.

Returns:

data – The loaded data stored in a NXdata object.

Return type:

nexusformat.nexus.tree.NXdata

nxs_analysis_tools.datareduction.load_transform(path, print_tree=True, use_nxlink=False)

Load transform data from an nxrefine output file.

Parameters:
  • path (str) – The path to the transform data file.

  • print_tree (bool, optional) – If True, prints the NeXus data tree upon loading. Default is True.

  • use_nxlink (bool, optional) – If True, maintains the NXlink defined in the data file, which references the raw data in the transform.nxs file. This saves memory when working with many datasets. In this case, the axes are in reverse order. Default is False.

Returns:

data – The loaded transform data as an NXdata object.

Return type:

nexusformat.nexus.tree.NXdata

nxs_analysis_tools.datareduction.plot_slice(data, X=None, Y=None, sum_axis=None, transpose=False, vmin=None, vmax=None, skew_angle=90, ax=None, xlim=None, ylim=None, xticks=None, yticks=None, cbar=True, logscale=False, symlogscale=False, cmap='viridis', linthresh=1, title=None, mdheading=None, cbartitle=None, **kwargs)

Plot a 2D slice of the provided dataset, with optional transformations and customizations.

Parameters:
  • data (nexusformat.nexus.tree.NXdata or numpy.ndarray) – The dataset to plot. Can be an NXdata object or a numpy array.

  • sum_axis (int, optional) – If the input data is 3D, this specifies the axis to sum over in order to reduce the data to 2D for plotting. Required if data has three dimensions.

  • transpose (bool, optional) – If True, transpose the dataset and its axes before plotting. Default is False.

  • vmin (float, optional) –

    The minimum value for the color scale. If not provided, the minimum

    value of the dataset is used.

  • vmax (float, optional) –

    The maximum value for the color scale. If not provided, the maximum

    value of the dataset is used.

  • skew_angle (float, optional) – The angle in degrees to shear the plot. Default is 90 degrees (no skew).

  • ax (matplotlib.axes.Axes, optional) –

    The matplotlib axis to plot on. If None, a new figure and axis will

    be created.

  • xlim (tuple, optional) –

    The limits for the x-axis. If None, the limits are set automatically

    based on the data.

  • ylim (tuple, optional) –

    The limits for the y-axis. If None, the limits are set automatically

    based on the data.

  • xticks (float or list of float, optional) –

    The major tick interval or specific tick locations for the x-axis.

    Default is to use a minor tick interval of 1.

  • yticks (float or list of float, optional) – The major tick interval or specific tick locations for the y-axis. Default is to use a minor tick interval of 1.

  • cbar (bool, optional) – Whether to include a colorbar. Default is True.

  • logscale (bool, optional) – Whether to use a logarithmic color scale. Default is False.

  • symlogscale (bool, optional) – Whether to use a symmetrical logarithmic color scale. Default is False.

  • cmap (str or Colormap, optional) – The colormap to use for the plot. Default is ‘viridis’.

  • linthresh (float, optional) – The linear threshold for symmetrical logarithmic scaling. Default is 1.

  • title (str, optional) – The title for the plot. If None, no title is set.

  • mdheading (str, optional) –

    A Markdown heading to display above the plot. If ‘None’ or not provided,

    no heading is displayed.

  • cbartitle (str, optional) –

    The title for the colorbar. If None, the colorbar label will be set to

    the name of the signal.

  • **kwargs – Additional keyword arguments passed to pcolormesh.

Returns:

p – The matplotlib QuadMesh object representing the plotted data.

Return type:

matplotlib.collections.QuadMesh

class nxs_analysis_tools.datareduction.Scissors

Scissors class provides functionality for reducing data to a 1D linecut using an integration window.

data

The data to be cut.

Type:

nexusformat.nexus.tree.NXdata or None

center

Central coordinate around which to perform the linecut.

Type:

tuple or None

window

Extents of the window for integration along each axis.

Type:

tuple or None

axis

Axis along which to perform the integration.

Type:

int or None

integration_volume

Data array after applying the integration window.

Type:

nexusformat.nexus.tree.NXdata or None

integrated_axes

Indices of axes that were integrated.

Type:

tuple or None

linecut

1D linecut data after integration.

Type:

nexusformat.nexus.tree.NXdata or None

integration_window

Slice object representing the integration window in the data array.

Type:

tuple or None

set_data(data)

Set the input nexusformat.nexus.tree.NXdata.

get_data()

Get the input nexusformat.nexus.tree.NXdata.

set_center(center)

Set the central coordinate for the linecut.

set_window(window, axis=None, verbose=False)

Set the extents of the integration window.

get_window()

Get the extents of the integration window.

cut_data(center=None, window=None, axis=None, verbose=False)

Reduce data to a 1D linecut using the integration window.

plot_integration_window(**kwargs)

Plot the integration window on a 2D heatmap.

Methods

cut_data([center, window, axis, verbose])

Reduces data to a 1D linecut with integration extents specified by the window about a central coordinate.

get_data()

Get the input data array.

get_window()

Get the extents of the integration window.

highlight_integration_window([data, width, ...])

Plots the integration window highlighted on the principal cross-sections.

plot_integration_window([data, ...])

Plots the principal 2D cross-sections of the dataset, centered around the linecut.

set_center(center)

Set the central coordinate for the linecut.

set_data(data)

Set the input NXdata.

set_window(window[, axis, verbose])

Set the extents of the integration window.

__init__(data=None, center=None, window=None, axis=None)

Initializes a Scissors object.

Parameters:
  • data (nexusformat.nexus.tree.NXdata or None, optional) – Input NXdata. Default is None.

  • center (tuple or None, optional) – Central coordinate around which to perform the linecut. Default is None.

  • window (tuple or None, optional) – Extents of the window for integration along each axis. Default is None.

  • axis (int or None, optional) – Axis along which to perform the integration. Default is None.

set_data(data)

Set the input NXdata.

Parameters:

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

get_data()

Get the input data array.

Returns:

Input data array.

Return type:

nexusformat.nexus.tree.NXdata

set_center(center)

Set the central coordinate for the linecut.

Parameters:

center (tuple) – Central coordinate around which to perform the linecut.

set_window(window, axis=None, verbose=False)

Set the extents of the integration window.

Parameters:
  • window (tuple) – Extents of the window for integration along each axis.

  • axis (int or None, optional) – The axis along which to perform the linecut. If not specified, the value from the object’s attribute will be used.

  • verbose (bool, optional) – Enables printout of linecut axis and integrated axes. Default False.

get_window()

Get the extents of the integration window.

Returns:

Extents of the integration window.

Return type:

tuple or None

cut_data(center=None, window=None, axis=None, verbose=False)

Reduces data to a 1D linecut with integration extents specified by the window about a central coordinate.

Parameters:
  • center (float or None, optional) – Central coordinate for the linecut. If not specified, the value from the object’s attribute will be used.

  • window (tuple or None, optional) – Integration window extents around the central coordinate. If not specified, the value from the object’s attribute will be used.

  • axis (int or None, optional) – The axis along which to perform the linecut. If not specified, the value from the object’s attribute will be used.

  • verbose (bool) – Enables printout of linecut axis and integrated axes. Default False.

Returns:

integrated_data – 1D linecut data after integration.

Return type:

nexusformat.nexus.tree.NXdata

plot_integration_window(data=None, show_highlight=True, width=None, height=None, label=None, highlight_color='red', **kwargs)

Plots the principal 2D cross-sections of the dataset, centered around the linecut.

Parameters:
  • data (array-like, optional) – The dataset to visualize. If not provided, defaults to self.data.

  • show_highlight (bool, optional) – Whether to overlay a rectangle highlighting the integration window. Default is True.

  • width (float, optional) – Width of the visible x-axis range to zoom in on the integration region.

  • height (float, optional) – Height of the visible y-axis range to zoom in on the integration region.

  • label (str, optional) – Label for the rectangle patch used in the legend.

  • highlight_color (str, optional) – Color of the rectangle edges highlighting the integration window. Default is ‘red’.

  • **kwargs (dict, optional) – Additional keyword arguments passed to plot_slice (e.g., cmap, vmin, vmax).

Returns:

plots – The plotted QuadMesh objects. Returns a single object for 2D, or three for 3D.

Return type:

tuple of matplotlib.collections.QuadMesh

highlight_integration_window(data=None, width=None, height=None, label=None, highlight_color='red', **kwargs)

Plots the integration window highlighted on the principal cross-sections.

Deprecated since version `highlight_integration_window`: is deprecated and will be removed in a future version. Please use plot_integration_window(show_highlight=True) instead.

nxs_analysis_tools.datareduction.reciprocal_lattice_params(lattice_params)

Calculate the reciprocal lattice parameters from the given direct lattice parameters.

Parameters:

lattice_params (tuple) – A tuple containing the real space lattice parameters [e.g., (a, b, c, alpha, beta, gamma)], where a, b, and c are the magnitudes of the lattice vectors, and alpha, beta, and gamma are the angles between them in degrees. These should be provided in the order corresponding to the axes of the dataset.

Returns:

A tuple containing the reciprocal lattice parameters. [e.g., (a*, b*, c*, alpha*, beta*, gamma*), where a*, b*, and c* are the magnitudes of the reciprocal lattice vectors, and alpha*, beta*, and gamma* are the angles between them in degrees]

Return type:

tuple

nxs_analysis_tools.datareduction.rotate_data(data, lattice_angle, rotation_angle, rotation_axis=None, rotation_order=None, aspect=None, aspect_order=None, printout=False)

Rotates slices of data around the normal axis.

Parameters:
  • data (nexusformat.nexus.tree.NXdata) – Input data.

  • lattice_angle (float) – Angle between the two in-plane lattice axes in degrees.

  • rotation_angle (float) – Angle of rotation in degrees.

  • rotation_axis (int, optional) – Axis of rotation (0, 1, or 2). Only necessary when data is three-dimensional.

  • rotation_order (int, optional) – Interpolation order passed to scipy.ndimage.rotate(). Determines the spline interpolation used during rotation. Valid values are integers from 0 (nearest-neighbor) to 5 (higher-order splines). Defaults to 0 if not specified.

  • aspect (float, optional) – True aspect ratio between the lengths of the basis vectors of the two principal axes of the plane to be rotated. Calculated as aspect = (length of y) / (length of x). Defaults to 1.

  • aspect_order (int, optional) – Interpolation order passed to scipy.ndimage.zoom() when applying and undoing the coordinate aspect ratio correction. Determines the spline interpolation used during resampling. Valid values are integers from 0 (nearest-neighbor) to 5. Defaults to 0 if not specified.

  • printout (bool, optional) – Enables printout of rotation progress for three-dimensional data. If set to True, information about each rotation slice will be printed to the console, indicating the axis being rotated and the corresponding coordinate value. Defaults to False.

Returns:

rotated_data – Rotated data as an NXdata object.

Return type:

nexusformat.nexus.tree.NXdata

nxs_analysis_tools.datareduction.convert_to_inverse_angstroms(data, lattice_params)

Convert the axes of a 3D NXdata object from reciprocal lattice units (r.l.u.) to inverse angstroms using provided lattice parameters.

Parameters:
  • data (nexusformat.nexus.tree.NXdata) – A 3D NXdata object with axes in reciprocal lattice units.

  • lattice_params (tuple of float) – A tuple containing the real-space lattice parameters [e.g., (a, b, c, alpha, beta, gamma)] in Angstroms and degrees.

Returns:

A new NXdata object with axes scaled to inverse angstroms.

Return type:

nexusformat.nexus.tree.NXdata

nxs_analysis_tools.datareduction.array_to_nxdata(array, data_template, signal_name=None)

Create an NXdata object from an input array and an NXdata template, with an optional signal name.

Parameters:
  • array (array-like) – The data array to be included in the NXdata object.

  • data_template (nexusformat.nexus.tree.NXdata) – An NXdata object serving as a template, which provides information about axes and other metadata.

  • signal_name (str, optional) – The name of the signal within the NXdata object. If not provided, the signal name is inherited from the data_template.

Returns:

An NXdata object containing the input data array and associated axes based on the template.

Return type:

NXdata

class nxs_analysis_tools.datareduction.Padder

A class to symmetrically pad and unpad datasets with a region of zeros.

data

The input data to be padded.

Type:

nexusformat.nexus.tree.NXdata or None

padded

The padded data with symmetric zero padding.

Type:

nexusformat.nexus.tree.NXdata or None

padding

The number of zero-value pixels added along each edge of the array.

Type:

tuple or None

steps

The step sizes along each axis of the dataset.

Type:

tuple or None

maxes

The maximum values along each axis of the unpadded dataset.

Type:

tuple or None

set_data(data)

Set the input data for padding.

pad(padding)

Symmetrically pads the data with zero values.

save(fout_name=None)

Saves the padded dataset to a .nxs file.

unpad(data)

Removes the padded region from the data.

Methods

pad(padding)

Symmetrically pads the data with zero values.

save([fout_name])

Saves the padded dataset to a .nxs file.

set_data(data)

Set the input data for padding.

unpad(data)

Removes the padded region from the data.

__init__(data=None)

Initialize the Padder object.

Parameters:

data (nexusformat.nexus.tree.NXdata, optional) – The input data to be padded. If provided, the set_data method is called to set the data.

set_data(data)

Set the input data for padding.

Parameters:

data (nexusformat.nexus.tree.NXdata) – The input data to be padded.

pad(padding)

Symmetrically pads the data with zero values.

Parameters:

padding (tuple) – The number of zero-value pixels to add along each edge of the array.

Returns:

The padded data with symmetric zero padding.

Return type:

NXdata

save(fout_name=None)

Saves the padded dataset to a .nxs file.

Parameters:

fout_name (str, optional) – The output file name. Default is padded_(Hpadding)_(Kpadding)_(Lpadding).nxs

unpad(data)

Removes the padded region from the data.

Parameters:

data (nexusformat.nexus.tree.NXdata or numpy.ndarray) – The padded data from which to remove the padding.

Returns:

The unpadded data, with the symmetric padding region removed.

Return type:

nexusformat.nexus.tree.NXdata or numpy.ndarray

nxs_analysis_tools.datareduction.rebin_nxdata(data)

Rebins the signal and axes of an NXdata object by a factor of 2 along each dimension.

This function first checks each axis of the input NXdata object:
  • If the axis has an odd number of elements, the last element is excluded before rebinning.

  • Then, each axis is rebinned using rebin_1d.

The signal array is similarly cropped to remove the last element along any dimension with an odd shape, and then the data is averaged over 2x2x… blocks.

Parameters:

data (nexusformat.nexus.tree.NXdata) – The NeXus data group containing the signal and axes to be rebinned.

Returns:

A new NXdata object with signal and axes rebinned by a factor of 2 along each dimension.

Return type:

NXdata

nxs_analysis_tools.datareduction.rebin_3d(array)

Rebins a 3D NumPy array by a factor of 2 along each dimension.

This function reduces the size of the input array by averaging over non-overlapping 2x2x2 blocks. Each dimension of the input array must be divisible by 2.

Parameters:

array (numpy.ndarray) – A 3-dimensional NumPy array to be rebinned.

Returns:

A rebinned array with shape (N//2, M//2, L//2) if the original shape was (N, M, L).

Return type:

numpy.ndarray

nxs_analysis_tools.datareduction.rebin_1d(array)

Rebins a 1D NumPy array by a factor of 2.

This function reduces the size of the input array by averaging over non-overlapping pairs of elements. The input array length must be divisible by 2.

Parameters:

array (numpy.ndarray) – A 1-dimensional NumPy array to be rebinned.

Returns:

A rebinned array with length N//2 if the original length was N.

Return type:

numpy.ndarray

nxs_analysis_tools.datareduction.animate_slice_temp(temp_dependence, slice_obj, ax=None, reverse_temps=False, interval=500, save_gif=False, filename='animation', title=True, title_fmt='d', plot_slice_kwargs=None, ax_kwargs=None)

Animate 2D slices from a temperature-dependent dataset.

Creates a matplotlib animation by extracting 2D slices from each dataset in a TempDependence object and animating them in sequence by temperature. Optionally displays the animation inline and/or saves it as a GIF.

Parameters:
  • temp_dependence (nxs_analysis_tools.chess.TempDependence) – Object holding datasets at various temperatures.

  • slice_obj (list of slice or None) – Slice object to apply to each dataset; None entries are treated as ‘:’.

  • ax (matplotlib.axes.Axes, optional) – The axes object to plot on. If None, a new figure and axes will be created.

  • reverse_temps (bool, optional) – If True, animates datasets with increasing temperature. Default is False.

  • interval (int, optional) – Delay between frames in milliseconds. Default is 500.

  • save_gif (bool, optional) – If True, saves the animation to a .gif file. Default is False.

  • filename (str, optional) – Filename (without extension) for saved .gif. Default is ‘animation’.

  • title (bool, optional) – If True, displays the temperature in the title of each frame. Default is True.

  • title_fmt (str, optional) – Format string for temperature values (e.g., ‘.2f’ for 2 decimals). Default is ‘d’ (integer).

  • plot_slice_kwargs (dict, optional) – Additional keyword arguments passed to plot_slice.

  • ax_kwargs (dict, optional) – Keyword arguments passed to ax.set.

Returns:

ani – The resulting animation object.

Return type:

matplotlib.animation.FuncAnimation

nxs_analysis_tools.datareduction.animate_slice_axis(data, axis, axis_values, ax=None, interval=500, save_gif=False, filename='animation', title=True, title_fmt='.2f', plot_slice_kwargs={}, ax_kwargs={})

Animate 2D slices of a 3D dataset along a given axis.

Creates a matplotlib animation by sweeping through 2D slices of a 3D dataset along the specified axis. Optionally displays the animation inline (e.g., in Jupyter) and/or saves it as a GIF.

Parameters:
  • data (nexusformat.nexus.tree.NXdata) – The 3D dataset to visualize.

  • axis (int) – The axis along which to animate (must be 0, 1, or 2).

  • axis_values (iterable) – The values along the animation axis to use as animation frames.

  • ax (matplotlib.axes.Axes, optional) – The axes object to plot on. If None, a new figure and axes will be created.

  • interval (int, optional) – Delay between frames in milliseconds. Default is 500.

  • save_gif (bool, optional) – If True, saves the animation as a .gif file. Default is False.

  • filename (str, optional) – Filename (without extension) to use for the saved .gif. Default is ‘animation’.

  • title (bool, optional) – If True, displays the axis value as a title for each frame. Default is True.

  • title_fmt (str, optional) – Format string for axis value in the title (e.g., ‘.2f’ for 2 decimals). Default is ‘.2f’.

  • plot_slice_kwargs (dict, optional) – Additional keyword arguments passed to plot_slice.

  • ax_kwargs (dict, optional) – Keyword arguments passed to ax.set to update axis settings.

Returns:

ani – The animation object.

Return type:

matplotlib.animation.FuncAnimation

chess

This module provides classes and functions for analyzing scattering datasets collected at CHESS (ID4B) with temperature dependence. It includes functions for loading temperature series and performing operations on all datasets in the series at once (e.g., cutting, fitting).

class nxs_analysis_tools.chess.TempDependence

A class for analyzing temperature-dependent scattering datasets collected at CHESS (ID4B).

The TempDependence class facilitates the loading, processing, and analysis of scattering data across different temperatures. It includes methods for handling datasets, setting lattice parameters, performing linecuts, modeling the data, and visualizing the results.

sample_directory

Path to the directory containing the datasets.

Type:

str

xlabel

Label for the x-axis of plots, determined by the axis of the linecuts.

Type:

str

datasets

Dictionary storing datasets keyed by temperature.

Type:

dict

temperatures

List of temperatures for which data is available.

Type:

list of str

scissors

Dictionary of Scissors objects, one for each temperature, used for data manipulation and linecut operations.

Type:

dict

linecuts

Dictionary storing the linecut data for each temperature.

Type:

dict

linecutmodels

Dictionary of LinecutModel objects, one for each temperature, used for fitting the linecuts.

Type:

dict

a, b, c, al, be, ga

Lattice parameters (a, b, c, alpha, beta, gamma) of the crystal.

Type:

float or None

a_star, b_star, c_star, al_star, be_star, ga_star

Reciprocal lattice parameters (a*, b*, c*, alpha*, beta*, gamma*).

Type:

float or None

set_temperatures(temperatures):

Set the list of temperatures for the datasets.

find_temperatures():

Set the list of temperatures by automatically scanning the sample directory.

set_sample_directory(path):

Set the directory path where the datasets are located.

initialize():

Initialize Scissors and LinecutModel objects for each temperature.

set_data(temperature, data):

Set the dataset for a specific temperature.

load_transforms(temperatures_list=None, exclude_temperatures=None, print_tree=True):

Load transform datasets (from nxrefine) based on temperature.

load_datasets(file_ending='hkli.nxs', temperatures_list=None, exclude_temperatures=None,

print_tree=True):

Load datasets (legacy CHESS format) from the specified folder.

get_sample_directory():

Get the folder path where the datasets are located.

clear_datasets():

Clear the datasets stored in the TempDependence instance.

set_Lattice_params(lattice_params):

Set lattice parameters and calculate reciprocal lattice parameters.

set_window(window, verbose=False):

Set the extents of the integration window for each temperature.

set_center(center):

Set the central coordinate for the linecut for each temperature.

cut_data(center=None, window=None, axis=None, verbose=False):

Perform data cutting for each temperature dataset.

plot_linecuts(vertical_offset=0, \*\*kwargs):

Plot the linecuts obtained from data cutting.

plot_linecuts_heatmap(ax=None, \*\*kwargs):

Plot a heatmap of the linecuts obtained from data cutting.

plot_integration_window(temperature=None, \*\*kwargs):

Plot the integration window cross-sections for a specific temperature.

set_model_components(model_components):

Set the model components for all line cut models.

set_param_hint(*args, \*\*kwargs):

Set parameter hints for all line cut models.

make_params():

Create parameters for all line cut models.

guess():

Make initial parameter guesses for all line cut models.

print_initial_params():

Print the initial parameter values for all line cut models.

plot_initial_guess():

Plot the initial guess for all line cut models.

fit(verbose=False):

Fit the line cut models for each temperature.

plot_fit(mdheadings=False, \*\*kwargs):

Plot the fit results for each temperature.

overlay_fits(numpoints=None, vertical_offset=0, cmap='viridis', ax=ax,

data_kwargs=None, fit_kwargs=None):

Plot raw data and fitted models for each temperature.

fit_peak_simple():

Perform a basic fit using a pseudo-Voigt peak shape, linear background, and no constraints.

plot_order_parameter(ax, param_name='peakheight', \*\*kwargs):

Plot the temperature dependence of the peakheight parameter.

print_fit_report():

Print the fit report for each temperature.

Methods

clear_datasets()

Clear the datasets stored in the TempDependence instance.

cut_data([center, window, axis, verbose])

Perform data cutting for each temperature dataset.

find_temperatures()

Set the list of temperatures by automatically scanning the sample directory for .nxs files from NXRefine.

fit([verbose])

Fit the line cut models.

fit_peak_simple()

Fit all linecuts in the temperature series using a pseudo-Voigt peak shape and linear background, with no constraints.

get_sample_directory()

Get the folder path where the datasets are located.

guess()

Make initial parameter guesses for all line cut models.

highlight_integration_window([temperature])

Displays the integration window plot for a specific temperature.

initialize()

Initialize Scissors and LinecutModel objects for each temperature.

load_datasets([file_ending, ...])

Load datasets (CHESS format) from the specified folder.

load_transforms([temperatures_list, ...])

Load transform datasets (from NXRefine) based on temperature.

make_params()

Create and initialize the parameters for all models.

overlay_fits([numpoints, vertical_offset, ...])

Plot raw data and fitted models for each temperature with optional vertical offsets.

params_set(name, **kwargs)

Set constraints on a parameter for all line cut models.

plot_fit([mdheadings])

Plot the fit results.

plot_initial_guess()

Plot the initial guess for all line cut models.

plot_integration_window([temperature, ...])

Plots the principal cross-sections of the dataset for a specific temperature.

plot_linecuts([ax, vertical_offset])

Plot the linecuts obtained from data cutting.

plot_linecuts_heatmap([ax])

Plot the linecuts obtained from data cutting.

plot_order_parameter([param_name, ax])

Plot the temperature dependence of the peak height (order parameter).

print_fit_report()

Plot the fit results.

print_initial_params()

Print the initial parameter values for all line cut models.

set_center(center)

Set the central coordinate for the linecut for each temperature.

set_data(temperature, data)

Set the dataset for a specific temperature.

set_lattice_params(lattice_params)

Set lattice parameters and calculate reciprocal lattice parameters.

set_model_components(model_components)

Set the model components for all line cut models.

set_param_hint(*args, **kwargs)

Set parameter hints for all line cut models.

set_sample_directory(path)

Set the directory path where the datasets are located.

set_temperatures(temperatures)

Set the list of temperatures for the datasets.

set_window(window[, verbose])

Set the extents of the integration window for each temperature.

__init__(sample_directory=None)

Initialize the TempDependence class.

Parameters:

sample_directory (str, optional) – Path to the directory containing the temperature folders. If None, no directory is set initially.

set_temperatures(temperatures)

Set the list of temperatures for the datasets.

Parameters:

temperatures (list) – List of temperatures to set.

find_temperatures()

Set the list of temperatures by automatically scanning the sample directory for .nxs files from NXRefine.

set_sample_directory(path)

Set the directory path where the datasets are located.

Parameters:

path (str) – Path to the sample directory.

initialize()

Initialize Scissors and LinecutModel objects for each temperature.

set_data(temperature, data)

Set the dataset for a specific temperature.

Parameters:
  • temperature (str) – Temperature for which to set the data.

  • data (object) – The dataset to be set.

load_transforms(temperatures_list=None, exclude_temperatures=None, print_tree=True, use_nxlink=False)

Load transform datasets (from NXRefine) based on temperature.

Parameters:
  • temperatures_list (list of int, float, or None, optional) – List of temperatures to load. If None, all available temperatures are loaded.

  • exclude_temperatures (int, float, str, or list, optional) – Temperatures to skip. Applied after filtering with temperatures_list, if provided.

  • print_tree (bool, optional) – Whether to print the data tree upon loading. Default True.

  • use_nxlink (bool, optional) – If True, maintains the NXlink defined in the data file, which references the raw data in the transform.nxs file. This saves memory when working with many datasets. In this case, the axes are in reverse order. Default is False.

load_datasets(file_ending='hkli.nxs', temperatures_list=None, exclude_temperatures=None, print_tree=True)

Load datasets (CHESS format) from the specified folder.

Parameters:
  • file_ending (str, optional) – File extension of datasets to load. Default is ‘hkli.nxs’.

  • temperatures_list (list of int or str, optional) – Specific temperatures to load. If None, all temperatures are loaded.

  • exclude_temperatures (list of int or str, optional) – Temperatures to skip. Applied after filtering with temperatures_list, if provided.

  • print_tree (bool, optional) – If True, prints the NeXus tree structure for each file. Default is True.

get_sample_directory()

Get the folder path where the datasets are located.

Returns:

The folder path.

Return type:

str

clear_datasets()

Clear the datasets stored in the TempDependence instance.

set_lattice_params(lattice_params)

Set lattice parameters and calculate reciprocal lattice parameters.

Parameters:

lattice_params (tuple) – Tuple containing lattice parameters (a, b, c, al, be, ga).

set_window(window, verbose=False)

Set the extents of the integration window for each temperature.

Parameters:
  • window (tuple) – Extents of the window for integration along each axis.

  • verbose (bool, optional) – Enables printout of linecut axis and integrated axes. Default is False.

set_center(center)

Set the central coordinate for the linecut for each temperature.

Parameters:

center (tuple) – Central coordinate around which to perform the linecut.

cut_data(center=None, window=None, axis=None, verbose=False)

Perform data cutting for each temperature dataset.

Parameters:
  • center (tuple, optional) – The center point for cutting the data. Defaults to the first temperature’s center if None.

  • window (tuple, optional) – The window size for cutting the data. Defaults to the first temperature’s window if None.

  • axis (int or None, optional) – The axis along which to perform the cutting. Defaults to the longest axis in window if None.

  • verbose (bool, optional) – Enables printout of linecut progress. Default is False.

Returns:

A dictionary of linecuts obtained from the cutting operation.

Return type:

dict

plot_linecuts(ax=None, vertical_offset=0, **kwargs)

Plot the linecuts obtained from data cutting.

Parameters:
  • ax (matplotlib.axes.Axes, optional) – The matplotlib Axes object on which to plot. If None, a new figure and axes are created. Default None.

  • vertical_offset (float, optional) – The vertical offset between linecuts on the plot. The default is 0.

  • **kwargs – Additional keyword arguments passed to the matplotlib plot function.

plot_linecuts_heatmap(ax=None, **kwargs)

Plot the linecuts obtained from data cutting.

Parameters:
  • ax (matplotlib.axes.Axes, optional) – The axes on which to plot the heatmap. If None, a new figure and axes are created. The default is None.

  • **kwargs – Additional keyword arguments to be passed to the pcolormesh function.

Returns:

The plotted heatmap object.

Return type:

QuadMesh

plot_integration_window(temperature=None, show_highlight=False, **kwargs)

Plots the principal cross-sections of the dataset for a specific temperature.

Parameters:
  • temperature (str, optional) – The temperature at which to plot. If provided, the plot will be generated using the dataset corresponding to the specified temperature. If not provided, defaults to the first temperature.

  • show_highlight (bool, optional) – Whether to overlay a rectangle highlighting the integration window. Default is False.

  • **kwargs (keyword arguments, optional) – Additional keyword arguments passed to customize the plot.

highlight_integration_window(temperature=None, **kwargs)

Displays the integration window plot for a specific temperature.

Deprecated since version `highlight_integration_window`: is deprecated and will be removed in a future version. Please use plot_integration_window(show_highlight=True) instead.

set_model_components(model_components)

Set the model components for all line cut models.

This method sets the same model components for all line cut models in the analysis. It iterates over each line cut model and calls their respective set_model_components method with the provided model_components.

Parameters:

model_components (Model, CompositeModel, or iterable of Model) – The model components to set for all line cut models.

set_param_hint(*args, **kwargs)

Set parameter hints for all line cut models.

This method sets the parameter hints for all line cut models in the analysis. It iterates over each line cut model and calls their respective set_param_hint method with the provided arguments and keyword arguments. These are implemented when the .make_params() method is called.

Parameters:
  • *args – Variable length argument list.

  • **kwargs – Arbitrary keyword arguments.

params_set(name, **kwargs)

Set constraints on a parameter for all line cut models.

This method updates the specified parameter across all models in self.linecutmodels using the keyword arguments provided. These keyword arguments are passed to the set() method of the parameter, which comes from a lmfit.Parameters object.

Parameters:
  • name (str) – Name of the parameter to modify (must exist in each model).

  • **kwargs – Constraint arguments passed to Parameter.set(), such as value, min, max, vary, etc.

Raises:

KeyError – If the parameter name does not exist in one of the models.

Example

>>> sample.params_set('peakamplitude', value=5, min=0, vary=True)
make_params()

Create and initialize the parameters for all models.

This method creates the parameters for all line cut models in the analysis. It iterates over each line cut model and calls their respective make_params method.

guess()

Make initial parameter guesses for all line cut models. This overwrites any prior initial values and constraints.

This method generates initial parameter guesses for all line cut models in the analysis. It iterates over each line cut model and calls their respective guess method.

print_initial_params()

Print the initial parameter values for all line cut models.

This method prints the initial parameter values for all line cut models in the analysis. It iterates over each line cut model and calls their respective print_initial_params method.

plot_initial_guess()

Plot the initial guess for all line cut models.

This method plots the initial guess for all line cut models in the analysis. It iterates over each line cut model and calls their respective plot_initial_guess method.

fit(verbose=False)

Fit the line cut models.

This method fits the line cut models for each temperature in the analysis. It iterates over each line cut model, performs the fit, and prints the fitting progress.

Parameters:
verbosebool, optional

Enables printout of fitting progress. Default False.

plot_fit(mdheadings=False, **kwargs)

Plot the fit results.

This method plots the fit results for each temperature in the analysis. It iterates over each line cut model, calls their respective plot_fit method, and sets the xlabel, ylabel, and title for the plot.

overlay_fits(numpoints=None, vertical_offset=0, cmap='viridis', ax=None, data_kwargs=None, fit_kwargs=None)

Plot raw data and fitted models for each temperature with optional vertical offsets.

fit_peak_simple()

Fit all linecuts in the temperature series using a pseudo-Voigt peak shape and linear background, with no constraints.

plot_order_parameter(param_name='peakheight', ax=None, **kwargs)

Plot the temperature dependence of the peak height (order parameter).

This method extracts the values of a chosen parameter from each temperature-dependent line cut fit stored in linecutmodels and plots it as a function of temperature.

Parameters:
  • ax (matplotlib.axes.Axes, optional) – Axis object to plot on. If None, a new figure and axis are created.

  • param_name (str, optional) – The name of the lmfit parameter to extract. Default is ‘peakheight’.

  • **kwargs – Keyword arguments to be passed to the plot function.

Returns:

  • Figure – Matplotlib Figure object containing the peak height vs. temperature plot.

  • Axes – Matplotlib Axes object associated with the figure.

Notes

  • Temperature values are converted to integers for plotting.

  • Peak heights are extracted from the ‘peakheight’ parameter in the model results.

  • The plot uses standard axes labels with temperature in Kelvin.

print_fit_report()

Plot the fit results.

This method plots the fit results for each temperature in the analysis. It iterates over each line cut model, calls their respective plot_fit method, and sets the xlabel, ylabel, and title for the plot.

fitting

Module for fitting of linecuts using the lmfit package.

class nxs_analysis_tools.fitting.LinecutModel

A class representing a linecut model for data analysis and fitting.

y

The dependent variable data.

Type:

array-like or None

x

The independent variable data.

Type:

array-like or None

y_eval

The evaluated y-values of the fitted model.

Type:

array-like or None

x_eval

The x-values used for evaluation.

Type:

array-like or None

y_eval_components

The evaluated y-values of the model components.

Type:

dict or None

y_fit_components

The fitted y-values of the model components.

Type:

dict or None

y_fit

The fitted y-values of the model.

Type:

array-like or None

x_fit

The x-values used for fitting.

Type:

array-like or None

y_init_fit

The initial guess of the y-values.

Type:

array-like or None

params

The parameters of the model.

Type:

Parameters or None

model_components

The model component(s) used for fitting.

Type:

Model or list of Models or None

model

The composite model used for fitting.

Type:

Model or None

modelresult

The result of the model fitting.

Type:

ModelResult or None

data

The 1D linecut data used for analysis.

Type:

nexusformat.nexus.tree.NXdata or None

__init__(self, data=None)

Initialize the LinecutModel.

set_data(self, data)

Set the data for analysis.

set_model_components(self, model_components)

Set the model components.

set_param_hint(self, \*args, \*\*kwargs)

Set parameter hints for the model.

make_params(self)

Create and initialize the parameters for the model.

guess(self)

Perform initial guesses for each model component.

print_initial_params(self)

Print out initial guesses for each parameter of the model.

plot_initial_guess(self, numpoints=None)

Plot the initial guess.

fit(self)

Fit the model to the data.

plot_fit(self, numpoints=None, fit_report=True, \*\*kwargs)

Plot the fitted model.

fit_peak_simple():

Perform a basic fit using a pseudo-Voigt peak shape, linear background, and no constraints.

print_fit_report(self)

Print the fit report.

Methods

fit()

Fit the model to the data.

fit_peak_simple([positive_amp, constraints])

Fit all linecuts in the temperature series using a pseudo-Voigt peak shape and linear background, with no default constraints except a positive peak amplitude.

guess()

Perform initial guesses for each model component and update params.

make_params()

Create and initialize the parameters for the model.

plot_fit([numpoints, fit_report])

Plot the fitted model.

plot_initial_guess([numpoints])

Plot initial guess.

print_fit_report()

Show fit report.

print_initial_params()

Print out initial guesses for each parameter of the model.

set_data(data)

Set the data for analysis.

set_model_components(model_components)

Set the model components

set_param_hint(*args, **kwargs)

Set parameter hints for the model.

__init__(data=None)

Initialize the LinecutModel.

set_data(data)

Set the data for analysis.

Parameters:

data (nexusformat.nexus.tree.NXdata) – The 1D linecut data to be used for analysis.

set_model_components(model_components)

Set the model components

Parameters:

model_components (Model, CompositeModel, or iterable of Model) – The model component(s) to be used for fitting.

set_param_hint(*args, **kwargs)

Set parameter hints for the model. These are implemented when the .make_params() method is called.

Parameters:
  • *args (positional arguments) – Positional arguments passed to the set_param_hint method of the underlying model.

  • **kwargs (keyword arguments) – Keyword arguments passed to the set_param_hint method of the underlying model.

make_params()

Create and initialize the parameters for the model.

Returns:

The initialized parameters for the model.

Return type:

Parameters

guess()

Perform initial guesses for each model component and update params. This overwrites any prior initial values and constraints.

Returns:

components_params – A list containing params objects for each component of the model.

Return type:

list

print_initial_params()

Print out initial guesses for each parameter of the model.

plot_initial_guess(numpoints=None)

Plot initial guess.

fit()

Fit the model to the data.

This method fits the model to the data using the specified parameters and the x-values. It updates the model result, fitted y-values, and the evaluated components.

plot_fit(numpoints=None, fit_report=True, **kwargs)

Plot the fitted model.

This method plots the fitted model along with the original data. It evaluates the model and its components at the specified number of points (numpoints) and plots the results.

Parameters:
  • numpoints (int, optional) – Number of points to evaluate the model and its components. If not provided, it defaults to the length of the x-values.

  • fit_report (bool, optional) – Whether to print the fit report. Default is True.

  • **kwargs (dict, optional) – Additional keyword arguments to be passed to the plot method.

Returns:

ax – The Axes object containing the plot.

Return type:

matplotlib.axes.Axes

fit_peak_simple(positive_amp=True, constraints=None)

Fit all linecuts in the temperature series using a pseudo-Voigt peak shape and linear background, with no default constraints except a positive peak amplitude.

Parameters:
  • positive_amp (bool, optional) – If False, negative peak amplitude is allowed. Default True.

  • constraints (dict or None) – Optional parameter constraints, e.g.: {‘peakamplitude’: {‘value’: 500, ‘max’: 1000}, ‘peaksigma’: {‘min’: 0.01, ‘max’: 0.5}} Accepts any keyword recognised by lmfit’s Parameter.set(): value, min, max, vary, expr.

print_fit_report()

Show fit report.

pairdistribution

Tools for generating single crystal pair distribution functions.

class nxs_analysis_tools.pairdistribution.Symmetrizer2D

A class for symmetrizing 2D datasets.

The Symmetrizer2D class provides functionality to apply symmetry operations such as rotation and mirroring to 2D datasets.

mirror_axis

The axis along which mirroring is performed. Default is None, meaning no mirroring is applied.

Type:

int or None

symmetrized

The symmetrized dataset after applying the symmetrization operations. Default is None until symmetrization is performed.

Type:

nexusformat.nexus.tree.NXdata or None

rotations

The number of rotations needed to reconstruct the full dataset from a single wedge. Default is None until parameters are set.

Type:

int or None

transform

The transformation matrix used for skewing and scaling the dataset. Default is None until parameters are set.

Type:

Affine2D or None

mirror

Indicates whether mirroring is performed during symmetrization. Default is None until parameters are set.

Type:

bool or None

skew_angle
The skew angle (in degrees) between the principal axes of the plane

to be symmetrized. Default is None until parameters are set.

Type:

float or None

theta_max
The maximum angle (in degrees) for symmetrization. Default is None

until parameters are set.

Type:

float or None

theta_min
The minimum angle (in degrees) for symmetrization. Default is None

until parameters are set.

Type:

float or None

wedge
The dataset wedge used in the symmetrization process. Default is

None until symmetrization is performed.

Type:

nexusformat.nexus.tree.NXdata or None

symmetrization_mask
The mask used for selecting the region of the dataset to be symmetrized.

Default is None until symmetrization is performed.

Type:

nexusformat.nexus.tree.NXdata or None

__init__(**kwargs):
Initializes the Symmetrizer2D object and optionally sets the parameters

using set_parameters.

set_parameters(theta_min, theta_max, lattice_angle=90, mirror=True, mirror_axis=0):
Sets the parameters for the symmetrization operation, including angle limits,

lattice angle, and mirroring options.

symmetrize_2d(data):

Symmetrizes a 2D dataset based on the set parameters.

test(data, \*\*kwargs):
Performs a test visualization of the symmetrization process, displaying the

original data, mask, wedge, and symmetrized result.

Methods

set_parameters(theta_min, theta_max[, ...])

Sets the parameters for the symmetrization operation, and calculates the

symmetrize_2d(data)

Symmetrizes a 2D dataset based on the set parameters, applying padding

test(data, **kwargs)

Performs a test visualization of the symmetrization process to help assess

__init__(**kwargs)

Initializes the Symmetrizer2D object.

Parameters:

**kwargs (dict, optional) –

Keyword arguments that can be passed to the set_parameters method to

set the symmetrization parameters during initialization.

set_parameters(theta_min, theta_max, lattice_angle=90, mirror=True, mirror_axis=None)
Sets the parameters for the symmetrization operation, and calculates the

required transformations and rotations.

Parameters:
  • theta_min (float) – The minimum angle in degrees for symmetrization.

  • theta_max (float) – The maximum angle in degrees for symmetrization.

  • lattice_angle (float, optional) –

    The angle in degrees between the two principal axes of the plane to be

    symmetrized (default: 90).

  • mirror (bool, optional) – If True, perform mirroring during symmetrization (default: True).

  • mirror_axis (int, optional) – The axis along which to perform mirroring (default: 0).

symmetrize_2d(data)
Symmetrizes a 2D dataset based on the set parameters, applying padding

to prevent rotation cutoff and handling overlapping pixels.

Parameters:

data (nexusformat.nexus.tree.NXdata) – The input 2D dataset to be symmetrized.

Returns:

symmetrized – The symmetrized 2D dataset.

Return type:

nexusformat.nexus.tree.NXdata

test(data, **kwargs)
Performs a test visualization of the symmetrization process to help assess

the effect of the parameters.

Parameters:
  • data (numpy.ndarray) – The input 2D dataset to be used for the test visualization.

  • **kwargs (dict) – Additional keyword arguments to be passed to the plot_slice function.

Returns:

  • fig (Figure) – The matplotlib Figure object that contains the test visualization plot.

  • axesarr (numpy.ndarray) –

    The numpy array of Axes objects representing the subplots in the test

    visualization.

Notes

This method uses the symmetrize_2d method to perform the symmetrization on

the input data and visualize the process.

The test visualization plot includes the following subplots: - Subplot 1: The original dataset. - Subplot 2: The symmetrization mask. - Subplot 3: The wedge slice used for reconstruction of the full symmetrized dataset. - Subplot 4: The symmetrized dataset.

Example

>>> s = Symmetrizer2D()
>>> s.set_parameters(theta_min, theta_max, skew_angle, mirror)
>>> s.test(data)
class nxs_analysis_tools.pairdistribution.Symmetrizer3D
A class to symmetrize 3D datasets by performing sequential 2D symmetrization on

different planes.

This class applies 2D symmetrization on the three principal planes of a 3D dataset, effectively enhancing the symmetry of the data across all axes.

Methods

save([fout_name])

Save the symmetrized dataset to a NeXus file.

set_data(data)

Sets the 3D dataset to be symmetrized and updates the corresponding q-vectors and planes.

set_lattice_params(lattice_params)

Sets the lattice parameters and calculates the reciprocal lattice parameters.

symmetrize([positive_values])

Symmetrize the 3D dataset by sequentially applying 2D symmetrization on the three principal planes.

__init__(data=None)

Initialize the Symmetrizer3D object with an optional 3D dataset.

If data is provided, the corresponding q-vectors and planes are automatically

set up for symmetrization.

Parameters:

data (nexusformat.nexus.tree.NXdata, optional) – The input 3D dataset to be symmetrized.

set_data(data)

Sets the 3D dataset to be symmetrized and updates the corresponding q-vectors and planes.

Parameters:

data (nexusformat.nexus.tree.NXdata) – The input 3D dataset to be symmetrized.

set_lattice_params(lattice_params)

Sets the lattice parameters and calculates the reciprocal lattice parameters.

Parameters:

lattice_params (tuple of float) – The lattice parameters (a, b, c, alpha, beta, gamma) in real space. These should be provided in the order corresponding to the axes of the relevant dataset.

symmetrize(positive_values=True)

Symmetrize the 3D dataset by sequentially applying 2D symmetrization on the three principal planes.

This method performs symmetrization along the (q1-q2), (q1-q3), and (q2-q3) planes, ensuring that the dataset maintains expected symmetry properties. Optionally, negative values resulting from the symmetrization process can be set to zero.

Parameters:

positive_values (bool, optional) – If True, sets negative symmetrized values to zero (default is True).

Returns:

The symmetrized 3D dataset stored in the symmetrized attribute.

Return type:

nexusformat.nexus.tree.NXdata

Notes

  • Symmetrization is performed sequentially across three principal planes using corresponding 2D symmetrization methods.

  • The process prints progress updates and timing information.

  • If theta_max is not set for a particular plane symmetrizer, that plane is skipped.

save(fout_name=None)

Save the symmetrized dataset to a NeXus file.

Parameters:

fout_name (str, optional) – The name of the output file. If not provided, the default name ‘symmetrized.nxs’ will be used.

class nxs_analysis_tools.pairdistribution.Puncher

A class for applying masks to datasets, typically for data processing in reciprocal space.

This class provides methods for setting data, applying masks, and generating
masks based on various criteria. It can be used to “punch” or modify datasets

by setting specific regions to NaN according to the mask.

data

The input dataset to be processed.

Type:

nexusformat.nexus.tree.NXdata

meshgrid

Meshgrid arrays for the coordinates of the dataset.

Type:

tuple of numpy.ndarray

mask

The mask used for removing regions of the dataset.

Type:

numpy.ndarray

lattice_params

The lattice parameters [e.g., (a, b, c, alpha, beta, gamma)].

Type:

tuple

reciprocal_lattice_params

The reciprocal lattice parameters derived from the lattice parameters.

Type:

tuple

a, b, c, al, be, ga

Individual lattice parameters.

Type:

float

a_star, b_star, c_star, al_star, be_star, ga_star

Individual reciprocal lattice parameters.

Type:

float

punched

The dataset with regions modified (punched) based on the mask.

Type:

nexusformat.nexus.tree.NXdata

set_data(data)

Sets the dataset to be processed and initializes the coordinate arrays and mask.

set_lattice_params(lattice_params)

Sets the lattice parameters and computes the reciprocal lattice parameters.

add_mask(maskaddition)

Adds regions to the current mask using a logical OR operation.

subtract_mask(masksubtraction)

Removes regions from the current mask using a logical AND NOT operation.

generate_bragg_mask(punch_radius, coeffs=None, thresh=None)

Generates an ellipsoidal mask at integer coordinates.

generate_intensity_mask(thresh, radius, verbose=True)
Generates a mask based on intensity thresholds, including a pixel-spherical

region around high-intensity points.

generate_mask_at_coord(coordinate, punch_radius, coeffs=None, thresh=None)
Generates an ellipsoidal mask centered at a specific coordinate in reciprocal space

with a specified radius.

punch()

Applies the mask to the dataset, setting masked regions to NaN.

Methods

add_mask(maskaddition)

Add regions to the current mask using a logical OR operation.

generate_bragg_mask(punch_radius[, coeffs, ...])

Generate an ellipsoidal mask at integer coordinates.

generate_intensity_mask(thresh, radius[, ...])

Generate a mask based on intensity thresholds.

generate_mask_at_coord(coordinate, punch_radius)

Generate a mask centered at a specific coordinate.

punch()

Apply the mask to the dataset, setting masked regions to NaN.

set_data(data)

Set the dataset and initialize the mask if not already set.

set_lattice_params(lattice_params)

Set the lattice parameters [e.g., (a, b, c, alpha, beta, gamma)] and compute the reciprocal lattice parameters.

subtract_mask(masksubtraction)

Remove regions from the current mask using a logical AND NOT operation.

__init__()

Initialize the Puncher object.

This method sets up the initial state of the Puncher instance, including
attributes for storing the dataset, lattice parameters, and masks.

It prepares the object for further data processing and masking operations.

data

The input dataset to be processed, initialized as None.

Type:

nexusformat.nexus.tree.NXdata, optional

meshgrid

Meshgrid arrays for the coordinates of the dataset. Initialized as None.

Type:

tuple of numpy.ndarray

mask

The mask used for removing regions of the dataset, initialized as None.

Type:

numpy.ndarray, optional

reciprocal_lattice_params

The reciprocal lattice parameters, initialized as None.

Type:

tuple, optional

lattice_params
The lattice parameters (a, b, c, alpha, beta, gamma),

initialized as None.

Type:

tuple, optional

a, b, c, al, be, ga

Individual lattice parameters, initialized as None.

Type:

float

a_star, b_star, c_star, al_star, be_star, ga_star

Individual reciprocal lattice parameters, initialized as None.

Type:

float

punched

The dataset with modified (punched) regions, initialized as None.

Type:

nexusformat.nexus.tree.NXdata, optional

set_data(data)

Set the dataset and initialize the mask if not already set.

Parameters:

data (nexusformat.nexus.tree.NXdata) – The dataset to be processed.

Notes

This method also sets up coordinate meshgrids for the dataset.

set_lattice_params(lattice_params)

Set the lattice parameters [e.g., (a, b, c, alpha, beta, gamma)] and compute the reciprocal lattice parameters. These should be provided in the order corresponding to the axes of the relevant dataset.

Parameters:

lattice_params (tuple) – Tuple of lattice parameters (a, b, c, alpha, beta, gamma).

add_mask(maskaddition)

Add regions to the current mask using a logical OR operation.

Parameters:

maskaddition (numpy.ndarray) – The mask to be added.

subtract_mask(masksubtraction)

Remove regions from the current mask using a logical AND NOT operation.

Parameters:

masksubtraction (numpy.ndarray) – The mask to be subtracted.

generate_bragg_mask(punch_radius, coeffs=None, thresh=None)

Generate an ellipsoidal mask at integer coordinates.

Parameters:
  • punch_radius (float) – Radius for the mask around each integer coordinate.

  • coeffs (list, optional) – Coefficients for the expression of the ellipse/ellipsoid to be removed around each integer coordinate (Bragg position). For 3D: [H, HK, K, KL, L, LH] terms. Default is [1, 0, 1, 0, 1, 0]. For 2D: [H, HK, K] terms. Default is [1, 0, 1].

  • thresh (float, optional) – Intensity threshold for applying the mask.

Returns:

mask – Boolean mask identifying ellipsoidal regions to be removed around each integer coordinate.

Return type:

numpy.ndarray

generate_intensity_mask(thresh, radius, verbose=True)

Generate a mask based on intensity thresholds.

Parameters:
  • thresh (float) – Intensity threshold for creating the mask.

  • radius (int) – Radius around high-intensity points to include in the mask.

  • verbose (bool, optional) – Whether to print progress information.

Returns:

mask – Boolean mask highlighting regions with high intensity.

Return type:

numpy.ndarray

generate_mask_at_coord(coordinate, punch_radius, coeffs=None, thresh=None)

Generate a mask centered at a specific coordinate.

Parameters:
  • coordinate (tuple of float) – Center coordinate for the mask.

  • punch_radius (float) – Radius for the mask.

  • coeffs (list, optional) – Coefficients for the expression of the ellipse/ellipsoid to be removed around the specific coordinate. For 3D: [H, HK, K, KL, L, LH] terms. Default is [1, 0, 1, 0, 1, 0]. For 2D: [H, HK, K] terms. Default is [1, 0, 1].

  • thresh (float, optional) – Intensity threshold for applying the mask.

Returns:

mask – Boolean mask for the specified coordinate.

Return type:

numpy.ndarray

punch()

Apply the mask to the dataset, setting masked regions to NaN.

This method creates a new dataset where the masked regions are set to NaN, effectively “punching” those regions.

class nxs_analysis_tools.pairdistribution.Interpolator
A class to perform data interpolation using convolution with a specified

kernel.

interp_time

Time taken for the last interpolation operation. Defaults to None.

Type:

float or None

window

Window function to be applied to the interpolated data. Defaults to None.

Type:

numpy.ndarray or None

interpolated

The result of the interpolation operation. Defaults to None.

Type:

numpy.ndarray or None

data

The dataset to be interpolated. Defaults to None.

Type:

nexusformat.nexus.tree.NXdata or None

kernel

The kernel used for convolution during interpolation. Defaults to None.

Type:

numpy.ndarray or None

tapered

The interpolated data after applying the window function. Defaults to None.

Type:

numpy.ndarray or None

Methods

apply_window()

Apply the window function to the interpolated data.

interpolate([verbose, positive_values])

Perform interpolation on the dataset using the specified kernel.

set_data(data)

Set the dataset to be interpolated.

set_ellipsoidal_tukey_window([tukey_alpha, ...])

Set an ellipsoidal/elliptical Tukey window function.

set_hexagonal_tukey_window([tukey_alphas, ...])

Set a hexagonal Tukey window function.

set_kernel(kernel)

Set the kernel to be used for interpolation.

set_tukey_window([tukey_alphas])

Set a Tukey window function for data tapering.

set_window(window)

Set a custom window function for data tapering.

__init__()

Initialize an Interpolator object.

Sets up an instance of the Interpolator class with the following attributes initialized to None:

  • interp_time

  • window

  • interpolated

  • data

  • kernel

  • tapered

set_data(data)

Set the dataset to be interpolated.

Parameters:

data (nexusformat.nexus.tree.NXdata) – The dataset containing the data to be interpolated.

set_kernel(kernel)

Set the kernel to be used for interpolation.

Parameters:

kernel (numpy.ndarray) – The kernel to be used for convolution during interpolation.

interpolate(verbose=True, positive_values=True)

Perform interpolation on the dataset using the specified kernel.

This method convolves the dataset with a kernel using convolve_fft to perform interpolation. The resulting interpolated data is stored in the interpolated attribute.

Parameters:
  • verbose (bool, optional) – If True, prints progress messages and timing information (default is True).

  • positive_values (bool, optional) – If True, sets negative interpolated values to zero (default is True).

Notes

  • The convolution operation is performed in Fourier space.

  • If a previous interpolation time is recorded, it is displayed before starting a new interpolation.

Return type:

None

set_tukey_window(tukey_alphas=None)

Set a Tukey window function for data tapering.

Parameters:

tukey_alphas (tuple of floats, optional) – The alpha parameters for the Tukey window in each dimension. Defaults to 1.0 for all dimensions.

set_hexagonal_tukey_window(tukey_alphas=None, reverse_axes=False)

Set a hexagonal Tukey window function.

Parameters:
  • tukey_alphas (tuple of floats, optional) – The alpha parameters for the Tukey window. For 3D: (H, K, HK, L). Default is (1.0, 1.0, 1.0, 1.0). For 2D: (H, K, HK). Default is (1.0, 1.0, 1.0).

  • reverse_axes (bool, optional) – If True in 3D, uses the first axis (q0) as the out-of-plane axis. Default False, which uses the third axis (q2) as the out-of-plane axis. If True in 2D, transposes the applied hexagonal window.

set_ellipsoidal_tukey_window(tukey_alpha=1.0, coeffs=None)

Set an ellipsoidal/elliptical Tukey window function.

Parameters:
  • tukey_alpha (float, optional) – Tapering parameter for the Tukey window, between 0 and 1. - tukey_alpha = 0 results in an ellipsoidal window (no tapering). - tukey_alpha = 1 results in a full cosine taper. Default is 1.0.

  • coeffs (tuple of float, optional) –

    Coefficients defining the ellipsoidal quadratic form. For 3D (c0, c1, c2, c3, c4, c5):

    R^2 = c0*H^2 + c1*H*K + c2*K^2 + c3*K*L + c4*L^2 + c5*L*H

    For 2D (c0, c1, c2):

    R^2 = c0*H^2 + c1*H*K + c2*K^2

    If None, coefficients are automatically set to match the edges of the reciprocal space axes.

  • Sets

  • ----

  • self.window (numpy.ndarray) – An N-dimensional array of the same shape as the data, containing the Tukey window values between 0 and 1.

set_window(window)

Set a custom window function for data tapering.

Parameters:

window (numpy.ndarray) – A custom window function to be applied to the interpolated data.

apply_window()

Apply the window function to the interpolated data.

The window function, if set, is applied to the interpolated data

to produce the tapered result.

Return type:

None

nxs_analysis_tools.pairdistribution.fourier_transform_nxdata(data, method='complete', verbose=True)

Perform a Fourier Transform on an NXdata object.

Parameters:
  • data (nexusformat.nexus.tree.NXdata) – An NXdata object containing the data to be transformed.

  • method ({'complete', 'staged'}, optional) –

    The FFT method to use:

    • ’complete’ (default): performs a full n-dimensional FFT using pyfftw.

    • ’staged’: performs a 2+1D FFT in two stages - first within the planes defined by the first two axes, then along the third axis. Requires 3D data and the third axis must be normal to the plane of the first two axes.

  • verbose (bool, optional) – If True, prints progress messages during computation.

Returns:

A new NXdata object containing the Fourier-transformed data (real part).

Return type:

nexusformat.nexus.tree.NXdata

Notes

  • Uses pyfftw for efficient Fourier Transform computation.

  • Only the real part of the FFT is returned.

  • In version v0.1.15 and beyond, the default method was changed from method=’staged’ to method=’complete’. Previous behavior can be restored by explicitly setting method=’staged’.

  • method=’staged’ may produce incorrect results if the third coordinate axis is not perpendicular to the plane of the first two axes; a warning is issued in this case.

class nxs_analysis_tools.pairdistribution.Gaussian3DKernel

Initialize a 3D Gaussian kernel.

This constructor creates a 3D Gaussian kernel with the specified standard deviation and size. The Gaussian kernel is generated based on the provided coefficients and is then normalized.

Parameters:
  • stddev (float) – The standard deviation of the Gaussian distribution, which controls the width of the kernel.

  • size (tuple of int) – The dimensions of the kernel, given as (x_dim, y_dim, z_dim).

  • coeffs (list of float, optional) – Coefficients for the Gaussian expression. The default is [1, 0, 1, 0, 1, 0], corresponding to the Gaussian form: (1 * X^2 + 0 * X * Y + 1 * Y^2 + 0 * Y * Z + 1 * Z^2 + 0 * Z * X).

Raises:

ValueError – If the dimensions in size are not positive integers.

Notes

The kernel is generated over a grid that spans twice the size of each dimension, and the resulting array is normalized.

Attributes

array

Filter kernel array.

center

Index of the kernel center.

dimension

Kernel dimension.

is_bool

Indicates if kernel is bool.

model

Kernel response model.

separable

Indicates if the filter kernel is separable.

shape

Shape of the kernel array.

truncation

Absolute deviation of the sum of the kernel array values from one.

Methods

normalize([mode])

Normalize the filter kernel.

__init__(stddev, size, coeffs=None)
class nxs_analysis_tools.pairdistribution.DeltaPDF

A class for processing and analyzing 3D diffraction data using various operations, including masking, interpolation, padding, and Fourier transformation.

fft

The Fourier transformed data.

Type:

nexusformat.nexus.tree.NXdata or None

data

The input diffraction data.

Type:

nexusformat.nexus.tree.NXdata or None

lattice_params

Lattice parameters [e.g., (a, b, c, alpha, beta, gamma)]. These should be provided in the order corresponding to the axes of the relevant dataset.

Type:

tuple or None

reciprocal_lattice_params

Reciprocal lattice parameters [e.g., (a*, b*, c*, al*, be*, ga*)].

Type:

tuple or None

puncher

An instance of the Puncher class for generating masks and punching the data.

Type:

Puncher

interpolator

An instance of the Interpolator class for interpolating and applying windows to the data.

Type:

Interpolator

padder

An instance of the Padder class for padding the data.

Type:

Padder

mask

The mask used for data processing.

Type:

numpy.ndarray or None

kernel

The kernel used for interpolation.

Type:

Kernel or None

window

The window applied to the interpolated data.

Type:

numpy.ndarray or None

padded

The padded data.

Type:

numpy.ndarray or None

tapered

The data after applying the window.

Type:

numpy.ndarray or None

interpolated

The interpolated data.

Type:

nexusformat.nexus.tree.NXdata or None

punched

The punched data.

Type:

nexusformat.nexus.tree.NXdata or None

Methods

add_mask(maskaddition)

Add regions to the current mask using a logical OR operation.

apply_window()

Apply the window function to the interpolated data.

generate_bragg_mask(punch_radius[, coeffs, ...])

Generate a mask for Bragg peaks.

generate_intensity_mask(thresh, radius[, ...])

Generate a mask based on intensity thresholds.

generate_mask_at_coord(coordinate, punch_radius)

Generate a mask centered at a specific coordinate.

interpolate([verbose, positive_values])

Perform interpolation on the dataset using the specified kernel.

pad(padding)

Symmetrically pads the data with zero values.

perform_fft([is_2d])

Perform a 3D Fourier Transform on the padded data.

punch()

Apply the mask to the dataset, setting masked regions to NaN.

set_data(data)

Set the input diffraction data and update the Puncher and Interpolator

set_ellipsoidal_tukey_window([tukey_alpha, ...])

Set an ellipsoidal/elliptical Tukey window function.

set_hexagonal_tukey_window([tukey_alphas, ...])

Set a hexagonal Tukey window function.

set_kernel(kernel)

Set the kernel to be used for interpolation.

set_lattice_params(lattice_params)

Sets the lattice parameters and calculates the reciprocal lattice

set_tukey_window([tukey_alphas])

Set a Tukey window function for data tapering.

set_window(window)

Set a custom window function for data tapering.

subtract_mask(masksubtraction)

Remove regions from the current mask using a logical AND NOT operation.

__init__()

Initialize a DeltaPDF object with default attributes.

set_data(data)
Set the input diffraction data and update the Puncher and Interpolator

with the data.

Parameters:

data (nexusformat.nexus.tree.NXdata) – The diffraction data to be processed.

set_lattice_params(lattice_params)
Sets the lattice parameters and calculates the reciprocal lattice

parameters.

Parameters:

lattice_params (tuple of float) – The lattice parameters [e.g., (a, b, c, alpha, beta, gamma)] in real space. These should be provided in the order corresponding to the axes of the relevant dataset.

add_mask(maskaddition)

Add regions to the current mask using a logical OR operation.

Parameters:

maskaddition (numpy.ndarray) – The mask to be added.

subtract_mask(masksubtraction)

Remove regions from the current mask using a logical AND NOT operation.

Parameters:

masksubtraction (numpy.ndarray) – The mask to be subtracted.

generate_bragg_mask(punch_radius, coeffs=None, thresh=None)

Generate a mask for Bragg peaks.

Parameters:
  • punch_radius (float) – Radius for the Bragg peak mask.

  • coeffs (list, optional) –

    Coefficients for the expression of the sphere to be removed
    around each Bragg position, corresponding to coefficients

    for H, HK, K, KL, L, and LH terms. Default is [1, 0, 1, 0, 1, 0].

  • thresh (float, optional) – Intensity threshold for applying the mask.

Returns:

mask – Boolean mask identifying the Bragg peaks.

Return type:

numpy.ndarray

generate_intensity_mask(thresh, radius, verbose=True)

Generate a mask based on intensity thresholds.

Parameters:
  • thresh (float) – Intensity threshold for creating the mask.

  • radius (int) – Radius around high-intensity points to include in the mask.

  • verbose (bool, optional) – Whether to print progress information.

Returns:

mask – Boolean mask highlighting regions with high intensity.

Return type:

numpy.ndarray

generate_mask_at_coord(coordinate, punch_radius, coeffs=None, thresh=None)

Generate a mask centered at a specific coordinate.

Parameters:
  • coordinate (tuple of float) – Center coordinate for the mask.

  • punch_radius (float) – Radius for the mask.

  • coeffs (list, optional) – Coefficients for the expression of the ellipse/ellipsoid to be removed around the specific coordinate. For 3D: [H, HK, K, KL, L, LH] terms. Default is [1, 0, 1, 0, 1, 0]. For 2D: [H, HK, K] terms. Default is [1, 0, 1].

  • thresh (float, optional) – Intensity threshold for applying the mask.

Returns:

mask – Boolean mask for the specified coordinate.

Return type:

numpy.ndarray

punch()

Apply the mask to the dataset, setting masked regions to NaN.

This method creates a new dataset where the masked regions are set to

NaN, effectively “punching” those regions.

set_kernel(kernel)

Set the kernel to be used for interpolation.

Parameters:

kernel (numpy.ndarray) – The kernel to be used for convolution during interpolation.

interpolate(verbose=True, positive_values=True)

Perform interpolation on the dataset using the specified kernel.

This method convolves the dataset with a kernel using convolve_fft to perform interpolation. The resulting interpolated data is stored in the interpolated attribute.

Parameters:
  • verbose (bool, optional) – If True, prints progress messages and timing information (default is True).

  • positive_values (bool, optional) – If True, sets negative interpolated values to zero (default is True).

Notes

  • The convolution operation is performed in Fourier space.

  • If a previous interpolation time is recorded, it is displayed before starting a new interpolation.

Return type:

None

set_tukey_window(tukey_alphas=None)

Set a Tukey window function for data tapering.

Parameters:

tukey_alphas (tuple of floats, optional) – The alpha parameters for the Tukey window in each dimension. Defaults to 1.0 for all dimensions.

set_hexagonal_tukey_window(tukey_alphas=None, reverse_axes=False)

Set a hexagonal Tukey window function.

Parameters:
  • tukey_alphas (tuple of floats, optional) – The alpha parameters for the Tukey window. For 3D: (H, K, HK, L). Default is (1.0, 1.0, 1.0, 1.0). For 2D: (H, K, HK). Default is (1.0, 1.0, 1.0).

  • reverse_axes (bool, optional) – If True in 3D, uses the first axis (q0) as the out-of-plane axis. Default False, which uses the third axis (q2) as the out-of-plane axis. If True in 2D, transposes the applied hexagonal window.

set_ellipsoidal_tukey_window(tukey_alpha=1.0, coeffs=None)

Set an ellipsoidal/elliptical Tukey window function.

Parameters:
  • tukey_alpha (float, optional) – Tapering parameter for the Tukey window, between 0 and 1. - tukey_alpha = 0 results in an ellipsoidal window (no tapering). - tukey_alpha = 1 results in a full cosine taper. Default is 1.0.

  • coeffs (tuple of float, optional) –

    Coefficients defining the ellipsoidal quadratic form. For 3D (c0, c1, c2, c3, c4, c5):

    R^2 = c0*H^2 + c1*H*K + c2*K^2 + c3*K*L + c4*L^2 + c5*L*H

    For 2D (c0, c1, c2):

    R^2 = c0*H^2 + c1*H*K + c2*K^2

    If None, coefficients are automatically set to match the edges of the reciprocal space axes.

  • Sets

  • ----

  • self.window (numpy.ndarray) – An N-dimensional array of the same shape as the data, containing the Tukey window values between 0 and 1.

set_window(window)

Set a custom window function for data tapering.

Parameters:

window (numpy.ndarray) – A custom window function to be applied to the interpolated data.

apply_window()

Apply the window function to the interpolated data.

The window function, if set, is applied to the interpolated data to

produce the tapered result.

Return type:

None

pad(padding)

Symmetrically pads the data with zero values.

Parameters:

padding (tuple) – The number of zero-value pixels to add along each edge of the array.

Returns:

The padded data with symmetric zero padding.

Return type:

nexusformat.nexus.tree.NXdata

perform_fft(is_2d=None, **kwargs)

Perform a 3D Fourier Transform on the padded data.

Parameters:
  • method ({'complete', 'staged'}, optional) – The FFT method to use: - ‘complete’ (default): performs a full n-dimensional FFT using pyfftw. - ‘staged’: performs a 2+1D FFT in two stages—first within the planes defined by the first two axes, then along the third axis. Requires 3D data and the third axis must be normal to the plane of the first two axes.

  • verbose (bool, optional) – If True, prints progress messages during computation.

Return type:

None

Notes

  • Calls fourier_transform_nxdata to perform the transformation.

  • The output includes frequency components computed from the step

sizes of the original data axes.

nxs_analysis_tools.pairdistribution.generate_gaussian(H, K, L, amp, stddev, lattice_params, coeffs=None, center=None)

Generate a 3D Gaussian distribution.

This function creates a 3D Gaussian distribution in reciprocal space based

on the specified parameters.

Parameters:
  • H (numpy.ndarray or nexusformat.nexus.tree.NXfield) – The three principal axes of the reciprocal space grid. These should be provided in the order corresponding to the axes of the relevant dataset.

  • K (numpy.ndarray or nexusformat.nexus.tree.NXfield) – The three principal axes of the reciprocal space grid. These should be provided in the order corresponding to the axes of the relevant dataset.

  • L (numpy.ndarray or nexusformat.nexus.tree.NXfield) – The three principal axes of the reciprocal space grid. These should be provided in the order corresponding to the axes of the relevant dataset.

  • amp (float) – Amplitude of the Gaussian distribution.

  • stddev (float) – Standard deviation of the Gaussian distribution.

  • lattice_params (tuple) – Lattice parameters [e.g., (a, b, c, alpha, beta, gamma)]. These should be provided in the order corresponding to the axes of the relevant dataset.

  • coeffs (list, optional) –

    Coefficients for the Gaussian expression, including cross-terms between axes.

    Default is [1, 0, 1, 0, 1, 0], corresponding to (1*H**2 + 0*H*K + 1*K**2 + 0*K*L + 1*L**2 + 0*L*H).

  • center (tuple) – Tuple of coordinates for the center of the Gaussian. Default is (0,0,0).

Returns:

gaussian – 3D Gaussian distribution array.

Return type:

numpy.ndarray