rainbow-api 1.0.16__tar.gz → 1.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {rainbow_api-1.0.16/rainbow_api.egg-info → rainbow_api-1.1.0}/PKG-INFO +3 -2
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/README.md +2 -1
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/pyproject.toml +1 -1
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/rainbow/__init__.py +10 -3
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/rainbow/agilent/__init__.py +16 -4
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/rainbow/agilent/masshunter.py +378 -48
- {rainbow_api-1.0.16 → rainbow_api-1.1.0/rainbow_api.egg-info}/PKG-INFO +3 -2
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/tests/test_masshunter.py +195 -2
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/COPYING +0 -0
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/COPYING.LESSER +0 -0
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/MANIFEST.in +0 -0
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/rainbow/agilent/_msprofile.pyx +0 -0
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/rainbow/agilent/_uvdelta.pyx +0 -0
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/rainbow/agilent/chemstation.py +0 -0
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/rainbow/agilent/openlab.py +0 -0
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/rainbow/datadirectory.py +0 -0
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/rainbow/datafile.py +0 -0
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/rainbow/waters/__init__.py +0 -0
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/rainbow/waters/masslynx.py +0 -0
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/rainbow_api.egg-info/SOURCES.txt +0 -0
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/rainbow_api.egg-info/dependency_links.txt +0 -0
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/rainbow_api.egg-info/requires.txt +0 -0
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/rainbow_api.egg-info/top_level.txt +0 -0
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/setup.cfg +0 -0
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/setup.py +0 -0
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/tests/test_accelerator.py +0 -0
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/tests/test_agilent.py +0 -0
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/tests/test_datadirectory.py +0 -0
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/tests/test_datafile.py +0 -0
- {rainbow_api-1.0.16 → rainbow_api-1.1.0}/tests/test_waters.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: rainbow-api
|
|
3
|
-
Version: 1.0
|
|
3
|
+
Version: 1.1.0
|
|
4
4
|
Summary: Read chromatography and mass spectrometry binary files
|
|
5
5
|
Author: Evan Shi and Eugene Kwan
|
|
6
6
|
Author-email: evanyshi@cmu.edu
|
|
@@ -28,7 +28,8 @@ Dynamic: license-file
|
|
|
28
28
|
* `.uv` - UV spectrum (supports incomplete files)
|
|
29
29
|
* `.ch` - UV, FID, CAD, and ELSD channels
|
|
30
30
|
* `.ms` - MS (supports incomplete files)
|
|
31
|
-
* `MSProfile.bin` - HRMS
|
|
31
|
+
* `MSProfile.bin` - HRMS profile spectrum (parse with `hrms=True`)
|
|
32
|
+
* `MSPeak.bin` - centroid (peak-picked) spectrum (parse with `centroid=True`)
|
|
32
33
|
|
|
33
34
|
**Agilent .dx (OpenLab CDS)**
|
|
34
35
|
* `.UV` - DAD spectrum
|
|
@@ -9,7 +9,8 @@
|
|
|
9
9
|
* `.uv` - UV spectrum (supports incomplete files)
|
|
10
10
|
* `.ch` - UV, FID, CAD, and ELSD channels
|
|
11
11
|
* `.ms` - MS (supports incomplete files)
|
|
12
|
-
* `MSProfile.bin` - HRMS
|
|
12
|
+
* `MSProfile.bin` - HRMS profile spectrum (parse with `hrms=True`)
|
|
13
|
+
* `MSPeak.bin` - centroid (peak-picked) spectrum (parse with `centroid=True`)
|
|
13
14
|
|
|
14
15
|
**Agilent .dx (OpenLab CDS)**
|
|
15
16
|
* `.UV` - DAD spectrum
|
|
@@ -4,7 +4,8 @@ from rainbow.datadirectory import DataDirectory
|
|
|
4
4
|
from rainbow import agilent, waters
|
|
5
5
|
|
|
6
6
|
|
|
7
|
-
def read(path, prec=0, hrms=False, requested_files=None, telemetry=False
|
|
7
|
+
def read(path, prec=0, hrms=False, requested_files=None, telemetry=False,
|
|
8
|
+
centroid=False):
|
|
8
9
|
"""
|
|
9
10
|
Reads a chromatogram data directory. Main method of the package.
|
|
10
11
|
|
|
@@ -25,9 +26,11 @@ def read(path, prec=0, hrms=False, requested_files=None, telemetry=False):
|
|
|
25
26
|
Args:
|
|
26
27
|
path (str): Path of the directory.
|
|
27
28
|
prec (int, optional): Number of decimals to round ylabels.
|
|
28
|
-
hrms (bool, optional): Flag for Agilent HRMS parsing.
|
|
29
|
+
hrms (bool, optional): Flag for Agilent HRMS (MSProfile.bin) parsing.
|
|
29
30
|
requested_files (list, optional): List of filenames to parse.
|
|
30
31
|
telemetry (bool, optional): Flag for Agilent .dx telemetry traces.
|
|
32
|
+
centroid (bool, optional): Flag for Agilent MassHunter centroid
|
|
33
|
+
(MSPeak.bin) parsing.
|
|
31
34
|
|
|
32
35
|
Returns:
|
|
33
36
|
DataDirectory representing the directory.
|
|
@@ -46,6 +49,9 @@ def read(path, prec=0, hrms=False, requested_files=None, telemetry=False):
|
|
|
46
49
|
if not isinstance(hrms, bool):
|
|
47
50
|
raise Exception(f"The hrms flag must be a boolean.")
|
|
48
51
|
|
|
52
|
+
if not isinstance(centroid, bool):
|
|
53
|
+
raise Exception(f"The centroid flag must be a boolean.")
|
|
54
|
+
|
|
49
55
|
if requested_files is not None and not isinstance(requested_files, list):
|
|
50
56
|
raise Exception(f"The requested_files argument must be a list.")
|
|
51
57
|
|
|
@@ -54,7 +60,8 @@ def read(path, prec=0, hrms=False, requested_files=None, telemetry=False):
|
|
|
54
60
|
|
|
55
61
|
datadir = None
|
|
56
62
|
if ext.upper() == '.D' or ext.lower() == '.dx':
|
|
57
|
-
datadir = agilent.read(
|
|
63
|
+
datadir = agilent.read(
|
|
64
|
+
path, prec, hrms, requested_files, telemetry, centroid)
|
|
58
65
|
elif ext.lower() == '.raw':
|
|
59
66
|
datadir = waters.read(path, prec, requested_files)
|
|
60
67
|
|
|
@@ -4,16 +4,20 @@ from rainbow.agilent import chemstation
|
|
|
4
4
|
from rainbow.datadirectory import DataDirectory
|
|
5
5
|
|
|
6
6
|
|
|
7
|
-
def read(path, prec=0, hrms=False, requested_files=None, telemetry=False
|
|
7
|
+
def read(path, prec=0, hrms=False, requested_files=None, telemetry=False,
|
|
8
|
+
centroid=False):
|
|
8
9
|
"""
|
|
9
10
|
Reads an Agilent .D directory or .dx archive.
|
|
10
11
|
|
|
11
12
|
Args:
|
|
12
13
|
path (str): Path of the directory or .dx file.
|
|
13
14
|
prec (int, optional): Number of decimals to round masses.
|
|
14
|
-
hrms (bool, optional): Flag for
|
|
15
|
+
hrms (bool, optional): Flag for parsing the MassHunter profile
|
|
16
|
+
spectrum (MSProfile.bin).
|
|
15
17
|
requested_files (list, optional): List of filenames to parse.
|
|
16
18
|
telemetry (bool, optional): Flag for parsing .dx telemetry traces.
|
|
19
|
+
centroid (bool, optional): Flag for parsing the MassHunter centroid
|
|
20
|
+
spectrum (MSPeak.bin).
|
|
17
21
|
|
|
18
22
|
Returns:
|
|
19
23
|
DataDirectory representing the Agilent data.
|
|
@@ -25,15 +29,23 @@ def read(path, prec=0, hrms=False, requested_files=None, telemetry=False):
|
|
|
25
29
|
|
|
26
30
|
datafiles = []
|
|
27
31
|
datafiles.extend(chemstation.parse_allfiles(path, prec, requested_files))
|
|
28
|
-
if hrms:
|
|
32
|
+
if hrms or centroid:
|
|
29
33
|
try:
|
|
30
34
|
from rainbow.agilent import masshunter
|
|
31
|
-
datafiles.extend(
|
|
35
|
+
datafiles.extend(
|
|
36
|
+
masshunter.parse_allfiles(path, prec, hrms, centroid))
|
|
32
37
|
except ModuleNotFoundError:
|
|
33
38
|
raise ModuleNotFoundError("You must install python-lzf to parse masshunter files.")
|
|
34
39
|
|
|
35
40
|
metadata = chemstation.parse_metadata(path, datafiles)
|
|
36
41
|
|
|
42
|
+
# Surface unread MassHunter centroid data so the centroid flag is
|
|
43
|
+
# discoverable: a .D with MSPeak.bin holds a centroid spectrum that is only
|
|
44
|
+
# parsed when centroid=True.
|
|
45
|
+
if not centroid and os.path.isfile(
|
|
46
|
+
os.path.join(path, "AcqData", "MSPeak.bin")):
|
|
47
|
+
metadata['centroid_available'] = True
|
|
48
|
+
|
|
37
49
|
return DataDirectory(path, datafiles, metadata)
|
|
38
50
|
|
|
39
51
|
|
|
@@ -27,19 +27,22 @@ MAIN PARSING METHOD
|
|
|
27
27
|
|
|
28
28
|
"""
|
|
29
29
|
|
|
30
|
-
def parse_allfiles(path, prec=0):
|
|
30
|
+
def parse_allfiles(path, prec=0, hrms=False, centroid=False):
|
|
31
31
|
"""
|
|
32
|
-
Finds and parses Agilent Masshunter data files.
|
|
33
|
-
Currently, only HRMS data is supported. \
|
|
34
|
-
See the documentation on :obj:`parse_msdata` for info on the limitations.
|
|
32
|
+
Finds and parses Agilent Masshunter MS data files.
|
|
35
33
|
|
|
36
|
-
|
|
37
|
-
|
|
34
|
+
MassHunter stores a scan's spectrum as a dense profile trace
|
|
35
|
+
(``MSProfile.bin``) and/or a peak-picked centroid list (``MSPeak.bin``).
|
|
36
|
+
Both are opt-in: ``hrms`` parses the profile and ``centroid`` parses the
|
|
37
|
+
centroids (see :obj:`parse_msdata` and :obj:`parse_mspeakdata`). With
|
|
38
|
+
neither flag set nothing is parsed here.
|
|
38
39
|
|
|
39
40
|
Args:
|
|
40
41
|
path (str): Path to the Agilent .D directory.
|
|
41
42
|
prec (int, optional): Number of decimals to round ylabels.
|
|
42
|
-
|
|
43
|
+
hrms (bool, optional): Parse the profile spectrum (MSProfile.bin).
|
|
44
|
+
centroid (bool, optional): Parse the centroid spectrum (MSPeak.bin).
|
|
45
|
+
|
|
43
46
|
Returns:
|
|
44
47
|
List containing a DataFile for each parsed file.
|
|
45
48
|
|
|
@@ -51,15 +54,14 @@ def parse_allfiles(path, prec=0):
|
|
|
51
54
|
return datafiles
|
|
52
55
|
|
|
53
56
|
acqdata_files = set(os.listdir(acqdata_path))
|
|
54
|
-
# MSTS.xml is no longer required: the scan count is recovered
|
|
55
|
-
# MSScan.bin
|
|
56
|
-
# .rslt/.sirslt result folders, which omit MSTS.xml.
|
|
57
|
+
# MSTS.xml is no longer required: the scan count is recovered from the
|
|
58
|
+
# MSScan.bin record geometry (see read_scan_records). This lets us parse
|
|
59
|
+
# Agilent OpenLab .rslt/.sirslt result folders, which omit MSTS.xml.
|
|
57
60
|
if {"MSScan.xsd", "MSScan.bin"} <= acqdata_files:
|
|
58
|
-
if "
|
|
61
|
+
if centroid and "MSPeak.bin" in acqdata_files:
|
|
62
|
+
datafiles.append(parse_mspeakdata(acqdata_path, prec))
|
|
63
|
+
if hrms and "MSProfile.bin" in acqdata_files:
|
|
59
64
|
datafiles.append(parse_msdata(acqdata_path, prec))
|
|
60
|
-
# Future work should also parse the MSPeak.bin format.
|
|
61
|
-
# elif "MSPeak.bin" in acqdata_files:
|
|
62
|
-
# ...
|
|
63
65
|
|
|
64
66
|
return datafiles
|
|
65
67
|
|
|
@@ -109,7 +111,7 @@ def parse_msdata(path, prec=0):
|
|
|
109
111
|
# - the uncompressed length in bytes
|
|
110
112
|
# - the calibration id (selects a polynomial calibration; see below)
|
|
111
113
|
scan_records = read_scan_records(
|
|
112
|
-
os.path.join(path, "MSScan.bin"), complextypes_dict)
|
|
114
|
+
os.path.join(path, "MSScan.bin"), complextypes_dict, count_scans(path))
|
|
113
115
|
num_times = len(scan_records)
|
|
114
116
|
data_info = [
|
|
115
117
|
(rec['ScanTime'],
|
|
@@ -120,22 +122,15 @@ def parse_msdata(path, prec=0):
|
|
|
120
122
|
rec.get('CalibrationID'))
|
|
121
123
|
for rec in scan_records]
|
|
122
124
|
|
|
123
|
-
#
|
|
124
|
-
#
|
|
125
|
-
#
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
f.close()
|
|
133
|
-
|
|
134
|
-
# DefaultMassCal.xml: per-calibration-id flags selecting which polynomial
|
|
135
|
-
# coefficients are active. Absent for older/LZF data, in which case
|
|
136
|
-
# only the traditional calibration is applied.
|
|
137
|
-
calib_flags = parse_default_masscal(
|
|
138
|
-
os.path.join(path, "DefaultMassCal.xml"))
|
|
125
|
+
# Mass calibration (see _load_calibration and calibrate_mz): the per-scan
|
|
126
|
+
# 10 doubles and polynomial flags. A profile m/z axis is stored as raw
|
|
127
|
+
# time-of-flight, so MSProfile.bin always needs the calibration.
|
|
128
|
+
calib_vals, calib_flags = _load_calibration(
|
|
129
|
+
path, [cid for *_, cid in data_info])
|
|
130
|
+
if calib_vals is None:
|
|
131
|
+
raise FileNotFoundError(
|
|
132
|
+
"Cannot calibrate MSProfile.bin: neither MSMassCal.bin nor a "
|
|
133
|
+
f"usable DefaultMassCal.xml was found in {path}.")
|
|
139
134
|
|
|
140
135
|
# MSProfile.bin: Extract the data values.
|
|
141
136
|
# Each retention time has a data segment that starts with two doubles
|
|
@@ -151,7 +146,9 @@ def parse_msdata(path, prec=0):
|
|
|
151
146
|
# UncompressedByteCount does not reliably distinguish the two (it is
|
|
152
147
|
# sometimes set, sometimes zero, for the RLE case), so we detect the
|
|
153
148
|
# RLE format from the segment's own header (see segment_is_rle).
|
|
154
|
-
|
|
149
|
+
profile_path = os.path.join(path, "MSProfile.bin")
|
|
150
|
+
profile_size = os.path.getsize(profile_path)
|
|
151
|
+
f = open(profile_path, 'rb')
|
|
155
152
|
twodoubles_unpack = struct.Struct('<dd').unpack
|
|
156
153
|
times = np.empty(num_times)
|
|
157
154
|
num_mz_per_time = np.empty(num_times)
|
|
@@ -159,6 +156,16 @@ def parse_msdata(path, prec=0):
|
|
|
159
156
|
inten_arrs = []
|
|
160
157
|
for i in range(num_times):
|
|
161
158
|
time, num_mz, offset, comp_len, decomp_len, calib_id = data_info[i]
|
|
159
|
+
|
|
160
|
+
# An interrupted acquisition leaves MSScan.bin describing scans whose
|
|
161
|
+
# MSProfile.bin segment was never (fully) written. Stop at the first
|
|
162
|
+
# such scan and keep the complete prefix instead of failing the parse.
|
|
163
|
+
if offset + comp_len > profile_size:
|
|
164
|
+
num_times = i
|
|
165
|
+
times = times[:num_times]
|
|
166
|
+
num_mz_per_time = num_mz_per_time[:num_times]
|
|
167
|
+
break
|
|
168
|
+
|
|
162
169
|
times[i] = time
|
|
163
170
|
num_mz_per_time[i] = num_mz
|
|
164
171
|
|
|
@@ -197,6 +204,10 @@ def parse_msdata(path, prec=0):
|
|
|
197
204
|
|
|
198
205
|
f.close()
|
|
199
206
|
|
|
207
|
+
if num_times == 0:
|
|
208
|
+
raise ValueError(
|
|
209
|
+
f"MSProfile.bin in {path} contains no complete scans.")
|
|
210
|
+
|
|
200
211
|
# Concatenating the per-scan arrays avoids materializing a ~100M-element
|
|
201
212
|
# Python list (and the numpy round-trip through it), which otherwise
|
|
202
213
|
# dominates parsing of large profile files.
|
|
@@ -259,6 +270,126 @@ def bin_to_grid(mz_arr, intensities, rows, num_times, prec):
|
|
|
259
270
|
return mz_ylabels, grid.reshape(num_times, mz_ylabels.size)
|
|
260
271
|
|
|
261
272
|
|
|
273
|
+
# Bytes-per-peak -> (mz dtype, intensity dtype) for the MSPeak.bin centroid
|
|
274
|
+
# encodings seen in the wild. 8 and 12 interleave one mz and one intensity per
|
|
275
|
+
# peak; 16 stores all mz values then all intensities (a split block).
|
|
276
|
+
_PEAK_DTYPES = {8: ('<f4', '<f4'), 12: ('<f8', '<f4'), 16: ('<f8', '<f8')}
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def parse_mspeakdata(path, prec=0):
|
|
280
|
+
"""
|
|
281
|
+
Parses Masshunter centroided MS data stored in MSPeak.bin.
|
|
282
|
+
|
|
283
|
+
MSPeak.bin holds the peak-picked (centroid) spectrum of each scan - a list
|
|
284
|
+
of (mz, intensity) pairs - in contrast to the dense profile trace in
|
|
285
|
+
MSProfile.bin (:obj:`parse_msdata`). GC quadrupole acquisitions store only
|
|
286
|
+
centroids; Q-TOF/TOF acquisitions store a profile block and a centroid block
|
|
287
|
+
per scan (see :obj:`read_scan_records`), and this reads the centroid one.
|
|
288
|
+
|
|
289
|
+
The following files are used:
|
|
290
|
+
- MSScan.xsd -> File structure of MSScan.bin.
|
|
291
|
+
- MSScan.bin -> Per-scan metadata and pointers into MSPeak.bin.
|
|
292
|
+
- MSPeak.bin -> Raw (mz, intensity) peak pairs.
|
|
293
|
+
|
|
294
|
+
The MSPeak.bin centroid decoding was contributed by denisshragin (issue #37).
|
|
295
|
+
|
|
296
|
+
Args:
|
|
297
|
+
path (str): Path to the AcqData subdirectory.
|
|
298
|
+
prec (int, optional): Number of decimals to round mz values.
|
|
299
|
+
|
|
300
|
+
Returns:
|
|
301
|
+
DataFile containing Masshunter centroided MS data.
|
|
302
|
+
|
|
303
|
+
"""
|
|
304
|
+
complextypes_dict = parse_scan_xsd(os.path.join(path, "MSScan.xsd"))
|
|
305
|
+
scan_records = read_scan_records(
|
|
306
|
+
os.path.join(path, "MSScan.bin"), complextypes_dict, count_scans(path))
|
|
307
|
+
num_times = len(scan_records)
|
|
308
|
+
|
|
309
|
+
# Mass calibration. GC-quadrupole MSPeak.bin already stores m/z (no
|
|
310
|
+
# calibration files, so calib_vals is None), but a TOF/Q-TOF centroid axis
|
|
311
|
+
# is raw time-of-flight and is calibrated exactly like the profile axis.
|
|
312
|
+
calibration_ids = [record.get('CalibrationID') for record in scan_records]
|
|
313
|
+
calib_vals, calib_flags = _load_calibration(path, calibration_ids)
|
|
314
|
+
|
|
315
|
+
peak_path = os.path.join(path, "MSPeak.bin")
|
|
316
|
+
peak_size = os.path.getsize(peak_path)
|
|
317
|
+
times = np.empty(num_times)
|
|
318
|
+
num_peaks_per_time = np.zeros(num_times, dtype=np.int64)
|
|
319
|
+
mz_arrs = []
|
|
320
|
+
inten_arrs = []
|
|
321
|
+
with open(peak_path, 'rb') as f:
|
|
322
|
+
for i, record in enumerate(scan_records):
|
|
323
|
+
times[i] = record['ScanTime']
|
|
324
|
+
block = _select_centroid_block(record['SpectrumParamsBlocks'])
|
|
325
|
+
if block is None:
|
|
326
|
+
continue
|
|
327
|
+
num_peaks = block['PointCount']
|
|
328
|
+
offset = block['SpectrumOffset']
|
|
329
|
+
byte_count = block['ByteCount']
|
|
330
|
+
# Skip scans with no peaks, or whose data was never (fully) written
|
|
331
|
+
# (an interrupted acquisition - keep the complete scans).
|
|
332
|
+
if (num_peaks <= 0 or byte_count <= 0
|
|
333
|
+
or offset + byte_count > peak_size):
|
|
334
|
+
continue
|
|
335
|
+
f.seek(offset)
|
|
336
|
+
mzs, intensities = _decode_peak_block(
|
|
337
|
+
f.read(byte_count), num_peaks, byte_count // num_peaks)
|
|
338
|
+
if calib_vals is not None:
|
|
339
|
+
mzs = calibrate_mz(np.asarray(mzs, dtype=np.float64),
|
|
340
|
+
calib_vals[i], calib_flags.get(
|
|
341
|
+
calibration_ids[i]))
|
|
342
|
+
mz_arrs.append(np.round(mzs, prec))
|
|
343
|
+
inten_arrs.append(intensities)
|
|
344
|
+
num_peaks_per_time[i] = num_peaks
|
|
345
|
+
|
|
346
|
+
if not mz_arrs:
|
|
347
|
+
return DataFile(
|
|
348
|
+
"MSPeak.bin", 'MS', times, np.array([], dtype=np.float64),
|
|
349
|
+
np.zeros((num_times, 0), dtype=np.uint64), {})
|
|
350
|
+
|
|
351
|
+
mz_arr = np.concatenate(mz_arrs)
|
|
352
|
+
intensities = np.concatenate(inten_arrs).astype(np.uint64)
|
|
353
|
+
rows = np.repeat(np.arange(num_times), num_peaks_per_time)
|
|
354
|
+
mz_ylabels, data = bin_to_grid(mz_arr, intensities, rows, num_times, prec)
|
|
355
|
+
return DataFile("MSPeak.bin", 'MS', times, mz_ylabels, data, {})
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _select_centroid_block(blocks):
|
|
359
|
+
"""
|
|
360
|
+
Returns the centroid (MSPeak.bin) block among a scan's SpectrumParamValues
|
|
361
|
+
blocks, or None if there is no peak block.
|
|
362
|
+
|
|
363
|
+
A centroid block stores fixed-width (mz, intensity) peaks, so its ByteCount
|
|
364
|
+
is an exact multiple of PointCount equal to one of the known bytes-per-peak
|
|
365
|
+
widths. A profile block's ByteCount is a compressed length and does not
|
|
366
|
+
satisfy this, which distinguishes the two on instruments that store both.
|
|
367
|
+
"""
|
|
368
|
+
for block in blocks:
|
|
369
|
+
num_peaks = block['PointCount']
|
|
370
|
+
byte_count = block['ByteCount']
|
|
371
|
+
if (num_peaks > 0 and byte_count % num_peaks == 0
|
|
372
|
+
and byte_count // num_peaks in _PEAK_DTYPES):
|
|
373
|
+
return block
|
|
374
|
+
return None
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def _decode_peak_block(raw, num_peaks, bytes_per_peak):
|
|
378
|
+
"""
|
|
379
|
+
Decodes one MSPeak.bin centroid segment into (mz, intensity) float arrays.
|
|
380
|
+
|
|
381
|
+
The segment is a split block: all ``num_peaks`` mz values followed by all
|
|
382
|
+
``num_peaks`` intensities. ``bytes_per_peak`` selects the dtypes (see
|
|
383
|
+
:data:`_PEAK_DTYPES`).
|
|
384
|
+
"""
|
|
385
|
+
mz_dtype, inten_dtype = _PEAK_DTYPES[bytes_per_peak]
|
|
386
|
+
mz_bytes = num_peaks * np.dtype(mz_dtype).itemsize
|
|
387
|
+
mzs = np.frombuffer(raw[:mz_bytes], dtype=mz_dtype)
|
|
388
|
+
intensities = np.frombuffer(
|
|
389
|
+
raw[mz_bytes:num_peaks * bytes_per_peak], dtype=inten_dtype)
|
|
390
|
+
return mzs, intensities
|
|
391
|
+
|
|
392
|
+
|
|
262
393
|
def parse_default_masscal(xml_path):
|
|
263
394
|
"""
|
|
264
395
|
Reads the polynomial ``ValueUseFlags`` for each calibration id from
|
|
@@ -294,6 +425,94 @@ def parse_default_masscal(xml_path):
|
|
|
294
425
|
return flags
|
|
295
426
|
|
|
296
427
|
|
|
428
|
+
def read_default_masscal_rows(xml_path):
|
|
429
|
+
"""
|
|
430
|
+
Reads the default per-calibration-id calibration rows from
|
|
431
|
+
DefaultMassCal.xml.
|
|
432
|
+
|
|
433
|
+
Used as the fallback when the per-scan MSMassCal.bin is absent. Each
|
|
434
|
+
``DefaultCalibration`` provides a ``Traditional`` step (coeff, base) and,
|
|
435
|
+
optionally, a ``Polynomial`` step (left, right, then six coefficients).
|
|
436
|
+
Together these are the ten doubles MSMassCal.bin would otherwise store per
|
|
437
|
+
scan - ``[coeff, base, left, right, c0..c5]`` - so a row can stand in for a
|
|
438
|
+
MSMassCal.bin row directly (see :obj:`calibrate_mz`). The polynomial's
|
|
439
|
+
ValueUseFlags is read separately by :obj:`parse_default_masscal`.
|
|
440
|
+
|
|
441
|
+
Args:
|
|
442
|
+
xml_path (str): Path to DefaultMassCal.xml.
|
|
443
|
+
|
|
444
|
+
Returns:
|
|
445
|
+
Dictionary mapping calibration id (int) to a length-10 list of doubles.
|
|
446
|
+
Empty if the file does not exist or defines no traditional calibration.
|
|
447
|
+
|
|
448
|
+
"""
|
|
449
|
+
if not os.path.exists(xml_path):
|
|
450
|
+
return {}
|
|
451
|
+
rows = {}
|
|
452
|
+
root = etree.parse(xml_path).getroot()
|
|
453
|
+
for calibration in root.iter("DefaultCalibration"):
|
|
454
|
+
calib_id = calibration.get("DefaultCalibrationID")
|
|
455
|
+
if calib_id is None:
|
|
456
|
+
continue
|
|
457
|
+
traditional, polynomial = [], []
|
|
458
|
+
for step in calibration.iter("Step"):
|
|
459
|
+
values = [float(v.text) for v in step.iter("Value")]
|
|
460
|
+
formula = step.findtext("CalibrationFormula")
|
|
461
|
+
if formula == "Traditional":
|
|
462
|
+
traditional = values
|
|
463
|
+
elif formula == "Polynomial":
|
|
464
|
+
polynomial = values
|
|
465
|
+
if len(traditional) < 2:
|
|
466
|
+
continue
|
|
467
|
+
row = list(traditional[:2]) + list(polynomial[:8])
|
|
468
|
+
row += [0.0] * (10 - len(row))
|
|
469
|
+
rows[int(calib_id)] = row[:10]
|
|
470
|
+
return rows
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def _load_calibration(path, calibration_ids):
|
|
474
|
+
"""
|
|
475
|
+
Loads the per-scan mass calibration for an AcqData directory.
|
|
476
|
+
|
|
477
|
+
Returns ``(calib_vals, calib_flags)`` where ``calib_vals`` is an ``(N, 10)``
|
|
478
|
+
array of the ten calibration doubles for each of the N scans (in the order
|
|
479
|
+
of ``calibration_ids``) and ``calib_flags`` maps each CalibrationID to its
|
|
480
|
+
polynomial ValueUseFlags. The values come from the per-scan MSMassCal.bin
|
|
481
|
+
when present, otherwise from DefaultMassCal.xml by CalibrationID (see
|
|
482
|
+
:obj:`read_default_masscal_rows`); the per-scan refinement MSMassCal.bin
|
|
483
|
+
adds is sub-ppm.
|
|
484
|
+
|
|
485
|
+
Returns ``(None, None)`` when the directory has no calibration at all - e.g.
|
|
486
|
+
GC-quadrupole centroid data, whose MSPeak.bin already stores m/z directly.
|
|
487
|
+
|
|
488
|
+
Args:
|
|
489
|
+
path (str): Path to the AcqData subdirectory.
|
|
490
|
+
calibration_ids (list): CalibrationID of each scan, in scan order.
|
|
491
|
+
|
|
492
|
+
Returns:
|
|
493
|
+
Tuple ``(calib_vals, calib_flags)``, or ``(None, None)`` if uncalibrated.
|
|
494
|
+
|
|
495
|
+
"""
|
|
496
|
+
masscal_path = os.path.join(path, "MSMassCal.bin")
|
|
497
|
+
if os.path.isfile(masscal_path):
|
|
498
|
+
with open(masscal_path, 'rb') as f:
|
|
499
|
+
f.seek(0x4c) # start offset
|
|
500
|
+
calib_vals = np.ndarray(
|
|
501
|
+
(len(calibration_ids), 10), '<d', f.read(), 0, (84, 8))
|
|
502
|
+
else:
|
|
503
|
+
default_rows = read_default_masscal_rows(
|
|
504
|
+
os.path.join(path, "DefaultMassCal.xml"))
|
|
505
|
+
if not default_rows:
|
|
506
|
+
return None, None
|
|
507
|
+
fallback_row = next(iter(default_rows.values()))
|
|
508
|
+
calib_vals = np.array(
|
|
509
|
+
[default_rows.get(cid, fallback_row) for cid in calibration_ids],
|
|
510
|
+
dtype='<d')
|
|
511
|
+
calib_flags = parse_default_masscal(
|
|
512
|
+
os.path.join(path, "DefaultMassCal.xml"))
|
|
513
|
+
return calib_vals, calib_flags
|
|
514
|
+
|
|
515
|
+
|
|
297
516
|
def calibrate_mz(tof, calib_row, use_flags):
|
|
298
517
|
"""
|
|
299
518
|
Converts a raw time-of-flight axis to calibrated mz values.
|
|
@@ -462,24 +681,69 @@ def parse_scan_xsd(xsd_path):
|
|
|
462
681
|
return complextypes_dict
|
|
463
682
|
|
|
464
683
|
|
|
465
|
-
|
|
684
|
+
# Byte sizes of the MSScan.xsd "simple" types (mirrors the readers in
|
|
685
|
+
# read_type). Used to compute a record's on-disk size without reading it.
|
|
686
|
+
_SIMPLE_TYPE_SIZES = {
|
|
687
|
+
'xs:byte': 1, 'xs:short': 2, 'xs:int': 4,
|
|
688
|
+
'xs:long': 8, 'xs:float': 4, 'xs:double': 8,
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
# A scan may store more than one SpectrumParamValues block; this bounds how many
|
|
692
|
+
# we will consider when inferring the record stride (see read_scan_records).
|
|
693
|
+
_MAX_SPECTRUM_BLOCKS = 8
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
def type_size(complextypes_dict, name):
|
|
697
|
+
"""
|
|
698
|
+
Returns the on-disk byte size of one MSScan.bin record of the given type.
|
|
699
|
+
|
|
700
|
+
Mirrors :obj:`read_complextype`/:obj:`read_type`: each member is counted
|
|
701
|
+
once, so for ScanRecordType this is the size of a record with a single
|
|
702
|
+
SpectrumParamValues block. Lets read_scan_records reason about the record
|
|
703
|
+
stride without reading the file.
|
|
704
|
+
|
|
705
|
+
Args:
|
|
706
|
+
complextypes_dict (dict): Output of :obj:`parse_scan_xsd`.
|
|
707
|
+
name (str): A simple ("xs:int", ...) or complex type name.
|
|
708
|
+
|
|
709
|
+
Returns:
|
|
710
|
+
Size in bytes (int).
|
|
711
|
+
|
|
466
712
|
"""
|
|
467
|
-
|
|
713
|
+
if name in _SIMPLE_TYPE_SIZES:
|
|
714
|
+
return _SIMPLE_TYPE_SIZES[name]
|
|
715
|
+
return sum(type_size(complextypes_dict, subtype)
|
|
716
|
+
for _, subtype in complextypes_dict[name.split(':')[-1]])
|
|
468
717
|
|
|
469
|
-
The records are contiguous and the file ends exactly on a record
|
|
470
|
-
boundary, so reading until EOF yields one record per retention time.
|
|
471
|
-
The length of the returned list is therefore the scan count, which was
|
|
472
|
-
historically read from MSTS.xml. Recovering it here removes that
|
|
473
|
-
dependency, so result folders that omit MSTS.xml (Agilent OpenLab
|
|
474
|
-
.rslt/.sirslt) can be parsed.
|
|
475
718
|
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
719
|
+
def read_scan_records(msscan_path, complextypes_dict, num_records=None):
|
|
720
|
+
"""
|
|
721
|
+
Reads the scan records (ScanRecordType) from MSScan.bin, one per retention
|
|
722
|
+
time.
|
|
723
|
+
|
|
724
|
+
Each record holds the scalar scan fields followed by one or more
|
|
725
|
+
``SpectrumParamValues`` blocks - the schema element is
|
|
726
|
+
``maxOccurs="unbounded"``. A profile-only acquisition writes a single block,
|
|
727
|
+
but an acquisition that also stores centroids (MSPeak.bin) writes a profile
|
|
728
|
+
block *and* a centroid block, making the record larger.
|
|
729
|
+
:obj:`read_complextype` reads only the first block, so reading records
|
|
730
|
+
back-to-back would mis-parse the trailing block(s) as the next record.
|
|
731
|
+
|
|
732
|
+
To stay aligned we read each record at the true record stride and skip to
|
|
733
|
+
the next. The stride is ``scalar + n * block`` for some block count ``n``;
|
|
734
|
+
it is taken from the MSTS.xml scan count when that is consistent, otherwise
|
|
735
|
+
inferred as the value of ``n`` that tiles the record region exactly. The
|
|
736
|
+
first block of each record is the profile spectrum, which is what
|
|
737
|
+
:obj:`parse_msdata` consumes. Only when no stride tiles the region (a record
|
|
738
|
+
truncated mid-write) do we fall back to reading single-block records to EOF.
|
|
479
739
|
|
|
480
740
|
Args:
|
|
481
741
|
msscan_path (str): Path to MSScan.bin.
|
|
482
742
|
complextypes_dict (dict): Output of :obj:`parse_scan_xsd`.
|
|
743
|
+
num_records (int, optional): Scan count from MSTS.xml (:obj:`count_scans`),
|
|
744
|
+
used as a hint. May be None (OpenLab result folders omit MSTS.xml)
|
|
745
|
+
or stale (interrupted acquisitions); the stride is validated against
|
|
746
|
+
the file geometry either way.
|
|
483
747
|
|
|
484
748
|
Returns:
|
|
485
749
|
List of dictionaries, one per retention time, each mapping the
|
|
@@ -487,17 +751,83 @@ def read_scan_records(msscan_path, complextypes_dict):
|
|
|
487
751
|
|
|
488
752
|
"""
|
|
489
753
|
file_size = os.path.getsize(msscan_path)
|
|
754
|
+
block = type_size(complextypes_dict, "SpectrumParamsType")
|
|
755
|
+
scalar = type_size(complextypes_dict, "ScanRecordType") - block
|
|
490
756
|
records = []
|
|
491
757
|
with open(msscan_path, 'rb') as f:
|
|
492
758
|
f.seek(0x58) # offset to the uint32 pointer at the start of records
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
759
|
+
rec_start = struct.unpack('<I', f.read(4))[0]
|
|
760
|
+
body = file_size - rec_start
|
|
761
|
+
|
|
762
|
+
candidates = [scalar + n * block
|
|
763
|
+
for n in range(1, _MAX_SPECTRUM_BLOCKS + 1)]
|
|
764
|
+
stride = None
|
|
765
|
+
# Trust the MSTS scan count when it implies a structurally valid stride.
|
|
766
|
+
if num_records and num_records > 0 and body % num_records == 0:
|
|
767
|
+
hinted = body // num_records
|
|
768
|
+
if hinted in candidates:
|
|
769
|
+
stride = hinted
|
|
770
|
+
# Otherwise infer it: the record size must tile the region exactly. If
|
|
771
|
+
# several block counts do, prefer the scan count nearest MSTS (a stale
|
|
772
|
+
# MSTS is still in the right range), else the fewest blocks.
|
|
773
|
+
if stride is None:
|
|
774
|
+
divisors = [s for s in candidates if body % s == 0]
|
|
775
|
+
if divisors:
|
|
776
|
+
stride = min(divisors, key=lambda s: (
|
|
777
|
+
abs(body // s - num_records) if num_records else s))
|
|
778
|
+
|
|
779
|
+
if stride is not None:
|
|
780
|
+
# Number of SpectrumParamValues blocks per record (e.g. a profile
|
|
781
|
+
# block plus a centroid block). read_complextype consumes the scalar
|
|
782
|
+
# fields and the first block; read any remaining blocks explicitly so
|
|
783
|
+
# callers that need the centroid block (parse_mspeakdata) can see it.
|
|
784
|
+
num_blocks = (stride - scalar) // block
|
|
785
|
+
for i in range(body // stride):
|
|
786
|
+
f.seek(rec_start + i * stride)
|
|
787
|
+
record = read_complextype(
|
|
788
|
+
f, complextypes_dict, "ScanRecordType")
|
|
789
|
+
blocks = [record['SpectrumParamValues']]
|
|
790
|
+
for _ in range(num_blocks - 1):
|
|
791
|
+
blocks.append(read_complextype(
|
|
792
|
+
f, complextypes_dict, "SpectrumParamsType"))
|
|
793
|
+
record['SpectrumParamsBlocks'] = blocks
|
|
794
|
+
records.append(record)
|
|
795
|
+
else:
|
|
796
|
+
# No stride tiles the region (e.g. truncated mid-record): best-effort
|
|
797
|
+
# single-block read to EOF.
|
|
798
|
+
f.seek(rec_start)
|
|
799
|
+
while f.tell() < file_size:
|
|
800
|
+
record = read_complextype(
|
|
801
|
+
f, complextypes_dict, "ScanRecordType")
|
|
802
|
+
record['SpectrumParamsBlocks'] = [record['SpectrumParamValues']]
|
|
803
|
+
records.append(record)
|
|
498
804
|
return records
|
|
499
805
|
|
|
500
806
|
|
|
807
|
+
def count_scans(acqdata_path):
|
|
808
|
+
"""
|
|
809
|
+
Returns the total scan count from MSTS.xml, or None if MSTS.xml is absent.
|
|
810
|
+
|
|
811
|
+
MSTS.xml lists the number of scans per acquisition time segment
|
|
812
|
+
(``<NumOfScans>``); the total is their sum. Agilent OpenLab .rslt/.sirslt
|
|
813
|
+
result folders omit MSTS.xml, in which case :obj:`read_scan_records` infers
|
|
814
|
+
the scan count from the record geometry instead.
|
|
815
|
+
|
|
816
|
+
Args:
|
|
817
|
+
acqdata_path (str): Path to the AcqData subdirectory.
|
|
818
|
+
|
|
819
|
+
Returns:
|
|
820
|
+
Total scan count (int), or None if MSTS.xml does not exist.
|
|
821
|
+
|
|
822
|
+
"""
|
|
823
|
+
msts_path = os.path.join(acqdata_path, "MSTS.xml")
|
|
824
|
+
if not os.path.isfile(msts_path):
|
|
825
|
+
return None
|
|
826
|
+
root = etree.parse(msts_path).getroot()
|
|
827
|
+
counts = [int(el.text) for el in root.iter("NumOfScans") if el.text]
|
|
828
|
+
return sum(counts) if counts else None
|
|
829
|
+
|
|
830
|
+
|
|
501
831
|
def read_complextype(f, complextypes_dict, name):
|
|
502
832
|
"""
|
|
503
833
|
Reads a "complex" type from :obj:`f`. Used only for MSScan.bin.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: rainbow-api
|
|
3
|
-
Version: 1.0
|
|
3
|
+
Version: 1.1.0
|
|
4
4
|
Summary: Read chromatography and mass spectrometry binary files
|
|
5
5
|
Author: Evan Shi and Eugene Kwan
|
|
6
6
|
Author-email: evanyshi@cmu.edu
|
|
@@ -28,7 +28,8 @@ Dynamic: license-file
|
|
|
28
28
|
* `.uv` - UV spectrum (supports incomplete files)
|
|
29
29
|
* `.ch` - UV, FID, CAD, and ELSD channels
|
|
30
30
|
* `.ms` - MS (supports incomplete files)
|
|
31
|
-
* `MSProfile.bin` - HRMS
|
|
31
|
+
* `MSProfile.bin` - HRMS profile spectrum (parse with `hrms=True`)
|
|
32
|
+
* `MSPeak.bin` - centroid (peak-picked) spectrum (parse with `centroid=True`)
|
|
32
33
|
|
|
33
34
|
**Agilent .dx (OpenLab CDS)**
|
|
34
35
|
* `.UV` - DAD spectrum
|
|
@@ -9,6 +9,16 @@ from lxml import etree
|
|
|
9
9
|
|
|
10
10
|
from rainbow.agilent import masshunter
|
|
11
11
|
|
|
12
|
+
# gold/copper have LZF-compressed MSProfile.bin (real TOF data), so decoding
|
|
13
|
+
# them end to end needs python-lzf. The rest of the suite stays lzf-free (the
|
|
14
|
+
# magenta/cyan profile fixtures are run-length encoded on purpose), so the
|
|
15
|
+
# end-to-end gold/copper tests are skipped when python-lzf is not installed.
|
|
16
|
+
try:
|
|
17
|
+
import lzf as _lzf # noqa: F401
|
|
18
|
+
HAVE_LZF = True
|
|
19
|
+
except ImportError:
|
|
20
|
+
HAVE_LZF = False
|
|
21
|
+
|
|
12
22
|
|
|
13
23
|
# The `yellow` fixture is a MassHunter GC-MS acquisition whose AcqData folder
|
|
14
24
|
# contains MSScan.xsd, MSScan.bin, and MSTS.xml (but no MSProfile.bin). It
|
|
@@ -34,6 +44,18 @@ CYAN_D = os.path.join("tests", "inputs", "cyan.D")
|
|
|
34
44
|
# base peak), used to validate the mass calibration against ground truth.
|
|
35
45
|
BIOCONFIRM_APEX_MZ = {MAGENTA_D: 734.4836, CYAN_D: 825.4221}
|
|
36
46
|
|
|
47
|
+
# `gold` and `copper` are trimmed slices of a real Agilent TOF-MS acquisition
|
|
48
|
+
# (10 Hz) whose scans store BOTH a profile block (MSProfile.bin) and a centroid
|
|
49
|
+
# block (MSPeak.bin). Each ScanRecordType therefore carries two
|
|
50
|
+
# SpectrumParamValues blocks - the schema element is maxOccurs="unbounded" -
|
|
51
|
+
# which desynced the old fixed-size reader. Neither fixture has MSMassCal.bin,
|
|
52
|
+
# so they also exercise the DefaultMassCal.xml calibration fallback.
|
|
53
|
+
# - gold: 3 complete scans; MSScan.bin, MSProfile.bin, MSPeak.bin all agree.
|
|
54
|
+
# - copper: MSScan.bin describes 4 scans but MSProfile.bin was truncated after
|
|
55
|
+
# 3 (a deliberately interrupted/incomplete acquisition).
|
|
56
|
+
GOLD_D = os.path.join("tests", "inputs", "gold.D")
|
|
57
|
+
COPPER_D = os.path.join("tests", "inputs", "copper.D")
|
|
58
|
+
|
|
37
59
|
|
|
38
60
|
class TestMasshunter(unittest.TestCase):
|
|
39
61
|
"""
|
|
@@ -117,7 +139,7 @@ class TestMasshunterProfile(unittest.TestCase):
|
|
|
117
139
|
def _assert_decodes(self, directory):
|
|
118
140
|
""" Parses the fixture and checks each scan's decoded maximum
|
|
119
141
|
intensity against the MaxY field stored independently in MSScan.bin. """
|
|
120
|
-
datafiles = masshunter.parse_allfiles(directory)
|
|
142
|
+
datafiles = masshunter.parse_allfiles(directory, hrms=True)
|
|
121
143
|
self.assertEqual(len(datafiles), 1)
|
|
122
144
|
datafile = datafiles[0]
|
|
123
145
|
|
|
@@ -167,7 +189,7 @@ class TestMasshunterProfile(unittest.TestCase):
|
|
|
167
189
|
|
|
168
190
|
def test_mass_calibration_in_range(self):
|
|
169
191
|
""" The calibrated mz axis spans a sensible HRMS range. """
|
|
170
|
-
datafile = masshunter.parse_allfiles(CYAN_D)[0]
|
|
192
|
+
datafile = masshunter.parse_allfiles(CYAN_D, hrms=True)[0]
|
|
171
193
|
self.assertGreater(datafile.ylabels.min(), 100)
|
|
172
194
|
self.assertLess(datafile.ylabels.max(), 5000)
|
|
173
195
|
self.assertTrue((datafile.ylabels[1:] > datafile.ylabels[:-1]).all())
|
|
@@ -238,5 +260,176 @@ class TestMasshunterProfile(unittest.TestCase):
|
|
|
238
260
|
masshunter.decompress_inten_list(memoryview(too_many)[0:], 5)
|
|
239
261
|
|
|
240
262
|
|
|
263
|
+
class TestMasshunterMultiBlock(unittest.TestCase):
|
|
264
|
+
"""
|
|
265
|
+
Tests parsing MassHunter profile data whose scans also store centroids.
|
|
266
|
+
|
|
267
|
+
When an acquisition writes MSPeak.bin alongside MSProfile.bin, each
|
|
268
|
+
ScanRecordType holds a profile block *and* a centroid block. The reader must
|
|
269
|
+
step over the extra block at the true record stride (rather than mis-parsing
|
|
270
|
+
it as the next scan), recover the m/z calibration from DefaultMassCal.xml
|
|
271
|
+
when the per-scan MSMassCal.bin is absent, and keep the complete scans of an
|
|
272
|
+
interrupted acquisition whose trailing MSProfile.bin segments were never
|
|
273
|
+
written.
|
|
274
|
+
"""
|
|
275
|
+
def _acqdata(self, directory):
|
|
276
|
+
return os.path.join(directory, "AcqData")
|
|
277
|
+
|
|
278
|
+
def _complextypes(self, directory):
|
|
279
|
+
return masshunter.parse_scan_xsd(
|
|
280
|
+
os.path.join(self._acqdata(directory), "MSScan.xsd"))
|
|
281
|
+
|
|
282
|
+
def test_type_size_matches_reader(self):
|
|
283
|
+
""" type_size predicts the bytes read_complextype consumes, which is
|
|
284
|
+
what lets read_scan_records reason about the record stride. """
|
|
285
|
+
ctd = self._complextypes(GOLD_D)
|
|
286
|
+
# SpectrumParamsType is the 64-byte block that repeats per scan.
|
|
287
|
+
self.assertEqual(masshunter.type_size(ctd, "SpectrumParamsType"), 64)
|
|
288
|
+
|
|
289
|
+
path = os.path.join(self._acqdata(GOLD_D), "MSScan.bin")
|
|
290
|
+
with open(path, 'rb') as f:
|
|
291
|
+
f.seek(0x58)
|
|
292
|
+
f.seek(struct.unpack('<I', f.read(4))[0])
|
|
293
|
+
start = f.tell()
|
|
294
|
+
masshunter.read_complextype(f, ctd, "ScanRecordType")
|
|
295
|
+
consumed = f.tell() - start
|
|
296
|
+
self.assertEqual(consumed, masshunter.type_size(ctd, "ScanRecordType"))
|
|
297
|
+
|
|
298
|
+
def test_fixtures_lack_msmasscal(self):
|
|
299
|
+
""" These fixtures intentionally have no per-scan MSMassCal.bin, so they
|
|
300
|
+
exercise the DefaultMassCal.xml fallback. """
|
|
301
|
+
for directory in (GOLD_D, COPPER_D):
|
|
302
|
+
self.assertFalse(os.path.exists(
|
|
303
|
+
os.path.join(self._acqdata(directory), "MSMassCal.bin")))
|
|
304
|
+
|
|
305
|
+
def test_two_block_records_read_at_correct_stride(self):
|
|
306
|
+
""" Two-block records are read one per scan, not mis-split into extra
|
|
307
|
+
single-block records, and carry monotonic scan times. """
|
|
308
|
+
acqdata = self._acqdata(GOLD_D)
|
|
309
|
+
records = masshunter.read_scan_records(
|
|
310
|
+
os.path.join(acqdata, "MSScan.bin"),
|
|
311
|
+
self._complextypes(GOLD_D), masshunter.count_scans(acqdata))
|
|
312
|
+
self.assertEqual(len(records), 3)
|
|
313
|
+
times = [r['ScanTime'] for r in records]
|
|
314
|
+
self.assertTrue(all(t2 >= t1 for t1, t2 in zip(times, times[1:])))
|
|
315
|
+
|
|
316
|
+
def test_stride_inferred_without_msts(self):
|
|
317
|
+
""" The two-block stride is recovered from the record geometry alone -
|
|
318
|
+
i.e. parsing still finds all four records if MSTS.xml is unavailable. """
|
|
319
|
+
acqdata = self._acqdata(COPPER_D)
|
|
320
|
+
records = masshunter.read_scan_records(
|
|
321
|
+
os.path.join(acqdata, "MSScan.bin"),
|
|
322
|
+
self._complextypes(COPPER_D), None)
|
|
323
|
+
self.assertEqual(len(records), 4)
|
|
324
|
+
|
|
325
|
+
@unittest.skipUnless(HAVE_LZF, "python-lzf required to decode LZF MSProfile.bin")
|
|
326
|
+
def test_gold_parses_with_default_masscal(self):
|
|
327
|
+
""" gold parses end to end to a profile grid with a sensible TOF m/z
|
|
328
|
+
axis, calibrated from DefaultMassCal.xml (no MSMassCal.bin). """
|
|
329
|
+
datafile = masshunter.parse_allfiles(GOLD_D, hrms=True)[0]
|
|
330
|
+
self.assertEqual(datafile.data.shape[0], 3) # 3 scans
|
|
331
|
+
self.assertEqual(datafile.xlabels.size, 3)
|
|
332
|
+
self.assertEqual(datafile.data.shape[1], datafile.ylabels.size)
|
|
333
|
+
self.assertGreater(datafile.ylabels.min(), 50)
|
|
334
|
+
self.assertLess(datafile.ylabels.max(), 2000)
|
|
335
|
+
self.assertTrue((datafile.ylabels[1:] > datafile.ylabels[:-1]).all())
|
|
336
|
+
|
|
337
|
+
def test_default_masscal_row_matches_msmasscal(self):
|
|
338
|
+
""" A DefaultMassCal.xml row reproduces the per-scan MSMassCal.bin row a
|
|
339
|
+
fixture with both stores, confirming it is a faithful stand-in. """
|
|
340
|
+
acqdata = os.path.join(MAGENTA_D, "AcqData")
|
|
341
|
+
rows = masshunter.read_default_masscal_rows(
|
|
342
|
+
os.path.join(acqdata, "DefaultMassCal.xml"))
|
|
343
|
+
records = masshunter.read_scan_records(
|
|
344
|
+
os.path.join(acqdata, "MSScan.bin"),
|
|
345
|
+
masshunter.parse_scan_xsd(os.path.join(acqdata, "MSScan.xsd")))
|
|
346
|
+
with open(os.path.join(acqdata, "MSMassCal.bin"), 'rb') as f:
|
|
347
|
+
per_scan = np.ndarray(
|
|
348
|
+
(len(records), 10), '<d', f.read()[0x4c:], 0, (84, 8))
|
|
349
|
+
calib_id = records[0].get('CalibrationID')
|
|
350
|
+
# The per-scan refinement is sub-ppm; everything else matches exactly.
|
|
351
|
+
np.testing.assert_allclose(
|
|
352
|
+
rows[calib_id], per_scan[0], rtol=0, atol=1e-6)
|
|
353
|
+
|
|
354
|
+
@unittest.skipUnless(HAVE_LZF, "python-lzf required to decode LZF MSProfile.bin")
|
|
355
|
+
def test_incomplete_acquisition_keeps_complete_scans(self):
|
|
356
|
+
""" copper's MSScan.bin describes four scans but MSProfile.bin holds
|
|
357
|
+
only three; parsing keeps the three complete scans rather than failing
|
|
358
|
+
on the truncated segment. """
|
|
359
|
+
datafile = masshunter.parse_allfiles(COPPER_D, hrms=True)[0]
|
|
360
|
+
self.assertEqual(datafile.data.shape[0], 3)
|
|
361
|
+
self.assertEqual(datafile.xlabels.size, 3)
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
class TestMasshunterCentroid(unittest.TestCase):
|
|
365
|
+
"""
|
|
366
|
+
Tests parsing centroided MS data from MSPeak.bin - the opt-in counterpart to
|
|
367
|
+
the MSProfile.bin profile spectrum (centroid=True).
|
|
368
|
+
|
|
369
|
+
MSPeak.bin is uncompressed, so these run without python-lzf. They cover a
|
|
370
|
+
GC-quadrupole acquisition whose MSPeak.bin already stores m/z (yellow), a
|
|
371
|
+
Q-TOF acquisition whose centroid axis is time-of-flight and is calibrated
|
|
372
|
+
like the profile (gold), the centroid=True flag, and the discoverability
|
|
373
|
+
metadata note.
|
|
374
|
+
"""
|
|
375
|
+
def test_select_centroid_block(self):
|
|
376
|
+
""" On a scan that stores both, the centroid (fixed-width peak) block is
|
|
377
|
+
chosen over the compressed profile block. """
|
|
378
|
+
acqdata = os.path.join(GOLD_D, "AcqData")
|
|
379
|
+
complextypes = masshunter.parse_scan_xsd(
|
|
380
|
+
os.path.join(acqdata, "MSScan.xsd"))
|
|
381
|
+
records = masshunter.read_scan_records(
|
|
382
|
+
os.path.join(acqdata, "MSScan.bin"), complextypes,
|
|
383
|
+
masshunter.count_scans(acqdata))
|
|
384
|
+
blocks = records[0]['SpectrumParamsBlocks']
|
|
385
|
+
self.assertEqual(len(blocks), 2) # profile block + centroid block
|
|
386
|
+
chosen = masshunter._select_centroid_block(blocks)
|
|
387
|
+
self.assertIsNotNone(chosen)
|
|
388
|
+
self.assertIn(chosen['ByteCount'] // chosen['PointCount'], (8, 12, 16))
|
|
389
|
+
|
|
390
|
+
def test_yellow_centroid_axis_matches_data_ms(self):
|
|
391
|
+
""" The GC-quadrupole MSPeak.bin m/z axis (already calibrated) matches
|
|
392
|
+
the independent data.ms axis for the same acquisition. """
|
|
393
|
+
centroid = masshunter.parse_mspeakdata(YELLOW_ACQDATA)
|
|
394
|
+
self.assertEqual(centroid.name, "MSPeak.bin")
|
|
395
|
+
self.assertEqual(centroid.detector, "MS")
|
|
396
|
+
self.assertEqual(centroid.data.shape[0], centroid.xlabels.size)
|
|
397
|
+
self.assertEqual(centroid.data.shape[1], centroid.ylabels.size)
|
|
398
|
+
self.assertTrue((centroid.ylabels[1:] > centroid.ylabels[:-1]).all())
|
|
399
|
+
|
|
400
|
+
import rainbow as rb
|
|
401
|
+
data_ms = rb.read("tests/inputs/yellow.D").get_file("data.ms")
|
|
402
|
+
np.testing.assert_array_equal(centroid.ylabels, data_ms.ylabels)
|
|
403
|
+
|
|
404
|
+
def test_gold_centroid_is_calibrated(self):
|
|
405
|
+
""" A TOF centroid axis is stored as time-of-flight; parsing calibrates
|
|
406
|
+
it to real m/z (within the profile's m/z range, not raw flight time). """
|
|
407
|
+
centroid = masshunter.parse_mspeakdata(os.path.join(GOLD_D, "AcqData"))
|
|
408
|
+
self.assertGreater(centroid.ylabels.min(), 50)
|
|
409
|
+
self.assertLess(centroid.ylabels.max(), 1100)
|
|
410
|
+
self.assertTrue((centroid.ylabels[1:] > centroid.ylabels[:-1]).all())
|
|
411
|
+
|
|
412
|
+
def test_centroid_flag_end_to_end(self):
|
|
413
|
+
""" centroid=True adds the MSPeak.bin DataFile; by default it is not
|
|
414
|
+
parsed but a metadata note advertises that it is available. """
|
|
415
|
+
import rainbow as rb
|
|
416
|
+
|
|
417
|
+
default = rb.read("tests/inputs/yellow.D")
|
|
418
|
+
self.assertNotIn("MSPeak.bin", [df.name for df in default.datafiles])
|
|
419
|
+
self.assertTrue(default.metadata.get("centroid_available"))
|
|
420
|
+
|
|
421
|
+
with_centroid = rb.read("tests/inputs/yellow.D", centroid=True)
|
|
422
|
+
self.assertIn("MSPeak.bin", [df.name for df in with_centroid.datafiles])
|
|
423
|
+
# data.ms is untouched - centroid is additive, not a replacement.
|
|
424
|
+
self.assertIn("data.ms", [df.name for df in with_centroid.datafiles])
|
|
425
|
+
self.assertNotIn("centroid_available", with_centroid.metadata)
|
|
426
|
+
|
|
427
|
+
def test_centroid_truncation_is_graceful(self):
|
|
428
|
+
""" A truncated MSPeak.bin segment is skipped rather than crashing. """
|
|
429
|
+
centroid = masshunter.parse_mspeakdata(os.path.join(COPPER_D, "AcqData"))
|
|
430
|
+
self.assertEqual(centroid.name, "MSPeak.bin")
|
|
431
|
+
self.assertGreaterEqual(centroid.data.shape[0], 3)
|
|
432
|
+
|
|
433
|
+
|
|
241
434
|
if __name__ == '__main__':
|
|
242
435
|
unittest.main()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|