rainbow-api 1.0.16__tar.gz → 1.2.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 (42) hide show
  1. {rainbow_api-1.0.16 → rainbow_api-1.2.0}/MANIFEST.in +2 -0
  2. {rainbow_api-1.0.16/rainbow_api.egg-info → rainbow_api-1.2.0}/PKG-INFO +30 -35
  3. {rainbow_api-1.0.16 → rainbow_api-1.2.0}/README.md +27 -34
  4. {rainbow_api-1.0.16 → rainbow_api-1.2.0}/pyproject.toml +9 -1
  5. rainbow_api-1.2.0/rainbow/__init__.py +186 -0
  6. rainbow_api-1.2.0/rainbow/_binning.py +72 -0
  7. {rainbow_api-1.0.16 → rainbow_api-1.2.0}/rainbow/agilent/__init__.py +16 -4
  8. rainbow_api-1.2.0/rainbow/agilent/_chdelta.pyx +96 -0
  9. {rainbow_api-1.0.16 → rainbow_api-1.2.0}/rainbow/agilent/chemstation.py +28 -36
  10. rainbow_api-1.2.0/rainbow/agilent/masshunter.py +1018 -0
  11. {rainbow_api-1.0.16 → rainbow_api-1.2.0}/rainbow/waters/masslynx.py +20 -51
  12. {rainbow_api-1.0.16 → rainbow_api-1.2.0/rainbow_api.egg-info}/PKG-INFO +30 -35
  13. {rainbow_api-1.0.16 → rainbow_api-1.2.0}/rainbow_api.egg-info/SOURCES.txt +4 -0
  14. {rainbow_api-1.0.16 → rainbow_api-1.2.0}/rainbow_api.egg-info/requires.txt +3 -0
  15. {rainbow_api-1.0.16 → rainbow_api-1.2.0}/setup.py +5 -4
  16. rainbow_api-1.2.0/tests/test_accelerator.py +167 -0
  17. rainbow_api-1.2.0/tests/test_agilent.py +63 -0
  18. rainbow_api-1.2.0/tests/test_binning.py +95 -0
  19. rainbow_api-1.2.0/tests/test_datadirectory.py +85 -0
  20. rainbow_api-1.2.0/tests/test_datafile.py +111 -0
  21. rainbow_api-1.2.0/tests/test_masshunter.py +449 -0
  22. rainbow_api-1.2.0/tests/test_read.py +81 -0
  23. rainbow_api-1.2.0/tests/test_waters.py +31 -0
  24. rainbow_api-1.0.16/rainbow/__init__.py +0 -86
  25. rainbow_api-1.0.16/rainbow/agilent/masshunter.py +0 -555
  26. rainbow_api-1.0.16/tests/test_accelerator.py +0 -103
  27. rainbow_api-1.0.16/tests/test_agilent.py +0 -103
  28. rainbow_api-1.0.16/tests/test_datadirectory.py +0 -85
  29. rainbow_api-1.0.16/tests/test_datafile.py +0 -109
  30. rainbow_api-1.0.16/tests/test_masshunter.py +0 -242
  31. rainbow_api-1.0.16/tests/test_waters.py +0 -57
  32. {rainbow_api-1.0.16 → rainbow_api-1.2.0}/COPYING +0 -0
  33. {rainbow_api-1.0.16 → rainbow_api-1.2.0}/COPYING.LESSER +0 -0
  34. {rainbow_api-1.0.16 → rainbow_api-1.2.0}/rainbow/agilent/_msprofile.pyx +0 -0
  35. {rainbow_api-1.0.16 → rainbow_api-1.2.0}/rainbow/agilent/_uvdelta.pyx +0 -0
  36. {rainbow_api-1.0.16 → rainbow_api-1.2.0}/rainbow/agilent/openlab.py +0 -0
  37. {rainbow_api-1.0.16 → rainbow_api-1.2.0}/rainbow/datadirectory.py +0 -0
  38. {rainbow_api-1.0.16 → rainbow_api-1.2.0}/rainbow/datafile.py +0 -0
  39. {rainbow_api-1.0.16 → rainbow_api-1.2.0}/rainbow/waters/__init__.py +0 -0
  40. {rainbow_api-1.0.16 → rainbow_api-1.2.0}/rainbow_api.egg-info/dependency_links.txt +0 -0
  41. {rainbow_api-1.0.16 → rainbow_api-1.2.0}/rainbow_api.egg-info/top_level.txt +0 -0
  42. {rainbow_api-1.0.16 → rainbow_api-1.2.0}/setup.cfg +0 -0
@@ -3,5 +3,7 @@
3
3
  # are regenerated from the .pyx at build time (Cython is in build-system.requires).
4
4
  include rainbow/agilent/_uvdelta.pyx
5
5
  include rainbow/agilent/_msprofile.pyx
6
+ include rainbow/agilent/_chdelta.pyx
6
7
  exclude rainbow/agilent/_uvdelta.c
7
8
  exclude rainbow/agilent/_msprofile.c
9
+ exclude rainbow/agilent/_chdelta.c
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rainbow-api
3
- Version: 1.0.16
3
+ Version: 1.2.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
@@ -15,6 +15,8 @@ Requires-Dist: numpy
15
15
  Requires-Dist: matplotlib
16
16
  Requires-Dist: lxml
17
17
  Requires-Dist: pandas
18
+ Provides-Extra: test
19
+ Requires-Dist: pytest; extra == "test"
18
20
  Dynamic: license-file
19
21
 
20
22
  # rainbow
@@ -24,20 +26,18 @@ Dynamic: license-file
24
26
 
25
27
  *rainbow* provides programmatic access to the raw data encoded in chromatography and mass spectrometry binary files. This library supports the following vendors and detectors:
26
28
 
27
- **Agilent .D**
28
- * `.uv` - UV spectrum (supports incomplete files)
29
- * `.ch` - UV, FID, CAD, and ELSD channels
30
- * `.ms` - MS (supports incomplete files)
31
- * `MSProfile.bin` - HRMS
32
-
33
- **Agilent .dx (OpenLab CDS)**
34
- * `.UV` - DAD spectrum
35
- * `.CH` - single-wavelength UV/DAD signals
36
- * `.IT` - instrument telemetry, as analog data (parse with `telemetry=True`)
37
-
38
- **Waters .raw**
39
- * `CHRO` - CAD and ELSD, as well as miscellaneous analog data
40
- * `FUNC` - UV and MS
29
+ | Container | File | Data | Parse with |
30
+ | --- | --- | --- | --- |
31
+ | **Agilent `.D`** | `.uv` | UV spectrum (supports incomplete files) | |
32
+ | | `.ch` | UV, FID, CAD, and ELSD channels | |
33
+ | | `.ms` | MS (supports incomplete files) | |
34
+ | | `MSProfile.bin` | HRMS and ICP-MS profile spectrum | `hrms=True` |
35
+ | | `MSPeak.bin` | centroid (peak-picked) spectrum | `centroid=True` |
36
+ | **Agilent `.dx`** (OpenLab CDS) | `.UV` | DAD spectrum | |
37
+ | | `.CH` | single-wavelength UV/DAD signals | |
38
+ | | `.IT` | instrument telemetry, as analog data | `telemetry=True` |
39
+ | **Waters `.raw`** | `CHRO` | CAD and ELSD, plus miscellaneous analog data | |
40
+ | | `FUNC` | UV and MS | |
41
41
 
42
42
  There is [documentation](http://rainbow-api.readthedocs.io/) for *rainbow* that also details the structure of each [binary file format](https://rainbow-api.readthedocs.io/en/latest/formats.html).
43
43
 
@@ -62,6 +62,13 @@ datafile = datadir.get_file("DAD1A.uv")
62
62
  ```
63
63
 
64
64
  Here, the `datadir` DataDirectory object contains a DataFile object for `DAD1A.uv`.
65
+
66
+ *rainbow* normally infers the vendor from the path suffix (`.D`/`.dx` for Agilent, `.raw` for Waters). A directory whose name lacks that suffix is identified from its contents instead, so renamed datasets still parse. To force a parser explicitly, pass `format`:
67
+
68
+ ```python
69
+ datadir = rb.read("Noscapine 3", format="waters")
70
+ ```
71
+
65
72
  The raw UV data is contained in numpy arrays that are attributes of `datafile`. Users may find the following particularly useful:
66
73
  * `datafile.xlabels` - 1D numpy array with retention times
67
74
  * `datafile.ylabels` - 1D numpy array with wavelengths
@@ -71,30 +78,18 @@ There is a [tutorial](https://rainbow-api.readthedocs.io/en/latest/tutorial.html
71
78
 
72
79
  ## Performance
73
80
 
74
- Decoding Agilent diode-array (DAD) `.uv` files is the one hot spot in the
75
- library: each file holds a large retention-time × wavelength grid of
76
- delta-encoded absorbances, and the decoding is inherently sequential, so it
77
- cannot be vectorized with NumPy. *rainbow* ships an optional compiled extension
78
- (`rainbow/agilent/_uvdelta.pyx`, built with Cython) that runs this inner loop in
79
- C, decoding large DAD files roughly **100× faster** while producing
80
- bit-identical results.
81
-
82
- The accelerator is entirely optional:
83
-
84
- * Prebuilt wheels on PyPI already include it, so `pip install rainbow-api`
85
- gives you the fast path with no compiler needed.
86
- * If you install from source without a compiler (or without Cython), the build
87
- simply skips the extension and *rainbow* falls back to a pure-Python decoder
88
- with identical output. You can check which path is active with
89
- `rainbow.agilent.chemstation._uvdelta_fast is not None`.
90
-
91
- Other formats (`.ch` channels, `.ms`, MassHunter) are already fast and do not
92
- use the accelerator.
81
+ A few inherently-sequential decode loops are sped up by optional compiled
82
+ (Cython) extensions: roughly **100x faster**, bit-identical, with a transparent
83
+ pure-Python fallback when no compiler is available (prebuilt PyPI wheels include
84
+ them). See the
85
+ [Performance](https://rainbow-api.readthedocs.io/en/latest/performance.html)
86
+ page in the documentation for the optimization strategies behind *rainbow* and
87
+ the considerations for adding a new format.
93
88
 
94
89
  ## Contents
95
90
  * `rainbow/` contains the code of the Python library.
96
91
  * `docs/` contains code for generating documentation. To build documentation locally, you will need to install the `sphinx` and `sphinx-rtd-theme` packages. Then, move to the `docs/` directory and run `make html`. The docpages will be generated under `docs/_build`.
97
- * `tests/` contains unit tests for the library. These can be run with `python -m unittest`.
92
+ * `tests/` contains unit tests for the library. These can be run with `pytest` from the repository root (install the test dependency with `pip install -e .[test]`).
98
93
 
99
94
  For development, an editable install (`pip install -e .`) compiles the optional
100
95
  accelerator in place if a C compiler and Cython are available; otherwise the
@@ -5,20 +5,18 @@
5
5
 
6
6
  *rainbow* provides programmatic access to the raw data encoded in chromatography and mass spectrometry binary files. This library supports the following vendors and detectors:
7
7
 
8
- **Agilent .D**
9
- * `.uv` - UV spectrum (supports incomplete files)
10
- * `.ch` - UV, FID, CAD, and ELSD channels
11
- * `.ms` - MS (supports incomplete files)
12
- * `MSProfile.bin` - HRMS
13
-
14
- **Agilent .dx (OpenLab CDS)**
15
- * `.UV` - DAD spectrum
16
- * `.CH` - single-wavelength UV/DAD signals
17
- * `.IT` - instrument telemetry, as analog data (parse with `telemetry=True`)
18
-
19
- **Waters .raw**
20
- * `CHRO` - CAD and ELSD, as well as miscellaneous analog data
21
- * `FUNC` - UV and MS
8
+ | Container | File | Data | Parse with |
9
+ | --- | --- | --- | --- |
10
+ | **Agilent `.D`** | `.uv` | UV spectrum (supports incomplete files) | |
11
+ | | `.ch` | UV, FID, CAD, and ELSD channels | |
12
+ | | `.ms` | MS (supports incomplete files) | |
13
+ | | `MSProfile.bin` | HRMS and ICP-MS profile spectrum | `hrms=True` |
14
+ | | `MSPeak.bin` | centroid (peak-picked) spectrum | `centroid=True` |
15
+ | **Agilent `.dx`** (OpenLab CDS) | `.UV` | DAD spectrum | |
16
+ | | `.CH` | single-wavelength UV/DAD signals | |
17
+ | | `.IT` | instrument telemetry, as analog data | `telemetry=True` |
18
+ | **Waters `.raw`** | `CHRO` | CAD and ELSD, plus miscellaneous analog data | |
19
+ | | `FUNC` | UV and MS | |
22
20
 
23
21
  There is [documentation](http://rainbow-api.readthedocs.io/) for *rainbow* that also details the structure of each [binary file format](https://rainbow-api.readthedocs.io/en/latest/formats.html).
24
22
 
@@ -43,6 +41,13 @@ datafile = datadir.get_file("DAD1A.uv")
43
41
  ```
44
42
 
45
43
  Here, the `datadir` DataDirectory object contains a DataFile object for `DAD1A.uv`.
44
+
45
+ *rainbow* normally infers the vendor from the path suffix (`.D`/`.dx` for Agilent, `.raw` for Waters). A directory whose name lacks that suffix is identified from its contents instead, so renamed datasets still parse. To force a parser explicitly, pass `format`:
46
+
47
+ ```python
48
+ datadir = rb.read("Noscapine 3", format="waters")
49
+ ```
50
+
46
51
  The raw UV data is contained in numpy arrays that are attributes of `datafile`. Users may find the following particularly useful:
47
52
  * `datafile.xlabels` - 1D numpy array with retention times
48
53
  * `datafile.ylabels` - 1D numpy array with wavelengths
@@ -52,30 +57,18 @@ There is a [tutorial](https://rainbow-api.readthedocs.io/en/latest/tutorial.html
52
57
 
53
58
  ## Performance
54
59
 
55
- Decoding Agilent diode-array (DAD) `.uv` files is the one hot spot in the
56
- library: each file holds a large retention-time × wavelength grid of
57
- delta-encoded absorbances, and the decoding is inherently sequential, so it
58
- cannot be vectorized with NumPy. *rainbow* ships an optional compiled extension
59
- (`rainbow/agilent/_uvdelta.pyx`, built with Cython) that runs this inner loop in
60
- C, decoding large DAD files roughly **100× faster** while producing
61
- bit-identical results.
62
-
63
- The accelerator is entirely optional:
64
-
65
- * Prebuilt wheels on PyPI already include it, so `pip install rainbow-api`
66
- gives you the fast path with no compiler needed.
67
- * If you install from source without a compiler (or without Cython), the build
68
- simply skips the extension and *rainbow* falls back to a pure-Python decoder
69
- with identical output. You can check which path is active with
70
- `rainbow.agilent.chemstation._uvdelta_fast is not None`.
71
-
72
- Other formats (`.ch` channels, `.ms`, MassHunter) are already fast and do not
73
- use the accelerator.
60
+ A few inherently-sequential decode loops are sped up by optional compiled
61
+ (Cython) extensions: roughly **100x faster**, bit-identical, with a transparent
62
+ pure-Python fallback when no compiler is available (prebuilt PyPI wheels include
63
+ them). See the
64
+ [Performance](https://rainbow-api.readthedocs.io/en/latest/performance.html)
65
+ page in the documentation for the optimization strategies behind *rainbow* and
66
+ the considerations for adding a new format.
74
67
 
75
68
  ## Contents
76
69
  * `rainbow/` contains the code of the Python library.
77
70
  * `docs/` contains code for generating documentation. To build documentation locally, you will need to install the `sphinx` and `sphinx-rtd-theme` packages. Then, move to the `docs/` directory and run `make html`. The docpages will be generated under `docs/_build`.
78
- * `tests/` contains unit tests for the library. These can be run with `python -m unittest`.
71
+ * `tests/` contains unit tests for the library. These can be run with `pytest` from the repository root (install the test dependency with `pip install -e .[test]`).
79
72
 
80
73
  For development, an editable install (`pip install -e .`) compiles the optional
81
74
  accelerator in place if a C compiler and Cython are available; otherwise the
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "rainbow-api"
7
- version = "1.0.16"
7
+ version = "1.2.0"
8
8
  description = "Read chromatography and mass spectrometry binary files"
9
9
  readme = "README.md"
10
10
  license = {text = "COPYING.LESSER"}
@@ -22,6 +22,9 @@ dependencies = [
22
22
  "pandas"
23
23
  ]
24
24
 
25
+ [project.optional-dependencies]
26
+ test = ["pytest"]
27
+
25
28
  [project.urls]
26
29
  Repository = "https://github.com/evanyeyeye/rainbow"
27
30
  Documentation = "https://rainbow-api.readthedocs.io"
@@ -39,3 +42,8 @@ include = ["rainbow*"]
39
42
  # (pure-Python-fallback) wheel, and the sdist covers everything else.
40
43
  build = "cp38-* cp39-* cp310-* cp311-* cp312-* cp313-*"
41
44
  skip = "*-musllinux* *_i686 *-win32"
45
+
46
+ [tool.pytest.ini_options]
47
+ # Tests are run from the repo root (fixtures are referenced as tests/inputs/...
48
+ # and the suite imports the `tests` package).
49
+ testpaths = ["tests"]
@@ -0,0 +1,186 @@
1
+ import os
2
+ import re
3
+ from rainbow.datafile import DataFile
4
+ from rainbow.datadirectory import DataDirectory
5
+ from rainbow import agilent, waters
6
+
7
+
8
+ # Vendor parsers that rainbow can dispatch to.
9
+ VENDORS = ('agilent', 'waters')
10
+
11
+
12
+ def _sniff_vendor(path):
13
+ """
14
+ Identifies the vendor of a directory from its contents.
15
+
16
+ Used as a fallback when a directory's name lacks the conventional vendor
17
+ suffix (e.g. a Waters .raw folder renamed to ``Noscapine 3``). Returns
18
+ 'agilent', 'waters', or None if no signature matches.
19
+
20
+ Args:
21
+ path (str): Path of the directory.
22
+
23
+ Returns:
24
+ Vendor name, or None.
25
+
26
+ """
27
+ try:
28
+ names = os.listdir(path)
29
+ except OSError:
30
+ return None
31
+ lower = {name.lower() for name in names}
32
+
33
+ # Waters .raw: the function/header manifests or numbered _FUNC data files.
34
+ if '_functns.inf' in lower or '_header.txt' in lower \
35
+ or any(re.fullmatch(r'_func\d{3}\.dat', name) for name in lower):
36
+ return 'waters'
37
+
38
+ # Agilent .D: the AcqData subdirectory or any Chemstation data file.
39
+ if 'acqdata' in lower \
40
+ or any(os.path.splitext(name)[1] in ('.ch', '.uv', '.ms')
41
+ for name in lower):
42
+ return 'agilent'
43
+
44
+ return None
45
+
46
+
47
+ def _detect_vendor(path):
48
+ """
49
+ Determines which vendor parser to use for a path.
50
+
51
+ The path's extension is tried first (.D/.dx -> Agilent, .raw -> Waters),
52
+ which preserves rainbow's historical behavior exactly. If the extension is
53
+ unrecognized and the path is a directory, its contents are sniffed for a
54
+ vendor signature, so datasets whose folders were renamed without the
55
+ conventional suffix still parse. Because this fallback only runs when the
56
+ extension matches nothing, it can only make a previously-unreadable path
57
+ readable -- it never changes how an already-recognized path is parsed.
58
+
59
+ Args:
60
+ path (str): Path of the directory or .dx file.
61
+
62
+ Returns:
63
+ Vendor name ('agilent' or 'waters'), or None.
64
+
65
+ """
66
+ if not isinstance(path, str):
67
+ return None
68
+ ext = os.path.splitext(path)[1].lower()
69
+ if ext in ('.d', '.dx'):
70
+ return 'agilent'
71
+ if ext == '.raw':
72
+ return 'waters'
73
+ if os.path.isdir(path):
74
+ return _sniff_vendor(path)
75
+ return None
76
+
77
+
78
+ def _resolve_vendor(path, format):
79
+ """Resolves the vendor from an explicit override or by detection."""
80
+ if format is not None:
81
+ if not isinstance(format, str) or format.lower() not in VENDORS:
82
+ raise Exception(
83
+ f"The format argument must be one of {VENDORS} or None.")
84
+ return format.lower()
85
+ return _detect_vendor(path)
86
+
87
+
88
+ def read(path, prec=0, hrms=False, requested_files=None, telemetry=False,
89
+ centroid=False, format=None):
90
+ """
91
+ Reads a chromatogram data directory. Main method of the package.
92
+
93
+ Increasing the precision may drastically increase memory usage for \
94
+ larger files. Specifying a higher precision mainly affects the \
95
+ parsing of MS data, because intensities are summed within the given \
96
+ precision for each ylabel.
97
+
98
+ Max precision available for Agilent MS data is 1.
99
+
100
+ Max precision recommended for Waters MS data is 3.
101
+
102
+ Agilent HRMS parsing may be slow. Set the flag to enable it.
103
+
104
+ For Agilent .dx archives, instrument telemetry traces (e.g. pressure, \
105
+ temperature) are skipped unless the telemetry flag is set.
106
+
107
+ The vendor is normally detected from the path: a .D/.dx path is read as \
108
+ Agilent and a .raw path as Waters. A directory whose name lacks that \
109
+ suffix is identified from its contents instead. Pass ``format`` \
110
+ ('agilent' or 'waters') to override detection entirely.
111
+
112
+ Args:
113
+ path (str): Path of the directory.
114
+ prec (int, optional): Number of decimals to round ylabels.
115
+ hrms (bool, optional): Flag for Agilent HRMS (MSProfile.bin) parsing.
116
+ requested_files (list, optional): List of filenames to parse.
117
+ telemetry (bool, optional): Flag for Agilent .dx telemetry traces.
118
+ centroid (bool, optional): Flag for Agilent MassHunter centroid
119
+ (MSPeak.bin) parsing.
120
+ format (str, optional): Force the vendor parser ('agilent' or
121
+ 'waters'), bypassing extension/content detection.
122
+
123
+ Returns:
124
+ DataDirectory representing the directory.
125
+
126
+ """
127
+ vendor = _resolve_vendor(path, format)
128
+
129
+ ext = os.path.splitext(path)[1].lower() if isinstance(path, str) else ''
130
+ if ext == '.dx':
131
+ if not isinstance(path, str) or not os.path.isfile(path):
132
+ raise Exception(f"{path} is not a file.")
133
+ elif not isinstance(path, str) or not os.path.isdir(path):
134
+ raise Exception(f"{path} is not a directory.")
135
+
136
+ if not isinstance(prec, int) or prec < 0:
137
+ raise Exception(f"Invalid precision: {prec}.")
138
+
139
+ if not isinstance(hrms, bool):
140
+ raise Exception(f"The hrms flag must be a boolean.")
141
+
142
+ if not isinstance(centroid, bool):
143
+ raise Exception(f"The centroid flag must be a boolean.")
144
+
145
+ if requested_files is not None and not isinstance(requested_files, list):
146
+ raise Exception(f"The requested_files argument must be a list.")
147
+
148
+ if requested_files:
149
+ requested_files = list(map(str.lower, requested_files))
150
+
151
+ datadir = None
152
+ if vendor == 'agilent':
153
+ datadir = agilent.read(
154
+ path, prec, hrms, requested_files, telemetry, centroid)
155
+ elif vendor == 'waters':
156
+ datadir = waters.read(path, prec, requested_files)
157
+
158
+ if datadir is None:
159
+ raise Exception(f"Rainbow cannot read {path}.")
160
+ return datadir
161
+
162
+
163
+ def read_metadata(path, format=None):
164
+ """
165
+ Reads the metadata for a chromatogram data directory. Main method of the package.
166
+
167
+ Args:
168
+ path (str): Path of the directory.
169
+ format (str, optional): Force the vendor parser ('agilent' or
170
+ 'waters'), bypassing extension/content detection.
171
+
172
+ Returns:
173
+ Dictionary containing a list of datafiles and the metadata.
174
+
175
+ """
176
+ vendor = _resolve_vendor(path, format)
177
+
178
+ metadata = None
179
+ if vendor == 'agilent':
180
+ metadata = agilent.read_metadata(path)
181
+ elif vendor == 'waters':
182
+ metadata = waters.read_metadata(path)
183
+
184
+ if metadata is None:
185
+ raise Exception(f"Rainbow cannot read {path}.")
186
+ return metadata
@@ -0,0 +1,72 @@
1
+ """
2
+ Shared helper for binning (key, value) data pairs into a spectrum matrix.
3
+
4
+ Several vendor parsers store a scan's spectrum as a flat list of
5
+ ``(ylabel, value)`` pairs - Waters ``_FUNC.DAT`` (m/z or wavelength) and
6
+ Agilent ``.ms`` (m/z) - and need to lay those pairs out as a
7
+ ``(retention time x ylabel)`` matrix, summing pairs that share a ylabel within
8
+ a scan. This module provides one vectorized implementation of that step.
9
+ """
10
+
11
+ import numpy as np
12
+
13
+
14
+ def bin_datapairs(keys, values, pair_counts, prec, data_dtype=np.int64):
15
+ """
16
+ Bins (key, value) data pairs into a (retention time x ylabel) matrix.
17
+
18
+ Each scan (retention time) contributes ``pair_counts[i]`` consecutive pairs
19
+ from the flat :obj:`keys`/:obj:`values` arrays. Pairs that share a ylabel
20
+ within the same scan are summed.
21
+
22
+ The keys must already be rounded to :obj:`prec` decimals and be
23
+ non-negative (m/z or wavelength), so the unique ylabels and each pair's
24
+ column are found with an integer histogram in O(n) instead of sorting every
25
+ pair with ``np.unique``/``np.searchsorted``. The values are accumulated into
26
+ a ``data_dtype`` matrix (matching whatever dtype - and overflow/truncation
27
+ behavior - the caller's prior per-scan ``np.add.at`` loop used).
28
+
29
+ Args:
30
+ keys (np.ndarray): Flat ylabels, rounded to :obj:`prec`, non-negative.
31
+ values (np.ndarray): Flat values paired with :obj:`keys`.
32
+ pair_counts (np.ndarray): Number of pairs at each retention time.
33
+ prec (int): Number of decimals the keys were rounded to.
34
+ data_dtype (np.dtype, optional): dtype of the output matrix.
35
+
36
+ Returns:
37
+ 1D numpy array with ylabels (in the keys' dtype). 2D ``data_dtype``
38
+ numpy array with data values (rows are retention times, columns are
39
+ ylabels).
40
+
41
+ """
42
+ num_times = pair_counts.size
43
+
44
+ if keys.size == 0:
45
+ return (np.empty(0, dtype=keys.dtype),
46
+ np.zeros((num_times, 0), dtype=data_dtype))
47
+
48
+ # Map each rounded key onto a non-negative integer bin so the unique
49
+ # ylabels and per-pair columns come from a histogram, not a sort.
50
+ scale = 10 ** prec if prec > 0 else 1
51
+ int_keys = np.rint(keys * scale).astype(np.int64)
52
+ int_keys -= int_keys.min()
53
+
54
+ present = np.zeros(int(int_keys.max()) + 1, dtype=bool)
55
+ present[int_keys] = True
56
+ num_ylabels = int(present.sum())
57
+
58
+ # Column of each pair = its dense bin's rank among the present bins.
59
+ # Columns increase with the key value, so scattering the (already rounded)
60
+ # keys yields the sorted unique ylabels - in the keys' own dtype, matching
61
+ # the previous np.unique(keys) (e.g. float32 for calibrated Waters m/z).
62
+ columns = (np.cumsum(present) - 1)[int_keys]
63
+ ylabels = np.empty(num_ylabels, dtype=keys.dtype)
64
+ ylabels[columns] = keys
65
+
66
+ rows = np.repeat(np.arange(num_times), pair_counts)
67
+ flat_indices = rows * num_ylabels + columns
68
+
69
+ data = np.zeros(num_times * num_ylabels, dtype=data_dtype)
70
+ np.add.at(data, flat_indices, values)
71
+
72
+ return ylabels, data.reshape(num_times, num_ylabels)
@@ -4,16 +4,20 @@ from rainbow.agilent import chemstation
4
4
  from rainbow.datadirectory import DataDirectory
5
5
 
6
6
 
7
- def read(path, prec=0, hrms=False, requested_files=None, telemetry=False):
7
+ def read(path, prec=0, hrms=False, requested_files=None, telemetry=False,
8
+ centroid=False):
8
9
  """
9
10
  Reads an Agilent .D directory or .dx archive.
10
11
 
11
12
  Args:
12
13
  path (str): Path of the directory or .dx file.
13
14
  prec (int, optional): Number of decimals to round masses.
14
- hrms (bool, optional): Flag for HRMS parsing.
15
+ hrms (bool, optional): Flag for parsing the MassHunter profile
16
+ spectrum (MSProfile.bin).
15
17
  requested_files (list, optional): List of filenames to parse.
16
18
  telemetry (bool, optional): Flag for parsing .dx telemetry traces.
19
+ centroid (bool, optional): Flag for parsing the MassHunter centroid
20
+ spectrum (MSPeak.bin).
17
21
 
18
22
  Returns:
19
23
  DataDirectory representing the Agilent data.
@@ -25,15 +29,23 @@ def read(path, prec=0, hrms=False, requested_files=None, telemetry=False):
25
29
 
26
30
  datafiles = []
27
31
  datafiles.extend(chemstation.parse_allfiles(path, prec, requested_files))
28
- if hrms:
32
+ if hrms or centroid:
29
33
  try:
30
34
  from rainbow.agilent import masshunter
31
- datafiles.extend(masshunter.parse_allfiles(path))
35
+ datafiles.extend(
36
+ masshunter.parse_allfiles(path, prec, hrms, centroid))
32
37
  except ModuleNotFoundError:
33
38
  raise ModuleNotFoundError("You must install python-lzf to parse masshunter files.")
34
39
 
35
40
  metadata = chemstation.parse_metadata(path, datafiles)
36
41
 
42
+ # Surface unread MassHunter centroid data so the centroid flag is
43
+ # discoverable: a .D with MSPeak.bin holds a centroid spectrum that is only
44
+ # parsed when centroid=True.
45
+ if not centroid and os.path.isfile(
46
+ os.path.join(path, "AcqData", "MSPeak.bin")):
47
+ metadata['centroid_available'] = True
48
+
37
49
  return DataDirectory(path, datafiles, metadata)
38
50
 
39
51
 
@@ -0,0 +1,96 @@
1
+ # cython: boundscheck=False, wraparound=False, cdivision=True, language_level=3
2
+ """
3
+ Compiled accelerator for the Agilent ``.ch`` delta decode loop.
4
+
5
+ The pure-Python ``decode_delta`` in :mod:`rainbow.agilent.chemstation` spends
6
+ almost all of its time in a per-sample loop that reads the channel signal
7
+ (CAD/ELSD/UV ``.ch`` files) one struct at a time. The encoding is inherently
8
+ sequential (a running accumulator with a sentinel that resets it) and its
9
+ record stride is data-dependent, so it cannot be vectorized with NumPy; only a
10
+ compiled inner loop removes the interpreter overhead. This module is that loop,
11
+ written to produce output bit-identical to the pure-Python reference.
12
+
13
+ It is imported opportunistically by ``chemstation.py``. If the extension was
14
+ not built (no compiler or no Cython at install time), the package falls back to
15
+ the pure-Python implementation transparently.
16
+
17
+ Format
18
+ ------
19
+ The signal is a sequence of segments. Each segment is a 2-byte header - the
20
+ byte ``0x10`` then a one-byte sample count - followed by that many samples; a
21
+ header byte other than ``0x10`` (or the end of the buffer) terminates the
22
+ stream. Each sample is a big-endian 16-bit delta added to a running
23
+ accumulator, *unless* it equals ``-0x8000`` (the sentinel), in which case the
24
+ following big-endian 32-bit integer is the new absolute accumulator value. The
25
+ ``.ch`` fields are big-endian, so the multi-byte values are assembled from
26
+ individual bytes rather than copied.
27
+ """
28
+
29
+ import numpy as np
30
+
31
+ # 16-bit sentinel: the next sample is an absolute 32-bit value, not a delta.
32
+ cdef short _SENTINEL = -0x8000
33
+ # Segment header marker; any other leading byte ends the stream.
34
+ cdef unsigned char _SEGMENT = 0x10
35
+
36
+
37
+ def decode_delta(const unsigned char[::1] buf, Py_ssize_t offset):
38
+ """Decode an Agilent ``.ch`` delta stream into accumulated signal values.
39
+
40
+ Args:
41
+ buf: The whole file as a bytes-like buffer.
42
+ offset: Offset of the first segment header.
43
+
44
+ Returns:
45
+ An ``int64`` array of the accumulated values (one per sample), matching
46
+ ``np.array(decode_delta(...))`` from the pure-Python path.
47
+
48
+ On a well-formed stream (terminated by a non-``0x10`` header byte) this is
49
+ bit-identical to the pure-Python reference. The one difference is on a
50
+ truncated/corrupt stream that ends mid-record: this returns the values
51
+ decoded so far, whereas the pure-Python path raises ``struct.error`` on the
52
+ short read. Graceful truncation is the intended behavior here.
53
+ """
54
+ cdef Py_ssize_t n = buf.shape[0]
55
+ cdef Py_ssize_t off = offset
56
+
57
+ # Each sample is at least two bytes, so the sample count cannot exceed half
58
+ # the remaining bytes; allocate that upper bound once and slice at the end.
59
+ cdef Py_ssize_t ub = (n - offset) // 2
60
+ if ub < 0:
61
+ ub = 0
62
+ out_arr = np.empty(ub, dtype=np.int64)
63
+ cdef long long[::1] out = out_arr
64
+
65
+ cdef Py_ssize_t k = 0
66
+ cdef long long acc = 0
67
+ cdef int count, j
68
+ cdef short delta
69
+ cdef int absolute
70
+
71
+ while off < n:
72
+ if buf[off] != _SEGMENT:
73
+ break
74
+ off += 1
75
+ if off >= n:
76
+ break
77
+ count = buf[off]
78
+ off += 1
79
+ for j in range(count):
80
+ if off + 2 > n:
81
+ break
82
+ delta = <short>((buf[off] << 8) | buf[off + 1])
83
+ off += 2
84
+ if delta == _SENTINEL:
85
+ if off + 4 > n:
86
+ break
87
+ absolute = <int>((buf[off] << 24) | (buf[off + 1] << 16)
88
+ | (buf[off + 2] << 8) | buf[off + 3])
89
+ off += 4
90
+ acc = absolute
91
+ else:
92
+ acc += delta
93
+ out[k] = acc
94
+ k += 1
95
+
96
+ return out_arr[:k]