nres ===

nres: Simple yet powerful package for neutron resonance fitting

nres.cross_section

class nres.cross_section.CrossSection(isotopes=None, name='', total_weight=1.0, L=10.59, tstep=1.56255e-09, tbins=640, first_tbin=1, splitby='elements', **materials)[source]

Bases: object

A class representing neutron cross-sections for single or multiple isotopes.

This class handles the loading, manipulation, and analysis of neutron cross-section data. It supports operations on individual isotopes as well as combinations of isotopes with different weights. The class provides functionality for interpolation and calculation of total cross-sections based on weighted sums.

isotopes

Dictionary mapping isotope names or CrossSection objects to their respective weights.

Type

Dict[Union[str, ‘CrossSection’], float]

name

Identifier for this cross-section combination.

Type

str

weights

Normalized weights for each isotope, ensuring they sum to 1.

Type

pd.Series

table

DataFrame containing the interpolated cross-section data. Includes columns for each isotope and a ‘total’ column.

Type

pd.DataFrame

L

Flight path length in meters.

Type

float

tstep

Time step for the simulation in seconds.

Type

float

tbins

Number of time bins for the simulation.

Type

int

first_tbin

Index of the first time bin (typically 1).

Type

int

n

Number density calculated based on isotope weights.

Type

float

materials

Dictionary containing material information and properties.

Type

Dict

add_material(name, material_data, splitby='elements', total_weight=1.0)[source]

Add a new material with complete information.

Parameters
  • name (str) – str, name of the material

  • material_data (Dict) – Dict, material composition data

  • splitby (str) – str, how to split the material (‘elements’, ‘isotopes’, or ‘materials’)

  • total_weight (float) – float, total weight of the material

iplot(**kwargs)[source]

Create an interactive plotly plot of the cross-section data.

Generates an interactive plot showing the total cross-section and individual isotope contributions, with customizable axes scales and energy range.

Parameters

**kwargs – Additional keyword arguments for plot customization: - title: Plot title (default: self.name) - ylabel: Y-axis label (default: “σ [barn]”) - xlabel: X-axis label (default: “Energy [eV]”) - emin: Minimum energy to plot (default: 0.1 eV) - emax: Maximum energy to plot (default: 2e7 eV) - scalex: X-axis scale (“log” or “linear”, default: “log”) - scaley: Y-axis scale (“log” or “linear”, default: “log”) - Additional arguments passed to plotly

Returns

Interactive figure object

Return type

plotly.graph_objects.Figure

Note

This method uses plotly as the backend for interactive visualization, allowing for features like zooming, panning, and hover tooltips.

plot(**kwargs)[source]

Create a matplotlib plot of the cross-section data.

Generates a plot showing the total cross-section and individual isotope contributions, with weights displayed in the legend.

Parameters

**kwargs – Additional keyword arguments for plot customization: - title: Plot title (default: self.name) - ylabel: Y-axis label (default: “σ [barn]”) - xlabel: X-axis label (default: “Energy [eV]”) - lw: Line width (default: 1.0) - Additional arguments passed to pandas.DataFrame.plot

Returns

The axes object containing the plot

Return type

matplotlib.axes.Axes

Note

The total cross-section is plotted in black with increased line width for emphasis. Individual isotope contributions are plotted in different colors with their weights shown as percentages in the legend.

nres.models

class nres.models.TransmissionModel(cross_section, response='expo_gauss', background='polynomial3', tof_calibration='linear', vary_weights=None, vary_background=None, vary_tof=None, vary_response=None, params=None, **kwargs)[source]

Bases: lmfit.model.Model

fit(data, params=None, emin=500000.0, emax=20000000.0, method='rietveld', xtol=None, ftol=None, gtol=None, verbose=False, progress_bar=True, param_groups=None, **kwargs)[source]

Fit the model to data.

This method supports both: - Standard single-stage fitting (default) - Rietveld-style staged refinement (method=”rietveld”) with accumulative parameter refinement with accumulative parameter refinement

Parameters
  • data (pandas.DataFrame or Data or array-like) – The input data. - For pandas.DataFrame or Data: must have columns “energy”, “trans”, and “err”. - For array-like: will be passed directly to lmfit.Model.fit.

  • params (lmfit.Parameters, optional) – Parameters to use for fitting. If None, uses the model’s default parameters.

  • emin (float, optional) – Minimum and maximum energy for fitting (ignored for array-like input and overridden per stage if param_groups specify “emin=…” or “emax=…” strings).

  • emax (float, optional) – Minimum and maximum energy for fitting (ignored for array-like input and overridden per stage if param_groups specify “emin=…” or “emax=…” strings).

  • method (str, optional) – Fitting method. - “rietveld” (default) will run staged refinement via _rietveld_fit. - “least-squares” or any method supported by lmfit for single-stage fitting.

  • xtol (float, optional) – Convergence tolerances (passed to lmfit).

  • ftol (float, optional) – Convergence tolerances (passed to lmfit).

  • gtol (float, optional) – Convergence tolerances (passed to lmfit).

  • verbose (bool, optional) – If True, prints detailed fitting information.

  • progress_bar (bool, optional) – If True, shows a progress bar for fitting: - For “rietveld”: shows stage name, energy range, and reduced chi² per stage. - For regular fits: shows overall fit progress.

  • param_groups (list, dict, or None, optional) –

    Used only for “rietveld”. Groups of parameters to fit in each stage. Groups may also contain “emin=…” and/or “emax=…” strings to override the energy fitting range for that specific stage. For example:

    ```python param_groups = {

    ”Basic”: [“basic”], “Background”: [“background”, “emin=3”, “emax=8”], “Extinction”: [“extinction”],

    These per-stage overrides temporarily replace the global emin/emax only during the stage.

  • **kwargs

    Additional keyword arguments passed to lmfit.Model.fit.

    For grouped data, additional parameters: - n_jobs (int): Number of parallel jobs (default: 10). Use -1 for all CPUs,

    but beware of memory issues. For threading, consider n_jobs=4 or less.

    • max_nbytes (str): Maximum memory per worker (default: ‘100M’). Prevents memory exhaustion. Increase for complex models or set to None to disable.

Returns

The fit result object, with extra methods: - .plot() — plot the fit result. - .plot_stage_progression(), .plot_chi2_progression() for advanced diagnostics. - .stages_summary (for “rietveld”).

Return type

lmfit.model.ModelResult

Examples

Basic fit: `python result = model.fit(data_df, emin=1.0, emax=5.0) result.plot() `

Rietveld-style staged refinement with per-stage energy overrides: ```python param_groups = {

“Norm/Thick”: [“norm”, “thickness”], “Background”: [“b0”, “b1”, “emin=3”, “emax=8”], “Extinction”: [“ext_l”, “ext_Gg”],

} result = model.fit(

data_df, method=”rietveld”, param_groups=param_groups, progress_bar=True

) print(result.stages_summary) ```

get_stages_summary_table()[source]

Get the stages summary table showing parameter progression through refinement stages.

Returns

Multi-index DataFrame with parameters as rows and stages as columns. Each stage has columns for ‘value’, ‘stderr’, ‘vary’, and ‘redchi’.

Return type

pandas.DataFrame

classmethod load(filename)[source]

Load a model from a JSON file.

Parameters

filename (str) – Path to the JSON file containing the saved model.

Returns

The loaded model instance.

Return type

TransmissionModel

Examples

>>> model = TransmissionModel.load("my_model.json")
>>> result = model.fit(data)
classmethod load_result(filename, model=None)[source]

Load a fit result from a JSON file.

Parameters
  • filename (str) – Path to the JSON file containing the saved result.

  • model (TransmissionModel, optional) – Model to use for the result. If None and the file contains a model, it will be loaded from the file. If the file doesn’t contain a model, this parameter is required.

Returns

A tuple containing (model, params_dict) where model is the TransmissionModel instance and params_dict contains the fit parameters and statistics.

Return type

tuple

Examples

>>> model, result_data = TransmissionModel.load_result("my_result.json")
>>> print(result_data["redchi"])
>>> # Or with compressed result
>>> model, result_data = TransmissionModel.load_result(
...     "result.json", model=my_model
... )
manually_calibrate_tof(inputs=None, references=None, input_type='tof', reference_type='energy', **kwargs)[source]

Manually calibrate time-of-flight (TOF) correction parameters.

Parameters
  • inputs (list or np.ndarray) – Input values for calibration (time-like values).

  • references (list or np.ndarray) – Corresponding reference values for calibration (energy-like values).

  • input_type (str, optional) – Type of input values. Options are: - ‘tof’: Direct time values in units of seconds - ‘energy’: Convert energy to time using utils.energy2time - ‘slice’: Convert slice indices to time by multiplying with tstep Default is ‘tof’.

  • reference_type (str, optional) – Type of reference values. Options are: - ‘tof’: Direct time values in units of seconds - ‘energy’: Convert energy to time using utils.energy2time - ‘slice’: Convert slice indices to time by multiplying with tstep Default is ‘energy’.

Returns

Detailed linear regression result with fitting information

Return type

lmfit ModelResult object

plot(data=None, plot_bg=True, correct_tof=True, stage=None, index=None, **kwargs)[source]

Plot the results of the fit or model.

Parameters
  • data (nres.Data, optional) – Show data alongside the model (useful before performing the fit).

  • plot_bg (bool, optional) – Whether to include the background in the plot, by default True.

  • correct_tof (bool, optional) – Apply TOF correction if L0 and t0 parameters are present, by default True.

  • stage (int, optional) – If provided, plot results from a specific Rietveld fitting stage (1-indexed). Only works if Rietveld fitting has been performed.

  • index (int, tuple, or str, optional) – For grouped data, specify which group to plot. - For 2D grids: can use tuple (0, 0) or string “(0, 0)” - For 1D arrays: can use int 5 or string “5” - For named groups: use string “groupname” If None and data is grouped, raises an error.

  • kwargs (dict, optional) – Additional plot settings like color, marker size, etc.

Returns

The axes of the plot.

Return type

matplotlib.axes.Axes

plot_chi2_progression(**kwargs)[source]

Plot the χ² progression through Rietveld stages with stage names on x-axis.

plot_stage_progression(stages=None, **kwargs)[source]

Plot the progression of Rietveld refinement stages showing how the fit improves.

save(filename)[source]

Save the model to a JSON file.

Parameters

filename (str) – Path to the JSON file where the model will be saved.

Notes

The model is saved as JSON, which is portable and human-readable. The saved file can be loaded using the TransmissionModel.load() class method.

Examples

>>> model = TransmissionModel(cross_section)
>>> model.save("my_model.json")
>>> loaded_model = TransmissionModel.load("my_model.json")
set_cross_section(xs, inplace=True)[source]

Set a new cross-section for the model.

Parameters
  • xs (CrossSection) – The new cross-section to apply.

  • inplace (bool, optional) – If True, modify the current object. If False, return a new modified object, by default True.

Returns

The updated model (either modified in place or a new instance).

Return type

TransmissionModel

show_available_params(show_groups=True, show_params=True)[source]

Display available parameter groups and individual parameters for Rietveld fitting.

Parameters
  • show_groups (bool, optional) – If True, show predefined parameter groups

  • show_params (bool, optional) – If True, show all individual parameters

property stages

Get the current fitting stages.

transmission(E, thickness=1, norm=1.0, **kwargs)[source]

Transmission function model with background components.

Parameters
  • E (np.ndarray) – The energy values at which to calculate the transmission.

  • thickness (float, optional) – The thickness of the material (in cm), by default 1.

  • norm (float, optional) – Normalization factor, by default 1.

  • kwargs (dict, optional) – Additional arguments for background, response, or cross-section.

Returns

The calculated transmission values.

Return type

np.ndarray

Notes

This function combines the cross-section with the response and background models to compute the transmission, which is given by:

\[T(E) = \text{norm} \cdot e^{- \sigma \cdot \text{thickness} \cdot n} \cdot (1 - \text{bg}) + \text{bg}\]

where sigma is the cross-section, bg is the background function, and n is the total atomic weight.

update_params(params={}, values_only=True, inplace=True)[source]

Update the parameters of the model.

Parameters
  • params (dict) – Dictionary of new parameters to update.

  • values_only (bool, optional) – If True, update only the values of the parameters, by default True.

  • inplace (bool, optional) – If True, modify the current object. If False, return a new modified object, by default True.

vary_all(vary=None, except_for=[])[source]

Toggle the ‘vary’ attribute for all model parameters.

Parameters
  • vary (bool, optional) – The value to set for all parameters’ ‘vary’ attribute.

  • except_for (list of str, optional) – List of parameter names to exclude from this operation, by default [].

weighted_thickness(params=None)[source]

Returns the weighted thickness in [cm]

Parameters

params (lmfit.Parameters, optional) – parameters object. Defaults to None.

nres.response

class nres.response.Background(kind='expo_norm', vary=False)[source]

Bases: object

constant_background(E, b0=0.0, **kwargs)[source]

Generates a constant background.

Parameters: E (np.ndarray): Energy values. b0 (float): Constant background value.

empty_background(E, **kwargs)[source]

Returns a zero background array.

plot(E, params=None, **kwargs)[source]

Plots the background function.

Parameters: E (np.ndarray): Energy values. params (dict): Parameters for the background function.

polynomial3_background(E, b0=0.0, b1=1.0, b2=0.0, **kwargs)[source]

Computes a third-degree polynomial background.

Parameters: E (np.ndarray): Energy values. b0 (float): Constant term. b1 (float): Linear term. b2 (float): Quadratic term.

polynomial5_background(E, b0=0.0, b1=1.0, b2=0.0, b3=0.0, b4=0.0, **kwargs)[source]

Computes a fifth-degree polynomial background.

Parameters: E (np.ndarray): Energy values. b0 (float): Constant term. b1 (float): Linear term. b2 (float): Quadratic term. b3 (float): Cubic term. b4 (float): Quartic term.

class nres.response.Response(kind='expo_gauss', vary=False, eps=1e-06, tstep=1.56255e-09, nbins=300)[source]

Bases: object

cut_array_symmetric(arr, threshold)[source]

Symmetrically cuts the array based on a threshold.

Parameters: arr (np.ndarray): Input array to be cut. threshold (float): The threshold value for cutting the array.

Returns: np.ndarray: Symmetrically cut array with an odd number of elements.

empty_response(**kwargs)[source]

Returns an empty response [0.0, 1.0, 0.0].

expogauss_response(K=0.01, x0=0.0, τ=1e-09, **kwargs)[source]

Computes the exponential-Gaussian response function.

Parameters: K (float): Shape parameter for the exponential. x0 (float): Location parameter for the Gaussian. τ (float): Scale parameter for the exponential.

Returns: np.ndarray: Normalized response array.

plot(params=None, **kwargs)[source]

Plots the response function.

Parameters: params (dict): Parameters for the response function. **kwargs: Additional arguments for plot customization.

register_response(response_func, lmfit_params=None, **kwargs)[source]

Registers a new response using any scipy.stats function.

Parameters: response_func (function): A function from scipy.stats, e.g., exponnorm.pdf. lmfit_params (lmfit.Parameters): Optional lmfit.Parameters to define limits and vary. kwargs: Default parameter values for the response function.

nres.data

class nres.data.Data(**kwargs)[source]

Bases: object

A class for handling neutron transmission data, including reading counts data, calculating transmission, and plotting the results.

tablepandas.DataFrame or None

A dataframe containing energy, transmission, and error values.

tgridpandas.Series or None

A time-of-flight grid corresponding to the time steps in the data.

signalpandas.DataFrame or None

The signal counts data (tof, counts, err).

openbeampandas.DataFrame or None

The open beam counts data (tof, counts, err).

Lfloat or None

Distance (meters) used in the energy conversion from time-of-flight.

tstepfloat or None

Time step (seconds) for converting time-of-flight to energy.

is_groupedbool

Whether this Data object contains grouped data.

groupsdict or None

Dict mapping index -> table for grouped data.

indiceslist or None

List of string indices for grouped data.

group_shapetuple or None

Tuple (nx, ny) for 2D, (n,) for 1D, None for named groups.

classmethod from_counts(signal, openbeam, empty_signal='', empty_openbeam='', tstep=1.56255e-09, L=10.59, L0=1.0, t0=0.0, verbosity=1)[source]

Creates a Data object from signal and open beam counts data, calculates transmission, and converts tof to energy.

signalstr

Path to the CSV file containing the signal data (tof, counts, err).

openbeamstr

Path to the CSV file containing the open beam data (tof, counts, err).

empty_signalstr, optional

Path to the CSV file containing the empty signal data for background correction. Default is an empty string.

empty_openbeamstr, optional

Path to the CSV file containing the empty open beam data for background correction. Default is an empty string.

tstepfloat, optional

Time step (seconds) for converting time-of-flight (tof) to energy. Default is 1.56255e-9.

Lfloat, optional

Distance (meters) used in the energy conversion from time-of-flight. Default is 10.59 m.

L0float, optional

Flight path scale factor from vary_tof optimization. Default is 1.0. Values > 1.0 indicate a longer path, < 1.0 a shorter path.

t0float, optional

Time offset correction in seconds from vary_tof optimization. Default is 0.0. Will be converted to TOF channel units internally using tstep.

verbosityint, optional

Verbosity level. If 0, suppresses warnings from sqrt operations. Default is 1.

Data

A Data object containing transmission and energy data.

classmethod from_grouped(signal, openbeam, empty_signal='', empty_openbeam='', tstep=1.56255e-09, L=10.59, L0=1.0, t0=0.0, pattern='auto', indices=None, verbosity=1, n_jobs=- 1)[source]

Creates a Data object from grouped counts data using glob patterns.

Supports 1D arrays, 2D grids, and named indices for spatially-resolved analysis.

signalstr

Glob pattern for signal files (e.g., “archive/pixel_*.csv” or “data/grid_*_x*_y*.csv”). Can also be a folder path - all .csv files in the folder will be loaded.

openbeamstr

Glob pattern for openbeam files. Can also be a folder path.

empty_signalstr, optional

Glob pattern for empty signal files for background correction.

empty_openbeamstr, optional

Glob pattern for empty openbeam files for background correction.

tstepfloat, optional

Time step (seconds) for converting time-of-flight to energy. Default is 1.56255e-9.

Lfloat, optional

Distance (meters) used in the energy conversion from time-of-flight. Default is 10.59 m.

L0float, optional

Flight path scale factor from vary_tof optimization. Default is 1.0.

t0float, optional

Time offset correction in seconds from vary_tof optimization. Default is 0.0. Will be converted to TOF channel units internally using tstep.

patternstr, optional

Coordinate extraction pattern. Default is “auto” which tries common patterns: - “x{x}_y{y}” for 2D grids (e.g., “grid_x10_y20.csv”) - “idx{i}” or “pixel_{i}” for 1D arrays Custom patterns can use {x}, {y}, {i}, or {name}.

indiceslist, optional

If provided, use these indices instead of extracting from filenames. Can be list of ints (1D), list of tuples (2D), or list of strings (named).

verbosityint, optional

Verbosity level. If >= 1, shows progress bar. Default is 1.

n_jobsint, optional

Number of parallel jobs for loading files. Default is -1 (use all CPUs). Set to 1 for sequential loading.

Data

A Data object with grouped data stored in self.groups.

# 2D grid from filenames like “pixel_x10_y20.csv” >>> data = Data.from_grouped(“folder/pixel_*.csv”, “folder_ob/pixel_*.csv”)

# 1D array with custom indices >>> data = Data.from_grouped( … “data/det_*.csv”, “data_ob/det_*.csv”, indices=[0, 1, 2, 3] … )

# Named groups >>> data = Data.from_grouped( … “samples/.csv”, “ref/.csv”, indices=[“sample1”, “sample2”] … )

classmethod from_grouped_arrays(tof, trans, err, L, tstep, L0=1.0, t0=0.0, indices=None)[source]

Creates a Data object from grouped transmission arrays.

This method is useful for creating grouped data from numpy arrays, such as data from imaging detectors or multi-sample measurements.

tofarray-like

Time-of-flight bins (1D array).

transarray-like

Transmission values. Shape: (n_groups, n_energy_bins)

errarray-like

Transmission uncertainties. Shape: (n_groups, n_energy_bins)

Lfloat

Flight path length in meters.

tstepfloat

Time step in seconds for TOF to energy conversion.

L0float, optional

Flight path scale factor. Default is 1.0.

t0float, optional

Time offset in seconds. Default is 0.0.

indiceslist, optional

List of group indices. Can be: - List of ints for 1D array: [0, 1, 2, …] - List of tuples for 2D grid: [(0,0), (0,1), (1,0), …] - List of strings for named groups: [‘sample1’, ‘sample2’, …] If not provided, will use sequential integers.

Data

A Data object with grouped data.

>>> # Create grouped data for 10 pixels with 100 energy bins each
>>> tof = np.arange(1, 101)
>>> trans_2d = np.random.rand(10, 100)
>>> err_2d = trans_2d * 0.05
>>> data = Data.from_grouped_arrays(tof, trans_2d, err_2d, L=10.0, tstep=1e-6)
classmethod from_transmission(filename)[source]

Creates a Data object directly from a transmission data file containing energy, transmission, and error values.

filenamestr

Path to the file containing the transmission data (energy, transmission, error) separated by whitespace.

Data

A Data object with the transmission data loaded into a dataframe.

plot(index=None, **kwargs)[source]

Plots the transmission data with error bars.

indexint, tuple, or str, optional

For grouped data, specify which group to plot: - int: 1D array index - tuple: (x, y) for 2D grid - str: named index If None and data is grouped, plots first group. If None and data is not grouped, plots the main table.

**kwargsdict, optional

Additional plotting parameters: - xlim : tuple, optional

Limits for the x-axis (default: (0.5e6, 1e7)).

  • ylim : tuple, optional Limits for the y-axis (default: (0., 1.)).

  • ecolor : str, optional Error bar color (default: “0.8”).

  • xlabel : str, optional Label for the x-axis (default: “Energy [eV]”).

  • ylabel : str, optional Label for the y-axis (default: “Transmission”).

  • logx : bool, optional Whether to plot the x-axis on a logarithmic scale (default: True).

matplotlib.Axes

The axes of the plot containing the transmission data.

plot_map(emin=500000.0, emax=20000000.0, emin2=None, emax2=None, logT=False, n_density=None, sigma=None, **kwargs)[source]

Plot transmission map averaged over energy range for grouped data.

eminfloat, optional

Minimum energy for averaging (default: 0.5e6 eV).

emaxfloat, optional

Maximum energy for averaging (default: 20e6 eV).

emin2float, optional

Minimum energy for second energy range. If provided with emax2, plots the ratio of transmissions: T(emin,emax) / T(emin2,emax2).

emax2float, optional

Maximum energy for second energy range.

logTbool, optional

If True, plots -ln(T)/(n*sigma) as thickness estimate in cm (default: False). Requires n_density and sigma parameters. According to Beer’s law T=exp(-n*sigma*d), this transformation gives an estimate of thickness d.

n_densityfloat, optional

Number density in atoms/cm^3 (required if logT=True).

sigmafloat, optional

Average cross-section in barns (required if logT=True).

**kwargsdict, optional

Additional plotting parameters: - cmap : str, optional

Colormap for 2D maps (default: ‘viridis’).

  • title : str, optional Plot title (default: auto-generated).

  • vmin, vmax : float, optional Color scale limits for 2D maps.

  • figsize : tuple, optional Figure size (width, height) in inches.

matplotlib.Axes

The axes of the plot.

ValueError

If called on non-grouped data, or if logT=True but n_density or sigma not provided.

>>> # For 2D grid data
>>> data = Data.from_grouped("pixel_x*_y*.csv", "ob_x*_y*.csv")
>>> data.plot_map(emin=1e6, emax=10e6)
>>> # For 1D array data
>>> data = Data.from_grouped("pixel_*.csv", "ob_*.csv")
>>> data.plot_map(emin=0.5e6, emax=5e6)
>>> # Plot thickness estimate
>>> data.plot_map(emin=1e6, emax=10e6, logT=True, n_density=8.5e22, sigma=10.0)
>>> # Plot transmission ratio
>>> data.plot_map(emin=1e6, emax=5e6, emin2=5e6, emax2=10e6)
rebin(n=None, tstep=None)[source]

Rebin the time-of-flight data by combining bins or using a new time step.

This method creates a new Data object with rebinned counts data, properly recalculated uncertainties, and updated transmission values. Works for both grouped and non-grouped data.

nint, optional

Number of original bins to combine into one new bin. E.g., n=2 combines every 2 bins, n=4 combines every 4 bins. Mutually exclusive with tstep.

tstepfloat, optional

New time step in seconds. Uses linear interpolation if the new bins don’t align with the original bins. Mutually exclusive with n.

linear_binsbool, optional

If True (default), creates linearly-spaced bins when using tstep parameter. If False, creates logarithmically-spaced bins in energy space, which is more appropriate for cross-section data that varies logarithmically with energy. Note: The cross-section C++ code assumes linear binning in time/energy, so use linear_bins=True for compatibility with the response function integration. Only affects tstep method, ignored for n method.

Data

A new Data object with rebinned data. All attributes (signal, openbeam, table, tgrid, etc.) are properly updated.

ValueError

If both n and tstep are provided, or if neither is provided. If the Data object doesn’t have original counts data (signal/openbeam). If called on non-grouped data created from transmission files.

>>> # Combine every 4 bins
>>> data_rebinned = data.rebin(n=4)
>>> # Use a new time step (2x the original)
>>> data_rebinned = data.rebin(tstep=2 * data.tstep)
>>> # Works with grouped data too
>>> grouped_data_rebinned = grouped_data.rebin(n=2)
  • Counts are summed in each new bin

  • Uncertainties are combined in quadrature: sqrt(sum(err^2))

  • Transmission and its error are recalculated from rebinned counts

  • Energy grid is recomputed from the new time-of-flight grid

  • For grouped data, rebinning is applied to all groups

  • NaN handling: Rows with NaN values in energy, transmission, or error columns are automatically removed before rebinning. This is safe because NaN values don’t contribute to fits. If all data is NaN, an empty table is returned for that group.

nres.utils

nres.utils.create_and_save_materials_cache()[source]
nres.utils.download_xsdata()[source]

Download the xsdata.npy file from GitHub and save it to the package directory.

nres.utils.elements_and_isotopes_dict()[source]

Generate a dictionary of elements and isotopes with details such as atoms per barn, total mass, and isotopic abundances.

Returns

A dictionary containing information for each element. isotopes (dict): A dictionary containing information for each isotope.

Return type

elements (dict)

nres.utils.energy2time(energy, flight_path_length)[source]

Convert energy to time-of-flight of the neutron.

Parameters: energy (float): Energy of the neutron in electronvolts (eV). flight_path_length (float): Flight path length in meters.

Returns: float: Time-of-flight in seconds.

nres.utils.format_isotope(isotope_string)[source]
nres.utils.get_cache_path()[source]
nres.utils.load_materials_data()[source]
nres.utils.load_or_create_materials_cache()[source]
nres.utils.materials_dict()[source]

Generate a dictionary containing information about materials, including their densities, atomic densities, chemical formulas, and elemental/isotopic compositions.

The function retrieves material data from the MaterialsCompendium package and organizes it into a dictionary. Each material’s total mass is calculated based on the atomic weights and weight fractions of its constituent elements. The mass of each element reflects its actual atomic mass, and the total mass is weighted by element fractions.

Returns

A dictionary containing information for each material.

Example structure: {

’MaterialName’: {

‘name’: ‘MaterialName’, ‘density’: <density>, # g/cm³ ‘n’: <atomic_density>, # atoms per barn ‘mass’: <total_mass>, # total mass (g/mol) ‘formula’: ‘ChemicalFormula’, ‘elements’: {

’ElementSymbol’: {

‘weight’: <weight_fraction>, ‘mass’: <element_atomic_mass>, # Actual atomic mass of the element (g/mol) ‘isotopes’: {

’IsotopeName’: <isotope_weight_fraction>, …

}

}

}

}

Return type

materials (dict)

nres.utils.register_material(name, components, fractions=None, fraction_type='atomic', density=None, formula=None)[source]

Register a new material with specified components and their fractions.

Parameters
  • name (str) – Name of the material

  • components (list or dict or any) – List of element/isotope names, dictionary of components and fractions, or material/element/isotope dict entries

  • fractions (list, optional) – Corresponding fractions for each component if components is a list

  • fraction_type (str, optional) – Type of fractions provided. Can be ‘atomic’ or ‘weight’. Defaults to ‘atomic’.

  • density (float, optional) – density of the new material [g/cm3]

  • formula (str, optional) – Custom chemical formula for the material

Returns

A material dictionary consistent with the materials database format

Return type

dict

Raises

ValueError – For invalid inputs or fraction-related inconsistencies

nres.utils.time2energy(time, flight_path_length)[source]

Convert time-of-flight to energy of the neutron.

Parameters: time (float): Time-of-flight in seconds. flight_path_length (float): Flight path length in meters.

Returns: float: Energy of the neutron in electronvolts (eV).