Skip to content

Spectrum2D #

Spectrum2D(
    f1: FloatArray | None = None,
    f2: FloatArray | None = None,
    amplitudes: ndarray | None = None,
    f1_unit: FrequencyUnit = HERTZ,
    f2_unit: FrequencyUnit = HERTZ,
    metadata: dict[str, Any] | None = None,
    reference_spectrum_f1: Spectrum1D
    | SpectrumNd
    | None = None,
    reference_spectrum_f2: Spectrum1D
    | SpectrumNd
    | None = None,
    f1_reference_frequency_hz: float | None = None,
    f2_reference_frequency_hz: float | None = None,
)

2D frequency-domain spectrum for NMR experiments (e.g., COSY, HSQC).

Attributes:

Name Type Description
f1, f2

FloatArray (np.ndarray[float64]) - frequency axes

amplitudes ndarray

np.ndarray[complex] with shape (len(f1), len(f2))

f1_unit, f2_unit

FrequencyUnit

f1_reference_frequency_hz, f2_reference_frequency_hz

Reference frequencies for PPM conversion

processing_history class-attribute instance-attribute #

processing_history: ProcessingHistory | None = (
    betterproto2.field(
        8, betterproto2.TYPE_MESSAGE, optional=True
    )
)

Processing history - read-only audit log of all operations applied to this spectrum

history property #

history: Sequence[ProcessingHistoryEntry]

Read-only access to processing history entries.

Returns:

Type Description
Sequence[ProcessingHistoryEntry]

Immutable sequence of history entries. Returns empty tuple if

Sequence[ProcessingHistoryEntry]

no history has been recorded yet.

metadata instance-attribute #

metadata: dict[str, str]

amplitudes property writable #

amplitudes: ndarray

reference_frequency_hz instance-attribute #

reference_frequency_hz: float | None

nucleus_f1 property writable #

nucleus_f1: Nucleus

Nucleus type for the F1 (indirect) axis.

nucleus_f2 property writable #

nucleus_f2: Nucleus

Nucleus type for the F2 (direct) axis.

is_diagonal_symmetrized property #

is_diagonal_symmetrized: bool

Whether :meth:symmetrize_diagonal has already been applied.

is_covariance_derived property #

is_covariance_derived: bool

Whether this plane came out of a covariance transform rather than an acquisition.

is_jres property #

is_jres: bool

Whether this plane is a J-resolved experiment (detected, never configured).

is_jres_tilted property #

is_jres_tilted: bool

Whether :meth:tilt_jres has already sheared this plane.

real property #

real: Self

imag property #

imag: Self

abs property #

abs: Self

raw_amplitudes property writable #

raw_amplitudes: bool

Whether the amplitudes are unprocessed vendor data, stored without any rounding.

Set by importers; kept by copy(); cleared by any write to the amplitudes. Unset, it follows the stored array (true when it was written losslessly). Integer values are stored exactly either way; this decides whether other values beyond float32 stay exact.

raw_scale property writable #

raw_scale: float | None

The factor the file's integers were multiplied by to give the raw amplitudes, if any.

Lets raw data a file declares as scaled integers (JCAMP-DX FACTOR) be stored as those integers; only used while raw_amplitudes holds.

points_f1 property writable #

points_f1: FloatNdArray

points_f2 property writable #

points_f2: FloatNdArray

visualization_handler property writable #

visualization_handler: str

Plugin visualization handler ID (e.g., 'nanalysis:cosy_2d').

x property writable #

x_units property writable #

x_units: FrequencyUnit

y property writable #

y_units property writable #

y_units: FrequencyUnit

role_f1 property writable #

role_f1: AxisRole

Physical role of the F1 (indirect) axis.

role_f2 property writable #

role_f2: AxisRole

Physical role of the F2 (direct) axis.

z property writable #

f1_unit property writable #

f1_unit: FrequencyUnit

Frequency unit for first dimension (F1/indirect).

f2_unit property writable #

f2_unit: FrequencyUnit

Frequency unit for second dimension (F2/direct).

f1_reference_frequency_hz property writable #

f1_reference_frequency_hz: float | None

Reference frequency for F1 dimension (for PPM conversion).

f2_reference_frequency_hz property writable #

f2_reference_frequency_hz: float | None

Reference frequency for F2 dimension (for PPM conversion).

reference_spectrum_f1 instance-attribute #

reference_spectrum_f1 = _reference_spectrum(
    reference_spectrum_f1
)

reference_spectrum_f2 instance-attribute #

reference_spectrum_f2 = _reference_spectrum(
    reference_spectrum_f2
)

f1 property writable #

Frequency coordinates for first dimension.

f2 property writable #

Frequency coordinates for second dimension.

f1_is_frequency property #

f1_is_frequency: bool

Whether F1 holds frequencies, not a parameter (delay, gradient) or times.

f2_is_frequency property #

f2_is_frequency: bool

Whether F2 holds frequencies, not a parameter (delay, gradient) or times.

shape property #

shape: tuple[int, int]

is_complex property #

is_complex: bool

Whether the spectrum has complex amplitudes.

f2_imaginary property writable #

f2_imaginary: ndarray | None

The F2-dispersion quadrant RI + i*II, or None for non-hypercomplex data.

This is a processing intermediate: it does not survive serialization, so it is only available while the spectrum stays in the process that produced it.

f1_acquisition_mode property #

f1_acquisition_mode: F1AcquisitionMode

How the indirect dimension was quadrature-detected.

Read from the metadata the transform stamps; "undefined" when the spectrum did not come from a 2D transform that knew the mode.

is_hypercomplex property #

is_hypercomplex: bool

Whether the F2-dispersion quadrant is available for an F2 phase correction.

True only for a spectrum produced in this process; a spectrum received over gRPC reports False since the quadrant is not carried over the wire.

is_f1_phase_sensitive property #

is_f1_phase_sensitive: bool

Whether an F1 phase correction can do anything to this spectrum.

True only for a phase-sensitive F1 acquisition scheme (States, States-TPPI, Echo-Antiecho or TPPI); a complex amplitudes array alone is not sufficient evidence.

is_f2_phase_sensitive property #

is_f2_phase_sensitive: bool

Whether an F2 phase correction can do anything to this spectrum.

True whenever there is an imaginary channel to rotate into: either the ordinary complex amplitudes, or the F2-dispersion quadrant.

absorb_creation #

absorb_creation(
    operation: str,
    parameters: dict[str, str],
    shape_before: tuple[int, ...],
    shape_after: tuple[int, ...],
) -> bool

Record the operation that produced this object AS its creation.

A transform returning a NEW object otherwise writes two entries on it in the same millisecond: the bare construction, then the operation. They are one event -- the object was created BY that operation -- and two rows for it read as the transform having run twice. The operation replaces the construction record and keeps its parameters, so the entry still says how big the object came out while naming what made it.

Only an object whose history is still just its creation is rewritten; anything already operated on has a real past that must not move.

Parameters:

Name Type Description Default
operation str

Name of the operation that produced this object.

required
parameters dict[str, str]

That operation's parameters; the creation's are kept too.

required
shape_before tuple[int, ...]

Shape the operation started from.

required
shape_after tuple[int, ...]

Shape of the produced object.

required

Returns:

Type Description
bool

True when the creation record was rewritten, False when the caller

bool

should append an entry of its own.

smooth #

smooth(
    sigma: float = 2.0,
    *,
    method: Literal[
        "gaussian", "savitzky_golay"
    ] = "gaussian",
    window_points: int = 11,
    poly_order: int = 3,
) -> Self

Apply smoothing to the 2D spectrum.

Parameters:

Name Type Description Default
sigma float

Gaussian width, in samples. Ignored by savitzky_golay.

2.0
method Literal['gaussian', 'savitzky_golay']

gaussian or savitzky_golay, applied along each axis in turn.

'gaussian'
window_points int

Savitzky-Golay window in samples; odd and above poly_order.

11
poly_order int

Savitzky-Golay polynomial order.

3

Returns:

Type Description
Self

Self

Raises:

Type Description
ProcessingParameterError

When a Savitzky-Golay window is even, not above the order, or longer than an axis.

suppress_region #

suppress_region(
    center: float,
    width: float,
    method: SuppressionMethod = SUPPRESS_INTERPOLATE,
    axis: Axis = "f2",
    center_f1: float | None = None,
    width_f1: float | None = None,
) -> Self

Suppress a band of every row (F2), of every column (F1), or both, in place.

Each row or column is treated exactly as Spectrum1D.suppress_region treats a 1D spectrum.

Parameters:

Name Type Description Default
center float

Centre of the F2 band, in the F2 axis unit.

required
width float

Full width of the F2 band, in the F2 axis unit.

required
method SuppressionMethod

Zero, interpolate across the edges, or fill with a fitted polynomial.

SUPPRESS_INTERPOLATE
axis Axis

Which band to suppress.

'f2'
center_f1 float | None

Centre of the F1 band, in the F1 axis unit; required for f1 and both.

None
width_f1 float | None

Full width of the F1 band; required for f1 and both.

None

Returns:

Type Description
Self

Self for method chaining.

Raises:

Type Description
ProcessingParameterError

When an F1 band is asked for without its centre and width.

ValueError

When a band lies outside its axis.

suppress_diagonal #

suppress_diagonal(
    width: float,
    method: SuppressionMethod = SUPPRESS_INTERPOLATE,
) -> Self

Suppress the band along the F1 = F2 diagonal of a homonuclear plane, in place.

Parameters:

Name Type Description Default
width float

Full width of the band about the diagonal, in the axis unit.

required
method SuppressionMethod

How the band is filled, as for suppress_region.

SUPPRESS_INTERPOLATE

Returns:

Type Description
Self

Self for method chaining.

Raises:

Type Description
ProcessingParameterError

On a heteronuclear plane, one with unknown nuclei, or axes in different units.

reference_to_ppm #

reference_to_ppm(
    target_f2_ppm: float | None,
    target_f1_ppm: float | None = None,
    search_window_f2_ppm: float = 0.5,
    search_window_f1_ppm: float = 0.5,
) -> Self

Shift the axes so the tallest peak near a target lies on it.

The peak is the largest magnitude inside the box of the two search windows about the target. An axis with no target is left alone; at least one target is needed.

Parameters:

Name Type Description Default
target_f2_ppm float | None

Where the peak should lie on F2, or None to shift F1 only.

required
target_f1_ppm float | None

Where it should lie on F1, or None to shift F2 only.

None
search_window_f2_ppm float

Half-width of the box on F2.

0.5
search_window_f1_ppm float

Half-width of the box on F1.

0.5

Returns:

Type Description
Self

Self with shifted axes.

Raises:

Type Description
ValueError

When no target is given, the box holds no data, or an axis cannot be put in ppm.

align_by_correlation #

align_by_correlation(reference: RegionMixin2D) -> Self

Align to a reference plane by the lag that maximises the correlation of the magnitudes.

Parameters:

Name Type Description Default
reference RegionMixin2D

Plane on the same grid, which is not modified.

required

Returns:

Type Description
Self

Self with shifted axes.

Raises:

Type Description
ValueError

When the planes differ in shape.

symmetrize_diagonal #

symmetrize_diagonal(
    method: Literal["min", "average"] = "min",
    magnitude: bool | None = None,
) -> Self

Symmetrise a homonuclear plane about the F1 = F2 diagonal.

The result is real-valued: phase does not survive, because a point and its mirror partner have none in common.

Parameters:

Name Type Description Default
method Literal['min', 'average']

"min" (the artefact-suppressing choice) or "average".

'min'
magnitude bool | None

Work on magnitudes rather than the signed real part. Unset follows the plane's F1 acquisition mode.

None

Returns:

Type Description
Self

Self, for chaining. Applying twice is a no-op.

Raises:

Type Description
ProcessingParameterError

On a heteronuclear or unlabelled plane.

suppress_t1_noise #

suppress_t1_noise(
    threshold: float = DEFAULT_T1_NOISE_THRESHOLD,
    strength: float = 1.0,
    magnitude: bool | None = None,
) -> Self

Suppress t1-noise streaks running along F1.

The result is real-valued on a magnitude-mode plane.

Parameters:

Name Type Description Default
threshold float

Noise-sigma multiple above which a column is called streaky.

DEFAULT_T1_NOISE_THRESHOLD
strength float

Fraction of the estimated streak removed, 0 to 1.

1.0
magnitude bool | None

Work on magnitudes rather than the signed real part. Unset follows the plane's F1 acquisition mode.

None

Returns:

Type Description
Self

Self, for chaining.

covariance #

covariance(
    mode: Literal["direct", "indirect"] = "direct",
    square_root: bool = True,
    magnitude: bool | None = None,
) -> Self

Build the covariance map of this plane as a new spectrum.

The result is a correlation map, not a measured spectrum: it is returned as a separate object, stamped in metadata, and never written back over the parent.

Parameters:

Name Type Description Default
mode Literal['direct', 'indirect']

"direct" (F1 gains F2's resolution) or "indirect" (the heteronuclear X-X correlation).

'direct'
square_root bool

Take the matrix square root of the covariance.

True
magnitude bool | None

Work on magnitudes rather than the signed real part. Unset follows the plane's F1 acquisition mode.

None

Returns:

Type Description
Self

A new spectrum, square in the retained axis.

Raises:

Type Description
ProcessingParameterError

When the matrix would be too large, or the contracted axis too short.

detect_jres #

detect_jres() -> JresDetection

Measure whether this plane's multiplets lie on a shearable line.

tilt_jres #

tilt_jres(force: bool = False) -> Self

Shear the plane so multiplets become vertical.

A plane whose peaks do not lie on a shearable line, and a plane already tilted, are returned untouched.

Parameters:

Name Type Description Default
force bool

Shear on the measured slope even when the alignment is too weak to pass detection. A plane with no measurable slope at all is still left alone.

False

Returns:

Type Description
Self

Self, for chaining.

symmetrize_f1 #

symmetrize_f1() -> Self

Symmetrise the plane about F1 = 0, suppressing asymmetric artefacts.

A no-op on an F1 axis with fewer than two points or a zero increment.

Returns:

Type Description
Self

Self, for chaining.

skyline_projection_f2 #

skyline_projection_f2() -> Spectrum1D

Maximum-magnitude projection onto F2 — a decoupled 1D spectrum once tilted.

Returns:

Type Description
Spectrum1D

A real-valued :class:Spectrum1D on this spectrum's F2 axis.

process_jres #

process_jres(symmetrize: bool = True) -> Self

Run the conventional JRES chain if, and only if, a shear collapses this plane.

Parameters:

Name Type Description Default
symmetrize bool

Also symmetrise about F1 = 0 after tilting (standard practice).

True

Returns:

Type Description
Self

Self, unchanged when the plane's peaks do not lie on a shearable line.

measure_noise #

measure_noise() -> PlaneNoiseEstimate

The magnitude plane's noise, to pass to find_peaks, group_peaks and infer_multiplets.

Stale once the amplitudes change.

find_peaks #

find_peaks(
    min_distance_points: int | None = None,
    min_height_ratio: float = 0.05,
    use_magnitude: bool = True,
    adaptive: bool = False,
    snr_threshold: float = 5.0,
    noise: tuple[float, float] | None = None,
) -> list[PeakInfo2D]

Find peaks in 2D spectrum.

Artefacts such as streaks and edge-truncated features are removed from the result.

Parameters:

Name Type Description Default
min_distance_points int | None

Minimum peak separation in points (in each dimension). If None, taken from the plane's measured line width.

None
min_height_ratio float

Minimum peak height as a ratio of the maximum height (0-1). Applies whether or not adaptive is set.

0.05
use_magnitude bool

If True, work on |z|, where a peak is a maximum. If False, work on Re(z), where a peak is an extremum of either sign: an inverted line is a line, and on a multiplicity-edited plane it is the CH2 evidence. Every reported height is positive; the sign is on signed_height.

True
adaptive bool

If True, the height threshold also follows the measured noise, using snr_threshold. Defaults to False.

False
snr_threshold float

When adaptive=True, minimum SNR for peak detection.

5.0
noise tuple[float, float] | None

The plane's already-measured (baseline level, sigma). On a large plane the measurement is expensive, so a caller that already has one can pass it. Measured here when None.

None

Returns:

Type Description
list[PeakInfo2D]

List of PeakInfo2D objects containing peak positions and heights,

list[PeakInfo2D]

with the plane's measurable artefacts removed.

calculate_peak_volumes #

calculate_peak_volumes(
    peaks: list[PeakInfo2D],
    radius_factor: float = 3.0,
    use_magnitude: bool = True,
) -> list[PeakInfo2D]

Calculate volumes for 2D peaks using elliptical integration regions.

For each peak, estimates the peak width in both dimensions by finding the half-height contour, then integrates within an ellipse of radius_factor * half-width.

Parameters:

Name Type Description Default
peaks list[PeakInfo2D]

List of PeakInfo2D objects from find_peaks().

required
radius_factor float

Multiplier for the half-width to define the integration ellipse (default 3.0 = ~99% of Gaussian).

3.0
use_magnitude bool

If True, integrate |z|, else integrate Re(z).

True

Returns:

Type Description
list[PeakInfo2D]

The same peaks with volume field populated.

estimate_snr #

estimate_snr(
    signal_region: tuple[
        tuple[float, float], tuple[float, float]
    ]
    | None = None,
) -> float

Estimate signal-to-noise ratio of the 2D spectrum.

The noise sigma comes from estimate_noise_plane, which measures the quiet regions of each row along the direct dimension.

Parameters:

Name Type Description Default
signal_region tuple[tuple[float, float], tuple[float, float]] | None

Optional ((f1_min, f1_max), (f2_min, f2_max)) to restrict signal calculation. If None, uses entire spectrum.

None

Returns:

Type Description
float

Signal-to-noise ratio (linear scale)

infer_multiplets #

infer_multiplets(
    peaks: list[PeakInfo2D] | None = None,
    group_axis: Literal["f1", "f2"] = "f1",
    snr_threshold: float = 30.0,
    margin_factor: float = 2.0,
    noise: float | None = None,
) -> list[MultipletGroup2D]

Infer multiplet patterns from 2D spectrum.

Every returned MultipletGroup2D.group_id equals the group_id carried by its member peaks, and peak_indices index into the peaks list exactly as supplied. A PPM axis with no usable reference leaves the Hz values at 0.0 and the couplings unset.

Parameters:

Name Type Description Default
peaks list[PeakInfo2D] | None

Pre-detected peaks. If None, runs find_peaks(adaptive=True).

None
group_axis Literal['f1', 'f2']

Which axis is the grouping (projected-over) axis. "f1" — spread along F2 gives multiplicity. "f2" — spread along F1 gives multiplicity.

'f1'
snr_threshold float

SNR threshold for peak detection (if peaks not provided).

30.0
margin_factor float

How much to expand the bounding box around each cluster (as a multiple of the cluster extent in each axis).

2.0
noise float | None

The plane's measure_noise().grouping_sigma; measured here when None.

None

Returns:

Type Description
list[MultipletGroup2D]

List of MultipletGroup2D with pattern, coupling constant, and score.

measure_peak_footprints #

measure_peak_footprints(
    peaks: list[PeakInfo2D], use_magnitude: bool = True
) -> list[PeakInfo2D]

Populate each peak's width_f1 / width_f2, in that axis' own units.

Each peak covers an axis-aligned ellipse sized from its measured line width on each axis. A peak whose width cannot be measured takes a representative width from the other peaks, so a footprint is never zero-sized.

Parameters:

Name Type Description Default
peaks list[PeakInfo2D]

Peaks to measure, from find_peaks().

required
use_magnitude bool

If True, measure widths on |z|, else on Re(z).

True

Returns:

Type Description
list[PeakInfo2D]

The same peaks with width_f1 and width_f2 populated.

group_extents #

group_extents(
    peaks: list[PeakInfo2D], use_magnitude: bool = True
) -> dict[int, tuple[float, float, float, float]]

Return each group's extent on the plane, in the axes' own units.

The extent is the axis-aligned bounding box of the group's members' elliptical footprints — each member's centre ± half its line width on each axis.

Parameters:

Name Type Description Default
peaks list[PeakInfo2D]

Grouped peaks; ungrouped peaks are grouped here first.

required
use_magnitude bool

If True, measure widths on |z|, else on Re(z).

True

Returns:

Type Description
dict[int, tuple[float, float, float, float]]

group_id → (f1_min, f1_max, f2_min, f2_max).

grouping_tolerances #

grouping_tolerances(
    peaks: list[PeakInfo2D],
    width_factor: float = DEFAULT_WIDTH_FACTOR,
    use_magnitude: bool = True,
) -> tuple[float, float]

Return the (F1, F2) grouping tolerances in each axis' own units.

Each tolerance scales with the typical line width of the supplied peaks along that axis, measured on this spectrum's own plane.

Parameters:

Name Type Description Default
peaks list[PeakInfo2D]

Peaks whose line widths set the scale, from find_peaks().

required
width_factor float

Multiple of the measured width to allow within a group.

DEFAULT_WIDTH_FACTOR
use_magnitude bool

If True, measure widths on |z|, else on Re(z).

True

Returns:

Type Description
tuple[float, float]

(tolerance_f1, tolerance_f2), each in the units of its own axis.

group_peaks #

group_peaks(
    peaks: list[PeakInfo2D],
    width_factor: float = DEFAULT_WIDTH_FACTOR,
    tolerance_f1: float | None = None,
    tolerance_f2: float | None = None,
    noise: float | None = None,
) -> list[PeakInfo2D]

Group 2D peaks by proximity, along whichever directions the plane shows.

Members of a group lie within the grouping tolerance of each other on both axes.

Parameters:

Name Type Description Default
peaks list[PeakInfo2D]

List of PeakInfo2D objects from find_peaks().

required
width_factor float

Multiple of the measured line width to allow within a group. Ignored on an axis given an explicit tolerance.

DEFAULT_WIDTH_FACTOR
tolerance_f1 float | None

Explicit F1 tolerance in F1 axis units.

None
tolerance_f2 float | None

Explicit F2 tolerance in F2 axis units.

None
noise float | None

The plane's measure_noise().grouping_sigma; measured here when None.

None

Returns:

Type Description
list[PeakInfo2D]

The same peaks with group_id assigned.

alignment_geometry #

alignment_geometry(
    peaks: list[PeakInfo2D],
) -> AlignmentGeometry | None

Measure the direction this plane's peaks line up in, or None if unmeasurable.

Answers which combination of the two coordinates the components of one feature share, and along which direction they are spread.

Parameters:

Name Type Description Default
peaks list[PeakInfo2D]

The peaks to measure, from find_peaks().

required

Returns:

Type Description
AlignmentGeometry | None

The geometry, or None when there are fewer than two peaks or an axis is

AlignmentGeometry | None

in ppm with no reference frequency, so the two axes cannot be put on one

AlignmentGeometry | None

Hz scale. Grouping then falls back to the per-axis rule, which needs no

AlignmentGeometry | None

such conversion.

correct_phase_auto #

correct_phase_auto(
    axis: Literal["f1", "f2", "both"] = "both",
    method: Literal["acme", "peak_minima"] = "acme",
    trace: Literal["max", "sum"] = "max",
    per_trace: bool = False,
    multi_start: bool = False,
    return_phases: Literal[False] = False,
) -> Self
correct_phase_auto(
    axis: Literal["f1", "f2", "both"] = "both",
    method: Literal["acme", "peak_minima"] = "acme",
    trace: Literal["max", "sum"] = "max",
    per_trace: bool = False,
    multi_start: bool = False,
    *,
    return_phases: Literal[True],
) -> tuple[Self, dict[str, tuple[float, float]]]
correct_phase_auto(
    axis: Literal["f1", "f2", "both"] = "both",
    method: Literal["acme", "peak_minima"] = "acme",
    trace: Literal["max", "sum"] = "max",
    per_trace: bool = False,
    multi_start: bool = False,
    return_phases: bool = False,
) -> Self | tuple[Self, dict[str, tuple[float, float]]]

Apply automatic phase correction along the specified axis.

One (p0, p1) pair is determined per axis and applied to every row or column. Phasing each trace independently (per_trace=True) can introduce discontinuities along the indirect dimension.

Parameters:

Name Type Description Default
axis Literal['f1', 'f2', 'both']

Which axis to correct ("f1", "f2", or "both").

'both'
method Literal['acme', 'peak_minima']

Phase objective, "acme" or "peak_minima".

'acme'
trace Literal['max', 'sum']

Which trace the phase is determined from: "max" or "sum".

'max'
per_trace bool

Whether to determine and apply a separate phase for every row or column. Off by default.

False
multi_start bool

Accepted for compatibility with the settings API; it has no effect.

False
return_phases bool

If True, also return the phases applied per axis.

False

Returns:

Type Description
Self | tuple[Self, dict[str, tuple[float, float]]]

Self, or (Self, {"f1": (p0, p1), "f2": (p0, p1)}) if return_phases=True.

correct_phase_auto_series #

correct_phase_auto_series(
    recovery: tuple[int, int] | None = None,
) -> Self

Phase every row of an arrayed spectrum (delays, gradients, times on F1) by one F2 phase.

Parameters:

Name Type Description Default
recovery tuple[int, int] | None

(earliest, latest) rows of a recovery series, whose lines all grow between them; None turns up the tallest line of the strongest row.

None

Returns:

Type Description
Self

Self. Rows keep their signs relative to one another, so inverted rows stay inverted.

correct_phase_manual #

correct_phase_manual(
    p0: float,
    p1: float = 0.0,
    axis: Literal["f1", "f2", "both"] = "both",
    p2: float = 0.0,
) -> Self

Apply manual phase correction along specified axis.

Parameters:

Name Type Description Default
p0 float

Zero-order phase correction (degrees)

required
p1 float

First-order phase correction (degrees)

0.0
axis Literal['f1', 'f2', 'both']

Which axis to correct ("f1", "f2", or "both")

'both'
p2 float

Second-order phase correction (degrees)

0.0

Returns:

Type Description
Self

Self

Raises:

Type Description
ProcessingParameterError

If F2 is asked of a hypercomplex spectrum whose F2-dispersion quadrant is gone (see :meth:correct_phase_manual_2d).

correct_phase_manual_2d #

correct_phase_manual_2d(
    f2: PhaseRamp | None = None, f1: PhaseRamp | None = None
) -> Self

Apply separate F2 and F1 phases, each about its own pivot.

Hypercomplex spectra are rotated through their quadrants, so F2 and F1 stay independent.

Parameters:

Name Type Description Default
f2 PhaseRamp | None

The F2 (direct, last-axis) phase, or None to leave F2 alone.

None
f1 PhaseRamp | None

The F1 (indirect, first-axis) phase, or None to leave F1 alone.

None

Returns:

Type Description
Self

Self.

Raises:

Type Description
ProcessingParameterError

If F1 is asked of a spectrum whose F1 carries no phase (QF/QSEQ magnitude modes, or an unknown mode), or F2 of a hypercomplex spectrum whose F2-dispersion quadrant did not survive (one received over gRPC).

correct_baseline #

correct_baseline(
    method: BaselineMethod2D = "arpls",
    axis: Literal["f1", "f2", "both"] = "both",
    edge_fraction: float = 0.1,
    poly_order: int = 1,
    smoothness_decades: float = 10.0,
    asymmetry: float = 0.001,
    iterations: int = 50,
    tol: float = 0.001,
    mask_sigma: float = 3.0,
    als_lambda: float = 100000.0,
    als_p: float = 0.01,
    als_iterations: int = 10,
    valley_prominence: float = 0.02,
    imaginary_method: ImaginaryBaselineMethod = "auto",
    allow_unsafe_poly_order: bool = False,
    exclude_regions: ExcludedRegions | None = None,
    edge_mode: BaselineEdgeMode = "open",
    **kwargs,
) -> Self

Apply baseline correction to a 2D spectrum.

Every method other than "plane" is applied trace by trace along the requested axis and behaves exactly as the 1D method of the same name.

Parameters:

Name Type Description Default
method BaselineMethod2D

Baseline correction method. "plane" fits a single 2D plane to the four corner regions; all other names are the 1D methods documented on BaselineCorrectionMixin1D.correct_baseline.

'arpls'
axis Literal['f1', 'f2', 'both']

Which axis to correct ("f1", "f2", or "both"); ignored for "plane".

'both'
edge_fraction float

Fraction of each edge used by the edge-anchored methods and by "plane" to size its corner regions.

0.1
poly_order int

Polynomial order for "polynomial" and "masked_poly".

1
smoothness_decades float

Smoothness of the fitted baseline on a log10 scale (larger is smoother). The effect does not depend on trace length.

10.0
asymmetry float

Asymmetry parameter p for "asls".

0.001
iterations int

Maximum reweighting iterations for the smooth-baseline methods.

50
tol float

Relative convergence tolerance for the smooth-baseline methods.

0.001
mask_sigma float

Signal-mask threshold in robust noise sigma.

3.0
als_lambda float

Smoothness parameter for "als"; the effect does not depend on spectrum length.

100000.0
als_p float

Asymmetry parameter for "als".

0.01
als_iterations int

Iteration count for "als"; must be >= 1.

10
valley_prominence float

Minimum valley prominence as a fraction of max|y|.

0.02
imaginary_method ImaginaryBaselineMethod

How to treat the dispersion channel; see BaselineCorrectionMixin1D.correct_baseline.

'auto'
allow_unsafe_poly_order bool

Permit poly_order above MAX_SAFE_EDGE_POLY_ORDER for the edge-only "polynomial" method.

False
exclude_regions ExcludedRegions | None

Spans of f2, as (low, high) pairs, that take no part in the fit; see BaselineCorrectionMixin1D.correct_baseline. They are quoted on the direct axis and applied to the f2 traces only, since that is the axis a suppressed solvent band occupies.

None
edge_mode BaselineEdgeMode

"open" (default) or "signal_free_mask"; see :data:BaselineEdgeMode.

'open'
**kwargs

Additional parameters (ignored for compatibility)

{}

Returns:

Type Description
Self

Self

Raises:

Type Description
ProcessingParameterError

If method is not supported.

pow #

pow(exponent: NumericScalar) -> Self

sqrt #

sqrt() -> Self

exp #

exp() -> Self

log #

log() -> Self

conjugate #

conjugate() -> Self

clip #

clip(
    minimum: float | None = None,
    maximum: float | None = None,
) -> Self

resample_as #

resample_as(other: Self) -> Self

Interpolate onto other's points inside the common axis range.

load #

load(
    stream: SupportsRead[bytes], size: int | None = None
) -> Self

parse classmethod #

parse(data: bytes) -> Self

FromString classmethod #

FromString(s: bytes) -> Self

to_nd #

to_nd(
    visualization_handler: str | None = None,
) -> SpectrumNd

copy #

copy() -> Self

Create a deep copy of this spectrum.

phase_f2_hypercomplex #

phase_f2_hypercomplex(
    p0: float, p1: float = 0.0, p2: float = 0.0
) -> Self

Rotate the F2 lineshape of a hypercomplex spectrum.

Parameters:

Name Type Description Default
p0 float

Zero-order phase in degrees.

required
p1 float

First-order phase in degrees, ramped across F2.

0.0
p2 float

Second-order phase in degrees.

0.0

Returns:

Type Description
Self

Self.

Raises:

Type Description
ProcessingParameterError

If the second quadrant is not available.

phase_f1_hypercomplex #

phase_f1_hypercomplex(
    p0: float, p1: float = 0.0, p2: float = 0.0
) -> Self

Rotate the F1 lineshape, keeping the second quadrant in step.

The rotation is applied to both quadrant planes when the spectrum is hypercomplex.

f2_complex_plane #

f2_complex_plane() -> ndarray

The F2-complex spectrum of the F1 absorption channel, RR + i*RI.

This is the array an F2 phase has to be measured on: it holds the F2 absorption and dispersion channels of the plane that will be displayed. Falls back to amplitudes when the spectrum is not hypercomplex.

normalize #

normalize(
    method: Literal["max", "rms", "unit"] = "max",
) -> Self

Normalize spectrum amplitudes.

Parameters:

Name Type Description Default
method Literal['max', 'rms', 'unit']

Normalization method ("max", "rms", "unit")

'max'

Returns:

Type Description
Self

Self for method chaining

to_ppm #

to_ppm() -> Self

Convert spectrum frequency axes to PPM scale.

Returns:

Type Description
Self

New spectrum with its frequency axes in PPM. A parameter or time axis

Self

(an arrayed series' delays) is returned as it is.

Raises:

Type Description
ValueError

If a frequency axis not already in PPM has no reference frequency

symmetrize #

symmetrize() -> Self

Symmetrize a 2D homonuclear spectrum by averaging with its transpose.

This is valid only for homonuclear experiments (COSY, NOESY, TOCSY) where F1 and F2 correspond to the same nucleus, and the amplitude matrix is square.

Returns:

Type Description
Self

Self for method chaining

Raises:

Type Description
ProcessingParameterError

If the spectrum is not square or not homonuclear

trim_frequency_range #

trim_frequency_range(
    f1_min: float = -inf,
    f1_max: float = inf,
    f2_min: float = -inf,
    f2_max: float = inf,
) -> Self

Trim spectrum to specified frequency ranges.

Parameters:

Name Type Description Default
f1_min float

Range for f1 axis (from)

-inf
f1_max float

Range for f1 axis (to)

inf
f2_min float

Range for f2 axis (from)

-inf
f2_max float

Range for f2 axis (to)

inf

Returns:

Type Description
Self

A new, trimmed spectrum (the original is left unchanged).

convert_frequency_unit #

convert_frequency_unit(
    target_unit: FrequencyUnit,
    axis: Literal["f1", "f2", "both"] = "both",
) -> Self

Convert frequency axes to different units.

Parameters:

Name Type Description Default
target_unit FrequencyUnit

Target frequency unit

required
axis Literal['f1', 'f2', 'both']

Which axis to convert; a parameter or time axis is never converted

'both'

Returns:

Type Description
Self

Self for method chaining

get_base_spectrum #

get_base_spectrum() -> Self

Get the main spectrum without reference data.

Returns a copy of this spectrum with reference fields set to None.

get_reference_f1 #

get_reference_f1() -> Spectrum1D | None

Get F1 (indirect dimension) reference spectrum.

get_reference_f2 #

get_reference_f2() -> Spectrum1D | None

Get F2 (direct dimension) reference spectrum.

has_references #

has_references() -> bool

Check if any reference spectra are attached.

apply_reference_correction #

apply_reference_correction() -> Self

Remove the reference acquisitions' phase from the plane.

Only the reference's phase is removed; every |amplitude| is left bit-for-bit unchanged, so there is no cost in signal-to-noise. Points where the reference is exactly zero define no phase and are left alone.

Returns:

Type Description
Self

Self for method chaining

to_signal #

to_signal(
    t1_unit: TimeUnit = MICROSECOND,
    t2_unit: TimeUnit = MICROSECOND,
    carrier_offset_hz_1: float | None = None,
    carrier_offset_hz_2: float | None = None,
    first_point_scale: bool | None = None,
) -> Signal2D

Convert spectrum back to a time-domain signal.

Parameters:

Name Type Description Default
t1_unit TimeUnit

Time unit for t1 axis (default: MICROSECOND)

MICROSECOND
t2_unit TimeUnit

Time unit for t2 axis (default: MICROSECOND)

MICROSECOND
carrier_offset_hz_1 float | None

Carrier offset for F1 in Hz. If provided, subtracted from F1 frequencies before conversion and stored in output signal.

None
carrier_offset_hz_2 float | None

Carrier offset for F2 in Hz. If provided, subtracted from F2 frequencies before conversion and stored in output signal.

None
first_point_scale bool | None

Whether to undo a first-point scaling applied by the forward transform on both axes, so the roundtrip is lossless. If None, read from the first_point_scale metadata flag recorded by to_spectrum.

None

Returns:

Name Type Description
Signal2D Signal2D

Time-domain 2D signal

from_proto classmethod #

from_proto(proto: Spectrum2D | SpectrumNd | None) -> Self