core.accessor
The primary xarray accessor namespace for the xmris package.
This module exposes the .xmr namespace to xarray DataArrays and Datasets.
It uses a “Hybrid Mixin” pattern: the user-facing API remains perfectly flat
for fluent method chaining (e.g., da.xmr.apodize_exp().xmr.fft()), while
the underlying developer API is strictly modularized into Mixin classes.
Classes¶
| Name | Description |
|---|---|
| XmrisAccessor | Main Accessor for xarray DataArrays to perform MRI and MRS operations. |
| XmrisDatasetAccessor | Accessor for xmris xr.Datasets (e.g., fitting results). |
| XmrisDatasetPlotAccessor | Sub-accessor for xmris xr.Datasets plotting functionalities. |
| XmrisFourierMixin | Mixin providing generalized N-dimensional Fourier transforms and shifts. |
| XmrisPhasingMixin | Mixin providing common MR spectra phasing tools. |
| XmrisPlotAccessor | Sub-accessor for xmris plotting functionalities (accessed via .xmr.plot). |
| XmrisProcessingMixin | Mixin providing common NMR/MRI Free Induction Decay processing tools. |
| XmrisSpectrumCoordsMixin | Mixin providing operations to translate physical coordinate systems. |
| XmrisWidgetAccessor | Sub-accessor for xmris interactive widget functionalities. |
XmrisAccessor¶
core.accessor.XmrisAccessor(xarray_obj)Main Accessor for xarray DataArrays to perform MRI and MRS operations.
This class is registered under the .xmr namespace. It inherits from
several domain-specific Mixins to provide a fluent, method-chaining API
(e.g., da.xmr.apodize_exp().xmr.to_spectrum().xmr.to_ppm()) without
creating an unmanageable monolithic class.
Attributes¶
| Name | Type | Description |
|---|---|---|
| _obj | xr.DataArray | The underlying xarray DataArray object being operated on. |
Methods¶
| Name | Description |
|---|---|
| fit_amares | Apply AMARES time-domain fitting to an N-dimensional FID. |
| remove_digital_filter | Remove the hardware digital filter group delay from Bruker FID data. |
| to_complex | Reconstruct a real-valued split array back into a standard complex array. |
| to_real_imag | Split a complex array into a real-valued array with an extra component dimension. |
fit_amares¶
core.accessor.XmrisAccessor.fit_amares(
prior_knowledge_file,
dim='time',
mhz=None,
sw=None,
deadtime=None,
method='leastsq',
initialize_with_lm=True,
num_workers=4,
init_fid=None,
**kwargs,
)Apply AMARES time-domain fitting to an N-dimensional FID.
This method wraps pyAMARES to perform parallelized batch fitting
across spatial or repetition dimensions. The numerical results and
the reconstructed time-domain fits are packed into an aligned xarray Dataset.
Requires the optional pyAMARES package to be installed.
Parameters¶
| Name | Type | Description | Default |
|---|---|---|---|
| prior_knowledge_file | str | Path | Path to the CSV or XLSX file containing the prior knowledge constraints. | required |
| dim | str | The time dimension along which to fit, by default “time”. | 'time' |
| mhz | float | Spectrometer frequency in MHz. If None, attempts to read from attrs[‘MHz’]. | None |
| sw | float | Spectral width in Hz. If None, attempts to calculate from dim coordinates. | None |
| deadtime | float | Time delay before the first point in seconds. If None, defaults to 0.0. | None |
| method | (leastsq, least_squares) | Fitting method. Defaults to ‘leastsq’ (Levenberg-Marquardt). | "leastsq" |
| initialize_with_lm | bool | Run an internal Levenberg-Marquardt initializer before fitting. Defaults to True. | True |
| num_workers | int | Number of parallel processes to spawn. Defaults to 4. | 4 |
| init_fid | np.ndarray | A 1D complex array to use as the template for pyAMARES initialization. If None, the function automatically selects the spectrum with the highest SNR. | None |
Returns¶
| Name | Type | Description |
|---|---|---|
| xr.Dataset | A dataset containing the original data, the fitted FIDs, the residuals, and the quantified parameters (amplitude, chem_shift, linewidth, phase, CRLB, SNR) mapped across the original dimensions and the new ‘Metabolite’ dimension. |
Raises¶
| Name | Type | Description |
|---|---|---|
| ImportError | If the pyAMARES package is not installed. |
remove_digital_filter¶
core.accessor.XmrisAccessor.remove_digital_filter(
group_delay,
dim='time',
keep_length=True,
)Remove the hardware digital filter group delay from Bruker FID data.
Bruker consoles use a cascade of digital FIR filters during analog-to-digital conversion. Because these filters calculate a moving average, they require time to “wake up”, introducing a causality delay at the start of the Free Induction Decay (FID). This manifests as a time-shift, effectively prepending the actual signal with a specific number of filter transient points.
Parameters¶
| Name | Type | Description | Default |
|---|---|---|---|
| group_delay | float | The exact delay value to remove. This should be read directly from the Bruker ACQ_RxFilterInfo parameter array. | required |
| dim | str | The time dimension along which to apply the correction, by default “time”. | 'time' |
| keep_length | bool | If True, appends pure zeros to the end of the FID to replace the truncated startup points, maintaining the original length. By default True. | True |
Returns¶
| Name | Type | Description |
|---|---|---|
| xr.DataArray | The corrected FID data with the filter transient stripped and phase aligned. |
to_complex¶
core.accessor.XmrisAccessor.to_complex(
dim=DIMS.component,
coords=('real', 'imag'),
)Reconstruct a real-valued split array back into a standard complex array.
to_real_imag¶
core.accessor.XmrisAccessor.to_real_imag(
dim=DIMS.component,
coords=('real', 'imag'),
)Split a complex array into a real-valued array with an extra component dimension.
XmrisDatasetAccessor¶
core.accessor.XmrisDatasetAccessor(xarray_obj)Accessor for xmris xr.Datasets (e.g., fitting results).
Attributes¶
| Name | Description |
|---|---|
plot | Access xmris plotting functionalities. |
XmrisDatasetPlotAccessor¶
core.accessor.XmrisDatasetPlotAccessor(obj)Sub-accessor for xmris xr.Datasets plotting functionalities.
Methods¶
| Name | Description |
|---|---|
| qc_grid | Plot a grid of spectra and fits to quickly visually inspect quality. |
| trajectory | Plot kinetic trajectories with CRLB shading. |
qc_grid¶
core.accessor.XmrisDatasetPlotAccessor.qc_grid(dim, config=None)Plot a grid of spectra and fits to quickly visually inspect quality.
trajectory¶
core.accessor.XmrisDatasetPlotAccessor.trajectory(
dim,
metabolites=None,
ax=None,
config=None,
)Plot kinetic trajectories with CRLB shading.
XmrisFourierMixin¶
core.accessor.XmrisFourierMixin()Mixin providing generalized N-dimensional Fourier transforms and shifts.
Methods¶
| Name | Description |
|---|---|
| fft | Perform a standard N-dimensional Fast Fourier Transform (no shifts). |
| fftc | Perform a centered N-dimensional FFT (ifftshift -> fft -> fftshift). |
| fftshift | Apply fftshift by rolling data and coordinates along specified dimensions. |
| ifft | Perform a standard N-dimensional Inverse FFT (no shifts). |
| ifftc | Perform a centered N-dimensional Inverse FFT (ifftshift -> ifft -> fftshift). |
| ifftshift | Apply ifftshift by rolling data and coordinates along specified dimensions. |
fft¶
core.accessor.XmrisFourierMixin.fft(dim=DIMS.time, out_dim=None)Perform a standard N-dimensional Fast Fourier Transform (no shifts).
Parameters¶
| Name | Type | Description | Default |
|---|---|---|---|
| dim | str or list of str | Dimension(s) to transform, by default DIMS.time. | DIMS.time |
| out_dim | str or list of str | Optional new dimension name(s), by default None. | None |
Returns¶
| Name | Type | Description |
|---|---|---|
| xr.DataArray | The transformed DataArray. |
fftc¶
core.accessor.XmrisFourierMixin.fftc(dim=DIMS.time, out_dim=None)Perform a centered N-dimensional FFT (ifftshift -> fft -> fftshift).
fftshift¶
core.accessor.XmrisFourierMixin.fftshift(dim)Apply fftshift by rolling data and coordinates along specified dimensions.
Moves the zero-frequency component to the center of the spectrum.
ifft¶
core.accessor.XmrisFourierMixin.ifft(dim=DIMS.frequency, out_dim=None)Perform a standard N-dimensional Inverse FFT (no shifts).
Parameters¶
| Name | Type | Description | Default |
|---|---|---|---|
| dim | str or list of str | Dimension(s) to transform, by default DIMS.frequency. | DIMS.frequency |
| out_dim | str or list of str | Optional new dimension name(s), by default None. | None |
Returns¶
| Name | Type | Description |
|---|---|---|
| xr.DataArray | The transformed DataArray. |
ifftc¶
core.accessor.XmrisFourierMixin.ifftc(dim=DIMS.frequency, out_dim=None)Perform a centered N-dimensional Inverse FFT (ifftshift -> ifft -> fftshift).
ifftshift¶
core.accessor.XmrisFourierMixin.ifftshift(dim)Apply ifftshift by rolling data and coordinates along specified dimensions.
The exact inverse of :meth:fftshift.
XmrisPhasingMixin¶
core.accessor.XmrisPhasingMixin()Mixin providing common MR spectra phasing tools.
Methods¶
| Name | Description |
|---|---|
| autophase | Automatically calculate and apply phase correction to a spectrum. |
| phase | Apply zero- and first-order phase correction to the spectrum. |
autophase¶
core.accessor.XmrisPhasingMixin.autophase(
dim=DIMS.frequency,
method='acme',
peak_width=100,
lb=0.0,
temp_time_dim=DIMS.time,
**kwargs,
)Automatically calculate and apply phase correction to a spectrum.
Parameters¶
| Name | Type | Description | Default |
|---|---|---|---|
| da | xr.DataArray | The input frequency-domain spectrum. | required |
| dim | str | The coordinate dimension to operate on, by default DIMS.frequency. | DIMS.frequency |
| method | (acme, peak_minima, positivity) | The scoring algorithm to use. “acme” relies on entropy and is best for multi-peak high SNR spectra. “positivity” and “peak_minima” are optimized for sparse/noisy spectra. By default “acme”. | "acme" |
| peak_width | float | Width of the ROI (in units of dim, e.g., Hz or ppm) for the local methods. Concentrates the solver on the region surrounding the target peak. By default 0.5. | 100 |
| target_coord | float | None | The explicit coordinate (e.g. 171.0 ppm) to target for local methods. If None, the coordinate of the maximum absolute magnitude is used. | required |
| p0_only | bool | If True, locks p1=0 and only optimizes the zero-order phase. Highly recommended for sparse spectra evaluated over a narrow peak_width. | required |
| lb | float | Optional exponential line broadening (in Hz). Can help smooth extreme noise for ACME, but usually unnecessary for local methods. By default 0.0. | 0.0 |
| temp_time_dim | str | The name used for the temporary time dimension if lb > 0. | DIMS.time |
| **kwargs | Additional keyword arguments passed to scipy.optimize.differential_evolution. | {} |
Returns¶
| Name | Type | Description |
|---|---|---|
| xr.DataArray | The phased spectrum. |
phase¶
core.accessor.XmrisPhasingMixin.phase(
dim=DIMS.frequency,
p0=0.0,
p1=0.0,
pivot=None,
)Apply zero- and first-order phase correction to the spectrum.
Parameters¶
| Name | Type | Description | Default |
|---|---|---|---|
| dim | str | The frequency dimension along which to apply phase correction, by default DIMS.frequency. | DIMS.frequency |
| p0 | float | Zero-order phase angle in degrees, by default 0.0. | 0.0 |
| p1 | float | First-order phase angle in degrees, by default 0.0. | 0.0 |
| pivot | float | The coordinate value (e.g., ppm or Hz) around which p1 is pivoted. If None, standard nmrglue index-0 pivoting is used. | None |
Returns¶
| Name | Type | Description |
|---|---|---|
| xr.DataArray | The phase-corrected spectrum with phase_p0 and phase_p1 stored in the attributes. |
XmrisPlotAccessor¶
core.accessor.XmrisPlotAccessor(obj)Sub-accessor for xmris plotting functionalities (accessed via .xmr.plot).
Methods¶
| Name | Description |
|---|---|
| heatmap | Generate a 2D heatmap plot of stacked 1D spectra. |
| ridge | Generate a ridge plot (2D waterfall) of stacked 1D spectra. |
heatmap¶
core.accessor.XmrisPlotAccessor.heatmap(
x_dim=None,
stack_dim=None,
ax=None,
config=None,
)Generate a 2D heatmap plot of stacked 1D spectra.
ridge¶
core.accessor.XmrisPlotAccessor.ridge(
x_dim=None,
stack_dim=None,
ax=None,
config=None,
)Generate a ridge plot (2D waterfall) of stacked 1D spectra.
XmrisProcessingMixin¶
core.accessor.XmrisProcessingMixin()Mixin providing common NMR/MRI Free Induction Decay processing tools.
Methods¶
| Name | Description |
|---|---|
| apodize_exp | Multiply the time-domain signal by a decreasing mono-exponential filter. |
| apodize_lg | Apply a Lorentzian-to-Gaussian transformation filter. |
| to_fid | Convert a frequency-domain spectrum to a time-domain FID. |
| to_spectrum | Convert a time-domain FID to a frequency-domain spectrum. |
| zero_fill | Pad the specified dimension with zero amplitude points. |
apodize_exp¶
core.accessor.XmrisProcessingMixin.apodize_exp(dim=DIMS.time, lb=1.0)Multiply the time-domain signal by a decreasing mono-exponential filter.
Parameters¶
| Name | Type | Description | Default |
|---|---|---|---|
| dim | str | The dimension corresponding to time, by default DIMS.time. | DIMS.time |
| lb | float | The desired line broadening factor in Hz, by default 1.0. | 1.0 |
Returns¶
| Name | Type | Description |
|---|---|---|
| xr.DataArray | A new apodized DataArray, preserving coordinates and attributes. |
apodize_lg¶
core.accessor.XmrisProcessingMixin.apodize_lg(dim=DIMS.time, lb=1.0, gb=1.0)Apply a Lorentzian-to-Gaussian transformation filter.
Parameters¶
| Name | Type | Description | Default |
|---|---|---|---|
| dim | str | The dimension corresponding to time, by default DIMS.time. | DIMS.time |
| lb | float | The Lorentzian line broadening to cancel in Hz, by default 1.0. | 1.0 |
| gb | float | The Gaussian line broadening to apply in Hz, by default 1.0. | 1.0 |
Returns¶
| Name | Type | Description |
|---|---|---|
| xr.DataArray | A new apodized DataArray, preserving coordinates and attributes. |
to_fid¶
core.accessor.XmrisProcessingMixin.to_fid(dim=DIMS.frequency, out_dim=DIMS.time)Convert a frequency-domain spectrum to a time-domain FID.
Parameters¶
| Name | Type | Description | Default |
|---|---|---|---|
| dim | str | The frequency dimension to transform, by default DIMS.frequency. | DIMS.frequency |
| out_dim | str | The name of the resulting time dimension, by default DIMS.time. | DIMS.time |
Returns¶
| Name | Type | Description |
|---|---|---|
| xr.DataArray | The un-shifted time-domain FID data. |
to_spectrum¶
core.accessor.XmrisProcessingMixin.to_spectrum(
dim=DIMS.time,
out_dim=DIMS.frequency,
)Convert a time-domain FID to a frequency-domain spectrum.
Parameters¶
| Name | Type | Description | Default |
|---|---|---|---|
| dim | str | The time dimension to transform, by default DIMS.time. | DIMS.time |
| out_dim | str | The name of the resulting frequency dimension, by default DIMS.frequency. | DIMS.frequency |
Returns¶
| Name | Type | Description |
|---|---|---|
| xr.DataArray | The centered frequency-domain spectrum. |
zero_fill¶
core.accessor.XmrisProcessingMixin.zero_fill(
dim=DIMS.time,
target_points=1024,
position='end',
)Pad the specified dimension with zero amplitude points.
Parameters¶
| Name | Type | Description | Default |
|---|---|---|---|
| dim | str | The dimension along which to pad zeros, by default DIMS.time. | DIMS.time |
| target_points | int | The total number of points desired after padding, by default 1024. | 1024 |
| position | (end, symmetric) | Where to apply the zeros. Use “end” for time-domain FIDs, and “symmetric” for spatial frequency domains like k-space. By default “end”. | "end" |
Returns¶
| Name | Type | Description |
|---|---|---|
| xr.DataArray | A new DataArray padded with zeros to the target length. |
XmrisSpectrumCoordsMixin¶
core.accessor.XmrisSpectrumCoordsMixin()Mixin providing operations to translate physical coordinate systems.
Methods¶
| Name | Description |
|---|---|
| to_hz | Convert absolute chemical shift axis [ppm] to relative frequency axis [Hz]. |
| to_ppm | Convert relative frequency axis [Hz] to absolute chemical shift axis [ppm]. |
to_hz¶
core.accessor.XmrisSpectrumCoordsMixin.to_hz(dim=DIMS.chemical_shift)Convert absolute chemical shift axis [ppm] to relative frequency axis [Hz].
to_ppm¶
core.accessor.XmrisSpectrumCoordsMixin.to_ppm(dim=DIMS.frequency)Convert relative frequency axis [Hz] to absolute chemical shift axis [ppm].
XmrisWidgetAccessor¶
core.accessor.XmrisWidgetAccessor(obj)Sub-accessor for xmris interactive widget functionalities.
This class provides a dedicated namespace for interactive UI components
powered by AnyWidget. It is accessed via the .xmr.widget attribute
on an xarray DataArray.
Methods¶
| Name | Description |
|---|---|
| phase_spectrum | Open an interactive zero- and first-order phase correction widget. |
| scroll_spectra | Open an interactive widget to scroll through a 2-D series of spectra. |
phase_spectrum¶
core.accessor.XmrisWidgetAccessor.phase_spectrum(
width=740,
height=400,
show_grid=True,
show_pivot=True,
**kwargs,
)Open an interactive zero- and first-order phase correction widget.
This method launches an AnyWidget-based user interface directly in the Jupyter Notebook. It allows for manual, real-time adjustment of the zero-order (p0) and first-order (p1) phase angles of a 1-D complex-valued NMR/MRS spectrum.
Parameters¶
| Name | Type | Description | Default |
|---|---|---|---|
| width | int | Width of the widget in pixels. Default is 740. | 740 |
| height | int | Height of the widget in pixels. Default is 400. | 400 |
| show_grid | bool | Toggle the background grid visibility. Default is True. | True |
| show_pivot | bool | Toggle the visibility of the p1 pivot indicator. Default is True. | True |
| **kwargs | Additional arguments passed to the underlying PhaseWidget. | {} |
Returns¶
| Name | Type | Description |
|---|---|---|
| PhaseWidget | The interactive widget instance. Assigning this to a variable allows you to programmatically extract the optimized phase angles after interacting with the UI. |
Raises¶
| Name | Type | Description |
|---|---|---|
| ValueError | If the underlying DataArray is not 1-dimensional or does not contain complex-valued data. |
Notes¶
Zero-order phase (p0): Adjusts the phase uniformly across the spectrum.
First-order phase (p1): Adjusts phase linearly relative to a pivot point.
The pivot point (p_pivot) is automatically set to the coordinate corresponding to the maximum magnitude peak.
scroll_spectra¶
core.accessor.XmrisWidgetAccessor.scroll_spectra(
scroll_axis=None,
part='real',
xlim=None,
ylim=None,
show_trace=True,
trace_count=10,
width=740,
height=400,
**kwargs,
)Open an interactive widget to scroll through a 2-D series of spectra.
This method launches a user interface for exploring multi-dimensional
spectroscopy data (e.g., transient repetitions, averages). It includes
a timeline scrubber, animation playback, and fading historical traces.
Clicking “Extract Slice” provides a copyable .isel(...) code snippet
to isolate the current view while preserving pipeline lineage.
Parameters¶
| Name | Type | Description | Default |
|---|---|---|---|
| scroll_axis | str | The specific dimension to scroll through. If None, it attempts to auto-detect ‘repetitions’ or ‘averages’, or falls back to the non-spectral dimension. | None |
| part | (real, imag, abs) | Which mathematical component of complex data to display. Default is ‘real’. | 'real' |
| xlim | tuple of float | Static (min, max) bounds for the spectral axis. | None |
| ylim | tuple of float | Static (min, max) bounds for intensity. If None, auto-ranges to the global minimum and maximum of the dataset. | None |
| show_trace | bool | Show fading historical traces behind the current scan. Default is True. | True |
| trace_count | int | The number of historical traces to overlay. Default is 10. | 10 |
| width | int | Width of the widget in pixels. Default is 740. | 740 |
| height | int | Height of the widget in pixels. Default is 400. | 400 |
| **kwargs | Additional arguments passed to the underlying ScrollWidget. | {} |
Returns¶
| Name | Type | Description |
|---|---|---|
| ScrollWidget | The interactive widget instance. |
Raises¶
| Name | Type | Description |
|---|---|---|
| ValueError | If the input DataArray is not exactly 2-dimensional. |