Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

core.accessor

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

NameDescription
XmrisAccessorMain Accessor for xarray DataArrays to perform MRI and MRS operations.
XmrisDatasetAccessorAccessor for xmris xr.Datasets (e.g., fitting results).
XmrisDatasetPlotAccessorSub-accessor for xmris xr.Datasets plotting functionalities.
XmrisFourierMixinMixin providing generalized N-dimensional Fourier transforms and shifts.
XmrisPhasingMixinMixin providing common MR spectra phasing tools.
XmrisPlotAccessorSub-accessor for xmris plotting functionalities (accessed via .xmr.plot).
XmrisProcessingMixinMixin providing common NMR/MRI Free Induction Decay processing tools.
XmrisSpectrumCoordsMixinMixin providing operations to translate physical coordinate systems.
XmrisWidgetAccessorSub-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

NameTypeDescription
_objxr.DataArrayThe underlying xarray DataArray object being operated on.

Methods

NameDescription
fit_amaresApply AMARES time-domain fitting to an N-dimensional FID.
remove_digital_filterRemove the hardware digital filter group delay from Bruker FID data.
to_complexReconstruct a real-valued split array back into a standard complex array.
to_real_imagSplit 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
NameTypeDescriptionDefault
prior_knowledge_filestr | PathPath to the CSV or XLSX file containing the prior knowledge constraints.required
dimstrThe time dimension along which to fit, by default “time”.'time'
mhzfloatSpectrometer frequency in MHz. If None, attempts to read from attrs[‘MHz’].None
swfloatSpectral width in Hz. If None, attempts to calculate from dim coordinates.None
deadtimefloatTime 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_lmboolRun an internal Levenberg-Marquardt initializer before fitting. Defaults to True.True
num_workersintNumber of parallel processes to spawn. Defaults to 4.4
init_fidnp.ndarrayA 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
NameTypeDescription
xr.DatasetA 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
NameTypeDescription
ImportErrorIf 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
NameTypeDescriptionDefault
group_delayfloatThe exact delay value to remove. This should be read directly from the Bruker ACQ_RxFilterInfo parameter array.required
dimstrThe time dimension along which to apply the correction, by default “time”.'time'
keep_lengthboolIf 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
NameTypeDescription
xr.DataArrayThe 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

NameDescription
plotAccess xmris plotting functionalities.

XmrisDatasetPlotAccessor

core.accessor.XmrisDatasetPlotAccessor(obj)

Sub-accessor for xmris xr.Datasets plotting functionalities.

Methods

NameDescription
qc_gridPlot a grid of spectra and fits to quickly visually inspect quality.
trajectoryPlot 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

NameDescription
fftPerform a standard N-dimensional Fast Fourier Transform (no shifts).
fftcPerform a centered N-dimensional FFT (ifftshift -> fft -> fftshift).
fftshiftApply fftshift by rolling data and coordinates along specified dimensions.
ifftPerform a standard N-dimensional Inverse FFT (no shifts).
ifftcPerform a centered N-dimensional Inverse FFT (ifftshift -> ifft -> fftshift).
ifftshiftApply 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
NameTypeDescriptionDefault
dimstr or list of strDimension(s) to transform, by default DIMS.time.DIMS.time
out_dimstr or list of strOptional new dimension name(s), by default None.None
Returns
NameTypeDescription
xr.DataArrayThe 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
NameTypeDescriptionDefault
dimstr or list of strDimension(s) to transform, by default DIMS.frequency.DIMS.frequency
out_dimstr or list of strOptional new dimension name(s), by default None.None
Returns
NameTypeDescription
xr.DataArrayThe 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

NameDescription
autophaseAutomatically calculate and apply phase correction to a spectrum.
phaseApply 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
NameTypeDescriptionDefault
daxr.DataArrayThe input frequency-domain spectrum.required
dimstrThe 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_widthfloatWidth 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_coordfloat | NoneThe 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_onlyboolIf True, locks p1=0 and only optimizes the zero-order phase. Highly recommended for sparse spectra evaluated over a narrow peak_width.required
lbfloatOptional 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_dimstrThe name used for the temporary time dimension if lb > 0.DIMS.time
**kwargsAdditional keyword arguments passed to scipy.optimize.differential_evolution.{}
Returns
NameTypeDescription
xr.DataArrayThe 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
NameTypeDescriptionDefault
dimstrThe frequency dimension along which to apply phase correction, by default DIMS.frequency.DIMS.frequency
p0floatZero-order phase angle in degrees, by default 0.0.0.0
p1floatFirst-order phase angle in degrees, by default 0.0.0.0
pivotfloatThe coordinate value (e.g., ppm or Hz) around which p1 is pivoted. If None, standard nmrglue index-0 pivoting is used.None
Returns
NameTypeDescription
xr.DataArrayThe 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

NameDescription
heatmapGenerate a 2D heatmap plot of stacked 1D spectra.
ridgeGenerate 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

NameDescription
apodize_expMultiply the time-domain signal by a decreasing mono-exponential filter.
apodize_lgApply a Lorentzian-to-Gaussian transformation filter.
to_fidConvert a frequency-domain spectrum to a time-domain FID.
to_spectrumConvert a time-domain FID to a frequency-domain spectrum.
zero_fillPad 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
NameTypeDescriptionDefault
dimstrThe dimension corresponding to time, by default DIMS.time.DIMS.time
lbfloatThe desired line broadening factor in Hz, by default 1.0.1.0
Returns
NameTypeDescription
xr.DataArrayA 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
NameTypeDescriptionDefault
dimstrThe dimension corresponding to time, by default DIMS.time.DIMS.time
lbfloatThe Lorentzian line broadening to cancel in Hz, by default 1.0.1.0
gbfloatThe Gaussian line broadening to apply in Hz, by default 1.0.1.0
Returns
NameTypeDescription
xr.DataArrayA 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
NameTypeDescriptionDefault
dimstrThe frequency dimension to transform, by default DIMS.frequency.DIMS.frequency
out_dimstrThe name of the resulting time dimension, by default DIMS.time.DIMS.time
Returns
NameTypeDescription
xr.DataArrayThe 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
NameTypeDescriptionDefault
dimstrThe time dimension to transform, by default DIMS.time.DIMS.time
out_dimstrThe name of the resulting frequency dimension, by default DIMS.frequency.DIMS.frequency
Returns
NameTypeDescription
xr.DataArrayThe 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
NameTypeDescriptionDefault
dimstrThe dimension along which to pad zeros, by default DIMS.time.DIMS.time
target_pointsintThe 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
NameTypeDescription
xr.DataArrayA new DataArray padded with zeros to the target length.

XmrisSpectrumCoordsMixin

core.accessor.XmrisSpectrumCoordsMixin()

Mixin providing operations to translate physical coordinate systems.

Methods

NameDescription
to_hzConvert absolute chemical shift axis [ppm] to relative frequency axis [Hz].
to_ppmConvert 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

NameDescription
phase_spectrumOpen an interactive zero- and first-order phase correction widget.
scroll_spectraOpen 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
NameTypeDescriptionDefault
widthintWidth of the widget in pixels. Default is 740.740
heightintHeight of the widget in pixels. Default is 400.400
show_gridboolToggle the background grid visibility. Default is True.True
show_pivotboolToggle the visibility of the p1 pivot indicator. Default is True.True
**kwargsAdditional arguments passed to the underlying PhaseWidget.{}
Returns
NameTypeDescription
PhaseWidgetThe interactive widget instance. Assigning this to a variable allows you to programmatically extract the optimized phase angles after interacting with the UI.
Raises
NameTypeDescription
ValueErrorIf the underlying DataArray is not 1-dimensional or does not contain complex-valued data.
Notes
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
NameTypeDescriptionDefault
scroll_axisstrThe 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'
xlimtuple of floatStatic (min, max) bounds for the spectral axis.None
ylimtuple of floatStatic (min, max) bounds for intensity. If None, auto-ranges to the global minimum and maximum of the dataset.None
show_traceboolShow fading historical traces behind the current scan. Default is True.True
trace_countintThe number of historical traces to overlay. Default is 10.10
widthintWidth of the widget in pixels. Default is 740.740
heightintHeight of the widget in pixels. Default is 400.400
**kwargsAdditional arguments passed to the underlying ScrollWidget.{}
Returns
NameTypeDescription
ScrollWidgetThe interactive widget instance.
Raises
NameTypeDescription
ValueErrorIf the input DataArray is not exactly 2-dimensional.