Models Module

class nres.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.