rainbow-api 1.5.4__tar.gz → 1.5.5__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 (47) hide show
  1. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/CHANGELOG.md +133 -0
  2. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/PKG-INFO +1 -1
  3. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/pyproject.toml +1 -1
  4. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/__init__.py +39 -11
  5. rainbow_api-1.5.5/rainbow/_optics.py +33 -0
  6. rainbow_api-1.5.5/rainbow/_version.py +6 -0
  7. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/agilent/__init__.py +102 -9
  8. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/agilent/chemstation.py +32 -3
  9. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/agilent/masshunter.py +37 -10
  10. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/agilent/openlab.py +15 -2
  11. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/agilent/sequence.py +22 -1
  12. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/asm.py +1360 -189
  13. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/datadirectory.py +1 -1
  14. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/datafile.py +5 -2
  15. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/datasequence.py +7 -7
  16. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/waters/masslynx.py +11 -3
  17. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow_api.egg-info/PKG-INFO +1 -1
  18. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow_api.egg-info/SOURCES.txt +2 -0
  19. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/COPYING +0 -0
  20. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/COPYING.LESSER +0 -0
  21. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/MANIFEST.in +0 -0
  22. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/README.md +0 -0
  23. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/_arguments.py +0 -0
  24. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/_binning.py +0 -0
  25. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/agilent/_chdelta.pyx +0 -0
  26. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/agilent/_msprofile.pyx +0 -0
  27. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/agilent/_uvdelta.pyx +0 -0
  28. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/agilent/acaml.py +0 -0
  29. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/agilent/method.py +0 -0
  30. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/debug/__init__.py +0 -0
  31. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/debug/_util.py +0 -0
  32. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/debug/chemstation_header.py +0 -0
  33. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/debug/chemstation_text.py +0 -0
  34. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/debug/dotnet.py +0 -0
  35. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/debug/ini.py +0 -0
  36. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/debug/method.py +0 -0
  37. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/debug/mzxml.py +0 -0
  38. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/debug/reg.py +0 -0
  39. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/debug/waters_header.py +0 -0
  40. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/debug/waters_inf.py +0 -0
  41. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/debug/xml.py +0 -0
  42. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow/waters/__init__.py +0 -0
  43. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow_api.egg-info/dependency_links.txt +0 -0
  44. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow_api.egg-info/requires.txt +0 -0
  45. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/rainbow_api.egg-info/top_level.txt +0 -0
  46. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/setup.cfg +0 -0
  47. {rainbow_api-1.5.4 → rainbow_api-1.5.5}/setup.py +0 -0
@@ -3,6 +3,139 @@
3
3
  All notable changes to `rainbow-api` are documented here. This project adheres
4
4
  to [Semantic Versioning](https://semver.org/).
5
5
 
6
+ ## [1.5.5] - 2026-10-17
7
+
8
+ ### Added
9
+ - **`rb.from_asm` and `rb.sequence_from_asm` read every measurement's peaks.**
10
+ They read a measurement's peaks only beside a rebuilt trace, and rebuilt
11
+ only absorbance cubes with inline data, so the peaks of every fluorescence
12
+ channel, of an FID run, and of every measurement in an index document
13
+ (whose cubes carry no values) were dropped. Over 531 local Empower and
14
+ OpenLab exports, 1.5.4 read 15,503 of 20,026 peaks; 1.5.5 reads all of them.
15
+ Each peak group also carries the channel's `detector` and `metadata`, so a
16
+ group with no trace beside it still says which channel it was integrated on.
17
+ - **Peaks carry their units, identifier and index.** `area_unit` and
18
+ `height_unit` say what each value is in; `identifier` and `index` are the
19
+ peak's own; each integration's `processing` gains its `description`.
20
+ - **More of the envelope.** `injection_time`, `sample_role`, `well_plate_id`
21
+ and `acq_method`, and the `data_system`, `analysis_sequence` and `project`
22
+ records, field by field as written; all are written back on export (see the
23
+ round-trip guide for where). A `scalar integer datum` reads as an `int`.
24
+ - **`rb.read(path, peaks=True)`** attaches one injection's integrated peaks,
25
+ found as `read_sequence(peaks=True)` finds them: the `sequence.acaml` beside
26
+ the .D, else its own `sequence.acam_`.
27
+ - **`rb.peaks_from_asm(measurement)`** reads one ASM measurement document's
28
+ peaks. **`rb.sniff_vendor(path)`** is the content check `rb.read` falls back
29
+ to for an unsuffixed folder, and **`rb.asm_technique(run)`** is the `"LC"` or
30
+ `"GC"` the export will use.
31
+ - **`rainbow.__version__`**, the version an export names as its converter.
32
+
33
+ ### Changed
34
+ - **Every chromatogram cube is rebuilt, not only absorbance.** Fluorescence,
35
+ electric current, intensity, refractive index and conductivity channels come
36
+ back as DataFiles with `metadata["unit"]` as written and
37
+ `metadata["measure"]`. The detector is named from the device type, then the
38
+ device identifier, then the cube label, then the measure: `UV`, `RID`, `FLD`
39
+ (new), `ELSD`, `FID`, or `CAD`; a channel rainbow has no name for, such as a
40
+ conductivity detector, is detector `None` and joins the directory's
41
+ `analog` traces. The channel metadata also holds `device_type` and
42
+ `acq_method`, and the optics from the device control settings, the cube
43
+ label, or the processed data description: `wavelength`, `bandwidth`,
44
+ `reference_wavelength`, `reference_bandwidth`, and a fluorescence channel's
45
+ `excitation_wavelength`, `excitation_bandwidth` and `emission_wavelength`.
46
+ - **A peak's `height` and `area` on a non-absorbance channel are kept as
47
+ written.** 1.5.4 read any unit it could not convert to mAU as `None`, which
48
+ lost every fluorescence peak, and converted µV to mAU whatever the channel
49
+ measured. An RFU, pA or ELSD µV value now comes back with its unit. Only on
50
+ an absorbance channel is AU or Empower's µV converted to mAU; the edge
51
+ heights are in the height's unit.
52
+ - **`Ref=off` reads as `reference_wavelength` None**, present, in the vendor
53
+ readers and in `from_asm`, so a channel without a reference is told apart
54
+ from one whose reference was not recorded. Code that reads
55
+ `metadata["reference_wavelength"]` may now find the key with the value
56
+ `None`, where it used to be absent.
57
+
58
+ ### Fixed
59
+ - **`to_asm` wrote every peak area as `mAU.s`**, an FID's or CAD's pA.s
60
+ included. A peak's area and height are now written in the unit of the cube
61
+ it was integrated on. REC/2026/06 gives electric current (pA), intensity
62
+ (RLU), voltage (mV) and fluorescence (RFU) their own peak lists, so such
63
+ a channel keeps its faithful cube when it carries peaks; only
64
+ a measure with no peak list in the schema (nA, V) is still relabeled to
65
+ absorbance. The relabel note now also records the real concept and unit as
66
+ structured custom information, and `from_asm` reads it (or the sentence
67
+ 1.5.4 wrote alone) to put the channel and its peaks back in their real
68
+ unit, so a relabeled channel re-exports to a valid document.
69
+ - **A fluorescence signal is FLD in every Agilent reader.** "FLD1 A, Ex=230,
70
+ Em=310" was typed UV at 230 nm in a ChemStation .ch; it is now an `FLD`
71
+ channel with `excitation_wavelength` and `emission_wavelength`, labelled by
72
+ its emission, in the .ch, OpenLab .dx and MassHunter .cg readers alike, and
73
+ `parse_optics` reads the `Ex=`/`Em=` clause. In the 179/181 .ch container
74
+ 1.5.4 typed it FID instead, which also exported the whole run as gas
75
+ chromatography.
76
+ - **`from_asm` scales an absorbance trace to mAU.** A cube in AU (or Empower's
77
+ µV) was rebuilt in its own unit while its peaks' heights and areas were
78
+ converted to mAU, so the trace minus an edge height was a thousand times
79
+ off. The trace is now scaled to mAU too, the unit rainbow holds UV data in
80
+ and to_asm writes, and `metadata["unit"]` says so.
81
+ - **The processing time and description are where REC/2026/06 puts them.**
82
+ `data processing time` is written in the data processing document, stamped
83
+ with `utc_offset=` (as custom information when it has no offset), and the
84
+ description under `description`, the name REC/2026/06 gave the 2025/03
85
+ `processed data description`; both are read from any of those places. A
86
+ sample role outside the schema's list is written as custom information.
87
+ - **Every peak and peak group has the same keys, whatever it was read from.**
88
+ A peak read from a vendor result document carries `identifier`, `index`,
89
+ `area_unit`, `height_unit`, `start_height`, `end_height` and the four
90
+ baseline keys too, as None, and its group `detector`, `metadata` and
91
+ `processing` as None and `alternates` as an empty list.
92
+ - **A unit published under another's name reads back as itself.** A
93
+ channel whose unit the schema has no term for (red.D's CAD in mAu) is
94
+ published under its detector's default unit, as before, and now with the
95
+ structured note a peak relabel writes, so `from_asm` restores its unit and
96
+ its peaks'. A peak area in a unit per minute is converted to per second,
97
+ and an absorbance area per an unknown time reads as None.
98
+ - **A re-exported data system record names rainbow as its converter.**
99
+ `ASM converter name` and `version` are rainbow-api's, `ASM conversion time`
100
+ is the time of the export (so two exports differ there), and `ASM file
101
+ identifier` is the file written, else one named for the run; the source
102
+ converter's are kept as the record's custom information, prefixed
103
+ `source`, and a second round trip keeps them as they were (the source
104
+ conversion time exactly as written). A record naming both a file and a
105
+ database row keeps the row and carries the file as custom information. The
106
+ record's times take `utc_offset=`. Every chromatogram channel's device
107
+ control keeps the source's device identifier (read into
108
+ `metadata["device_identifier"]`), names the detector there only when the
109
+ source had none, and names rainbow's detector in its custom information
110
+ (`rainbow detector`), which is what reads it back.
111
+ - **Bandwidth, reference and acquisition method survive a round trip.** A UV
112
+ channel's bandwidth and reference are written as their device control
113
+ settings (Ref=off as custom information), an FLD's excitation bandwidth
114
+ too, and the acquisition method as the measurement's custom information.
115
+ A CAD's device control names it in its device identifier, so rainbow's
116
+ own export reads back as CAD.
117
+ - **A vendor peak group names its detector and its peaks' units.**
118
+ `rb.read(peaks=True)` and `read_sequence(peaks=True)` fill each group's
119
+ `detector` and `metadata` from the channel's DataFile, and each peak's
120
+ `height_unit` and `area_unit` from its unit (the peak table is in the
121
+ channel's unit, per second for an area, and does not say so).
122
+ - **The detector is not read from a measurement identifier.** It is a key
123
+ (often a GUID), and a segment such as `adc4` typed a channel CAD.
124
+ - **A gas chromatography document re-exports as one.** `from_asm` records
125
+ the document's technique in `metadata["technique"]`, which the export
126
+ follows; one with no FID channel used to come back as liquid
127
+ chromatography.
128
+ - **A peak in AU or µV beside an absorbance cube is converted to mAU on
129
+ export**, as the cube is, rather than relabeled 1000 times off; a peak
130
+ group's `metadata["unit"]` is mAU when its trace is.
131
+ - **A ChemStation FLD channel is FLD by its name too**, as OpenLab's is by
132
+ its device, when its wavelengths are not numbers.
133
+ - **A Waters fluorescence channel is FLD.** One fluorescence parser serves
134
+ the Agilent readers, the Waters reader and `from_asm`.
135
+ - **`to_asm` dropped peak groups no exported channel carries** (peaks read from
136
+ an index document, or on an analog channel) without a word. It warns once
137
+ per group.
138
+
6
139
  ## [1.5.4] - 2026-10-17
7
140
 
8
141
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rainbow-api
3
- Version: 1.5.4
3
+ Version: 1.5.5
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.5.4"
7
+ version = "1.5.5"
8
8
  description = "Read chromatography and mass spectrometry binary files"
9
9
  readme = "README.md"
10
10
  license = {text = "LGPL-3.0-or-later"}
@@ -1,11 +1,13 @@
1
1
  import os
2
2
  import re
3
+ from rainbow._version import __version__
3
4
  from rainbow.datafile import DataFile
4
5
  from rainbow.datadirectory import DataDirectory
5
6
  from rainbow.datasequence import DataSequence
6
7
  from rainbow import agilent, waters
7
8
  from rainbow._binning import MZ_FLOORS
8
- from rainbow.asm import from_asm, iso_timestamp, sequence_from_asm
9
+ from rainbow.asm import (asm_technique, from_asm, iso_timestamp,
10
+ peaks_from_asm, sequence_from_asm)
9
11
 
10
12
 
11
13
  # `debug` is listed although it is not imported above: __getattr__ fetches it on
@@ -15,7 +17,8 @@ __all__ = [
15
17
  'DataFile', 'DataDirectory', 'DataSequence',
16
18
  'agilent', 'waters', 'debug',
17
19
  'read', 'read_sequence', 'read_metadata', 'mz_resolution',
18
- 'from_asm', 'sequence_from_asm', 'iso_timestamp',
20
+ 'from_asm', 'sequence_from_asm', 'peaks_from_asm', 'iso_timestamp',
21
+ 'asm_technique', 'sniff_vendor',
19
22
  'VENDORS', 'MZ_FLOORS',
20
23
  ]
21
24
 
@@ -114,19 +117,22 @@ def _warn_bin_width_floor(datafiles, bin_width, vendor):
114
117
  f"{described}; it only inserts empty bins.")
115
118
 
116
119
 
117
- def _sniff_vendor(path):
120
+ def sniff_vendor(path):
118
121
  """
119
122
  Identifies the vendor of a directory from its contents.
120
123
 
121
- Used as a fallback when a directory's name lacks the conventional vendor
122
- suffix (e.g. a Waters .raw folder renamed to ``Caffeine 3``). Returns
123
- 'agilent', 'waters', or None if no signature matches.
124
+ :func:`read` falls back to this when a directory's name lacks the
125
+ conventional vendor suffix (e.g. a Waters .raw folder renamed to
126
+ ``Caffeine 3``), so a caller deciding whether a folder is a run rainbow
127
+ can read asks the same question :func:`read` will. The name is not
128
+ consulted, so a ``.D`` folder holding nothing rainbow recognizes is None.
124
129
 
125
130
  Args:
126
131
  path (str): Path of the directory.
127
132
 
128
133
  Returns:
129
- Vendor name, or None.
134
+ 'agilent', 'waters', or None if no signature matches (or the path is
135
+ not a directory).
130
136
 
131
137
  """
132
138
  try:
@@ -149,6 +155,10 @@ def _sniff_vendor(path):
149
155
  return None
150
156
 
151
157
 
158
+ # The name it had while it was private, kept for callers that reached for it.
159
+ _sniff_vendor = sniff_vendor
160
+
161
+
152
162
  def _detect_vendor(path):
153
163
  """
154
164
  Determines which vendor parser to use for a path.
@@ -176,7 +186,7 @@ def _detect_vendor(path):
176
186
  if ext == '.raw':
177
187
  return 'waters'
178
188
  if os.path.isdir(path):
179
- return _sniff_vendor(path)
189
+ return sniff_vendor(path)
180
190
  return None
181
191
 
182
192
 
@@ -229,7 +239,7 @@ def _unreadable(path, what="read"):
229
239
 
230
240
  def read(path, display_precision='auto', hrms=False, requested_files=None,
231
241
  telemetry=False, centroid=False, format=None, bin_width=None,
232
- _labels_only=False, **removed):
242
+ peaks=False, _labels_only=False, **removed):
233
243
  """
234
244
  Reads a chromatogram data directory. Main method of the package.
235
245
 
@@ -282,6 +292,13 @@ def read(path, display_precision='auto', hrms=False, requested_files=None,
282
292
  default) to keep the per-scan representation, or pass a width to
283
293
  project the scans onto one shared m/z grid (see
284
294
  :ref:`hrms-data-model`).
295
+ peaks (bool, optional): Flag for reading the run's integrated peaks
296
+ into ``DataDirectory.peaks``, as :func:`read_sequence` does for a
297
+ whole sequence. For Agilent they come from the result document of
298
+ the sequence the run sits in (``sequence.acaml`` beside it), or
299
+ else from the run's own (``sequence.acam_`` inside it); a run with
300
+ neither has none. Waters results and a .dx archive's are not
301
+ read; asking for them warns.
285
302
 
286
303
  Returns:
287
304
  DataDirectory representing the directory.
@@ -309,6 +326,9 @@ def read(path, display_precision='auto', hrms=False, requested_files=None,
309
326
  if not isinstance(telemetry, bool):
310
327
  raise Exception("The telemetry flag must be a boolean.")
311
328
 
329
+ if not isinstance(peaks, bool):
330
+ raise Exception("The peaks flag must be a boolean.")
331
+
312
332
  # display_precision is a label precision (decimals for the reported m/z),
313
333
  # and is cosmetic: it rounds the labels, never the data. 'auto' is finalized
314
334
  # per file inside each parser, where the acquisition is actually known:
@@ -337,10 +357,18 @@ def read(path, display_precision='auto', hrms=False, requested_files=None,
337
357
  if vendor == 'agilent':
338
358
  datadir = agilent.read(
339
359
  path, display_precision, hrms, requested_files, telemetry, centroid,
340
- bin_width, _labels_only)
360
+ bin_width, peaks=peaks, _labels_only=_labels_only)
341
361
  elif vendor == 'waters':
342
362
  datadir = waters.read(
343
363
  path, display_precision, requested_files, bin_width, _labels_only)
364
+ if peaks and datadir is not None:
365
+ import warnings
366
+ # The run gets an empty list, which alone would read as a run
367
+ # nobody integrated, so the read says why it is empty.
368
+ warnings.warn(
369
+ f"rainbow does not read integrated peaks from Waters data; "
370
+ f"{os.path.basename(path)} is read without them.")
371
+ datadir.peaks = []
344
372
 
345
373
  if datadir is None:
346
374
  raise _unreadable(path, "read")
@@ -626,7 +654,7 @@ def read_sequence(path, display_precision='auto', hrms=False,
626
654
  """
627
655
  Reads a multi-injection sequence directory.
628
656
 
629
- Where :func:`read` reads a single injection, this reads the whole run: a
657
+ Where :func:`read` reads a single run, this reads the whole sequence: a
630
658
  directory holding one injection subdirectory per sample, plus the
631
659
  sequence-level method and metadata. Each injection is read with
632
660
  :func:`read`, and the injections are returned in sorted-name order, which is
@@ -0,0 +1,33 @@
1
+ """
2
+ The excitation and emission a fluorescence channel's description names.
3
+
4
+ Every reader that types a fluorescence channel asks the same question of a
5
+ vendor's text, in each vendor's spelling: ChemStation and OpenLab write
6
+ "FLD1 A, Ex=230, Em=310", Empower "ACQUITY FLR ChA Ex280,Em340 nm". One parser
7
+ answers it for all of them, so no two readers can disagree about which
8
+ channel is a fluorescence one, or about its wavelengths.
9
+ """
10
+ import re
11
+
12
+ _NUMBER = r"(\d+(?:\.\d+)?)"
13
+
14
+ EXCITATION_EMISSION_RE = re.compile(
15
+ r"\bEx\s*[:=]?\s*" + _NUMBER + r"\s*(?:nm)?\s*[,/ ]\s*Em\s*[:=]?\s*"
16
+ + _NUMBER, re.IGNORECASE)
17
+
18
+
19
+ def excitation_emission(text):
20
+ """
21
+ The ``(excitation, emission)`` wavelengths ``text`` names, in nm, or None.
22
+
23
+ Args:
24
+ text (str): A signal description, channel name, or cube label.
25
+
26
+ Returns:
27
+ tuple: Two floats, or None when the text names no Ex/Em pair.
28
+
29
+ """
30
+ match = EXCITATION_EMISSION_RE.search(text) if text else None
31
+ if match is None:
32
+ return None
33
+ return float(match.group(1)), float(match.group(2))
@@ -0,0 +1,6 @@
1
+ # The version of rainbow-api this source tree is, which an export names as its
2
+ # converter. It has to match pyproject.toml's; tests/test_asm_roundtrip.py
3
+ # checks that they agree. Read from here rather than from the installed
4
+ # distribution's metadata, which an editable install leaves at whatever
5
+ # version it was installed as.
6
+ __version__ = "1.5.5"
@@ -8,8 +8,8 @@ from rainbow.datasequence import DataSequence
8
8
 
9
9
 
10
10
  def read(path, display_precision='auto', hrms=False, requested_files=None,
11
- telemetry=False, centroid=False, bin_width=None, _labels_only=False,
12
- **removed):
11
+ telemetry=False, centroid=False, bin_width=None, peaks=False,
12
+ _labels_only=False, **removed):
13
13
  """
14
14
  Reads an Agilent .D directory or .dx archive.
15
15
 
@@ -32,6 +32,8 @@ def read(path, display_precision='auto', hrms=False, requested_files=None,
32
32
  representation (one
33
33
  :class:`~rainbow.agilent.masshunter.ProfileDataFile` per flight-time
34
34
  grid), or pass a width to project onto the shared m/z grid.
35
+ peaks (bool, optional): Flag for reading the run's integrated peaks
36
+ into ``DataDirectory.peaks`` (see :func:`injection_peaks`).
35
37
 
36
38
  Returns:
37
39
  DataDirectory representing the Agilent data.
@@ -46,8 +48,19 @@ def read(path, display_precision='auto', hrms=False, requested_files=None,
46
48
  validate_bin_width(bin_width)
47
49
  if os.path.splitext(path)[1].lower() == '.dx':
48
50
  from rainbow.agilent import openlab
49
- return openlab.read(
51
+ datadir = openlab.read(
50
52
  path, display_precision, requested_files, telemetry, bin_width)
53
+ if peaks and datadir is not None:
54
+ # An archive's results are not read. The run gets an empty list,
55
+ # which alone would read as a run nobody integrated, so the read
56
+ # says why it is empty.
57
+ import warnings
58
+ warnings.warn(
59
+ "rainbow does not read integrated peaks from an OpenLab .dx "
60
+ "archive; {} is read without them.".format(
61
+ os.path.basename(path)))
62
+ datadir.peaks = []
63
+ return datadir
51
64
 
52
65
  datafiles = []
53
66
  datafiles.extend(chemstation.parse_allfiles(
@@ -92,7 +105,49 @@ def read(path, display_precision='auto', hrms=False, requested_files=None,
92
105
  os.path.join(path, "AcqData", "MSPeak.bin")):
93
106
  metadata['centroid_available'] = True
94
107
 
95
- return DataDirectory(path, datafiles, metadata)
108
+ datadir = DataDirectory(path, datafiles, metadata)
109
+ if peaks:
110
+ datadir.peaks = _with_channels(datadir, injection_peaks(path))
111
+ return datadir
112
+
113
+
114
+ def injection_peaks(path):
115
+ """
116
+ Reads the integrated peaks of one injection .D directory.
117
+
118
+ The same peaks :func:`read_sequence` attaches to the injection, found the
119
+ same way: from the ``sequence.acaml`` of the sequence directory the .D
120
+ sits in, matched by the .D's folder name, or failing that from the .D's
121
+ own ``sequence.acam_``.
122
+
123
+ Each call parses the whole result document, which for a sequence holds
124
+ every injection's results. To read the peaks of many injections of one
125
+ sequence, ``read_sequence(path, peaks=True)`` parses it once for all of
126
+ them and is the efficient path.
127
+
128
+ Args:
129
+ path (str): Path of the .D directory.
130
+
131
+ Returns:
132
+ list: The injection's signal groups (see
133
+ :func:`rainbow.agilent.sequence.parse_peaks`), or ``[]`` when no
134
+ result document covers it.
135
+
136
+ """
137
+ from rainbow.agilent import sequence
138
+ # Absolute, so a relative path such as "run.D" still has a parent
139
+ # directory to look for the sequence.acaml in.
140
+ path = os.path.abspath(path)
141
+ name = os.path.basename(path)
142
+ sequence_acaml = sequence.find(os.path.dirname(path) or os.curdir)
143
+ groups = None
144
+ if sequence_acaml is not None:
145
+ groups = {injection.lower(): found for injection, found
146
+ in sequence.parse_peaks(sequence_acaml).items()
147
+ }.get(name.lower())
148
+ if not groups:
149
+ groups = _own_peaks(name, path)
150
+ return groups or []
96
151
 
97
152
 
98
153
  def injection_dirs(path):
@@ -167,7 +222,7 @@ def read_sequence(path, display_precision='auto', hrms=False,
167
222
  metadata = {'injection_count': len(injections)}
168
223
 
169
224
  # Merge the sequence-level document (instrument, operator), and let its
170
- # run-wide operator fill any injection that lacked one.
225
+ # sequence-wide operator fill any injection that lacked one.
171
226
  from rainbow.agilent import sequence
172
227
  sequence_acaml = sequence.find(path)
173
228
  if sequence_acaml is not None:
@@ -213,11 +268,49 @@ def _attach_peaks(injections, injection_paths, sequence_acaml):
213
268
  for injection, injection_path in zip(injections, injection_paths):
214
269
  groups = folded.get(injection.name.lower())
215
270
  if not groups:
216
- groups = _injection_peaks(injection, injection_path)
217
- injection.peaks = groups or []
271
+ groups = _own_peaks(injection.name, injection_path)
272
+ injection.peaks = _with_channels(injection, groups or [])
273
+
274
+
275
+ def _with_channels(datadir, groups):
276
+ """``groups`` with each one's detector and metadata from its DataFile.
277
+
278
+ A result document names the channel a signal was integrated on but not
279
+ its detector, which the run's own file for that channel does say. A
280
+ group whose channel the run did not read keeps None.
281
+ """
282
+ by_key = {os.path.splitext(datafile.name)[0].upper(): datafile
283
+ for datafile in datadir.datafiles + datadir.analog}
284
+ for group in groups:
285
+ channel = group.get("channel_file") or group.get("signal") or ""
286
+ datafile = by_key.get(
287
+ os.path.splitext(channel)[0].replace(" ", "").upper())
288
+ if datafile is not None:
289
+ group["detector"] = datafile.detector
290
+ group["metadata"] = dict(datafile.metadata)
291
+ _fill_units(group, datafile.metadata.get("unit"))
292
+ return groups
218
293
 
219
294
 
220
- def _injection_peaks(injection, injection_path):
295
+ def _fill_units(group, unit):
296
+ """Gives a group's peaks the channel's unit where they state none.
297
+
298
+ ChemStation's peak table is in the channel's unit, a height in it and an
299
+ area in it per second, but does not say so.
300
+ """
301
+ if not unit:
302
+ return
303
+ lists = [group["peaks"]] + [alternate["peaks"] for alternate
304
+ in group.get("alternates") or []]
305
+ for peaks in lists:
306
+ for peak in peaks:
307
+ if peak.get("height_unit") is None:
308
+ peak["height_unit"] = unit
309
+ if peak.get("area_unit") is None:
310
+ peak["area_unit"] = unit + ".s"
311
+
312
+
313
+ def _own_peaks(injection_name, injection_path):
221
314
  """Peaks from an injection's own result document (sequence.acam_)."""
222
315
  from rainbow.agilent import sequence
223
316
  document = sequence.find_result_document(injection_path)
@@ -227,7 +320,7 @@ def _injection_peaks(injection, injection_path):
227
320
  if not by_injection:
228
321
  return None
229
322
  folded = {name.lower(): groups for name, groups in by_injection.items()}
230
- groups = folded.get(injection.name.lower())
323
+ groups = folded.get(injection_name.lower())
231
324
  if groups is None and len(by_injection) == 1:
232
325
  # A per-injection document holds exactly this injection's peaks.
233
326
  groups = next(iter(by_injection.values()))
@@ -18,6 +18,7 @@ except ImportError:
18
18
  import xml.etree.ElementTree as etree
19
19
  from rainbow.datafile import DataFile
20
20
  from rainbow._binning import bin_datapairs
21
+ from rainbow._optics import excitation_emission
21
22
 
22
23
  # Optional compiled accelerators for the delta decode loops.
23
24
  # Falls back to the pure-Python implementations below if not built.
@@ -42,6 +43,10 @@ _MS_INT_POW8 = np.array([1, 8, 64, 512], dtype=np.uint32)
42
43
  # and other detectors have no Sig= clause. Shared with the OpenLab .dx parser.
43
44
  _SIG_RE = re.compile(r'Sig=([\d.]+),([\d.]+)')
44
45
  _REF_RE = re.compile(r'Ref=([\d.]+),([\d.]+)')
46
+ _REF_OFF_RE = re.compile(r'Ref=off\b', re.IGNORECASE)
47
+
48
+ # A fluorescence detector names its channels FLD1A, "FLD1 A", ...
49
+ _FLD_SIGNAL_RE = re.compile(r'\s*FLD\d', re.IGNORECASE)
45
50
 
46
51
  # Not every single-wavelength channel writes a Sig= clause. A variable- or
47
52
  # multi-wavelength detector often spells the same setting out, e.g.
@@ -55,12 +60,23 @@ def parse_optics(description):
55
60
 
56
61
  Returns a dict with any of ``wavelength``, ``bandwidth``,
57
62
  ``reference_wavelength``, and ``reference_bandwidth`` (in nm), parsed from
58
- the ``Sig=``/``Ref=`` clause of a single-wavelength channel. Descriptions
59
- without such a clause (spectra, FID, telemetry, ``Ref=off``) yield an
60
- empty or reference-free dict.
63
+ the ``Sig=``/``Ref=`` clause of a single-wavelength channel. ``Ref=off``
64
+ gives a ``reference_wavelength`` of None: the channel states that it has
65
+ no reference, which is not the same as stating nothing about one, and two
66
+ channels at one wavelength differ by it. A fluorescence channel's
67
+ ``Ex=``/``Em=`` clause gives ``excitation_wavelength`` and
68
+ ``emission_wavelength`` instead. Descriptions without such a clause
69
+ (spectra, FID, telemetry) yield an empty dict.
61
70
 
62
71
  """
63
72
  optics = {}
73
+ # A fluorescence channel names its excitation and emission instead, e.g.
74
+ # "FLD1 A, Ex=230, Em=310". Its first number is the excitation, so reading
75
+ # it as a UV wavelength put a fluorescence trace at 230 nm absorbance.
76
+ pair = excitation_emission(description)
77
+ if pair:
78
+ optics['excitation_wavelength'], optics['emission_wavelength'] = pair
79
+ return optics
64
80
  sig = _SIG_RE.search(description)
65
81
  if sig:
66
82
  optics['wavelength'] = float(sig.group(1))
@@ -69,6 +85,8 @@ def parse_optics(description):
69
85
  if ref:
70
86
  optics['reference_wavelength'] = float(ref.group(1))
71
87
  optics['reference_bandwidth'] = float(ref.group(2))
88
+ elif _REF_OFF_RE.search(description):
89
+ optics['reference_wavelength'] = None
72
90
  return optics
73
91
 
74
92
  """
@@ -205,6 +223,17 @@ def _detector_from_signal(metadata, default=None, uv_only=False):
205
223
  return 'UV', sig.group(1)
206
224
  if 'ADC' in signal:
207
225
  return ('ELSD' if 'CHANNEL' in signal else 'CAD'), ''
226
+ optics = parse_optics(signal)
227
+ if 'emission_wavelength' in optics:
228
+ # The y-axis label is the emission, the wavelength the detector
229
+ # measures at, as rb.from_asm labels a fluorescence channel.
230
+ metadata.update(optics)
231
+ return 'FLD', str(optics['emission_wavelength'])
232
+ if _FLD_SIGNAL_RE.match(signal):
233
+ # A fluorescence detector's own channel whose wavelengths are not
234
+ # spelled as numbers (a scan, a program): still FLD, as OpenLab types
235
+ # it by its device, rather than falling through to the FID default.
236
+ return 'FLD', ''
208
237
  if uv_only:
209
238
  # The 130/30 container holds no flame ionization channel, so the
210
239
  # ambiguity that forces the Sig= clause on 179/181 does not arise here:
@@ -3,6 +3,7 @@ Methods for parsing Agilent Masshunter files.
3
3
 
4
4
  """
5
5
  import os
6
+ import re
6
7
  import struct
7
8
  import warnings
8
9
  import numpy as np
@@ -348,8 +349,14 @@ _SD_WAVELENGTH_END = 56 # f64, nm
348
349
  # spectrum with its wavelengths, a .cg chromatogram with its retention times.
349
350
  _AXIS_PREFIX_SIZE = 16 # f64 start + f64 step
350
351
 
351
- # Devices that produce absorbance signals, matching the Chemstation naming.
352
- _DAD_DEVICES = ('DAD', 'MWD', 'VWD')
352
+ # Devices whose .cd/.cg chromatograms are read as detector signals, matching
353
+ # the Chemstation naming: the absorbance detectors, and a fluorescence
354
+ # detector, which writes the same pair. The pumps and column compartments,
355
+ # whose pairs hold only telemetry, are not among them.
356
+ _DAD_DEVICES = ('DAD', 'MWD', 'VWD', 'FLD')
357
+
358
+ # A description naming an excitation or emission, numeric or not.
359
+ _NAMES_EX_EM_RE = re.compile(r'\b(?:Ex|Em)\b', re.IGNORECASE)
353
360
 
354
361
 
355
362
  def parse_dadfiles(path, telemetry=False, requested_files=None, listing=None):
@@ -414,7 +421,10 @@ def parse_dadfiles(path, telemetry=False, requested_files=None, listing=None):
414
421
  # The spectra are one file under one name, so unlike the chromatograms
415
422
  # they match a request exactly - a name that is merely similar is not a
416
423
  # file anyone asked for.
417
- if (os.path.isfile(spectra_path) and os.path.isfile(desc_path)
424
+ # Only an absorbance detector's spectra are absorbance spectra; a
425
+ # fluorescence detector's would be read as UV.
426
+ if (stem[:3].upper() != 'FLD'
427
+ and os.path.isfile(spectra_path) and os.path.isfile(desc_path)
418
428
  and (not requested_files
419
429
  or os.path.basename(spectra_path).lower() in requested_files)):
420
430
  spectra = parse_dadspectra(spectra_path, desc_path)
@@ -569,14 +579,26 @@ def parse_dadchroms(path, signals, telemetry=False, requested_files=None):
569
579
 
570
580
  for signal in signals:
571
581
  # An absorbance signal is named the Chemstation way ("Sig=254.0,..."),
572
- # and carries mAU; the detector's telemetry traces have neither.
573
- is_absorbance = (signal['unit'].lower() == 'mau'
574
- or signal['description'].startswith('Sig='))
582
+ # and carries mAU; the detector's telemetry traces have neither. A
583
+ # fluorescence signal names its excitation and emission ("Ex=230,
584
+ # Em=310") in any unit.
585
+ optics = parse_optics(signal['description'])
586
+ # In an FLD's own file, a signal that names an excitation or emission
587
+ # in any form ("Ex=Scan"), or reads in its luminescence units, is a
588
+ # fluorescence signal too, not one of the detector's telemetry traces.
589
+ is_fluorescence = 'emission_wavelength' in optics or (
590
+ stem[:3].upper() == 'FLD'
591
+ and (_NAMES_EX_EM_RE.search(signal['description'])
592
+ or signal['unit'].strip().upper() == 'LU'))
593
+ is_absorbance = not is_fluorescence and (
594
+ signal['unit'].lower() == 'mau'
595
+ or signal['description'].startswith('Sig='))
575
596
  signal_name = f"{stem}{signal['letter']}.cg".lower()
576
597
  requested = bool(requested_files) and signal_name in requested_files
577
598
  # Naming a telemetry trace explicitly parses it whether or not the flag
578
599
  # is set, as it does for .dx telemetry.
579
- if not is_absorbance and not telemetry and not requested:
600
+ if not (is_absorbance or is_fluorescence) and not telemetry \
601
+ and not requested:
580
602
  continue
581
603
  if requested_files and not (requested or filename in requested_files):
582
604
  continue
@@ -599,11 +621,16 @@ def parse_dadchroms(path, signals, telemetry=False, requested_files=None):
599
621
  # filename (DAD1A.ch), keeping this format's own extension: here all
600
622
  # the signals share one file, so the letter is what tells them apart.
601
623
  name = os.path.join(os.path.dirname(path), f"{stem}{signal['letter']}.cg")
624
+ if is_fluorescence:
625
+ detector, ylabel = 'FLD', optics.get('emission_wavelength', '')
626
+ else:
627
+ detector = 'UV' if is_absorbance else None
628
+ ylabel = _signal_wavelength(signal['description'])
602
629
  datafiles.append(DataFile(
603
630
  name,
604
- 'UV' if is_absorbance else None,
631
+ detector,
605
632
  times,
606
- np.array([_signal_wavelength(signal['description'])]),
633
+ np.array([ylabel]),
607
634
  values.reshape(-1, 1).copy(),
608
635
  # The description follows the Chemstation convention, so its optics
609
636
  # are surfaced by the same parser the .ch and .dx readers use. A
@@ -611,7 +638,7 @@ def parse_dadchroms(path, signals, telemetry=False, requested_files=None):
611
638
  # is what lets an export record the channel's wavelength setting
612
639
  # rather than leaving it to be inferred from the ylabel.
613
640
  {'signal': signal['description'], 'unit': signal['unit'],
614
- **parse_optics(signal['description'])}))
641
+ **optics}))
615
642
 
616
643
  return datafiles
617
644