rainbow-api 1.1.0__tar.gz → 1.3.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 (41) hide show
  1. {rainbow_api-1.1.0 → rainbow_api-1.3.0}/MANIFEST.in +2 -0
  2. {rainbow_api-1.1.0/rainbow_api.egg-info → rainbow_api-1.3.0}/PKG-INFO +30 -36
  3. {rainbow_api-1.1.0 → rainbow_api-1.3.0}/README.md +27 -35
  4. {rainbow_api-1.1.0 → rainbow_api-1.3.0}/pyproject.toml +9 -1
  5. rainbow_api-1.3.0/rainbow/__init__.py +222 -0
  6. rainbow_api-1.3.0/rainbow/_binning.py +72 -0
  7. {rainbow_api-1.1.0 → rainbow_api-1.3.0}/rainbow/agilent/__init__.py +13 -7
  8. rainbow_api-1.3.0/rainbow/agilent/_chdelta.pyx +96 -0
  9. {rainbow_api-1.1.0 → rainbow_api-1.3.0}/rainbow/agilent/_msprofile.pyx +10 -8
  10. {rainbow_api-1.1.0 → rainbow_api-1.3.0}/rainbow/agilent/chemstation.py +46 -50
  11. {rainbow_api-1.1.0 → rainbow_api-1.3.0}/rainbow/agilent/masshunter.py +443 -61
  12. {rainbow_api-1.1.0 → rainbow_api-1.3.0}/rainbow/agilent/openlab.py +5 -2
  13. {rainbow_api-1.1.0 → rainbow_api-1.3.0}/rainbow/waters/__init__.py +10 -5
  14. {rainbow_api-1.1.0 → rainbow_api-1.3.0}/rainbow/waters/masslynx.py +36 -67
  15. {rainbow_api-1.1.0 → rainbow_api-1.3.0/rainbow_api.egg-info}/PKG-INFO +30 -36
  16. {rainbow_api-1.1.0 → rainbow_api-1.3.0}/rainbow_api.egg-info/SOURCES.txt +4 -0
  17. {rainbow_api-1.1.0 → rainbow_api-1.3.0}/rainbow_api.egg-info/requires.txt +3 -0
  18. {rainbow_api-1.1.0 → rainbow_api-1.3.0}/setup.py +5 -4
  19. rainbow_api-1.3.0/tests/test_accelerator.py +170 -0
  20. rainbow_api-1.3.0/tests/test_agilent.py +63 -0
  21. rainbow_api-1.3.0/tests/test_binning.py +95 -0
  22. rainbow_api-1.3.0/tests/test_datadirectory.py +85 -0
  23. rainbow_api-1.3.0/tests/test_datafile.py +111 -0
  24. rainbow_api-1.3.0/tests/test_masshunter.py +775 -0
  25. rainbow_api-1.3.0/tests/test_read.py +81 -0
  26. rainbow_api-1.3.0/tests/test_waters.py +31 -0
  27. rainbow_api-1.1.0/rainbow/__init__.py +0 -93
  28. rainbow_api-1.1.0/tests/test_accelerator.py +0 -103
  29. rainbow_api-1.1.0/tests/test_agilent.py +0 -103
  30. rainbow_api-1.1.0/tests/test_datadirectory.py +0 -85
  31. rainbow_api-1.1.0/tests/test_datafile.py +0 -109
  32. rainbow_api-1.1.0/tests/test_masshunter.py +0 -435
  33. rainbow_api-1.1.0/tests/test_waters.py +0 -57
  34. {rainbow_api-1.1.0 → rainbow_api-1.3.0}/COPYING +0 -0
  35. {rainbow_api-1.1.0 → rainbow_api-1.3.0}/COPYING.LESSER +0 -0
  36. {rainbow_api-1.1.0 → rainbow_api-1.3.0}/rainbow/agilent/_uvdelta.pyx +0 -0
  37. {rainbow_api-1.1.0 → rainbow_api-1.3.0}/rainbow/datadirectory.py +0 -0
  38. {rainbow_api-1.1.0 → rainbow_api-1.3.0}/rainbow/datafile.py +0 -0
  39. {rainbow_api-1.1.0 → rainbow_api-1.3.0}/rainbow_api.egg-info/dependency_links.txt +0 -0
  40. {rainbow_api-1.1.0 → rainbow_api-1.3.0}/rainbow_api.egg-info/top_level.txt +0 -0
  41. {rainbow_api-1.1.0 → rainbow_api-1.3.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.1.0
3
+ Version: 1.3.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,21 +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 profile spectrum (parse with `hrms=True`)
32
- * `MSPeak.bin` - centroid (peak-picked) spectrum (parse with `centroid=True`)
33
-
34
- **Agilent .dx (OpenLab CDS)**
35
- * `.UV` - DAD spectrum
36
- * `.CH` - single-wavelength UV/DAD signals
37
- * `.IT` - instrument telemetry, as analog data (parse with `telemetry=True`)
38
-
39
- **Waters .raw**
40
- * `CHRO` - CAD and ELSD, as well as miscellaneous analog data
41
- * `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 | |
42
41
 
43
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).
44
43
 
@@ -63,6 +62,13 @@ datafile = datadir.get_file("DAD1A.uv")
63
62
  ```
64
63
 
65
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
+
66
72
  The raw UV data is contained in numpy arrays that are attributes of `datafile`. Users may find the following particularly useful:
67
73
  * `datafile.xlabels` - 1D numpy array with retention times
68
74
  * `datafile.ylabels` - 1D numpy array with wavelengths
@@ -72,30 +78,18 @@ There is a [tutorial](https://rainbow-api.readthedocs.io/en/latest/tutorial.html
72
78
 
73
79
  ## Performance
74
80
 
75
- Decoding Agilent diode-array (DAD) `.uv` files is the one hot spot in the
76
- library: each file holds a large retention-time × wavelength grid of
77
- delta-encoded absorbances, and the decoding is inherently sequential, so it
78
- cannot be vectorized with NumPy. *rainbow* ships an optional compiled extension
79
- (`rainbow/agilent/_uvdelta.pyx`, built with Cython) that runs this inner loop in
80
- C, decoding large DAD files roughly **100× faster** while producing
81
- bit-identical results.
82
-
83
- The accelerator is entirely optional:
84
-
85
- * Prebuilt wheels on PyPI already include it, so `pip install rainbow-api`
86
- gives you the fast path with no compiler needed.
87
- * If you install from source without a compiler (or without Cython), the build
88
- simply skips the extension and *rainbow* falls back to a pure-Python decoder
89
- with identical output. You can check which path is active with
90
- `rainbow.agilent.chemstation._uvdelta_fast is not None`.
91
-
92
- Other formats (`.ch` channels, `.ms`, MassHunter) are already fast and do not
93
- 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.
94
88
 
95
89
  ## Contents
96
90
  * `rainbow/` contains the code of the Python library.
97
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`.
98
- * `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]`).
99
93
 
100
94
  For development, an editable install (`pip install -e .`) compiles the optional
101
95
  accelerator in place if a C compiler and Cython are available; otherwise the
@@ -5,21 +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 profile spectrum (parse with `hrms=True`)
13
- * `MSPeak.bin` - centroid (peak-picked) spectrum (parse with `centroid=True`)
14
-
15
- **Agilent .dx (OpenLab CDS)**
16
- * `.UV` - DAD spectrum
17
- * `.CH` - single-wavelength UV/DAD signals
18
- * `.IT` - instrument telemetry, as analog data (parse with `telemetry=True`)
19
-
20
- **Waters .raw**
21
- * `CHRO` - CAD and ELSD, as well as miscellaneous analog data
22
- * `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 | |
23
20
 
24
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).
25
22
 
@@ -44,6 +41,13 @@ datafile = datadir.get_file("DAD1A.uv")
44
41
  ```
45
42
 
46
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
+
47
51
  The raw UV data is contained in numpy arrays that are attributes of `datafile`. Users may find the following particularly useful:
48
52
  * `datafile.xlabels` - 1D numpy array with retention times
49
53
  * `datafile.ylabels` - 1D numpy array with wavelengths
@@ -53,30 +57,18 @@ There is a [tutorial](https://rainbow-api.readthedocs.io/en/latest/tutorial.html
53
57
 
54
58
  ## Performance
55
59
 
56
- Decoding Agilent diode-array (DAD) `.uv` files is the one hot spot in the
57
- library: each file holds a large retention-time × wavelength grid of
58
- delta-encoded absorbances, and the decoding is inherently sequential, so it
59
- cannot be vectorized with NumPy. *rainbow* ships an optional compiled extension
60
- (`rainbow/agilent/_uvdelta.pyx`, built with Cython) that runs this inner loop in
61
- C, decoding large DAD files roughly **100× faster** while producing
62
- bit-identical results.
63
-
64
- The accelerator is entirely optional:
65
-
66
- * Prebuilt wheels on PyPI already include it, so `pip install rainbow-api`
67
- gives you the fast path with no compiler needed.
68
- * If you install from source without a compiler (or without Cython), the build
69
- simply skips the extension and *rainbow* falls back to a pure-Python decoder
70
- with identical output. You can check which path is active with
71
- `rainbow.agilent.chemstation._uvdelta_fast is not None`.
72
-
73
- Other formats (`.ch` channels, `.ms`, MassHunter) are already fast and do not
74
- 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.
75
67
 
76
68
  ## Contents
77
69
  * `rainbow/` contains the code of the Python library.
78
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`.
79
- * `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]`).
80
72
 
81
73
  For development, an editable install (`pip install -e .`) compiles the optional
82
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.1.0"
7
+ version = "1.3.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,222 @@
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, precision='auto', hrms=False, requested_files=None,
89
+ telemetry=False, centroid=False, format=None, bin_width=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
+ precision (int or 'auto', optional): Number of decimals to round
115
+ reported m/z (and other ylabels) to. The default ``'auto'`` chooses
116
+ per file: 4 for high-resolution data (the Agilent HRMS profile and
117
+ TOF centroids) and 0 (whole numbers) for unit-resolution data (UV,
118
+ GC/quadrupole MS, Waters). Pass an explicit integer to override
119
+ (including ``0`` to force nominal mass).
120
+ hrms (bool, optional): Flag for Agilent HRMS (MSProfile.bin) parsing.
121
+ requested_files (list, optional): List of filenames to parse.
122
+ telemetry (bool, optional): Flag for Agilent .dx telemetry traces.
123
+ centroid (bool, optional): Flag for Agilent MassHunter centroid
124
+ (MSPeak.bin) parsing.
125
+ format (str, optional): Force the vendor parser ('agilent' or
126
+ 'waters'), bypassing extension/content detection.
127
+ bin_width (float, optional): Width in daltons of each shared-grid bin
128
+ for Agilent HRMS profile data. Omit it (the default) to keep the
129
+ per-scan representation; pass a width to project the scans onto one
130
+ shared m/z grid (see :ref:`hrms-data-model`). This is the grid's only
131
+ control and is fully independent of ``precision`` (which only rounds
132
+ the reported m/z labels, never the grid). A ``bin_width`` finer than
133
+ ``10**-precision`` is allowed but warns, since two bins may then round
134
+ to the same m/z label.
135
+
136
+ Returns:
137
+ DataDirectory representing the directory.
138
+
139
+ """
140
+ vendor = _resolve_vendor(path, format)
141
+
142
+ ext = os.path.splitext(path)[1].lower() if isinstance(path, str) else ''
143
+ if ext == '.dx':
144
+ if not isinstance(path, str) or not os.path.isfile(path):
145
+ raise Exception(f"{path} is not a file.")
146
+ elif not isinstance(path, str) or not os.path.isdir(path):
147
+ raise Exception(f"{path} is not a directory.")
148
+
149
+ if precision != 'auto' and (
150
+ isinstance(precision, bool) or not isinstance(precision, int)
151
+ or precision < 0):
152
+ raise Exception(
153
+ f"Invalid precision: {precision!r}. Use 'auto' or a non-negative "
154
+ f"integer.")
155
+
156
+ if not isinstance(hrms, bool):
157
+ raise Exception(f"The hrms flag must be a boolean.")
158
+
159
+ if not isinstance(centroid, bool):
160
+ raise Exception(f"The centroid flag must be a boolean.")
161
+
162
+ # precision is a label precision (decimals for reported m/z). 'auto' is
163
+ # finalized per file inside each parser, where the data type is actually
164
+ # known: high-resolution data (the HRMS profile, and TOF centroids) resolves
165
+ # to 4 decimals; unit-resolution data (UV, GC/quadrupole MS, Waters) to whole
166
+ # numbers.
167
+ #
168
+ # bin_width is the width of the shared HRMS profile grid, and it is what turns
169
+ # binning on: omit it for the per-scan representation, pass a width to project
170
+ # onto one shared grid. It is entirely independent of precision (precision
171
+ # only rounds the reported m/z labels, never the grid), with no default,
172
+ # because the shared grid has no sensible universal width. (If precision is
173
+ # too coarse to label the bins distinctly, parse_msdata warns; it is not an
174
+ # error.)
175
+ if bin_width is not None and (
176
+ isinstance(bin_width, bool)
177
+ or not isinstance(bin_width, (int, float)) or bin_width <= 0):
178
+ raise Exception(f"Invalid bin_width: {bin_width}.")
179
+
180
+ if requested_files is not None and not isinstance(requested_files, list):
181
+ raise Exception(f"The requested_files argument must be a list.")
182
+
183
+ if requested_files:
184
+ requested_files = list(map(str.lower, requested_files))
185
+
186
+ datadir = None
187
+ if vendor == 'agilent':
188
+ datadir = agilent.read(
189
+ path, precision, hrms, requested_files, telemetry, centroid,
190
+ bin_width)
191
+ elif vendor == 'waters':
192
+ datadir = waters.read(path, precision, requested_files)
193
+
194
+ if datadir is None:
195
+ raise Exception(f"Rainbow cannot read {path}.")
196
+ return datadir
197
+
198
+
199
+ def read_metadata(path, format=None):
200
+ """
201
+ Reads the metadata for a chromatogram data directory. Main method of the package.
202
+
203
+ Args:
204
+ path (str): Path of the directory.
205
+ format (str, optional): Force the vendor parser ('agilent' or
206
+ 'waters'), bypassing extension/content detection.
207
+
208
+ Returns:
209
+ Dictionary containing a list of datafiles and the metadata.
210
+
211
+ """
212
+ vendor = _resolve_vendor(path, format)
213
+
214
+ metadata = None
215
+ if vendor == 'agilent':
216
+ metadata = agilent.read_metadata(path)
217
+ elif vendor == 'waters':
218
+ metadata = waters.read_metadata(path)
219
+
220
+ if metadata is None:
221
+ raise Exception(f"Rainbow cannot read {path}.")
222
+ 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, precision, 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:`precision` 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:`precision`, 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
+ precision (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 ** precision if precision > 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,20 +4,26 @@ 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,
8
- centroid=False):
7
+ def read(path, precision='auto', hrms=False, requested_files=None,
8
+ telemetry=False, centroid=False, bin_width=None):
9
9
  """
10
10
  Reads an Agilent .D directory or .dx archive.
11
11
 
12
12
  Args:
13
13
  path (str): Path of the directory or .dx file.
14
- prec (int, optional): Number of decimals to round masses.
14
+ precision (int or 'auto', optional): Number of decimals to round masses.
15
+ ``'auto'`` picks 4 for high-resolution data and 0 otherwise, per file.
15
16
  hrms (bool, optional): Flag for parsing the MassHunter profile
16
17
  spectrum (MSProfile.bin).
17
18
  requested_files (list, optional): List of filenames to parse.
18
19
  telemetry (bool, optional): Flag for parsing .dx telemetry traces.
19
20
  centroid (bool, optional): Flag for parsing the MassHunter centroid
20
21
  spectrum (MSPeak.bin).
22
+ bin_width (float, optional): Shared-grid bin width in daltons for the
23
+ HRMS profile. Omit it (the default) to keep the per-scan
24
+ representation (one
25
+ :class:`~rainbow.agilent.masshunter.ProfileDataFile` per flight-time
26
+ grid); pass a width to project onto the shared m/z grid.
21
27
 
22
28
  Returns:
23
29
  DataDirectory representing the Agilent data.
@@ -25,15 +31,15 @@ def read(path, prec=0, hrms=False, requested_files=None, telemetry=False,
25
31
  """
26
32
  if os.path.splitext(path)[1].lower() == '.dx':
27
33
  from rainbow.agilent import openlab
28
- return openlab.read(path, prec, requested_files, telemetry)
34
+ return openlab.read(path, precision, requested_files, telemetry)
29
35
 
30
36
  datafiles = []
31
- datafiles.extend(chemstation.parse_allfiles(path, prec, requested_files))
37
+ datafiles.extend(chemstation.parse_allfiles(path, precision, requested_files))
32
38
  if hrms or centroid:
33
39
  try:
34
40
  from rainbow.agilent import masshunter
35
- datafiles.extend(
36
- masshunter.parse_allfiles(path, prec, hrms, centroid))
41
+ datafiles.extend(masshunter.parse_allfiles(
42
+ path, precision, hrms, centroid, bin_width))
37
43
  except ModuleNotFoundError:
38
44
  raise ModuleNotFoundError("You must install python-lzf to parse masshunter files.")
39
45