Skill Tracer
Skills › Scientific Agent Skills › pyopenms › data_structures.md

data_structures.md

119 lines · skills/pyopenms/references/data_structures.md at 5f2bc03

Open on GitHub
1# Data structures (pyOpenMS 3.6.0)
2

Data structures (pyOpenMS 3.6.0)

Raw lines 1 to 2
3## Spectra, chromatograms and copy semantics
4
5```python
6import pyopenms as ms
7spec = ms.MSSpectrum()
8spec.setRT(60.0) # seconds, not minutes
9spec.setMSLevel(1)
10spec.setType(ms.SpectrumSettings.SpectrumType.CENTROID)
11spec.set_peaks(([100.0, 200.0], [10.0, 20.0]))
12exp = ms.MSExperiment()
13exp.addSpectrum(spec)
15copy = exp.getSpectrum(0)
16copy.select([1]) # also filters associated peak arrays
17exp.setSpectra([copy]) # explicit writeback
18mz, intensity = exp[0].get_peaks()
19assert list(mz) == [200.0]
20```
22`MSExperiment` stores spectra and chromatograms separately. `len(exp)` concerns
23spectra; inspect `getNrChromatograms()` too. `getSpectrum()` and indexing return
24copies in this binding; do not rely on iteration to mutate stored peaks.
25`set_peaks()` changes the peak arrays but does not synchronize associated
26float/integer/string arrays; prefer `select` for peak removal.
28`MSChromatogram.get_peaks()` returns time in seconds and intensity. Precursor
29metadata in a chromatogram is not proof of an analyte identity. MS2 precursor
30m/z and charge come from `getPrecursors()`; the list may be empty or contain
31multiple entries. Charge zero means unknown. Keep collision energy, isolation
32windows, polarity and ion mobility metadata when they matter. Empty spectra and
33traces need explicit handling before min/max/argmax operations.
35`MSExperiment(exp)` makes a copy. Experiment metadata are available through
36`getInstrument()`, `getSample()`, `getSourceFiles()`, and
37`getExperimentalSettings()`. Preserve native IDs and source provenance when
38rewriting files.

Spectra, chromatograms and copy semantics

import pyopenms as ms
spec = ms.MSSpectrum()
spec.setRT(60.0)  # seconds, not minutes
spec.setMSLevel(1)
spec.setType(ms.SpectrumSettings.SpectrumType.CENTROID)
spec.set_peaks(([100.0, 200.0], [10.0, 20.0]))
exp = ms.MSExperiment()
exp.addSpectrum(spec)

copy = exp.getSpectrum(0)
copy.select([1])  # also filters associated peak arrays
exp.setSpectra([copy])  # explicit writeback
mz, intensity = exp[0].get_peaks()
assert list(mz) == [200.0]

MSExperiment stores spectra and chromatograms separately. len(exp) concerns spectra; inspect getNrChromatograms() too. getSpectrum() and indexing return copies in this binding; do not rely on iteration to mutate stored peaks. set_peaks() changes the peak arrays but does not synchronize associated float/integer/string arrays; prefer select for peak removal.

MSChromatogram.get_peaks() returns time in seconds and intensity. Precursor metadata in a chromatogram is not proof of an analyte identity. MS2 precursor m/z and charge come from getPrecursors(); the list may be empty or contain multiple entries. Charge zero means unknown. Keep collision energy, isolation windows, polarity and ion mobility metadata when they matter. Empty spectra and traces need explicit handling before min/max/argmax operations.

MSExperiment(exp) makes a copy. Experiment metadata are available through getInstrument(), getSample(), getSourceFiles(), and getExperimentalSettings(). Preserve native IDs and source provenance when rewriting files.

Raw lines 3 to 39
40## Features and consensus
42A `Feature` carries RT, m/z, intensity, charge, quality, hulls and optional
43subordinates/identifications. Hull coordinates are `(RT seconds, m/z)`; use
44`len(feature.getConvexHull().getHullPoints())`. Subordinates are algorithm-defined,
45not invariably isotope peaks. Overall quality is not a calibrated probability.
47```python
48features = ms.FeatureMap()
49f = ms.Feature()
50f.setRT(60.0)
51f.setMZ(200.0)
52f.setIntensity(1000.0)
53f.setCharge(1)
54features.push_back(f)
55features.setUniqueIds()
56features.setPrimaryMSRunPath(["run.mzML"])
57print(features.getPrimaryMSRunPath()) # list[str]
58print(features.get_df()[["rt", "mz", "intensity", "charge"]])
59```
61`getUniqueId()` is an object identifier, not a count. `FeatureMap.size()` is the
62number of features. Preserve source IDs when joining data. `ConsensusFeature`
63contains handles with `getMapIndex()`, `getUniqueId()` and the original
64feature coordinates/intensity. Absent handles mean missing observations.
66`ConsensusMap.getColumnHeaders()` returns the map-index/sample mapping. Modify
67it then call `setColumnHeaders(headers)` explicitly. `get_intensity_df()` and
68`get_metadata_df()` are the focused exports; row identities/sample names must
69be checked before joining. Positional concatenation avoids duplicate-index joins
70but the output row number is not a persistent scientific identifier.

Features and consensus

A Feature carries RT, m/z, intensity, charge, quality, hulls and optional subordinates/identifications. Hull coordinates are (RT seconds, m/z); use len(feature.getConvexHull().getHullPoints()). Subordinates are algorithm-defined, not invariably isotope peaks. Overall quality is not a calibrated probability.

features = ms.FeatureMap()
f = ms.Feature()
f.setRT(60.0)
f.setMZ(200.0)
f.setIntensity(1000.0)
f.setCharge(1)
features.push_back(f)
features.setUniqueIds()
features.setPrimaryMSRunPath(["run.mzML"])
print(features.getPrimaryMSRunPath())  # list[str]
print(features.get_df()[["rt", "mz", "intensity", "charge"]])

getUniqueId() is an object identifier, not a count. FeatureMap.size() is the number of features. Preserve source IDs when joining data. ConsensusFeature contains handles with getMapIndex(), getUniqueId() and the original feature coordinates/intensity. Absent handles mean missing observations.

ConsensusMap.getColumnHeaders() returns the map-index/sample mapping. Modify it then call setColumnHeaders(headers) explicitly. get_intensity_df() and get_metadata_df() are the focused exports; row identities/sample names must be checked before joining. Positional concatenation avoids duplicate-index joins but the output row number is not a persistent scientific identifier.

Raw lines 40 to 71
72## Identification containers
74Use `PeptideIdentificationList` with `push_back` for mutable peptide IDs.
75`IdXMLFile.load(path)` returns proteins plus peptide IDs in 3.6; output-argument
76loading also remains supported. A peptide ID has a search-run identifier, score
77type/direction, optional RT/m/z, and hits. Hits have sequences, charge, score,
78rank, protein evidence and metadata. Read `getScoreType()` and
79`isHigherScoreBetter()`; do not assume scores or mass-error meta keys have a
80universal meaning. `MS:1002252` is not a generic ppm-error key.
82`ProteinIdentification` describes a search run and protein hits/groups, not one
83protein. `getSearchParameters()` includes database, enzyme, modifications and
84tolerance units. Use the identification reference for FDR semantics.

Identification containers

Use PeptideIdentificationList with push_back for mutable peptide IDs. IdXMLFile.load(path) returns proteins plus peptide IDs in 3.6; output-argument loading also remains supported. A peptide ID has a search-run identifier, score type/direction, optional RT/m/z, and hits. Hits have sequences, charge, score, rank, protein evidence and metadata. Read getScoreType() and isHigherScoreBetter(); do not assume scores or mass-error meta keys have a universal meaning. MS:1002252 is not a generic ppm-error key.

ProteinIdentification describes a search run and protein hits/groups, not one protein. getSearchParameters() includes database, enzyme, modifications and tolerance units. Use the identification reference for FDR semantics.

Raw lines 72 to 85
86## Chemistry and parameters
88```python
89seq = ms.AASequence.fromString("PEPTIDEM(Oxidation)K")
90print(seq.getMonoWeight(), seq.getAverageWeight(), seq.getFormula().toString())
91formula = ms.EmpiricalFormula("C6H12O6")
92print(formula.getMonoWeight()) # neutral mass in Da
93pattern = formula.getIsotopeDistribution(ms.CoarseIsotopePatternGenerator(4))
94print([(p.getMZ(), p.getIntensity()) for p in pattern.getContainer()])
96algorithm = ms.FeatureFindingMetabo()
97params = algorithm.getDefaults()
98for key in params.keys():
99 print(key, params.getValue(key), params.getDescription(key))
100params.setValue("charge_lower_bound", 1)
101algorithm.setParameters(params)
102```
104The neutral-formula isotope container uses mass coordinates; do not label them
105charged m/z without applying the intended adduct/charge. Coarse isotope patterns
106are theoretical natural-abundance models; labeling/enrichment needs its own
107model. Mass and average mass are different quantities. Unknown/ambiguous sequence
108residues or modifications need deliberate treatment rather than silently
109substituting a standard residue.
111In 3.6 `Param.keys()` returns strings and typed parameter values may be booleans.
112String values `"true"`/`"false"` remain accepted for the bundled algorithms.
113Use installed defaults and descriptions to establish allowed names and units;
114setting an unused or misspelled parameter does not establish algorithm behavior.
116Sources: [3.6 release changes](https://openms.de/documentation/html/ChangeLog.html),
117[wheel metadata](https://pypi.org/project/pyopenms/3.6.0/), and native 3.6.0
118object/round-trip checks. The examples above are covered by synthetic checks;
119they do not validate real acquisition metadata or scientific inference.

Chemistry and parameters

seq = ms.AASequence.fromString("PEPTIDEM(Oxidation)K")
print(seq.getMonoWeight(), seq.getAverageWeight(), seq.getFormula().toString())
formula = ms.EmpiricalFormula("C6H12O6")
print(formula.getMonoWeight())  # neutral mass in Da
pattern = formula.getIsotopeDistribution(ms.CoarseIsotopePatternGenerator(4))
print([(p.getMZ(), p.getIntensity()) for p in pattern.getContainer()])

algorithm = ms.FeatureFindingMetabo()
params = algorithm.getDefaults()
for key in params.keys():
    print(key, params.getValue(key), params.getDescription(key))
params.setValue("charge_lower_bound", 1)
algorithm.setParameters(params)

The neutral-formula isotope container uses mass coordinates; do not label them charged m/z without applying the intended adduct/charge. Coarse isotope patterns are theoretical natural-abundance models; labeling/enrichment needs its own model. Mass and average mass are different quantities. Unknown/ambiguous sequence residues or modifications need deliberate treatment rather than silently substituting a standard residue.

In 3.6 Param.keys() returns strings and typed parameter values may be booleans. String values "true"/"false" remain accepted for the bundled algorithms. Use installed defaults and descriptions to establish allowed names and units; setting an unused or misspelled parameter does not establish algorithm behavior.

Sources: 3.6 release changes, wheel metadata, and native 3.6.0 object/round-trip checks. The examples above are covered by synthetic checks; they do not validate real acquisition metadata or scientific inference.

Raw lines 86 to 119