rainbow-api 1.3.1__tar.gz → 1.4.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.
Files changed (34) hide show
  1. {rainbow_api-1.3.1/rainbow_api.egg-info → rainbow_api-1.4.0}/PKG-INFO +1 -1
  2. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/pyproject.toml +1 -1
  3. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/rainbow/agilent/__init__.py +21 -11
  4. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/rainbow/agilent/masshunter.py +595 -4
  5. {rainbow_api-1.3.1 → rainbow_api-1.4.0/rainbow_api.egg-info}/PKG-INFO +1 -1
  6. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/tests/test_masshunter.py +479 -0
  7. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/COPYING +0 -0
  8. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/COPYING.LESSER +0 -0
  9. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/MANIFEST.in +0 -0
  10. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/README.md +0 -0
  11. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/rainbow/__init__.py +0 -0
  12. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/rainbow/_binning.py +0 -0
  13. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/rainbow/agilent/_chdelta.pyx +0 -0
  14. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/rainbow/agilent/_msprofile.pyx +0 -0
  15. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/rainbow/agilent/_uvdelta.pyx +0 -0
  16. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/rainbow/agilent/chemstation.py +0 -0
  17. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/rainbow/agilent/openlab.py +0 -0
  18. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/rainbow/datadirectory.py +0 -0
  19. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/rainbow/datafile.py +0 -0
  20. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/rainbow/waters/__init__.py +0 -0
  21. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/rainbow/waters/masslynx.py +0 -0
  22. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/rainbow_api.egg-info/SOURCES.txt +0 -0
  23. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/rainbow_api.egg-info/dependency_links.txt +0 -0
  24. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/rainbow_api.egg-info/requires.txt +0 -0
  25. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/rainbow_api.egg-info/top_level.txt +0 -0
  26. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/setup.cfg +0 -0
  27. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/setup.py +0 -0
  28. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/tests/test_accelerator.py +0 -0
  29. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/tests/test_agilent.py +0 -0
  30. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/tests/test_binning.py +0 -0
  31. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/tests/test_datadirectory.py +0 -0
  32. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/tests/test_datafile.py +0 -0
  33. {rainbow_api-1.3.1 → rainbow_api-1.4.0}/tests/test_read.py +0 -0
  34. {rainbow_api-1.3.1 → rainbow_api-1.4.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.3.1
3
+ Version: 1.4.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
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "rainbow-api"
7
- version = "1.3.1"
7
+ version = "1.4.0"
8
8
  description = "Read chromatography and mass spectrometry binary files"
9
9
  readme = "README.md"
10
10
  license = {text = "COPYING.LESSER"}
@@ -16,7 +16,8 @@ def read(path, precision='auto', hrms=False, requested_files=None,
16
16
  hrms (bool, optional): Flag for parsing the MassHunter profile
17
17
  spectrum (MSProfile.bin).
18
18
  requested_files (list, optional): List of filenames to parse.
19
- telemetry (bool, optional): Flag for parsing .dx telemetry traces.
19
+ telemetry (bool, optional): Flag for parsing instrument telemetry
20
+ traces, in a .dx archive or alongside a MassHunter DAD's signals.
20
21
  centroid (bool, optional): Flag for parsing the MassHunter centroid
21
22
  spectrum (MSPeak.bin).
22
23
  bin_width (float, optional): Shared-grid bin width in daltons for the
@@ -35,13 +36,13 @@ def read(path, precision='auto', hrms=False, requested_files=None,
35
36
 
36
37
  datafiles = []
37
38
  datafiles.extend(chemstation.parse_allfiles(path, precision, requested_files))
38
- if hrms or centroid:
39
- try:
40
- from rainbow.agilent import masshunter
41
- datafiles.extend(masshunter.parse_allfiles(
42
- path, precision, hrms, centroid, bin_width))
43
- except ModuleNotFoundError:
44
- raise ModuleNotFoundError("You must install python-lzf to parse masshunter files.")
39
+ # MassHunter is always consulted, not only under the MS flags: a .d may also
40
+ # hold DAD data, which is parsed unconditionally the way the Chemstation UV
41
+ # formats are. The MS parsing inside stays gated on hrms/centroid.
42
+ from rainbow.agilent import masshunter
43
+ datafiles.extend(masshunter.parse_allfiles(
44
+ path, precision, hrms, centroid, bin_width, telemetry,
45
+ requested_files))
45
46
 
46
47
  metadata = chemstation.parse_metadata(path, datafiles)
47
48
 
@@ -86,17 +87,26 @@ def read_metadata(path):
86
87
  # them (hrms / centroid), without parsing the binaries.
87
88
  acqdata_path = os.path.join(path, "AcqData")
88
89
  if os.path.isdir(acqdata_path):
90
+ from rainbow.agilent import masshunter
89
91
  acqdata_files = set(os.listdir(acqdata_path))
92
+ mh_datafiles = []
93
+ # A diode-array detector writes its chromatograms and spectra here too,
94
+ # and read() returns those with no flag needed - so a run holding them
95
+ # must not be reported as MS-only.
96
+ for name in sorted(acqdata_files):
97
+ stem, ext = os.path.splitext(name)
98
+ if (ext.lower() in ('.cg', '.sp')
99
+ and stem[:3].upper() in masshunter._DAD_DEVICES):
100
+ mh_datafiles.append(name)
90
101
  if {"MSScan.xsd", "MSScan.bin"} <= acqdata_files:
91
- mh_datafiles = []
92
102
  if "MSProfile.bin" in acqdata_files:
93
103
  mh_datafiles.append("MSProfile.bin")
94
104
  metadata['hrms_available'] = True
95
105
  if "MSPeak.bin" in acqdata_files:
96
106
  mh_datafiles.append("MSPeak.bin")
97
107
  metadata['centroid_available'] = True
98
- if mh_datafiles:
99
- return {'datafiles': mh_datafiles, 'metadata': metadata}
108
+ if mh_datafiles:
109
+ return {'datafiles': mh_datafiles, 'metadata': metadata}
100
110
 
101
111
  if len(metadata) == 1:
102
112
  datadir = read(path)
@@ -120,15 +120,18 @@ MAIN PARSING METHOD
120
120
  """
121
121
 
122
122
  def parse_allfiles(path, precision='auto', hrms=False, centroid=False,
123
- bin_width=None):
123
+ bin_width=None, telemetry=False, requested_files=None):
124
124
  """
125
- Finds and parses Agilent Masshunter MS data files.
125
+ Finds and parses Agilent Masshunter data files.
126
126
 
127
127
  MassHunter stores a scan's spectrum as a dense profile trace
128
128
  (``MSProfile.bin``) and/or a peak-picked centroid list (``MSPeak.bin``).
129
129
  Both are opt-in: ``hrms`` parses the profile and ``centroid`` parses the
130
130
  centroids (see :obj:`parse_msdata` and :obj:`parse_mspeakdata`). With
131
- neither flag set nothing is parsed here.
131
+ neither flag set no MS data is parsed here.
132
+
133
+ A DAD's data (see :obj:`parse_dadfiles`) is parsed unconditionally, as the
134
+ Chemstation UV formats are - it is uncompressed and cheap to read.
132
135
 
133
136
  Args:
134
137
  path (str): Path to the Agilent .D directory.
@@ -141,6 +144,9 @@ def parse_allfiles(path, precision='auto', hrms=False, centroid=False,
141
144
  the per-scan representation (:class:`ProfileDataFile`); pass a width
142
145
  in daltons to project onto the shared m/z grid; see
143
146
  :obj:`parse_msdata`.
147
+ telemetry (bool, optional): Parse the DAD's non-absorbance traces.
148
+ requested_files (list, optional): Lowercased filenames to restrict the
149
+ DAD parse to. The MS files are selected by their flags instead.
144
150
 
145
151
  Returns:
146
152
  List containing a DataFile for each parsed file.
@@ -153,6 +159,8 @@ def parse_allfiles(path, precision='auto', hrms=False, centroid=False,
153
159
  return datafiles
154
160
 
155
161
  acqdata_files = set(os.listdir(acqdata_path))
162
+ datafiles.extend(parse_dadfiles(
163
+ acqdata_path, telemetry, requested_files, acqdata_files))
156
164
  # MSTS.xml is no longer required: the scan count is recovered from the
157
165
  # MSScan.bin record geometry (see read_scan_records). This lets us parse
158
166
  # Agilent OpenLab .rslt/.sirslt result folders, which omit MSTS.xml.
@@ -180,7 +188,590 @@ def parse_allfiles(path, precision='auto', hrms=False, centroid=False,
180
188
 
181
189
 
182
190
  """
183
- MS PARSING METHODS
191
+ DAD PARSING METHODS
192
+
193
+ """
194
+
195
+ # The DAD files of a MassHunter .d are a family of four that share a 68-byte
196
+ # header whose only populated field is a little-endian u16 type tag. They pair
197
+ # up as descriptor/data: the descriptor indexes the data file, giving each
198
+ # record's byte offset and its length - in bytes for a .sd, in points for a
199
+ # .cd - so neither data file has to be walked with an assumed stride.
200
+ #
201
+ # DAD1.cd (0x0200) -> describes the signals in DAD1.cg
202
+ # DAD1.cg (0x0201) -> one chromatogram per signal
203
+ # DAD1.sd (0x0202) -> describes the spectra in DAD1.sp
204
+ # DAD1.sp (0x0203) -> the spectra themselves
205
+ #
206
+ # A tag names the kind of file, not the detector that wrote it: the pumps and
207
+ # column compartments write .cd/.cg pairs under the same two tags, which is why
208
+ # the DAD files are found by device name rather than by tag. Only the .sd/.sp
209
+ # spectra are unique to a detector.
210
+ #
211
+ # Everything is little-endian, uncompressed float64 - unlike the Chemstation
212
+ # .uv/.ch formats, there is no delta encoding and no scaling factor.
213
+ _DAD_HEADER_SIZE = 68
214
+ _DAD_TAGS = {'.cd': 0x0200, '.cg': 0x0201, '.sd': 0x0202, '.sp': 0x0203}
215
+
216
+ # Both descriptors carry their own header past the shared one, but lay it out
217
+ # differently: a .sd gives where its fixed width records begin and then how
218
+ # many there are, while a .cd gives its count first and starts its records
219
+ # directly afterwards.
220
+ _SD_DATA_OFFSET = 0x4c # u32: byte offset of the first spectrum record
221
+ _SD_NUM_RECORDS = 0x50 # u32
222
+ _CD_NUM_SIGNALS = 0x4c # u32
223
+ _CD_DATA_OFFSET = 0x50
224
+
225
+ # A .sd spectrum record: 80 bytes, of which we read these fields.
226
+ _SD_RECORD_SIZE = 80
227
+ _SD_RETENTION_TIME = 4 # f64, minutes
228
+ _SD_SP_OFFSET = 32 # u32, byte offset of the spectrum in .sp
229
+ _SD_SP_NBYTES = 40 # u32, its length in bytes
230
+ _SD_NUM_WAVELENGTHS = 44 # u32
231
+ _SD_WAVELENGTH_START = 48 # f64, nm
232
+ _SD_WAVELENGTH_END = 56 # f64, nm
233
+
234
+ # Both data files prefix a record with its own axis before the values: a .sp
235
+ # spectrum with its wavelengths, a .cg chromatogram with its retention times.
236
+ _AXIS_PREFIX_SIZE = 16 # f64 start + f64 step
237
+
238
+ # Devices that produce absorbance signals, matching the Chemstation naming.
239
+ _DAD_DEVICES = ('DAD', 'MWD', 'VWD')
240
+
241
+
242
+ def parse_dadfiles(path, telemetry=False, requested_files=None, listing=None):
243
+ """
244
+ Finds and parses the Agilent Masshunter DAD files of a .d directory.
245
+
246
+ A MassHunter DAD writes its data as a ``.cd``/``.cg`` pair holding the
247
+ wavelength chromatograms and a ``.sd``/``.sp`` pair holding the spectra -
248
+ the same two views the Chemstation format splits into ``.ch`` and ``.uv``
249
+ files. The spectra are returned as a single multi-wavelength DataFile and
250
+ each chromatogram as its own, named for the signal it carries
251
+ (``DAD1A.cg``, ``DAD1B.cg``, ...), carrying the signal letter Chemstation
252
+ would put in the filename since here they share one file.
253
+
254
+ Args:
255
+ path (str): Path to the AcqData subdirectory.
256
+ telemetry (bool, optional): Also parse the non-absorbance traces the
257
+ detector records alongside its signals (lamp voltage, board
258
+ temperature). Off by default, matching ``.dx`` telemetry.
259
+ requested_files (list, optional): Lowercased filenames to restrict the
260
+ parse to, as for the Chemstation parser. Both the file on disk
261
+ (``dad1.cg``) and a per-signal name (``dad1a.cg``) select.
262
+ listing (iterable, optional): The contents of ``path``, when the caller
263
+ has already listed it. Saves re-listing the directory.
264
+
265
+ Returns:
266
+ List containing a DataFile for each parsed signal and spectrum.
267
+
268
+ """
269
+ datafiles = []
270
+ if listing is None:
271
+ if not os.path.isdir(path):
272
+ return datafiles
273
+ listing = os.listdir(path)
274
+
275
+ # The siblings of a .cd share its casing, which matters on a case-sensitive
276
+ # filesystem: an acquisition written as DAD1.CD carries DAD1.CG beside it.
277
+ # Build this in sorted order, so that a directory holding names differing
278
+ # only by case resolves the same way every time.
279
+ by_name = {name.lower(): name for name in sorted(listing)}
280
+
281
+ def sibling(stem, ext):
282
+ want = (stem + ext).lower()
283
+ return os.path.join(path, by_name.get(want, stem + ext))
284
+
285
+ for name in sorted(listing):
286
+ stem, ext = os.path.splitext(name)
287
+ if ext.lower() != '.cd' or stem[:3].upper() not in _DAD_DEVICES:
288
+ continue
289
+
290
+ chrom_path = sibling(stem, '.cg')
291
+ if os.path.isfile(chrom_path) and _dad_requested(
292
+ requested_files, stem, '.cg'):
293
+ signals = read_dad_signals(
294
+ os.path.join(path, name), os.path.getsize(chrom_path))
295
+ if signals:
296
+ datafiles.extend(parse_dadchroms(
297
+ chrom_path, signals, telemetry, requested_files))
298
+
299
+ spectra_path = sibling(stem, '.sp')
300
+ desc_path = sibling(stem, '.sd')
301
+ # The spectra are one file under one name, so unlike the chromatograms
302
+ # they match a request exactly - a name that is merely similar is not a
303
+ # file anyone asked for.
304
+ if (os.path.isfile(spectra_path) and os.path.isfile(desc_path)
305
+ and (not requested_files
306
+ or os.path.basename(spectra_path).lower() in requested_files)):
307
+ spectra = parse_dadspectra(spectra_path, desc_path)
308
+ if spectra is not None:
309
+ datafiles.append(spectra)
310
+
311
+ return datafiles
312
+
313
+
314
+ def _dad_requested(requested_files, stem, ext):
315
+ """
316
+ Returns True if any requested filename could be served by ``stem + ext``.
317
+
318
+ The chromatograms all live in one .cg but are returned under per-signal
319
+ names, so a request for either form has to keep that file in play; which
320
+ signals it yields is settled in :obj:`parse_dadchroms`.
321
+
322
+ """
323
+ if not requested_files:
324
+ return True
325
+ return any(name.endswith(ext) and name.startswith(stem.lower())
326
+ for name in requested_files)
327
+
328
+
329
+ def read_dad_header(f, ext):
330
+ """
331
+ Validates a DAD file's header and returns True if it matches ``ext``.
332
+
333
+ Args:
334
+ f (_io.BufferedReader): File opened in 'rb' mode.
335
+ ext (str): Extension whose type tag is expected, e.g. '.sp'.
336
+
337
+ Returns:
338
+ True if the file carries the expected type tag, otherwise False.
339
+
340
+ """
341
+ f.seek(0)
342
+ head = f.read(_DAD_HEADER_SIZE)
343
+ if len(head) < _DAD_HEADER_SIZE:
344
+ return False
345
+ return struct.unpack_from('<H', head, 0)[0] == _DAD_TAGS[ext]
346
+
347
+
348
+ def read_dad_signals(path, data_size=None):
349
+ """
350
+ Parses an Agilent Masshunter DAD descriptor (.cd) file.
351
+
352
+ The descriptor holds one record per signal, each a run of length-prefixed
353
+ strings (the signal's letter, its description, and its unit) interleaved
354
+ with the fields locating that signal's data in the matching ``.cg``. A
355
+ record is variable width because the strings are, so it is walked rather
356
+ than indexed.
357
+
358
+ Args:
359
+ path (str): Path to the .cd file.
360
+ data_size (int): Size of the matching .cg in bytes, if known. Every
361
+ record indexes data inside that file, so giving its size lets a
362
+ coincidental byte pattern be told apart from a real record.
363
+
364
+ Returns:
365
+ List of dicts with the keys ``letter``, ``description``, ``unit``,
366
+ ``offset`` and ``num_times``; empty if the file cannot be parsed.
367
+
368
+ """
369
+ with open(path, 'rb') as f:
370
+ if not read_dad_header(f, '.cd'):
371
+ return []
372
+ f.seek(0)
373
+ raw = f.read()
374
+
375
+ if len(raw) < _CD_DATA_OFFSET + 4:
376
+ warnings.warn(
377
+ f"{os.path.basename(path)} is too short to hold a signal "
378
+ f"descriptor; no signals could be read.")
379
+ return []
380
+ num_signals = struct.unpack_from('<I', raw, _CD_NUM_SIGNALS)[0]
381
+
382
+ signals = []
383
+ pos = _CD_DATA_OFFSET
384
+ for _ in range(num_signals):
385
+ # Each record is the signal's letter and description followed by the
386
+ # fields locating its data: what kind of signal it is, the byte offset,
387
+ # an always-zero word, and the number of points.
388
+ header = _read_record_header(raw, pos, data_size)
389
+ if header is None:
390
+ break
391
+ letter, description, offset, num_times, pos = header
392
+ # The unit follows, but not adjacently - fields we have no use for sit
393
+ # in between - so scan ahead to the next record and take the unit from
394
+ # what lies before it.
395
+ end = _find_next_record(raw, pos, data_size) or len(raw)
396
+ signals.append({
397
+ 'letter': letter,
398
+ 'description': description.strip(),
399
+ 'unit': _find_unit(raw, pos, end),
400
+ 'offset': offset,
401
+ 'num_times': num_times,
402
+ })
403
+ pos = end
404
+
405
+ if len(signals) != num_signals:
406
+ # Losing a signal loses a whole trace, so say so rather than quietly
407
+ # returning a short list. An unreadable record is skipped over rather
408
+ # than ending the walk, so name what survived: the gap can fall
409
+ # anywhere, not only at the end.
410
+ read = ', '.join(signal['letter'] for signal in signals) or 'none'
411
+ warnings.warn(
412
+ f"{os.path.basename(path)} describes {num_signals} signals but only "
413
+ f"{len(signals)} could be read ({read}); the others are missing "
414
+ f"from the parse.")
415
+ return signals
416
+
417
+
418
+ def parse_dadchroms(path, signals, telemetry=False, requested_files=None):
419
+ """
420
+ Parses the chromatograms of an Agilent Masshunter DAD (.cg) file.
421
+
422
+ Each signal is stored as its own contiguous block: the retention time of
423
+ the first point, the time step, then one float64 absorbance per point. The
424
+ block's offset and length come from the ``.cd`` descriptor, so signals
425
+ recorded at different rates - the detector's telemetry traces are sampled
426
+ several times more often than its absorbance signals - are read correctly.
427
+
428
+ A signal's description gives the band it integrates and the band subtracted
429
+ from it, in the Chemstation form ``Sig=254.0,4.0 Ref=360.0,100.0`` (254 nm
430
+ over 4 nm, referenced to 360 nm over 100 nm). These chromatograms are
431
+ therefore not slices of the ``.sp`` spectra: they are band averages, minus
432
+ a reference, where the spectra are raw. They are stored by the instrument
433
+ rather than recomputed here.
434
+
435
+ Args:
436
+ path (str): Path to the .cg file.
437
+ signals (list): Signal records from :obj:`read_dad_signals`.
438
+ telemetry (bool, optional): Include the non-absorbance traces.
439
+ requested_files (list, optional): Lowercased filenames to restrict the
440
+ parse to; a signal is kept if its own name (``dad1a.cg``) or the
441
+ file it lives in (``dad1.cg``) was asked for.
442
+
443
+ Returns:
444
+ List with a DataFile per signal, in the order they are described.
445
+
446
+ """
447
+ datafiles = []
448
+ stem = os.path.splitext(os.path.basename(path))[0]
449
+ filename = os.path.basename(path).lower()
450
+
451
+ with open(path, 'rb') as f:
452
+ if not read_dad_header(f, '.cg'):
453
+ return datafiles
454
+ f.seek(0)
455
+ raw = f.read()
456
+
457
+ for signal in signals:
458
+ # An absorbance signal is named the Chemstation way ("Sig=254.0,..."),
459
+ # and carries mAU; the detector's telemetry traces have neither.
460
+ is_absorbance = (signal['unit'].lower() == 'mau'
461
+ or signal['description'].startswith('Sig='))
462
+ signal_name = f"{stem}{signal['letter']}.cg".lower()
463
+ requested = bool(requested_files) and signal_name in requested_files
464
+ # Naming a telemetry trace explicitly parses it whether or not the flag
465
+ # is set, as it does for .dx telemetry.
466
+ if not is_absorbance and not telemetry and not requested:
467
+ continue
468
+ if requested_files and not (requested or filename in requested_files):
469
+ continue
470
+
471
+ num_times = signal['num_times']
472
+ start = signal['offset']
473
+ end = start + _AXIS_PREFIX_SIZE + num_times * 8
474
+ if start < _DAD_HEADER_SIZE or end > len(raw):
475
+ warnings.warn(
476
+ f"Skipping DAD signal {signal['letter']} of {os.path.basename(path)}: "
477
+ f"its descriptor points outside the file.")
478
+ continue
479
+
480
+ first_time, time_step = struct.unpack_from('<dd', raw, start)
481
+ values = np.frombuffer(
482
+ raw, dtype='<f8', count=num_times, offset=start + _AXIS_PREFIX_SIZE)
483
+ times = first_time + time_step * np.arange(num_times)
484
+
485
+ # Give the trace the signal letter Chemstation would put in the
486
+ # filename (DAD1A.ch), keeping this format's own extension: here all
487
+ # the signals share one file, so the letter is what tells them apart.
488
+ name = os.path.join(os.path.dirname(path), f"{stem}{signal['letter']}.cg")
489
+ datafiles.append(DataFile(
490
+ name,
491
+ 'UV' if is_absorbance else None,
492
+ times,
493
+ np.array([_signal_wavelength(signal['description'])]),
494
+ values.reshape(-1, 1).copy(),
495
+ {'signal': signal['description'], 'unit': signal['unit']}))
496
+
497
+ return datafiles
498
+
499
+
500
+ def parse_dadspectra(path, desc_path):
501
+ """
502
+ Parses the spectra of an Agilent Masshunter DAD (.sp) file.
503
+
504
+ Every spectrum is stored as its own wavelength axis (a start and a step)
505
+ followed by one float64 absorbance per wavelength. The ``.sd`` descriptor
506
+ supplies each spectrum's retention time and its offset and length in the
507
+ ``.sp``, so the spectra are located rather than assumed to be evenly
508
+ spaced.
509
+
510
+ Spectra sharing one wavelength axis - the usual case - are returned as a
511
+ single (retention time x wavelength) DataFile. If the axis changes during
512
+ the run the spectra cannot form one grid, and None is returned with a
513
+ warning rather than silently reshaping mismatched rows.
514
+
515
+ Args:
516
+ path (str): Path to the .sp file.
517
+ desc_path (str): Path to the matching .sd file.
518
+
519
+ Returns:
520
+ DataFile with the DAD spectra, or None if they cannot be parsed.
521
+
522
+ """
523
+ with open(desc_path, 'rb') as f:
524
+ if not read_dad_header(f, '.sd'):
525
+ return None
526
+ f.seek(0)
527
+ desc = f.read()
528
+
529
+ if len(desc) < _SD_NUM_RECORDS + 4:
530
+ return None
531
+ # The descriptor states where its records begin and how many there are; it
532
+ # carries its own header past the shared one, so neither can be assumed.
533
+ data_offset = struct.unpack_from('<I', desc, _SD_DATA_OFFSET)[0]
534
+ num_times = struct.unpack_from('<I', desc, _SD_NUM_RECORDS)[0]
535
+ if (num_times == 0 or data_offset < _DAD_HEADER_SIZE
536
+ or data_offset + num_times * _SD_RECORD_SIZE > len(desc)):
537
+ warnings.warn(
538
+ f"Cannot parse {os.path.basename(desc_path)}: it describes "
539
+ f"{num_times} spectra from offset {data_offset}, which its size "
540
+ f"does not accommodate.")
541
+ return None
542
+ records = np.frombuffer(
543
+ desc, dtype=np.uint8, count=num_times * _SD_RECORD_SIZE,
544
+ offset=data_offset
545
+ ).reshape(num_times, _SD_RECORD_SIZE)
546
+
547
+ def field(offset, dtype):
548
+ width = np.dtype(dtype).itemsize
549
+ return records[:, offset:offset + width].copy().view(dtype).ravel()
550
+
551
+ times = field(_SD_RETENTION_TIME, '<f8')
552
+ offsets = field(_SD_SP_OFFSET, '<u4')
553
+ num_wavelengths = field(_SD_NUM_WAVELENGTHS, '<u4')
554
+ starts = field(_SD_WAVELENGTH_START, '<f8')
555
+ ends = field(_SD_WAVELENGTH_END, '<f8')
556
+
557
+ # One shared wavelength axis is what makes a dense 2D array meaningful.
558
+ if not (np.all(num_wavelengths == num_wavelengths[0])
559
+ and np.all(starts == starts[0]) and np.all(ends == ends[0])):
560
+ warnings.warn(
561
+ f"Cannot parse {os.path.basename(path)}: its wavelength axis changes "
562
+ f"during the run, so the spectra do not share a grid.")
563
+ return None
564
+
565
+ count = int(num_wavelengths[0])
566
+ if count <= 0:
567
+ warnings.warn(
568
+ f"Cannot parse {os.path.basename(path)}: its descriptor reports "
569
+ f"{count} wavelengths per spectrum.")
570
+ return None
571
+
572
+ with open(path, 'rb') as f:
573
+ if not read_dad_header(f, '.sp'):
574
+ return None
575
+ f.seek(0)
576
+ raw = f.read()
577
+
578
+ stride = _AXIS_PREFIX_SIZE + count * 8
579
+ # The descriptor states each spectrum's length too, so the stride derived
580
+ # from the wavelength count can be checked rather than assumed. A record
581
+ # may be longer than the values it holds, which only means it is padded or
582
+ # carries a trailer; one that is shorter would be read past its end.
583
+ nbytes = field(_SD_SP_NBYTES, '<u4')
584
+ if np.any(nbytes < stride):
585
+ warnings.warn(
586
+ f"Cannot parse {os.path.basename(path)}: its descriptor gives "
587
+ f"spectra shorter than {count} wavelengths ({stride} bytes).")
588
+ return None
589
+
590
+ spectrum_offsets = offsets.astype(np.int64)
591
+ if (spectrum_offsets.min() < _DAD_HEADER_SIZE
592
+ or spectrum_offsets.max() + stride > len(raw)):
593
+ warnings.warn(
594
+ f"Cannot parse {os.path.basename(path)}: its descriptor points to "
595
+ f"spectra outside the file.")
596
+ return None
597
+
598
+ # The spectra are contiguous and equally sized in every file seen so far,
599
+ # which lets the whole block be viewed at once instead of read per scan.
600
+ contiguous = np.array_equal(
601
+ spectrum_offsets, spectrum_offsets[0] + stride * np.arange(num_times))
602
+ prefix_size = _AXIS_PREFIX_SIZE // 8
603
+ if contiguous:
604
+ block = np.frombuffer(
605
+ raw, dtype='<f8', count=num_times * stride // 8,
606
+ offset=spectrum_offsets[0]
607
+ ).reshape(num_times, stride // 8)
608
+ axes = block[:, :prefix_size]
609
+ data = block[:, prefix_size:]
610
+ else:
611
+ axes = np.empty((num_times, prefix_size), dtype=np.float64)
612
+ data = np.empty((num_times, count), dtype=np.float64)
613
+ for i, start in enumerate(spectrum_offsets):
614
+ record = np.frombuffer(
615
+ raw, dtype='<f8', count=prefix_size + count, offset=start)
616
+ axes[i] = record[:prefix_size]
617
+ data[i] = record[prefix_size:]
618
+
619
+ # Every spectrum carries its own axis, so an acquisition could in principle
620
+ # change it mid-run. Those spectra share no grid and cannot be stacked, so
621
+ # check them all rather than trusting the first.
622
+ wavelength_start, wavelength_step = axes[0]
623
+ if not np.allclose(axes, axes[0]):
624
+ warnings.warn(
625
+ f"Cannot parse {os.path.basename(path)}: its spectra do not all "
626
+ f"share one wavelength axis.")
627
+ return None
628
+
629
+ # The axis is stated twice - as a start and step in the .sp, and as a range
630
+ # in the .sd - so check the two against each other rather than trusting one.
631
+ stated_end = wavelength_start + wavelength_step * (count - 1)
632
+ if not np.isclose(stated_end, ends[0]) or not np.isclose(
633
+ wavelength_start, starts[0]):
634
+ warnings.warn(
635
+ f"Cannot parse {os.path.basename(path)}: its spectra span "
636
+ f"{wavelength_start:g}-{stated_end:g} nm but its descriptor says "
637
+ f"{starts[0]:g}-{ends[0]:g} nm.")
638
+ return None
639
+
640
+ wavelengths = wavelength_start + wavelength_step * np.arange(count)
641
+ data = np.ascontiguousarray(data)
642
+ if not data.flags.writeable:
643
+ # A single spectrum needs no restriding, which would otherwise leave the
644
+ # read-only file buffer as the returned array.
645
+ data = data.copy()
646
+ return DataFile(path, 'UV', times, wavelengths, data,
647
+ {'signal': f"Spectra {starts[0]:g}-{ends[0]:g} nm",
648
+ 'unit': 'mAU'})
649
+
650
+
651
+ def _read_pascal_string(raw, pos):
652
+ """
653
+ Reads a length-prefixed ASCII string, or (None, pos) if there is not one.
654
+
655
+ Used only for the .cd descriptor, whose records are strings of varying
656
+ length interleaved with fixed-width fields.
657
+
658
+ """
659
+ if pos >= len(raw):
660
+ return None, pos
661
+ length = raw[pos]
662
+ end = pos + 1 + length
663
+ if length == 0 or end > len(raw):
664
+ return None, pos
665
+ chunk = raw[pos + 1:end]
666
+ # The strings are UTF-8, not ASCII: a DAD writes its temperature traces in
667
+ # degrees Celsius, whose degree sign is two bytes. Reject only control
668
+ # bytes, which is what actually distinguishes a string from binary here.
669
+ try:
670
+ text = chunk.decode('utf-8')
671
+ except UnicodeDecodeError:
672
+ return None, pos
673
+ if any(c < ' ' or c == '\x7f' for c in text):
674
+ return None, pos
675
+ return text, end
676
+
677
+
678
+ def _find_next_record(raw, pos, data_size=None):
679
+ """
680
+ Returns the offset of the next .cd signal record, or None at the end.
681
+
682
+ A record opens with the length-prefixed letter naming the signal. That
683
+ alone is too weak to anchor on - a one-character unit such as ``V`` has the
684
+ same shape - so a candidate is accepted only if a whole record header reads
685
+ out of it: the letter, a description, and the field block behind it.
686
+
687
+ """
688
+ for i in range(pos, len(raw) - 2):
689
+ if raw[i] != 1 or not _is_signal_letter(chr(raw[i + 1])):
690
+ continue
691
+ if _read_record_header(raw, i, data_size) is not None:
692
+ return i
693
+ return None
694
+
695
+
696
+ def _is_signal_letter(char):
697
+ """
698
+ Returns True if ``char`` could be the letter naming a signal.
699
+
700
+ Every signal seen is named A-Z, as under Chemstation. The scan and the
701
+ header reader have to agree on this, or a detector naming them some other
702
+ way would yield its first signal and silently lose the rest.
703
+
704
+ """
705
+ return char.isascii() and char.isalnum()
706
+
707
+
708
+ def _read_record_header(raw, pos, data_size=None):
709
+ """
710
+ Reads a .cd signal record header, or None if one does not start at ``pos``.
711
+
712
+ Returns ``(letter, description, offset, num_times, end)``, where ``end`` is
713
+ the position just past the field block.
714
+
715
+ """
716
+ letter, after_letter = _read_pascal_string(raw, pos)
717
+ if letter is None or len(letter) != 1 or not _is_signal_letter(letter):
718
+ return None
719
+ description, after_description = _read_pascal_string(raw, after_letter)
720
+ if description is None or after_description + 16 > len(raw):
721
+ return None
722
+ _, offset, _, num_times = struct.unpack_from('<IIII', raw, after_description)
723
+ # A real record locates data inside the .cg; a coincidental byte pattern
724
+ # almost never does. Where the .cg's size is known, requiring the record to
725
+ # fit inside it rules out nearly every such pattern - text read as a field
726
+ # gives implausibly large numbers.
727
+ if offset < _DAD_HEADER_SIZE or num_times <= 0:
728
+ return None
729
+ if data_size is not None and (
730
+ offset + _AXIS_PREFIX_SIZE + num_times * 8 > data_size):
731
+ return None
732
+ return letter, description, offset, num_times, after_description + 16
733
+
734
+
735
+ def _find_unit(raw, start, end):
736
+ """
737
+ Returns the unit string inside a .cd signal record, or '' if absent.
738
+
739
+ The unit is the last length-prefixed string before the next record, sitting
740
+ behind numeric fields we have no use for. Absorbance signals carry ``mAU``;
741
+ the detector's telemetry traces carry their own (``°C``, ``V``).
742
+
743
+ """
744
+ unit = ''
745
+ for i in range(start, min(end, len(raw))):
746
+ text, _ = _read_pascal_string(raw, i)
747
+ # Any short printable string here could be the unit: one may be a single
748
+ # symbol ('%', 'V') as readily as a word, so it cannot be required to
749
+ # contain a letter. Take the last rather than the first, since only the
750
+ # last is pinned to a known position - a stray run of bytes in the
751
+ # numeric fields ahead of it can read as a string too.
752
+ if text and 1 <= len(text) <= 8 and text.strip():
753
+ unit = text.strip()
754
+ return unit
755
+
756
+
757
+ def _signal_wavelength(description):
758
+ """
759
+ Pulls the wavelength out of a signal description, or 0 if it has none.
760
+
761
+ The descriptions follow the Chemstation convention, e.g.
762
+ ``Sig=254.0,4.0 Ref=360.0,100.0`` for a signal at 254 nm.
763
+
764
+ """
765
+ if not description.startswith('Sig='):
766
+ return 0.0
767
+ try:
768
+ return float(description[4:].split(',', 1)[0])
769
+ except ValueError:
770
+ return 0.0
771
+
772
+
773
+ """
774
+ MS PARSING METHODS
184
775
 
185
776
  """
186
777
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rainbow-api
3
- Version: 1.3.1
3
+ Version: 1.4.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
@@ -589,6 +589,27 @@ def test_read_metadata_locates_masshunter_datafiles():
589
589
  assert "centroid_available" not in profile_only["metadata"]
590
590
 
591
591
 
592
+ def test_read_metadata_reports_dad_files():
593
+ """ A DAD run's files are reported too. read() returns them with no flag
594
+ set, so a run holding them must not come back as MS-only - nor, when it has
595
+ no MS data at all, as nothing. """
596
+ dad_only = rb.read_metadata(BRONZE_D)
597
+ assert dad_only["datafiles"] == ["DAD1.cg", "DAD1.sp"]
598
+ assert "hrms_available" not in dad_only["metadata"]
599
+
600
+ with tempfile.TemporaryDirectory() as tmp:
601
+ # Give a MassHunter MS run a DAD alongside it: both must be reported.
602
+ combined = os.path.join(tmp, "combined.D")
603
+ shutil.copytree(GOLD_D, combined)
604
+ for name in ("DAD1.cd", "DAD1.cg", "DAD1.sd", "DAD1.sp"):
605
+ shutil.copy(os.path.join(BRONZE_ACQDATA, name),
606
+ os.path.join(combined, "AcqData", name))
607
+ both = rb.read_metadata(combined)
608
+ assert both["datafiles"] == [
609
+ "DAD1.cg", "DAD1.sp", "MSProfile.bin", "MSPeak.bin"]
610
+ assert both["metadata"].get("centroid_available")
611
+
612
+
592
613
  def test_hrms_flag_advertises_profile():
593
614
  """ hrms=True adds the MSProfile.bin DataFile; by default it is not parsed
594
615
  but a metadata note advertises that profile/HRMS data is available (mirrors
@@ -804,3 +825,461 @@ def test_waters_auto_precision_is_whole_numbers(path):
804
825
  ylabels = datafile.ylabels
805
826
  assert ylabels.size > 0
806
827
  np.testing.assert_array_equal(ylabels, np.round(ylabels))
828
+
829
+
830
+ # ---------------------------------------------------------------------------
831
+ # MassHunter DAD (.cd/.cg/.sd/.sp).
832
+ #
833
+ # A MassHunter DAD writes the same two views the Chemstation format splits into
834
+ # .ch and .uv files, but in its own binary family: a descriptor indexing a data
835
+ # file, twice over. `bronze` is a four-retention-time slice of a real QQQ+DAD
836
+ # acquisition, keeping all five absorbance signals, the three telemetry traces,
837
+ # and the full 190-550 nm axis. Its telemetry traces deliberately keep a
838
+ # different point count (8) from its absorbance signals (4), as they do on the
839
+ # instrument, so the per-signal geometry is exercised rather than assumed.
840
+ # ---------------------------------------------------------------------------
841
+
842
+ BRONZE_D = os.path.join("tests", "inputs", "bronze.D")
843
+ BRONZE_ACQDATA = os.path.join(BRONZE_D, "AcqData")
844
+
845
+
846
+ def test_dad_signals_are_described():
847
+ """ The .cd descriptor names every signal and locates its data in the .cg. """
848
+ signals = masshunter.read_dad_signals(
849
+ os.path.join(BRONZE_ACQDATA, "DAD1.cd"))
850
+ assert len(signals) == 8
851
+ assert [s['letter'] for s in signals] == list("ABCDEIJK")
852
+
853
+ absorbance = [s for s in signals if s['description'].startswith('Sig=')]
854
+ assert len(absorbance) == 5
855
+ assert all(s['unit'] == 'mAU' for s in absorbance)
856
+ assert absorbance[0]['description'].startswith('Sig=254.0')
857
+
858
+ # The telemetry traces carry their own units - which are UTF-8, not ASCII -
859
+ # and are sampled at their own rate.
860
+ telemetry = [s for s in signals if not s['description'].startswith('Sig=')]
861
+ assert [s['description'] for s in telemetry] == [
862
+ "Board Temperature", "Optical Unit Temperature", "UV Lamp Anode Voltage"]
863
+ assert [s['unit'] for s in telemetry] == ["\N{DEGREE SIGN}C",
864
+ "\N{DEGREE SIGN}C", "V"]
865
+ assert {s['num_times'] for s in telemetry} != {
866
+ s['num_times'] for s in absorbance}
867
+
868
+
869
+ def test_dad_chromatograms_are_named_per_signal():
870
+ """ Each signal becomes its own DataFile, named the Chemstation way. """
871
+ datadir = rb.read(BRONZE_D)
872
+ names = [df.name for df in datadir.datafiles]
873
+ assert names[:5] == ["DAD1A.cg", "DAD1B.cg", "DAD1C.cg",
874
+ "DAD1D.cg", "DAD1E.cg"]
875
+ for name, wavelength in zip(names, (254, 210, 280, 400, 260)):
876
+ datafile = datadir.get_file(name)
877
+ assert datafile.detector == 'UV'
878
+ assert datafile.data.shape == (4, 1)
879
+ assert datafile.ylabels[0] == wavelength
880
+
881
+
882
+ def test_dad_spectra_form_one_grid():
883
+ """ The .sp spectra land on the single wavelength axis the .sd describes. """
884
+ datadir = rb.read(BRONZE_D)
885
+ spectra = datadir.get_file("DAD1.sp")
886
+ assert spectra.detector == 'UV'
887
+ assert spectra.data.shape == (4, 181)
888
+ assert spectra.ylabels[0] == 190
889
+ assert spectra.ylabels[-1] == 550
890
+ np.testing.assert_allclose(np.diff(spectra.ylabels), 2)
891
+ # Retention times are minutes, ascending, and shared with the chromatograms.
892
+ assert (spectra.xlabels[1:] > spectra.xlabels[:-1]).all()
893
+ np.testing.assert_allclose(
894
+ spectra.xlabels, datadir.get_file("DAD1A.cg").xlabels)
895
+
896
+
897
+ def test_dad_spectra_agree_with_chromatograms():
898
+ """ The two views encode the same measurement, so a signal's chromatogram
899
+ is reproduced by the spectra over that signal's band.
900
+
901
+ A signal is a centre wavelength and a bandwidth ("Sig=400.0,4.0" is 400 nm
902
+ over 4 nm), so the comparison averages the spectra across the band rather
903
+ than reading a single column.
904
+
905
+ 400 nm is the case this can be asserted on: it is the one signal acquired
906
+ Ref=off, so its chromatogram is the band alone. The others subtract a
907
+ reference band, and reproducing Agilent's exact weighting is out of scope
908
+ here - averaging the reference band accounts for most of the difference but
909
+ not all of it, so those signals are only checked for the shared time axis
910
+ and a plausible absorbance scale. """
911
+ datadir = rb.read(BRONZE_D)
912
+ spectra = datadir.get_file("DAD1.sp")
913
+ wavelengths = np.asarray(spectra.ylabels, dtype=float)
914
+
915
+ def band(centre, width=4.0):
916
+ columns = np.abs(wavelengths - centre) <= width / 2
917
+ return spectra.data[:, columns].mean(axis=1)
918
+
919
+ unreferenced = datadir.get_file("DAD1D.cg") # Sig=400.0, Ref=off
920
+ np.testing.assert_allclose(unreferenced.data[:, 0], band(400), atol=5e-3)
921
+
922
+ for name, centre in (("DAD1A.cg", 254), ("DAD1B.cg", 210)):
923
+ chromatogram = datadir.get_file(name).data[:, 0]
924
+ assert chromatogram.shape == (4,)
925
+ # Same units and order of magnitude as the band it is drawn from.
926
+ assert np.abs(chromatogram - band(centre)).max() < 1.0
927
+
928
+
929
+ def test_dad_telemetry_is_opt_in_and_analog():
930
+ """ The detector's telemetry traces are parsed only on request, and land in
931
+ `analog` rather than among the detector signals. """
932
+ default = rb.read(BRONZE_D)
933
+ assert default.analog == []
934
+ assert len(default.datafiles) == 6
935
+
936
+ with_telemetry = rb.read(BRONZE_D, telemetry=True)
937
+ assert len(with_telemetry.datafiles) == 6 # unchanged: additive
938
+ assert [df.name for df in with_telemetry.analog] == [
939
+ "DAD1I.cg", "DAD1J.cg", "DAD1K.cg"]
940
+ for datafile in with_telemetry.analog:
941
+ assert datafile.detector is None
942
+ # Sampled at their own rate, not the absorbance signals'.
943
+ assert datafile.data.shape == (8, 1)
944
+
945
+
946
+ def test_dad_fixture_keeps_the_real_signal_kinds():
947
+ """ A .cd record marks a signal 1 for absorbance and 2 for telemetry. The
948
+ parser separates the two by unit instead, so nothing here reads the field -
949
+ but the fixture is only useful as evidence if it still says what the
950
+ instrument said. """
951
+ with open(os.path.join(BRONZE_ACQDATA, "DAD1.cd"), 'rb') as f:
952
+ raw = f.read()
953
+ absorbance = [0x71, 0xde, 0x14b, 0x1b0, 0x21d]
954
+ telemetry = [0x27e, 0x2e6, 0x34b]
955
+ for offset in absorbance:
956
+ assert struct.unpack_from('<I', raw, offset)[0] == 1
957
+ for offset in telemetry:
958
+ assert struct.unpack_from('<I', raw, offset)[0] == 2
959
+
960
+
961
+ def test_dad_parses_without_the_ms_flags():
962
+ """ DAD data is parsed unconditionally, as the Chemstation UV formats are -
963
+ a .d holding only DAD data still reads as UV with no flags set. """
964
+ datadir = rb.read(BRONZE_D)
965
+ assert datadir.detectors == {'UV'}
966
+ assert len(datadir.by_detector['UV']) == 6
967
+
968
+
969
+ def test_dad_rejects_a_foreign_file():
970
+ """ The type tag in the shared header identifies which member a file is, so
971
+ a mismatched one is declined rather than misread. """
972
+ with tempfile.TemporaryDirectory() as tmp:
973
+ acqdata = os.path.join(tmp, "fake.D", "AcqData")
974
+ os.makedirs(acqdata)
975
+ # The .sp content under a .cd name: right family, wrong member.
976
+ shutil.copy(os.path.join(BRONZE_ACQDATA, "DAD1.sp"),
977
+ os.path.join(acqdata, "DAD1.cd"))
978
+ assert masshunter.read_dad_signals(
979
+ os.path.join(acqdata, "DAD1.cd")) == []
980
+
981
+
982
+ def test_dad_varying_wavelength_axis_is_declined():
983
+ """ Spectra that do not share one wavelength axis cannot form a dense grid,
984
+ so they are declined with a warning instead of being reshaped. """
985
+ with tempfile.TemporaryDirectory() as tmp:
986
+ acqdata = os.path.join(tmp, "AcqData")
987
+ shutil.copytree(BRONZE_ACQDATA, acqdata)
988
+ desc_path = os.path.join(acqdata, "DAD1.sd")
989
+ with open(desc_path, 'rb') as descriptor:
990
+ desc = bytearray(descriptor.read())
991
+ data_offset = struct.unpack_from('<I', desc, 0x4c)[0]
992
+ # Give the second spectrum a different wavelength count.
993
+ struct.pack_into('<I', desc, data_offset + 80 + 44, 180)
994
+ with open(desc_path, 'wb') as descriptor:
995
+ descriptor.write(bytes(desc))
996
+
997
+ with pytest.warns(UserWarning, match="wavelength axis changes"):
998
+ spectra = masshunter.parse_dadspectra(
999
+ os.path.join(acqdata, "DAD1.sp"), desc_path)
1000
+ assert spectra is None
1001
+
1002
+
1003
+ def test_dad_honors_requested_files():
1004
+ """ requested_files narrows the DAD parse as it does the Chemstation one -
1005
+ by the per-signal name, or by the file the signals share. """
1006
+ one_signal = rb.read(BRONZE_D, requested_files=["DAD1B.cg"])
1007
+ assert [df.name for df in one_signal.datafiles] == ["DAD1B.cg"]
1008
+
1009
+ spectra_only = rb.read(BRONZE_D, requested_files=["DAD1.sp"])
1010
+ assert [df.name for df in spectra_only.datafiles] == ["DAD1.sp"]
1011
+
1012
+ # The shared filename selects every signal it holds, but not the spectra.
1013
+ every_signal = rb.read(BRONZE_D, requested_files=["DAD1.cg"])
1014
+ assert [df.name for df in every_signal.datafiles] == [
1015
+ "DAD1A.cg", "DAD1B.cg", "DAD1C.cg", "DAD1D.cg", "DAD1E.cg"]
1016
+
1017
+ assert rb.read(BRONZE_D, requested_files=["nothing.cg"]).datafiles == []
1018
+ # A name that merely resembles a real one is not a request for it: there is
1019
+ # no DAD1A.sp, so asking for one yields nothing.
1020
+ assert rb.read(BRONZE_D, requested_files=["DAD1A.sp"]).datafiles == []
1021
+ assert rb.read(BRONZE_D, requested_files=["DAD1.sd"]).datafiles == []
1022
+
1023
+
1024
+ def test_dad_telemetry_can_be_requested_by_name():
1025
+ """ Naming a telemetry trace parses it whether or not the flag is set, as
1026
+ it does for .dx telemetry. """
1027
+ datadir = rb.read(BRONZE_D, requested_files=["DAD1I.cg"])
1028
+ assert [df.name for df in datadir.analog] == ["DAD1I.cg"]
1029
+ assert datadir.datafiles == []
1030
+
1031
+
1032
+ def _bronze_copy(tmp):
1033
+ """ A writable copy of the bronze AcqData, for corrupting. """
1034
+ acqdata = os.path.join(tmp, "AcqData")
1035
+ shutil.copytree(BRONZE_ACQDATA, acqdata)
1036
+ return acqdata
1037
+
1038
+
1039
+ def _patch(path, offset, value, fmt='<I'):
1040
+ with open(path, 'rb') as f:
1041
+ raw = bytearray(f.read())
1042
+ struct.pack_into(fmt, raw, offset, value)
1043
+ with open(path, 'wb') as f:
1044
+ f.write(bytes(raw))
1045
+
1046
+
1047
+ def test_dad_short_descriptor_is_declined():
1048
+ """ A truncated .cd yields no signals rather than a partial parse. """
1049
+ with tempfile.TemporaryDirectory() as tmp:
1050
+ acqdata = _bronze_copy(tmp)
1051
+ path = os.path.join(acqdata, "DAD1.cd")
1052
+ with open(path, 'rb') as f:
1053
+ head = f.read(0x50)
1054
+ with open(path, 'wb') as f:
1055
+ f.write(head)
1056
+ with pytest.warns(UserWarning, match="too short to hold"):
1057
+ assert masshunter.read_dad_signals(path) == []
1058
+
1059
+
1060
+ def test_dad_missing_signals_are_reported():
1061
+ """ Reading fewer signals than the descriptor declares is warned about,
1062
+ not returned silently as a short list. """
1063
+ with tempfile.TemporaryDirectory() as tmp:
1064
+ acqdata = _bronze_copy(tmp)
1065
+ path = os.path.join(acqdata, "DAD1.cd")
1066
+ _patch(path, 0x4c, 9) # claim one more signal than exists
1067
+ with pytest.warns(UserWarning, match="describes 9 signals but only 8"):
1068
+ signals = masshunter.read_dad_signals(path)
1069
+ assert len(signals) == 8
1070
+
1071
+
1072
+ def _synthetic_cd(acqdata, signals):
1073
+ """ Writes a minimal .cd/.cg pair, one record per (letter, description,
1074
+ unit, num_times), and returns the .cg's size. The real fixture carries its
1075
+ only one-letter unit in its last record, where nothing can be lost behind
1076
+ it. """
1077
+ descriptor = bytearray(80)
1078
+ struct.pack_into('<H', descriptor, 0, 0x0200)
1079
+ struct.pack_into('<I', descriptor, 0x4c, len(signals))
1080
+
1081
+ chromatograms = bytearray(68)
1082
+ offsets = []
1083
+ for _, _, _, num_times in signals:
1084
+ offsets.append(len(chromatograms))
1085
+ chromatograms += struct.pack('<dd', 0.0, 0.01) + b'\x00' * num_times * 8
1086
+
1087
+ def pascal(text):
1088
+ encoded = text.encode('utf-8')
1089
+ return bytes([len(encoded)]) + encoded
1090
+
1091
+ for (letter, description, unit, num_times), offset in zip(signals, offsets):
1092
+ descriptor += pascal(letter) + pascal(description)
1093
+ descriptor += struct.pack('<IIII', 1, offset, 0, num_times)
1094
+ descriptor += b'\x00' * 8 + pascal(unit)
1095
+
1096
+ with open(os.path.join(acqdata, "DAD1.cd"), 'wb') as f:
1097
+ f.write(descriptor)
1098
+ with open(os.path.join(acqdata, "DAD1.cg"), 'wb') as f:
1099
+ f.write(chromatograms)
1100
+ return len(chromatograms)
1101
+
1102
+
1103
+ def test_dad_one_letter_unit_does_not_split_a_record():
1104
+ """ A single-uppercase-letter unit ("V") has the same byte shape as a
1105
+ record's leading letter. Put one on a middle record, where mistaking it for
1106
+ a boundary would cost the record behind it. """
1107
+ with tempfile.TemporaryDirectory() as tmp:
1108
+ acqdata = os.path.join(tmp, "synthetic.D", "AcqData")
1109
+ os.makedirs(acqdata)
1110
+ size = _synthetic_cd(acqdata, [
1111
+ ("A", "Sig=254.0,4.0 Ref=360.0,100.0", "mAU", 10),
1112
+ ("B", " UV Lamp Anode Voltage", "V", 40),
1113
+ ("C", "Sig=210.0,4.0 Ref=360.0,100.0", "mAU", 10)])
1114
+ signals = masshunter.read_dad_signals(
1115
+ os.path.join(acqdata, "DAD1.cd"), size)
1116
+
1117
+ assert [s['letter'] for s in signals] == ["A", "B", "C"]
1118
+ assert [s['unit'] for s in signals] == ["mAU", "V", "mAU"]
1119
+ assert [s['num_times'] for s in signals] == [10, 40, 10]
1120
+
1121
+
1122
+ def test_dad_records_are_bounded_by_the_chromatogram_file():
1123
+ """ Every record indexes data inside the .cg, so requiring it to fit rules
1124
+ out a coincidental byte pattern: text read as a field gives implausibly
1125
+ large numbers. """
1126
+ record = (b"\x01A\x1eSig=254.0,4.0 Ref=360.0,100.0"
1127
+ + struct.pack('<IIII', 1, 68, 0, 10))
1128
+ assert masshunter._read_record_header(record, 0, 68 + 16 + 10 * 8)
1129
+ assert masshunter._read_record_header(record, 0, 100) is None
1130
+ # The bound leaves the real fixture untouched.
1131
+ signals = masshunter.read_dad_signals(
1132
+ os.path.join(BRONZE_ACQDATA, "DAD1.cd"),
1133
+ os.path.getsize(os.path.join(BRONZE_ACQDATA, "DAD1.cg")))
1134
+ assert [s['letter'] for s in signals] == list("ABCDEIJK")
1135
+ assert signals[-1]['unit'] == "V"
1136
+
1137
+
1138
+ def test_dad_descriptor_pointing_outside_the_file_is_declined():
1139
+ """ A spectrum offset past the end of the .sp is refused, not read. """
1140
+ with tempfile.TemporaryDirectory() as tmp:
1141
+ acqdata = _bronze_copy(tmp)
1142
+ desc_path = os.path.join(acqdata, "DAD1.sd")
1143
+ data_offset = 164
1144
+ _patch(desc_path, data_offset + 32, 10 ** 7) # first spectrum offset
1145
+ with pytest.warns(UserWarning, match="outside the file"):
1146
+ assert masshunter.parse_dadspectra(
1147
+ os.path.join(acqdata, "DAD1.sp"), desc_path) is None
1148
+
1149
+
1150
+ def test_dad_zero_wavelengths_is_declined():
1151
+ """ A descriptor reporting no wavelengths is refused with a warning. """
1152
+ with tempfile.TemporaryDirectory() as tmp:
1153
+ acqdata = _bronze_copy(tmp)
1154
+ desc_path = os.path.join(acqdata, "DAD1.sd")
1155
+ for i in range(4):
1156
+ _patch(desc_path, 164 + i * 80 + 44, 0)
1157
+ with pytest.warns(UserWarning, match="0 wavelengths"):
1158
+ assert masshunter.parse_dadspectra(
1159
+ os.path.join(acqdata, "DAD1.sp"), desc_path) is None
1160
+
1161
+
1162
+ def test_dad_axis_disagreement_is_declined():
1163
+ """ The wavelength axis is stated in both the .sp and the .sd, so the two
1164
+ are checked against each other. """
1165
+ with tempfile.TemporaryDirectory() as tmp:
1166
+ acqdata = _bronze_copy(tmp)
1167
+ spectra_path = os.path.join(acqdata, "DAD1.sp")
1168
+ # Move every spectrum's start together, so the axes still agree with
1169
+ # each other and only the descriptor is left contradicting them.
1170
+ for i in range(4):
1171
+ _patch(spectra_path, 68 + i * 1464, 900.0, '<d')
1172
+ with pytest.warns(UserWarning, match="but its descriptor says"):
1173
+ assert masshunter.parse_dadspectra(
1174
+ spectra_path, os.path.join(acqdata, "DAD1.sd")) is None
1175
+
1176
+
1177
+ def test_dad_axis_changing_mid_run_is_declined():
1178
+ """ Each spectrum states its own axis, so a run that changes it partway
1179
+ yields rows that share no grid. Every spectrum is checked, not just the
1180
+ first. """
1181
+ with tempfile.TemporaryDirectory() as tmp:
1182
+ acqdata = _bronze_copy(tmp)
1183
+ spectra_path = os.path.join(acqdata, "DAD1.sp")
1184
+ _patch(spectra_path, 68 + 2 * 1464, 400.0, '<d') # the third one
1185
+ with pytest.warns(UserWarning, match="share one wavelength axis"):
1186
+ assert masshunter.parse_dadspectra(
1187
+ spectra_path, os.path.join(acqdata, "DAD1.sd")) is None
1188
+
1189
+
1190
+ def test_dad_padded_spectrum_records_are_read():
1191
+ """ A descriptor may give a record length longer than the values it holds,
1192
+ which only means the record is padded. Reading is driven by the wavelength
1193
+ count, so such a file parses rather than being declined. """
1194
+ reference = rb.read(BRONZE_D).get_file("DAD1.sp")
1195
+ pad = 8
1196
+ with tempfile.TemporaryDirectory() as tmp:
1197
+ acqdata = _bronze_copy(tmp)
1198
+ spectra_path = os.path.join(acqdata, "DAD1.sp")
1199
+ desc_path = os.path.join(acqdata, "DAD1.sd")
1200
+
1201
+ with open(spectra_path, 'rb') as f:
1202
+ raw = f.read()
1203
+ stride = 1464
1204
+ rebuilt = bytearray(raw[:68])
1205
+ for i in range(4):
1206
+ rebuilt += raw[68 + i * stride:68 + (i + 1) * stride] + b'\x00' * pad
1207
+ with open(spectra_path, 'wb') as f:
1208
+ f.write(rebuilt)
1209
+ for i in range(4):
1210
+ _patch(desc_path, 164 + i * 80 + 32, 68 + i * (stride + pad))
1211
+ _patch(desc_path, 164 + i * 80 + 40, stride + pad)
1212
+
1213
+ parsed = masshunter.parse_dadspectra(spectra_path, desc_path)
1214
+ assert parsed is not None
1215
+ assert np.array_equal(parsed.data, reference.data)
1216
+
1217
+
1218
+ def test_dad_short_spectrum_records_are_declined():
1219
+ """ A record shorter than its wavelength count would be read past its end,
1220
+ so it is refused rather than trusted. """
1221
+ with tempfile.TemporaryDirectory() as tmp:
1222
+ acqdata = _bronze_copy(tmp)
1223
+ desc_path = os.path.join(acqdata, "DAD1.sd")
1224
+ for i in range(4):
1225
+ _patch(desc_path, 164 + i * 80 + 40, 1000)
1226
+ with pytest.warns(UserWarning, match="shorter than"):
1227
+ assert masshunter.parse_dadspectra(
1228
+ os.path.join(acqdata, "DAD1.sp"), desc_path) is None
1229
+
1230
+
1231
+ def test_dad_single_spectrum_is_writeable():
1232
+ """ One spectrum needs no restriding, so the returned array must still be a
1233
+ copy rather than a view onto the read-only file buffer. """
1234
+ with tempfile.TemporaryDirectory() as tmp:
1235
+ acqdata = _bronze_copy(tmp)
1236
+ _patch(os.path.join(acqdata, "DAD1.sd"), 0x50, 1) # one record
1237
+ parsed = masshunter.parse_dadspectra(
1238
+ os.path.join(acqdata, "DAD1.sp"), os.path.join(acqdata, "DAD1.sd"))
1239
+ assert parsed.data.shape == (1, 181)
1240
+ parsed.data[0, 0] = 1.0
1241
+
1242
+
1243
+ def test_dad_non_contiguous_spectra_are_read():
1244
+ """ Spectra are located through the descriptor, so they need not be evenly
1245
+ spaced in the .sp. Rebuild one with a gap between every spectrum. """
1246
+ reference = rb.read(BRONZE_D).get_file("DAD1.sp")
1247
+ gap = 7
1248
+ with tempfile.TemporaryDirectory() as tmp:
1249
+ acqdata = _bronze_copy(tmp)
1250
+ spectra_path = os.path.join(acqdata, "DAD1.sp")
1251
+ desc_path = os.path.join(acqdata, "DAD1.sd")
1252
+
1253
+ with open(spectra_path, 'rb') as f:
1254
+ raw = f.read()
1255
+ stride = 16 + 181 * 8
1256
+ spread = bytearray(raw[:68])
1257
+ offsets = []
1258
+ for i in range(4):
1259
+ offsets.append(68 + len(spread) - 68)
1260
+ spread += raw[68 + i * stride: 68 + (i + 1) * stride]
1261
+ spread += b"\x00" * gap
1262
+ with open(spectra_path, 'wb') as f:
1263
+ f.write(bytes(spread))
1264
+ for i, offset in enumerate(offsets):
1265
+ _patch(desc_path, 164 + i * 80 + 32, offset)
1266
+
1267
+ spectra = masshunter.parse_dadspectra(spectra_path, desc_path)
1268
+ assert spectra is not None
1269
+ np.testing.assert_array_equal(spectra.data, reference.data)
1270
+ np.testing.assert_array_equal(spectra.ylabels, reference.ylabels)
1271
+
1272
+
1273
+ def test_dad_accepts_other_detector_stems():
1274
+ """ A multi- or variable-wavelength detector writes the same family under
1275
+ its own name, so the parse is not tied to "DAD". """
1276
+ with tempfile.TemporaryDirectory() as tmp:
1277
+ acqdata = os.path.join(tmp, "AcqData")
1278
+ os.makedirs(acqdata)
1279
+ for ext in (".cd", ".cg", ".sd", ".sp"):
1280
+ shutil.copy(os.path.join(BRONZE_ACQDATA, "DAD1" + ext),
1281
+ os.path.join(acqdata, "MWD1" + ext))
1282
+ datafiles = masshunter.parse_dadfiles(acqdata)
1283
+ assert [df.name for df in datafiles] == [
1284
+ "MWD1A.cg", "MWD1B.cg", "MWD1C.cg", "MWD1D.cg", "MWD1E.cg",
1285
+ "MWD1.sp"]
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes