Data Module
- class nres.Data(**kwargs)[source]
Bases:
objectA 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.