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
estimate_group_delayMeasure the true digital-filter group delay by minimizing residual phase.
fit_amaresApply AMARES time-domain fitting to an N-dimensional signal.
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.
estimate_group_delay
core.accessor.XmrisAccessor.estimate_group_delay(
    dim=DIMS.time,
    *,
    search_range=None,
    header_hint=None,
    window=16.0,
    metric='acme',
    refine=True,
    return_profile=False,
)

Measure the true digital-filter group delay by minimizing residual phase.

The vendor header value (Bruker ACQ_RxFilterInfo/GRPDLY) can under-count the real receiver digital-filter group delay for some ParaVision/probe combinations, leaving a residual first-order phase error after :meth:remove_digital_filter. This finds the delay that removes that residual by locating the value that makes the spectrum maximally absorptive under a single global zero-order phase (argmax(|FID|) is deliberately not used — it lands on the filter’s ringing).

Parameters
NameTypeDescriptionDefault
dimstrThe time dimension, by default DIMS.time.DIMS.time
search_rangetuple of floatExplicit (low, high) delay bounds (samples). If None (default), the window is anchored on the header: header ± window.None
header_hintfloatVendor-reported delay to anchor the search on. If None, falls back to the stored group_delay attribute, then to a broad default range.None
windowfloatHalf-width (samples) of the header-anchored search window, by default 16.0.16.0
metric(acme, coherence)Residual-phase cost, by default "acme" (whole-spectrum, alias-robust)."acme"
refineboolIf True (default), refine the best integer delay to sub-sample precision.True
return_profileboolIf True, also return the cost-vs-delay profile for diagnosing multimodality.False
Returns
NameTypeDescription
float or tuple[float, xr.DataArray]The measured group delay in samples, or (delay, profile) when return_profile=True.
fit_amares
core.accessor.XmrisAccessor.fit_amares(
    prior_knowledge,
    dim=DIMS.time,
    mhz=None,
    sw=None,
    deadtime=None,
    carrier=None,
    g_global=0.0,
    method='least_squares',
    initialize_with_lm=False,
    num_workers=1,
    init_fid=None,
    verbose=False,
)

Apply AMARES time-domain fitting to an N-dimensional signal.

Thin wrapper around the :func:xmris.fit_amares free function — see it for the full parameter reference, the domain-preserving contract (a complex spectrum is round-tripped through the FID and the fit returned in the representation you passed in, ppm in -> ppm out), and the robustness behavior (a single global magnitude normalization so the optimizer’s tolerance holds at any signal scale, and a NaN sentinel for a fit that fails).

Requires the optional pyAMARES package (pip install 'xmris[fitting]').

Returns
NameTypeDescription
xr.DatasetThe original data, the fitted model, the residuals, and the quantified parameters (amplitude, chem_shift, linewidth, phase, CRLB, SNR) mapped across the original dimensions and the new metabolite dimension.
See Also

xmris.fit_amares : The free function this delegates to, fully documented.

Raises
NameTypeDescription
ImportErrorIf the optional pyAMARES package is not installed.
remove_digital_filter
core.accessor.XmrisAccessor.remove_digital_filter(
    group_delay='header',
    dim=DIMS.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_delayfloat or {header, measure}The delay (in samples) to remove. By default "header", which reads the vendor-reported value from .attrs (written by the Bruker loader). Pass a float to force a value, or "measure" to estimate it from the data via :meth:estimate_group_delay — robust when the header under-counts the true delay.'header'
dimstrThe time dimension along which to apply the correction, by default DIMS.time.DIMS.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=None,
    method='acme',
    peak_width=0.5,
    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
dimstr or NoneThe spectral dimension to operate on. If None (default) it is resolved automatically to the spectral dim present (Hz or ppm); time-domain input is transformed to a spectrum first.None
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.0.5
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
carpetGenerate a 2D carpet plot of stacked 1D spectra.
waterfallGenerate a ridge plot (2D waterfall) of stacked 1D spectra.
carpet
core.accessor.XmrisPlotAccessor.carpet(
    x_dim=None,
    stack_dim=None,
    ax=None,
    config=None,
)

Generate a 2D carpet plot of stacked 1D spectra.

waterfall
core.accessor.XmrisPlotAccessor.waterfall(
    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.
baseline_alsApply Asymmetric Least Squares (AsLS) baseline correction to a spectrum.
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.
baseline_als
core.accessor.XmrisProcessingMixin.baseline_als(
    dim=None,
    lam=100000.0,
    p=0.001,
    n_iter=10,
)

Apply Asymmetric Least Squares (AsLS) baseline correction to a spectrum.

This method automatically estimates and subtracts a smooth baseline without requiring user-defined signal-free regions. It operates strictly on the real (absorption) component of the data.

.. warning:: Real-Valued Output Only: This function discards the imaginary (dispersion) component of the data. AsLS relies on the asymmetry of absorption-mode peaks and cannot be applied to complex data without breaking Kramers-Kronig relations. The resulting real-valued spectrum cannot be inverse-Fourier transformed back to the time domain.

Parameters
NameTypeDescriptionDefault
dimstr or NoneThe spectral dimension along which to apply correction. If None (default) it is resolved automatically to the spectral dim present (Hz or ppm); time-domain input is transformed to a spectrum first.None
lamfloatThe smoothness penalty (λ\lambda). Higher values result in a stiffer, flatter baseline. Typical NMR ranges are 10,000 to 10,000,000. Defaults to 100,000.100000.0
pfloatThe asymmetry parameter. Controls how aggressively positive peaks are ignored during the fit. Typical ranges are 0.001 to 0.05. Defaults to 0.001.0.001
n_iterintMaximum number of iterations for the sparse solver. Defaults to 10.10
Returns
NameTypeDescription
xr.DataArrayThe strictly real-valued, baseline-corrected spectrum.
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
apodizeOpen an interactive widget for NMR/MRS spectrum apodization.
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.
apodize
core.accessor.XmrisWidgetAccessor.apodize(
    dim=None,
    unit='ppm',
    width=740,
    height=550,
    lb_range=(0.0, 50.0),
    gb_range=(0.0, 50.0),
    **kwargs,
)

Open an interactive widget for NMR/MRS spectrum apodization.

This method launches an AnyWidget-based user interface to interactively apply and visualize line broadening (exponential) or resolution enhancement (Lorentz-to-Gauss) filters. It displays the modified time-domain FID alongside the resulting frequency-domain spectrum in real-time.

Parameters
NameTypeDescriptionDefault
dimstrThe time dimension to apply the filter along. If None, it will be auto-detected by the underlying function.None
unit(ppm, hz)The unit for the spectral x-axis display. Default is ‘ppm’.'ppm'
widthintWidth of the widget in pixels. Default is 740.740
heightintHeight of the widget in pixels. Default is 550.550
lb_rangetuple of floatThe (min, max) range for the Line Broadening slider. Default is (0.0, 50.0).(0.0, 50.0)
gb_rangetuple of floatThe (min, max) range for the Gaussian Broadening slider. Default is (0.0, 50.0).(0.0, 50.0)
**kwargsAdditional arguments passed to the underlying ApodizerWidget.{}
Returns
NameTypeDescription
ApodizerWidgetThe interactive widget instance. Closing the widget UI generates a copyable code snippet to apply the finalized filter parameters programmatically.
Raises
NameTypeDescription
ValueErrorIf the underlying DataArray is not 1-dimensional.
Notes
phase_spectrum
core.accessor.XmrisWidgetAccessor.phase_spectrum(
    dim=None,
    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
dimstrSpectral dimension to plot along. If None (default), the canonical spectral dimension (frequency or chemical_shift) is auto-detected; pass it explicitly for non-standard axis names.None
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,
    dim=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 dimension to scroll through. If None, it is derived as the non-spectral dimension of the 2-D array.None
dimstrThe spectral (display) dimension. If None, the canonical spectral dimension (frequency or chemical_shift) is auto-detected; pass it explicitly for non-standard axis names.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.