0
# MS Data Structures
1
2
Core data structures for representing mass spectrometry experiments, spectra, and chromatograms. These classes provide the foundation for all MS data processing in pyOpenMS with efficient data access patterns and numpy integration.
3
4
## Capabilities
5
6
### MS Experiment Container
7
8
#### MSExperiment
9
10
Central container for complete LC-MS experiments including spectra, chromatograms, and metadata.
11
12
```python { .api }
13
class MSExperiment:
14
def __init__(self) -> None: ...
15
16
def size(self) -> int:
17
"""
18
Get number of spectra in experiment.
19
20
Returns:
21
int: Number of spectra
22
"""
23
24
def empty(self) -> bool:
25
"""
26
Check if experiment is empty.
27
28
Returns:
29
bool: True if no spectra, False otherwise
30
"""
31
32
def getSpectrum(self, index: int) -> MSSpectrum:
33
"""
34
Get spectrum by index.
35
36
Args:
37
index (int): Spectrum index
38
39
Returns:
40
MSSpectrum: The spectrum at the given index
41
"""
42
43
def addSpectrum(self, spectrum: MSSpectrum) -> None:
44
"""
45
Add spectrum to experiment.
46
47
Args:
48
spectrum (MSSpectrum): Spectrum to add
49
"""
50
51
def removeSpectrum(self, index: int) -> None:
52
"""
53
Remove spectrum at index.
54
55
Args:
56
index (int): Index of spectrum to remove
57
"""
58
59
def getChromatograms(self) -> list[MSChromatogram]:
60
"""
61
Get all chromatograms.
62
63
Returns:
64
list[MSChromatogram]: List of chromatograms
65
"""
66
67
def addChromatogram(self, chromatogram: MSChromatogram) -> None:
68
"""
69
Add chromatogram to experiment.
70
71
Args:
72
chromatogram (MSChromatogram): Chromatogram to add
73
"""
74
75
def updateRanges(self) -> None:
76
"""Update RT/m/z ranges from contained spectra."""
77
78
def getMinRT(self) -> float:
79
"""Get minimum retention time."""
80
81
def getMaxRT(self) -> float:
82
"""Get maximum retention time."""
83
84
def getMinMZ(self) -> float:
85
"""Get minimum m/z value."""
86
87
def getMaxMZ(self) -> float:
88
"""Get maximum m/z value."""
89
90
def getMSLevels(self) -> list[int]:
91
"""
92
Get all MS levels present in experiment.
93
94
Returns:
95
list[int]: List of MS levels
96
"""
97
98
def get_df(self, ms_levels: list[int] = [], long: bool = False) -> DataFrame:
99
"""
100
Export experiment data to pandas DataFrame.
101
102
Args:
103
ms_levels (list[int]): MS levels to include (empty = all)
104
long (bool): Long format with one row per peak
105
106
Returns:
107
DataFrame: Experiment data in tabular format
108
"""
109
110
def get2DPeakData(self, min_rt: float, max_rt: float,
111
min_mz: float, max_mz: float, ms_level: int) -> tuple[list[float], list[float], list[float]]:
112
"""
113
Extract peak data as separate arrays for specified RT/m/z ranges.
114
115
Args:
116
min_rt (float): Minimum retention time
117
max_rt (float): Maximum retention time
118
min_mz (float): Minimum m/z
119
max_mz (float): Maximum m/z
120
ms_level (int): MS level to extract
121
122
Returns:
123
tuple: (rt_array, mz_array, intensity_array) as separate lists
124
"""
125
126
def get2DPeakDataPerSpectrum(self, min_rt: float, max_rt: float,
127
min_mz: float, max_mz: float, ms_level: int) -> tuple[list[float], list[list[float]], list[list[float]]]:
128
"""
129
Extract peak data organized per spectrum for specified ranges.
130
131
Args:
132
min_rt (float): Minimum retention time
133
max_rt (float): Maximum retention time
134
min_mz (float): Minimum m/z
135
max_mz (float): Maximum m/z
136
ms_level (int): MS level to extract
137
138
Returns:
139
tuple: (rt_array, mz_per_spectrum, intensity_per_spectrum)
140
"""
141
142
def get2DPeakDataIM(self, min_rt: float, max_rt: float, min_mz: float, max_mz: float,
143
ms_level: int) -> tuple[list[float], list[float], list[float], list[float]]:
144
"""
145
Extract peak data including ion mobility information.
146
147
Args:
148
min_rt (float): Minimum retention time
149
max_rt (float): Maximum retention time
150
min_mz (float): Minimum m/z
151
max_mz (float): Maximum m/z
152
ms_level (int): MS level to extract
153
154
Returns:
155
tuple: (rt_array, mz_array, intensity_array, ion_mobility_array)
156
"""
157
158
def aggregateFromMatrix(self, ranges: Matrix, ms_level: int, mz_agg: str) -> list[list[float]]:
159
"""
160
Aggregate intensity values for multiple m/z and RT ranges specified in a matrix.
161
162
Args:
163
ranges (Matrix): Matrix defining RT and m/z ranges
164
ms_level (int): MS level to process
165
mz_agg (str): Aggregation method ("sum", "mean", "max", etc.)
166
167
Returns:
168
list[list[float]]: Aggregated intensity values per range
169
"""
170
171
def extractXICsFromMatrix(self, ranges: Matrix, ms_level: int, mz_agg: str) -> list[MSChromatogram]:
172
"""
173
Extract XIC chromatograms for multiple m/z and RT ranges specified in a matrix.
174
175
Args:
176
ranges (Matrix): Matrix defining RT and m/z ranges
177
ms_level (int): MS level to process
178
mz_agg (str): Aggregation method for m/z ranges
179
180
Returns:
181
list[MSChromatogram]: Extracted ion chromatograms
182
"""
183
184
def getNrSpectra(self) -> int:
185
"""
186
Get number of spectra in experiment.
187
188
Returns:
189
int: Number of spectra
190
"""
191
192
def getNrChromatograms(self) -> int:
193
"""
194
Get number of chromatograms in experiment.
195
196
Returns:
197
int: Number of chromatograms
198
"""
199
200
def getSize(self) -> int:
201
"""
202
Get total number of peaks across all spectra.
203
204
Returns:
205
int: Total peak count
206
"""
207
208
def calculateTIC(self) -> MSChromatogram:
209
"""
210
Calculate total ion chromatogram.
211
212
Returns:
213
MSChromatogram: Total ion chromatogram
214
"""
215
216
def sortSpectra(self, sort_mz: bool = False) -> None:
217
"""
218
Sort spectra by retention time.
219
220
Args:
221
sort_mz (bool): Also sort peaks within spectra by m/z
222
"""
223
224
def sortChromatograms(self, sort_rt: bool = False) -> None:
225
"""
226
Sort chromatograms by m/z.
227
228
Args:
229
sort_rt (bool): Also sort data points within chromatograms by RT
230
"""
231
```
232
233
### Individual Spectrum
234
235
#### MSSpectrum
236
237
Individual mass spectrum with peaks, metadata, and processing information.
238
239
```python { .api }
240
class MSSpectrum:
241
def __init__(self) -> None: ...
242
243
def size(self) -> int:
244
"""
245
Get number of peaks in spectrum.
246
247
Returns:
248
int: Number of peaks
249
"""
250
251
def empty(self) -> bool:
252
"""
253
Check if spectrum is empty.
254
255
Returns:
256
bool: True if no peaks, False otherwise
257
"""
258
259
def getRT(self) -> float:
260
"""
261
Get retention time.
262
263
Returns:
264
float: Retention time in seconds
265
"""
266
267
def setRT(self, rt: float) -> None:
268
"""
269
Set retention time.
270
271
Args:
272
rt (float): Retention time in seconds
273
"""
274
275
def getMSLevel(self) -> int:
276
"""
277
Get MS level.
278
279
Returns:
280
int: MS level (1, 2, etc.)
281
"""
282
283
def setMSLevel(self, level: int) -> None:
284
"""
285
Set MS level.
286
287
Args:
288
level (int): MS level
289
"""
290
291
def get_peaks(self) -> tuple[np.ndarray, np.ndarray]:
292
"""
293
Get peak data as numpy arrays.
294
295
Returns:
296
tuple: (mz_array, intensity_array)
297
"""
298
299
def set_peaks(self, mz: np.ndarray, intensity: np.ndarray) -> None:
300
"""
301
Set peak data from numpy arrays.
302
303
Args:
304
mz (np.ndarray): m/z values
305
intensity (np.ndarray): Intensity values
306
"""
307
308
def getPrecursors(self) -> list[Precursor]:
309
"""
310
Get precursor information (for MS2+ spectra).
311
312
Returns:
313
list[Precursor]: List of precursors
314
"""
315
316
def setPrecursors(self, precursors: list[Precursor]) -> None:
317
"""
318
Set precursor information.
319
320
Args:
321
precursors (list[Precursor]): List of precursors
322
"""
323
324
def getProducts(self) -> list[Product]:
325
"""
326
Get product information.
327
328
Returns:
329
list[Product]: List of products
330
"""
331
332
def getNativeID(self) -> str:
333
"""
334
Get native spectrum ID.
335
336
Returns:
337
str: Native ID
338
"""
339
340
def setNativeID(self, id: str) -> None:
341
"""
342
Set native spectrum ID.
343
344
Args:
345
id (str): Native ID
346
"""
347
348
def getInstrumentSettings(self) -> InstrumentSettings:
349
"""
350
Get instrument settings.
351
352
Returns:
353
InstrumentSettings: Instrument configuration
354
"""
355
356
def getAcquisitionInfo(self) -> AcquisitionInfo:
357
"""
358
Get acquisition information.
359
360
Returns:
361
AcquisitionInfo: Acquisition metadata
362
"""
363
364
def getDriftTime(self) -> float:
365
"""
366
Get ion mobility drift time.
367
368
Returns:
369
float: Drift time value
370
"""
371
372
def setDriftTime(self, dt: float) -> None:
373
"""
374
Set ion mobility drift time.
375
376
Args:
377
dt (float): Drift time value
378
"""
379
380
def getDriftTimeUnit(self) -> DriftTimeUnit:
381
"""
382
Get drift time unit.
383
384
Returns:
385
DriftTimeUnit: Unit of drift time measurement
386
"""
387
388
def setDriftTimeUnit(self, unit: DriftTimeUnit) -> None:
389
"""
390
Set drift time unit.
391
392
Args:
393
unit (DriftTimeUnit): Unit of drift time measurement
394
"""
395
396
def getFloatDataArrays(self) -> list[FloatDataArray]:
397
"""
398
Get float data arrays (additional peak annotations).
399
400
Returns:
401
list[FloatDataArray]: List of float data arrays
402
"""
403
404
def setFloatDataArrays(self, arrays: list[FloatDataArray]) -> None:
405
"""
406
Set float data arrays.
407
408
Args:
409
arrays (list[FloatDataArray]): List of float data arrays
410
"""
411
412
def getStringDataArrays(self) -> list[StringDataArray]:
413
"""
414
Get string data arrays (additional peak annotations).
415
416
Returns:
417
list[StringDataArray]: List of string data arrays
418
"""
419
420
def setStringDataArrays(self, arrays: list[StringDataArray]) -> None:
421
"""
422
Set string data arrays.
423
424
Args:
425
arrays (list[StringDataArray]): List of string data arrays
426
"""
427
428
def getIntegerDataArrays(self) -> list[IntegerDataArray]:
429
"""
430
Get integer data arrays (additional peak annotations).
431
432
Returns:
433
list[IntegerDataArray]: List of integer data arrays
434
"""
435
436
def setIntegerDataArrays(self, arrays: list[IntegerDataArray]) -> None:
437
"""
438
Set integer data arrays.
439
440
Args:
441
arrays (list[IntegerDataArray]): List of integer data arrays
442
"""
443
444
def sortByIntensity(self) -> None:
445
"""Sort peaks by intensity (descending)."""
446
447
def sortByPosition(self) -> None:
448
"""Sort peaks by m/z position."""
449
450
def sortByIonMobility(self) -> None:
451
"""Sort peaks by ion mobility value."""
452
453
def isSorted(self) -> bool:
454
"""
455
Check if peaks are sorted by m/z.
456
457
Returns:
458
bool: True if sorted by m/z
459
"""
460
461
def isSortedByIM(self) -> bool:
462
"""
463
Check if peaks are sorted by ion mobility.
464
465
Returns:
466
bool: True if sorted by ion mobility
467
"""
468
469
def findNearest(self, mz: float) -> int:
470
"""
471
Find peak nearest to specified m/z.
472
473
Args:
474
mz (float): Target m/z value
475
476
Returns:
477
int: Index of nearest peak (-1 if not found)
478
"""
479
480
def findHighestInWindow(self, mz: float, tolerance: float) -> int:
481
"""
482
Find highest peak within m/z window.
483
484
Args:
485
mz (float): Center m/z value
486
tolerance (float): m/z tolerance
487
488
Returns:
489
int: Index of highest peak in window (-1 if not found)
490
"""
491
492
def containsIMData(self) -> bool:
493
"""
494
Check if spectrum contains ion mobility data.
495
496
Returns:
497
bool: True if ion mobility data present
498
"""
499
500
def getType(self) -> SpectrumType:
501
"""
502
Determine spectrum type (profile vs centroided).
503
504
Returns:
505
SpectrumType: Type of spectrum data
506
"""
507
508
def getBasePeak(self) -> Peak1D:
509
"""
510
Get base peak (most intense peak).
511
512
Returns:
513
Peak1D: Base peak
514
"""
515
516
def calculateTIC(self) -> float:
517
"""
518
Calculate total ion current.
519
520
Returns:
521
float: Total ion current (sum of all intensities)
522
"""
523
524
def select(self, start: int, end: int) -> MSSpectrum:
525
"""
526
Select subset of peaks by index range.
527
528
Args:
529
start (int): Start index
530
end (int): End index
531
532
Returns:
533
MSSpectrum: New spectrum with selected peaks
534
"""
535
536
def get_df(self, export_meta_values: bool = True) -> DataFrame:
537
"""
538
Export spectrum to pandas DataFrame.
539
540
Args:
541
export_meta_values (bool): Include metadata
542
543
Returns:
544
DataFrame: Spectrum data in tabular format
545
"""
546
```
547
548
### Chromatogram Data
549
550
#### MSChromatogram
551
552
Chromatographic data over retention time for specific m/z traces or transitions.
553
554
```python { .api }
555
class MSChromatogram:
556
def __init__(self) -> None: ...
557
558
def size(self) -> int:
559
"""
560
Get number of data points.
561
562
Returns:
563
int: Number of data points
564
"""
565
566
def empty(self) -> bool:
567
"""
568
Check if chromatogram is empty.
569
570
Returns:
571
bool: True if no data points, False otherwise
572
"""
573
574
def get_peaks(self) -> tuple[np.ndarray, np.ndarray]:
575
"""
576
Get chromatogram data as numpy arrays.
577
578
Returns:
579
tuple: (rt_array, intensity_array)
580
"""
581
582
def set_peaks(self, rt: np.ndarray, intensity: np.ndarray) -> None:
583
"""
584
Set chromatogram data from numpy arrays.
585
586
Args:
587
rt (np.ndarray): Retention time values
588
intensity (np.ndarray): Intensity values
589
"""
590
591
def getPrecursor(self) -> Precursor:
592
"""
593
Get precursor ion information.
594
595
Returns:
596
Precursor: Precursor ion data
597
"""
598
599
def setPrecursor(self, precursor: Precursor) -> None:
600
"""
601
Set precursor ion information.
602
603
Args:
604
precursor (Precursor): Precursor ion data
605
"""
606
607
def getProduct(self) -> Product:
608
"""
609
Get product ion information.
610
611
Returns:
612
Product: Product ion data
613
"""
614
615
def setProduct(self, product: Product) -> None:
616
"""
617
Set product ion information.
618
619
Args:
620
product (Product): Product ion data
621
"""
622
623
def getNativeID(self) -> str:
624
"""
625
Get native chromatogram ID.
626
627
Returns:
628
str: Native ID
629
"""
630
631
def setNativeID(self, id: str) -> None:
632
"""
633
Set native chromatogram ID.
634
635
Args:
636
id (str): Native ID
637
"""
638
639
def getChromatogramType(self) -> ChromatogramType:
640
"""
641
Get chromatogram type.
642
643
Returns:
644
ChromatogramType: Type of chromatogram
645
"""
646
647
def get_df(self, export_meta_values: bool = True) -> DataFrame:
648
"""
649
Export chromatogram to pandas DataFrame.
650
651
Args:
652
export_meta_values (bool): Include metadata
653
654
Returns:
655
DataFrame: Chromatogram data in tabular format
656
"""
657
```
658
659
### Peak Data Structures
660
661
#### Peak1D
662
663
Individual peak with m/z and intensity.
664
665
```python { .api }
666
class Peak1D:
667
def __init__(self, mz: float = 0.0, intensity: float = 0.0) -> None:
668
"""
669
Create 1D peak.
670
671
Args:
672
mz (float): m/z value
673
intensity (float): Intensity value
674
"""
675
676
def getMZ(self) -> float:
677
"""
678
Get m/z value.
679
680
Returns:
681
float: m/z value
682
"""
683
684
def setMZ(self, mz: float) -> None:
685
"""
686
Set m/z value.
687
688
Args:
689
mz (float): m/z value
690
"""
691
692
def getIntensity(self) -> float:
693
"""
694
Get intensity value.
695
696
Returns:
697
float: Intensity value
698
"""
699
700
def setIntensity(self, intensity: float) -> None:
701
"""
702
Set intensity value.
703
704
Args:
705
intensity (float): Intensity value
706
"""
707
```
708
709
#### Peak2D
710
711
Peak with retention time, m/z, and intensity coordinates.
712
713
```python { .api }
714
class Peak2D:
715
def __init__(self, rt: float = 0.0, mz: float = 0.0, intensity: float = 0.0) -> None:
716
"""
717
Create 2D peak.
718
719
Args:
720
rt (float): Retention time
721
mz (float): m/z value
722
intensity (float): Intensity value
723
"""
724
725
def getRT(self) -> float:
726
"""
727
Get retention time.
728
729
Returns:
730
float: Retention time
731
"""
732
733
def setRT(self, rt: float) -> None:
734
"""
735
Set retention time.
736
737
Args:
738
rt (float): Retention time
739
"""
740
741
def getMZ(self) -> float:
742
"""
743
Get m/z value.
744
745
Returns:
746
float: m/z value
747
"""
748
749
def setMZ(self, mz: float) -> None:
750
"""
751
Set m/z value.
752
753
Args:
754
mz (float): m/z value
755
"""
756
757
def getIntensity(self) -> float:
758
"""
759
Get intensity value.
760
761
Returns:
762
float: Intensity value
763
"""
764
765
def setIntensity(self, intensity: float) -> None:
766
"""
767
Set intensity value.
768
769
Args:
770
intensity (float): Intensity value
771
"""
772
```
773
774
### Ion Information
775
776
#### Precursor
777
778
Precursor ion information for MS/MS spectra.
779
780
```python { .api }
781
class Precursor:
782
def __init__(self) -> None: ...
783
784
def getMZ(self) -> float:
785
"""
786
Get precursor m/z.
787
788
Returns:
789
float: Precursor m/z
790
"""
791
792
def setMZ(self, mz: float) -> None:
793
"""
794
Set precursor m/z.
795
796
Args:
797
mz (float): Precursor m/z
798
"""
799
800
def getCharge(self) -> int:
801
"""
802
Get precursor charge.
803
804
Returns:
805
int: Precursor charge
806
"""
807
808
def setCharge(self, charge: int) -> None:
809
"""
810
Set precursor charge.
811
812
Args:
813
charge (int): Precursor charge
814
"""
815
816
def getIntensity(self) -> float:
817
"""
818
Get precursor intensity.
819
820
Returns:
821
float: Precursor intensity
822
"""
823
824
def setIntensity(self, intensity: float) -> None:
825
"""
826
Set precursor intensity.
827
828
Args:
829
intensity (float): Precursor intensity
830
"""
831
832
def getActivationMethods(self) -> set:
833
"""
834
Get activation methods used.
835
836
Returns:
837
set: Set of activation methods
838
"""
839
840
def getActivationEnergy(self) -> float:
841
"""
842
Get activation energy.
843
844
Returns:
845
float: Activation energy
846
"""
847
```
848
849
#### Product
850
851
Product ion information for transitions and MS/MS spectra.
852
853
```python { .api }
854
class Product:
855
def __init__(self) -> None: ...
856
857
def getMZ(self) -> float:
858
"""
859
Get product m/z.
860
861
Returns:
862
float: Product m/z
863
"""
864
865
def setMZ(self, mz: float) -> None:
866
"""
867
Set product m/z.
868
869
Args:
870
mz (float): Product m/z
871
"""
872
873
def getCharge(self) -> int:
874
"""
875
Get product charge.
876
877
Returns:
878
int: Product charge
879
"""
880
881
def setCharge(self, charge: int) -> None:
882
"""
883
Set product charge.
884
885
Args:
886
charge (int): Product charge
887
"""
888
```
889
890
### Instrument Settings
891
892
#### InstrumentSettings
893
894
Instrument configuration and acquisition parameters.
895
896
```python { .api }
897
class InstrumentSettings:
898
def __init__(self) -> None: ...
899
900
def getScanMode(self) -> ScanMode:
901
"""
902
Get scan mode.
903
904
Returns:
905
ScanMode: Scan mode
906
"""
907
908
def setScanMode(self, mode: ScanMode) -> None:
909
"""
910
Set scan mode.
911
912
Args:
913
mode (ScanMode): Scan mode
914
"""
915
916
def getPolarity(self) -> Polarity:
917
"""
918
Get ion polarity.
919
920
Returns:
921
Polarity: Ion polarity
922
"""
923
924
def setPolarity(self, polarity: Polarity) -> None:
925
"""
926
Set ion polarity.
927
928
Args:
929
polarity (Polarity): Ion polarity
930
"""
931
932
def getScanWindows(self) -> list[ScanWindow]:
933
"""
934
Get scan windows.
935
936
Returns:
937
list[ScanWindow]: List of scan windows
938
"""
939
```
940
941
## Types
942
943
### Data Array Types
944
945
```python { .api }
946
class FloatDataArray:
947
def __init__(self) -> None: ...
948
def getName(self) -> str: ...
949
def setName(self, name: str) -> None: ...
950
def getData(self) -> list[float]: ...
951
def setData(self, data: list[float]) -> None: ...
952
953
class StringDataArray:
954
def __init__(self) -> None: ...
955
def getName(self) -> str: ...
956
def setName(self, name: str) -> None: ...
957
def getData(self) -> list[str]: ...
958
def setData(self, data: list[str]) -> None: ...
959
960
class IntegerDataArray:
961
def __init__(self) -> None: ...
962
def getName(self) -> str: ...
963
def setName(self, name: str) -> None: ...
964
def getData(self) -> list[int]: ...
965
def setData(self, data: list[int]) -> None: ...
966
```
967
968
### Enumeration Types
969
970
```python { .api }
971
class DriftTimeUnit:
972
NONE = 0
973
MILLISECOND = 1
974
VOLT_SECOND_PER_SQUARE_CENTIMETER = 2
975
976
class SpectrumType:
977
UNKNOWN = 0
978
PROFILE = 1
979
CENTROIDED = 2
980
981
class ScanMode:
982
UNKNOWN = 0
983
MASS_SPECTRUM = 1
984
SIM = 2
985
SRM = 3
986
CRM = 4
987
Q1_SCAN = 5
988
Q3_SCAN = 6
989
NEUTRAL_LOSS_SCAN = 7
990
PRECURSOR_ION_SCAN = 8
991
ENHANCED_MULTIPLY_CHARGED = 9
992
TIME_DELAYED_FRAGMENTATION = 10
993
994
class Polarity:
995
UNKNOWN = 0
996
POSITIVE = 1
997
NEGATIVE = 2
998
999
class ChromatogramType:
1000
UNKNOWN = 0
1001
MASS_CHROMATOGRAM = 1
1002
TIC = 2
1003
BASEPEAK = 3
1004
SRM = 4
1005
SIM = 5
1006
EIC = 6
1007
```
1008
1009
### Matrix Type
1010
1011
```python { .api }
1012
class Matrix:
1013
def __init__(self, rows: int = 0, cols: int = 0) -> None:
1014
"""
1015
Create matrix for range specifications.
1016
1017
Args:
1018
rows (int): Number of rows
1019
cols (int): Number of columns
1020
"""
1021
1022
def getValue(self, row: int, col: int) -> float:
1023
"""Get value at position."""
1024
1025
def setValue(self, row: int, col: int, value: float) -> None:
1026
"""Set value at position."""
1027
1028
def rows(self) -> int:
1029
"""Get number of rows."""
1030
1031
def cols(self) -> int:
1032
"""Get number of columns."""
1033
```
1034
1035
## Usage Examples
1036
1037
### Basic Spectrum Processing
1038
1039
```python
1040
import pyopenms
1041
import numpy as np
1042
1043
# Create and populate spectrum
1044
spectrum = pyopenms.MSSpectrum()
1045
spectrum.setRT(123.45)
1046
spectrum.setMSLevel(1)
1047
1048
# Set peak data from numpy arrays
1049
mz_array = np.array([100.1, 200.2, 300.3])
1050
intensity_array = np.array([1000.0, 2000.0, 1500.0])
1051
spectrum.set_peaks(mz_array, intensity_array)
1052
1053
# Access peak data
1054
mz_data, intensity_data = spectrum.get_peaks()
1055
print(f"Spectrum at RT {spectrum.getRT():.2f} has {spectrum.size()} peaks")
1056
1057
# Sort peaks by m/z
1058
spectrum.sortByPosition()
1059
```
1060
1061
### MS Experiment Manipulation
1062
1063
```python
1064
import pyopenms
1065
1066
# Create experiment and add spectra
1067
exp = pyopenms.MSExperiment()
1068
1069
for i in range(10):
1070
spectrum = pyopenms.MSSpectrum()
1071
spectrum.setRT(i * 10.0) # RT every 10 seconds
1072
spectrum.setMSLevel(1)
1073
1074
# Add some peaks
1075
mz_array = np.array([100.0 + i, 200.0 + i, 300.0 + i])
1076
intensity_array = np.array([1000.0, 2000.0, 1500.0])
1077
spectrum.set_peaks(mz_array, intensity_array)
1078
1079
exp.addSpectrum(spectrum)
1080
1081
# Update ranges and get statistics
1082
exp.updateRanges()
1083
print(f"Experiment: {exp.size()} spectra")
1084
print(f"RT range: {exp.getMinRT():.1f} - {exp.getMaxRT():.1f}")
1085
print(f"m/z range: {exp.getMinMZ():.1f} - {exp.getMaxMZ():.1f}")
1086
print(f"MS levels: {exp.getMSLevels()}")
1087
```
1088
1089
### DataFrame Export
1090
1091
```python
1092
import pyopenms
1093
1094
# Load experiment
1095
exp = pyopenms.MSExperiment()
1096
pyopenms.MzMLFile().load("data.mzML", exp)
1097
1098
# Export to DataFrame (long format for analysis)
1099
df = exp.get_df(long=True)
1100
print(df.head())
1101
1102
# Export individual spectrum to DataFrame
1103
spectrum = exp.getSpectrum(0)
1104
spec_df = spectrum.get_df()
1105
print(spec_df.head())
1106
```
1107
1108
### Chromatogram Processing
1109
1110
```python
1111
import pyopenms
1112
import numpy as np
1113
1114
# Create chromatogram
1115
chrom = pyopenms.MSChromatogram()
1116
chrom.setNativeID("TIC")
1117
1118
# Set chromatogram data
1119
rt_array = np.linspace(0, 1000, 1000) # 1000 seconds
1120
intensity_array = np.random.normal(10000, 1000, 1000) # Random intensities
1121
chrom.set_peaks(rt_array, intensity_array)
1122
1123
# Set precursor information for XIC
1124
precursor = pyopenms.Precursor()
1125
precursor.setMZ(500.0)
1126
chrom.setPrecursor(precursor)
1127
1128
# Access chromatogram data
1129
rt_data, intensity_data = chrom.get_peaks()
1130
print(f"Chromatogram has {chrom.size()} data points")
1131
print(f"RT range: {rt_data[0]:.1f} - {rt_data[-1]:.1f}")
1132
```