MSSpectrum#

class pyopenms.MSSpectrum(*args, **kwargs)#

Bases: object

The representation of a 1D spectrum. Raw data access is proved by get_peaks and set_peaks, which yields numpy arrays Indexing and iteration yield copies of the peaks; write changes back with spec[i] = peak Extra data arrays can be accessed through getFloatDataArrays / getIntegerDataArrays / getStringDataArrays See help(SpectrumSettings) for information about meta-information Usage:

# Access data from an existing spectrum
ms_level = spectrum.getMSLevel()
rt = spectrum.getRT()
mz, intensities = spectrum.get_peaks()

# Create a new spectrum from scratch
from pyopenms import *
spectrum = MSSpectrum()
spectrum.setDriftTime(25) # 25 ms
spectrum.setRT(205.2) # 205.2 s
spectrum.setMSLevel(3) # MS3
p = Precursor()
p.setIsolationWindowLowerOffset(1.5)
p.setIsolationWindowUpperOffset(1.5)
p.setMZ(600) # isolation at 600 +/- 1.5 Th
p.setActivationEnergy(40) # 40 eV
p.setCharge(4) # 4+ ion
spectrum.setPrecursors( [p] )
# Add raw data to spectrum
spectrum.set_peaks( ([401.5], [900]) )
# Additional data arrays / peak annotations
fda = FloatDataArray()
fda.setName("Signal to Noise Array")
fda.push_back(15)
sda = StringDataArray()
sda.setName("Peak annotation")
sda.push_back("y15++")
spectrum.setFloatDataArrays( [fda] )
spectrum.setStringDataArrays( [sda] )
# Add spectrum to MSExperiment
exp = MSExperiment()
exp.addSpectrum(spectrum)
# Add second spectrum and store as mzML file
spectrum2 = MSSpectrum()
spectrum2.set_peaks( ([1, 2], [1, 2]) )
exp.addSpectrum(spectrum2)
MzMLFile().store("testfile.mzML", exp)
__init__(self) → None#
__init__(self, arg: std::initializer_list<OpenMS::Peak1D>, /) → None
__init__(self, arg: pyopenms._pyopenms_spectrum.MSSpectrum, /) → None

Methods

df_columns([columns, export_meta_values])

Returns a list of column names that to_df() would produce.

float_data_array_views()

Returns a list of live views of the float data arrays (see float_data_array_view).

get_base_peak()

Get the base peak (highest intensity peak).

get_data_dict([columns, export_meta_values])

Returns a dictionary of NumPy arrays with m/z, intensities, and metadata.

get_df(*args, **kwargs)

Deprecated: use to_df() instead.

get_df_columns(*args, **kwargs)

Deprecated: Use df_columns() instead.

get_drift_time_array_mv(*args, **kwargs)

get_drift_time_unit(*args, **kwargs)

get_tic()

Get total ion current (sum of all intensities).

integer_data_array_views()

Returns a list of live views of the integer data arrays (see integer_data_array_view).

intensityInRange(mz_min, mz_max)

Returns the sum of intensities of all peaks within the given m/z range.

iter_float_data_array_views()

Yields live views of the float data arrays, one at a time (see float_data_array_view).

iter_integer_data_array_views()

Yields live views of the integer data arrays, one at a time (see integer_data_array_view).

iter_string_data_array_views()

Yields live views of the string data arrays, one at a time (see string_data_array_view).

string_data_array_views()

Returns a list of live views of the string data arrays (see string_data_array_view).

to_arrow([columns, export_meta_values])

Returns an Apache Arrow Table representation of the MSSpectrum.

to_df([columns, export_meta_values])

Returns a pandas DataFrame representation of the MSSpectrum.

Attributes

calculateTIC

Returns the total ion current (sum of all peak intensities)

clear

Clears all data (and meta data if clear_meta_data is True)

clearMetaInfo

Removes all meta values

clearRanges

Resets all range dimensions

comment

The free-text comment

containsIMData

Returns whether the spectrum contains ion mobility data

drift_time

The drift time (-1 if not set)

drift_time_array_view

Returns writable view of drift time array if ion mobility data exists, else None

drift_time_unit

The ion mobility drift time unit

findHighestInWindow

Returns the index of the highest peak in the provided abs.

findNearest

Overloaded function.

float_data_array_view

Returns a live view of the float data array at index i.

getAcquisitionInfo

Returns a copy of the acquisition info

getAllNamesOfSpectrumType

getComment

Returns the free-text comment

getDataProcessing

getDriftTime

Returns the drift time (-1 if not set)

getDriftTimeUnit

Returns the ion mobility drift time unit

getDriftTimeUnitAsString

Returns the ion mobility drift time unit as string

getFloatDataArrays

Returns the float data arrays

getIMData

Returns (index, unit) for the per-peak ion mobility array.

getIMFormat

Returns the ion mobility format

getIMPeakType

Returns the IM peak type

getInstrumentSettings

Returns a copy of the instrument settings of the current spectrum

getIntegerDataArrays

Returns the integer data arrays

getKeys

Overloaded function.

getMSLevel

Returns the MS level

getMaxIntensity

Returns maximum intensity value

getMaxMZ

Returns maximum m/z value

getMetaValue

Returns the value corresponding to a string, or DataValue::EMPTY if not found

getMinIntensity

Returns minimum intensity value

getMinMZ

Returns minimum m/z value

getName

Returns the name of the spectrum

getNativeID

Returns the native identifier for the spectrum, used by the acquisition software

getPrecursors

Returns a copy of the precursors

getProducts

Returns a copy of the products

getRT

Returns the absolute retention time (in seconds)

getSourceFile

Returns a copy of the source file

getStringDataArrays

Returns the string data arrays

getType

Returns the spectrum type (centroided, profile or unknown).

get_drift_time_array

Returns drift time array if ion mobility data exists, else None

get_drift_time_array_unit

Returns the unit of the per-peak ion mobility array, or None if there is none.

get_intensity_array

Returns intensity values as numpy array

get_mz_array

Returns m/z values as numpy array

get_peaks

Returns a tuple of (mz_array, intensity_array) as numpy arrays

integer_data_array_view

Returns a live view of the integer data array at index i.

isMetaEmpty

Returns if the MetaInfo is empty

isSorted

Returns True if the spectrum is sorted by m/z

metaRegistry

metaValueExists

Returns whether an entry with the given name exists

ms_level

The MS level

name

The name of the spectrum

native_id

The native identifier for the spectrum, used by the acquisition software

peaks_struct

Returns zero-copy structured array with fields 'mz' (float64) and 'intensity' (float32).

push_back

Add a peak to the spectrum

rasterizeIMFrame

Rasterize an ion mobility frame into a 2D intensity matrix (IM vs m/z).

removeMetaValue

Removes the DataValue corresponding to name if it exists

reserve

Reserves space for n peaks in the underlying container

resize

Resizes the spectrum to contain n peaks

rt

The absolute retention time (in seconds)

select

Selects peaks by indices, removing all others.

setAcquisitionInfo

Sets the acquisition info

setComment

Sets the free-text comment

setDataProcessing

setDriftTime

Sets the drift time (-1 if not set)

setDriftTimeUnit

Sets the ion mobility drift time unit

setFloatDataArrays

Set the float data arrays

setIMFormat

Sets the ion mobility format

setIMPeakType

Sets the IM peak type (profile/centroided)

setInstrumentSettings

Sets the instrument settings of the current spectrum

setIntegerDataArrays

Set the integer data arrays

setMSLevel

Sets the MS level

setMetaValue

Sets the DataValue corresponding to a name

setName

Sets the name of the spectrum

setNativeID

Sets the native identifier for the spectrum, used by the acquisition software

setPrecursors

Sets the precursors

setProducts

Sets the products

setRT

Sets the absolute retention time (in seconds)

setSourceFile

Sets the source file

setStringDataArrays

Set the string data arrays

setType

Sets the spectrum type

set_drift_time_array

Set the per-peak ion mobility array, replacing any existing one.

set_peaks

Overloaded function.

size

Returns the number of peaks

sortByIntensity

Sorts the peaks by intensity (ascending if reverse is False, descending if True)

sortByPosition

Sorts the peaks by m/z position

spectrumTypeToString

string_data_array_view

Returns a live view of the string data array at index i.

toSpectrumType

unify

updateRanges

Recalculates the m/z and intensity ranges of the spectrum

class MSSpectrumRasterAggregation(*values)#

Bases: Enum

MAX = 1#
SUM = 0#
getMapping()#

Returns a dict mapping int values to enum member name strings.

calculateTIC#

Returns the total ion current (sum of all peak intensities)

clear#

Clears all data (and meta data if clear_meta_data is True)

clearMetaInfo#

Removes all meta values

clearRanges#

Resets all range dimensions

property comment#

The free-text comment

containsIMData#

Returns whether the spectrum contains ion mobility data

df_columns(columns='default', export_meta_values=True)#

Returns a list of column names that to_df() would produce.

property drift_time#

The drift time (-1 if not set)

drift_time_array_view#

Returns writable view of drift time array if ion mobility data exists, else None

property drift_time_unit#

The ion mobility drift time unit

findHighestInWindow#

Returns the index of the highest peak in the provided abs. m/z tolerance window (-1 if none match)

findNearest#

Overloaded function.

  1. findNearest(self, mz: float) -> int

Returns the index of the closest peak in m/z

  1. findNearest(self, mz: float, tolerance: float) -> int

Returns the index of the closest peak in the provided +/- m/z tolerance window (-1 if none match)

  1. findNearest(self, mz: float, tolerance_left: float, tolerance_right: float) -> int

Returns the index of the closest peak in the provided abs. m/z tolerance window to the left and right (-1 if none match)

float_data_array_view#

Returns a live view of the float data array at index i. Chain .data_view() on it for zero-copy numpy access into this object’s storage. The view aliases this object’s storage: edits through it are visible immediately, and it stays valid only until the data array list is resized or reordered. The parent object is kept alive automatically. For an owned copy use getFloatDataArrays()[i].

float_data_array_views()#

Returns a list of live views of the float data arrays (see float_data_array_view).

getAcquisitionInfo#

Returns a copy of the acquisition info

getAllNamesOfSpectrumType = <nanobind.nb_func object>#
getComment#

Returns the free-text comment

getDataProcessing#
getDriftTime#

Returns the drift time (-1 if not set)

getDriftTimeUnit#

Returns the ion mobility drift time unit

getDriftTimeUnitAsString#

Returns the ion mobility drift time unit as string

getFloatDataArrays#

Returns the float data arrays

getIMData#

Returns (index, unit) for the per-peak ion mobility array.

index indexes getFloatDataArrays() and unit is a DriftTimeUnit derived from that array’s name. Raises if the spectrum has no ion mobility array; use containsIMData() first.

getIMFormat#

Returns the ion mobility format

getIMPeakType#

Returns the IM peak type

getInstrumentSettings#

Returns a copy of the instrument settings of the current spectrum

getIntegerDataArrays#

Returns the integer data arrays

getKeys#

Overloaded function.

  1. getKeys(self, keys: list) -> None

Fills the given list with all meta value keys

  1. getKeys(self) -> list

Returns all meta value keys as a list

getMSLevel#

Returns the MS level

getMaxIntensity#

Returns maximum intensity value

getMaxMZ#

Returns maximum m/z value

getMetaValue#

Returns the value corresponding to a string, or DataValue::EMPTY if not found

getMinIntensity#

Returns minimum intensity value

getMinMZ#

Returns minimum m/z value

getName#

Returns the name of the spectrum

getNativeID#

Returns the native identifier for the spectrum, used by the acquisition software

getPrecursors#

Returns a copy of the precursors

getProducts#

Returns a copy of the products

getRT#

Returns the absolute retention time (in seconds)

getSourceFile#

Returns a copy of the source file

getStringDataArrays#

Returns the string data arrays

getType#

Returns the spectrum type (centroided, profile or unknown). If SpectrumSettings and DataProcessing information are not sufficient and query_data is True, the data will be queried (potentially expensive)

get_base_peak() → Tuple[float, float]#

Get the base peak (highest intensity peak).

get_data_dict(columns=None, export_meta_values=True)#

Returns a dictionary of NumPy arrays with m/z, intensities, and metadata.

get_df(*args, **kwargs)#

Deprecated: use to_df() instead.

get_df_columns(*args, **kwargs)#

Deprecated: Use df_columns() instead.

get_drift_time_array#

Returns drift time array if ion mobility data exists, else None

get_drift_time_array_mv(*args, **kwargs)#
get_drift_time_array_unit#

Returns the unit of the per-peak ion mobility array, or None if there is none.

This belongs to the get_drift_time_array() family and reports the unit derived from that array’s name. It is unrelated to getDriftTimeUnit() / the drift_time_unit property, which report the spectrum-wide scalar for a spectrum acquired at a single drift time; a spectrum may carry either or, on some vendor readers, both.

None means there is no ion mobility array at all. DriftTimeUnit.NONE is different: an array was found but its name did not pin down a unit.

get_drift_time_unit(*args, **kwargs)#
get_intensity_array#

Returns intensity values as numpy array

get_mz_array#

Returns m/z values as numpy array

get_peaks#

Returns a tuple of (mz_array, intensity_array) as numpy arrays

get_tic() → float#

Get total ion current (sum of all intensities).

integer_data_array_view#

Returns a live view of the integer data array at index i. Chain .data_view() on it for zero-copy numpy access into this object’s storage. The view aliases this object’s storage: edits through it are visible immediately, and it stays valid only until the data array list is resized or reordered. The parent object is kept alive automatically. For an owned copy use getIntegerDataArrays()[i].

integer_data_array_views()#

Returns a list of live views of the integer data arrays (see integer_data_array_view).

intensityInRange(mz_min: float, mz_max: float) → float#

Returns the sum of intensities of all peaks within the given m/z range.

Parameters#

mz_minfloat

Minimum m/z value (inclusive)

mz_maxfloat

Maximum m/z value (inclusive)

Returns#

float

Sum of intensities of peaks with mz_min <= m/z <= mz_max

isMetaEmpty#

Returns if the MetaInfo is empty

isSorted#

Returns True if the spectrum is sorted by m/z

iter_float_data_array_views()#

Yields live views of the float data arrays, one at a time (see float_data_array_view).

iter_integer_data_array_views()#

Yields live views of the integer data arrays, one at a time (see integer_data_array_view).

iter_string_data_array_views()#

Yields live views of the string data arrays, one at a time (see string_data_array_view).

metaRegistry = <nanobind.nb_func object>#
metaValueExists#

Returns whether an entry with the given name exists

property ms_level#

The MS level

property name#

The name of the spectrum

property native_id#

The native identifier for the spectrum, used by the acquisition software

peaks_struct#

Returns zero-copy structured array with fields ‘mz’ (float64) and ‘intensity’ (float32).

push_back#

Add a peak to the spectrum

rasterizeIMFrame#

Rasterize an ion mobility frame into a 2D intensity matrix (IM vs m/z).

Creates a 2D heatmap representation by binning peak intensities into a regular grid. Designed for spectra in IM_PEAK format where each peak has an associated ion mobility value.

Parameters#

outputnumpy.ndarray

Pre-allocated 2D float32 C-contiguous array with shape (mz_bins, im_bins). Will be filled in-place (zero-initialize before calling).

min_imfloat

Minimum ion mobility value for the output range.

max_imfloat

Maximum ion mobility value for the output range.

min_mzfloat

Minimum m/z value for the output range.

max_mzfloat

Maximum m/z value for the output range.

aggregationstr, optional

Aggregation mode: “sum” (default) or “max”.

removeMetaValue#

Removes the DataValue corresponding to name if it exists

reserve#

Reserves space for n peaks in the underlying container

resize#

Resizes the spectrum to contain n peaks

property rt#

The absolute retention time (in seconds)

select#

Selects peaks by indices, removing all others. Raises IndexError for an out-of-range index and ValueError for a duplicate index.

setAcquisitionInfo#

Sets the acquisition info

setComment#

Sets the free-text comment

setDataProcessing#
setDriftTime#

Sets the drift time (-1 if not set)

setDriftTimeUnit#

Sets the ion mobility drift time unit

setFloatDataArrays#

Set the float data arrays

setIMFormat#

Sets the ion mobility format

setIMPeakType#

Sets the IM peak type (profile/centroided)

setInstrumentSettings#

Sets the instrument settings of the current spectrum

setIntegerDataArrays#

Set the integer data arrays

setMSLevel#

Sets the MS level

setMetaValue#

Sets the DataValue corresponding to a name

setName#

Sets the name of the spectrum

setNativeID#

Sets the native identifier for the spectrum, used by the acquisition software

setPrecursors#

Sets the precursors

setProducts#

Sets the products

setRT#

Sets the absolute retention time (in seconds)

setSourceFile#

Sets the source file

setStringDataArrays#

Set the string data arrays

setType#

Sets the spectrum type

set_drift_time_array#

Set the per-peak ion mobility array, replacing any existing one.

values must have one entry per peak. unit names the array through the PSI-MS controlled vocabulary, which is what makes it discoverable again through containsIMData() and getIMData(); only DriftTimeUnit.MILLISECOND (drift time) and DriftTimeUnit.VSSC (1/K0) have a CV term for this and anything else is rejected. unit may be omitted only when the spectrum already carries an ion mobility array, whose unit is then reused.

This does not touch setDriftTime()/setDriftTimeUnit(), which describe a whole spectrum acquired at one drift time rather than a per-peak annotation; a frame carrying an ion mobility array leaves those unset, matching what IMDataConverter produces.

set_peaks#

Overloaded function.

  1. set_peaks(self, mz: object, intensity: object, metadata: str = 'error', ion_mobility: object | None = None, ion_mobility_unit: pyopenms._pyopenms_kernel.DriftTimeUnit = DriftTimeUnit.NONE) -> None

Set peaks from mz and intensity arrays

The binary data arrays are not resized. metadata decides what happens when the new peak count would leave a non-empty float, string or integer data array mis-sized: error (the default) raises and leaves the container untouched, clear drops the arrays that no longer fit, and keep keeps them, leaving the container internally inconsistent. Arrays that are already the right length, and empty ones, are kept in every case, so replacing peaks with an equally long set never touches them.

ion_mobility sets the per-peak ion mobility array in the same call, replacing any existing one; it must have one entry per peak. ion_mobility_unit names the array through the PSI-MS controlled vocabulary and may be omitted only when the spectrum already has an ion mobility array to inherit the unit from. Only DriftTimeUnit.MILLISECOND (drift time) and DriftTimeUnit.VSSC (1/K0) have a CV term for this, so other units are rejected. Because the ion mobility array is replaced rather than stranded, it is exempt from the metadata check above.

  1. set_peaks(self, peaks: object, *, metadata: str = 'error', ion_mobility: object | None = None, ion_mobility_unit: pyopenms._pyopenms_kernel.DriftTimeUnit = DriftTimeUnit.NONE) -> None

Set peaks from a tuple of (mz_array, intensity_array)

The binary data arrays are not resized. metadata decides what happens when the new peak count would leave a non-empty float, string or integer data array mis-sized: error (the default) raises and leaves the container untouched, clear drops the arrays that no longer fit, and keep keeps them, leaving the container internally inconsistent. Arrays that are already the right length, and empty ones, are kept in every case, so replacing peaks with an equally long set never touches them.

ion_mobility sets the per-peak ion mobility array in the same call, replacing any existing one; it must have one entry per peak. ion_mobility_unit names the array through the PSI-MS controlled vocabulary and may be omitted only when the spectrum already has an ion mobility array to inherit the unit from. Only DriftTimeUnit.MILLISECOND (drift time) and DriftTimeUnit.VSSC (1/K0) have a CV term for this, so other units are rejected. Because the ion mobility array is replaced rather than stranded, it is exempt from the metadata check above.

size#

Returns the number of peaks

sortByIntensity#

Sorts the peaks by intensity (ascending if reverse is False, descending if True)

sortByPosition#

Sorts the peaks by m/z position

spectrumTypeToString = <nanobind.nb_func object>#
string_data_array_view#

Returns a live view of the string data array at index i. Chain .data_view() on it for zero-copy numpy access into this object’s storage. The view aliases this object’s storage: edits through it are visible immediately, and it stays valid only until the data array list is resized or reordered. The parent object is kept alive automatically. For an owned copy use getStringDataArrays()[i].

string_data_array_views()#

Returns a list of live views of the string data arrays (see string_data_array_view).

toSpectrumType = <nanobind.nb_func object>#
to_arrow(columns=None, export_meta_values=True)#

Returns an Apache Arrow Table representation of the MSSpectrum.

to_df(columns=None, export_meta_values=True)#

Returns a pandas DataFrame representation of the MSSpectrum.

unify#
updateRanges#

Recalculates the m/z and intensity ranges of the spectrum