rainbow-api 1.2.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 (34) hide show
  1. {rainbow_api-1.2.0/rainbow_api.egg-info → rainbow_api-1.3.0}/PKG-INFO +1 -1
  2. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/pyproject.toml +1 -1
  3. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/rainbow/__init__.py +43 -7
  4. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/rainbow/_binning.py +5 -5
  5. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/rainbow/agilent/__init__.py +13 -7
  6. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/rainbow/agilent/_msprofile.pyx +10 -8
  7. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/rainbow/agilent/chemstation.py +20 -16
  8. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/rainbow/agilent/masshunter.py +309 -60
  9. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/rainbow/agilent/openlab.py +5 -2
  10. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/rainbow/waters/__init__.py +10 -5
  11. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/rainbow/waters/masslynx.py +18 -18
  12. {rainbow_api-1.2.0 → rainbow_api-1.3.0/rainbow_api.egg-info}/PKG-INFO +1 -1
  13. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/tests/test_accelerator.py +4 -1
  14. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/tests/test_masshunter.py +343 -17
  15. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/COPYING +0 -0
  16. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/COPYING.LESSER +0 -0
  17. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/MANIFEST.in +0 -0
  18. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/README.md +0 -0
  19. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/rainbow/agilent/_chdelta.pyx +0 -0
  20. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/rainbow/agilent/_uvdelta.pyx +0 -0
  21. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/rainbow/datadirectory.py +0 -0
  22. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/rainbow/datafile.py +0 -0
  23. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/rainbow_api.egg-info/SOURCES.txt +0 -0
  24. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/rainbow_api.egg-info/dependency_links.txt +0 -0
  25. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/rainbow_api.egg-info/requires.txt +0 -0
  26. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/rainbow_api.egg-info/top_level.txt +0 -0
  27. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/setup.cfg +0 -0
  28. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/setup.py +0 -0
  29. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/tests/test_agilent.py +0 -0
  30. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/tests/test_binning.py +0 -0
  31. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/tests/test_datadirectory.py +0 -0
  32. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/tests/test_datafile.py +0 -0
  33. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/tests/test_read.py +0 -0
  34. {rainbow_api-1.2.0 → rainbow_api-1.3.0}/tests/test_waters.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rainbow-api
3
- Version: 1.2.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
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "rainbow-api"
7
- version = "1.2.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"}
@@ -85,8 +85,8 @@ def _resolve_vendor(path, format):
85
85
  return _detect_vendor(path)
86
86
 
87
87
 
88
- def read(path, prec=0, hrms=False, requested_files=None, telemetry=False,
89
- centroid=False, format=None):
88
+ def read(path, precision='auto', hrms=False, requested_files=None,
89
+ telemetry=False, centroid=False, format=None, bin_width=None):
90
90
  """
91
91
  Reads a chromatogram data directory. Main method of the package.
92
92
 
@@ -111,7 +111,12 @@ def read(path, prec=0, hrms=False, requested_files=None, telemetry=False,
111
111
 
112
112
  Args:
113
113
  path (str): Path of the directory.
114
- prec (int, optional): Number of decimals to round ylabels.
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).
115
120
  hrms (bool, optional): Flag for Agilent HRMS (MSProfile.bin) parsing.
116
121
  requested_files (list, optional): List of filenames to parse.
117
122
  telemetry (bool, optional): Flag for Agilent .dx telemetry traces.
@@ -119,6 +124,14 @@ def read(path, prec=0, hrms=False, requested_files=None, telemetry=False,
119
124
  (MSPeak.bin) parsing.
120
125
  format (str, optional): Force the vendor parser ('agilent' or
121
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.
122
135
 
123
136
  Returns:
124
137
  DataDirectory representing the directory.
@@ -133,8 +146,12 @@ def read(path, prec=0, hrms=False, requested_files=None, telemetry=False,
133
146
  elif not isinstance(path, str) or not os.path.isdir(path):
134
147
  raise Exception(f"{path} is not a directory.")
135
148
 
136
- if not isinstance(prec, int) or prec < 0:
137
- raise Exception(f"Invalid precision: {prec}.")
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.")
138
155
 
139
156
  if not isinstance(hrms, bool):
140
157
  raise Exception(f"The hrms flag must be a boolean.")
@@ -142,6 +159,24 @@ def read(path, prec=0, hrms=False, requested_files=None, telemetry=False,
142
159
  if not isinstance(centroid, bool):
143
160
  raise Exception(f"The centroid flag must be a boolean.")
144
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
+
145
180
  if requested_files is not None and not isinstance(requested_files, list):
146
181
  raise Exception(f"The requested_files argument must be a list.")
147
182
 
@@ -151,9 +186,10 @@ def read(path, prec=0, hrms=False, requested_files=None, telemetry=False,
151
186
  datadir = None
152
187
  if vendor == 'agilent':
153
188
  datadir = agilent.read(
154
- path, prec, hrms, requested_files, telemetry, centroid)
189
+ path, precision, hrms, requested_files, telemetry, centroid,
190
+ bin_width)
155
191
  elif vendor == 'waters':
156
- datadir = waters.read(path, prec, requested_files)
192
+ datadir = waters.read(path, precision, requested_files)
157
193
 
158
194
  if datadir is None:
159
195
  raise Exception(f"Rainbow cannot read {path}.")
@@ -11,7 +11,7 @@ a scan. This module provides one vectorized implementation of that step.
11
11
  import numpy as np
12
12
 
13
13
 
14
- def bin_datapairs(keys, values, pair_counts, prec, data_dtype=np.int64):
14
+ def bin_datapairs(keys, values, pair_counts, precision, data_dtype=np.int64):
15
15
  """
16
16
  Bins (key, value) data pairs into a (retention time x ylabel) matrix.
17
17
 
@@ -19,7 +19,7 @@ def bin_datapairs(keys, values, pair_counts, prec, data_dtype=np.int64):
19
19
  from the flat :obj:`keys`/:obj:`values` arrays. Pairs that share a ylabel
20
20
  within the same scan are summed.
21
21
 
22
- The keys must already be rounded to :obj:`prec` decimals and be
22
+ The keys must already be rounded to :obj:`precision` decimals and be
23
23
  non-negative (m/z or wavelength), so the unique ylabels and each pair's
24
24
  column are found with an integer histogram in O(n) instead of sorting every
25
25
  pair with ``np.unique``/``np.searchsorted``. The values are accumulated into
@@ -27,10 +27,10 @@ def bin_datapairs(keys, values, pair_counts, prec, data_dtype=np.int64):
27
27
  behavior - the caller's prior per-scan ``np.add.at`` loop used).
28
28
 
29
29
  Args:
30
- keys (np.ndarray): Flat ylabels, rounded to :obj:`prec`, non-negative.
30
+ keys (np.ndarray): Flat ylabels, rounded to :obj:`precision`, non-negative.
31
31
  values (np.ndarray): Flat values paired with :obj:`keys`.
32
32
  pair_counts (np.ndarray): Number of pairs at each retention time.
33
- prec (int): Number of decimals the keys were rounded to.
33
+ precision (int): Number of decimals the keys were rounded to.
34
34
  data_dtype (np.dtype, optional): dtype of the output matrix.
35
35
 
36
36
  Returns:
@@ -47,7 +47,7 @@ def bin_datapairs(keys, values, pair_counts, prec, data_dtype=np.int64):
47
47
 
48
48
  # Map each rounded key onto a non-negative integer bin so the unique
49
49
  # ylabels and per-pair columns come from a histogram, not a sort.
50
- scale = 10 ** prec if prec > 0 else 1
50
+ scale = 10 ** precision if precision > 0 else 1
51
51
  int_keys = np.rint(keys * scale).astype(np.int64)
52
52
  int_keys -= int_keys.min()
53
53
 
@@ -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
 
@@ -46,8 +46,9 @@ def decompress_inten_list(const unsigned char[::1] comp_view, int num_mz):
46
46
 
47
47
  Args:
48
48
  comp_view: The segment bytes after its 16-byte (smallest mz, mz delta)
49
- header -- i.e. the 4-byte point-count word, the two negated int32
50
- preamble values, and the token stream.
49
+ header -- i.e. the 4-byte point-count word, the negated int32
50
+ leading-zero count, and the token stream (which opens at 4-byte
51
+ width).
51
52
  num_mz: The number of mz-intensity pairs (output length).
52
53
 
53
54
  Returns:
@@ -62,14 +63,13 @@ def decompress_inten_list(const unsigned char[::1] comp_view, int num_mz):
62
63
  cdef int init_zero_repeat
63
64
  cdef int width_flag
64
65
 
65
- # Two negated little-endian int32s follow the 4-byte point-count word.
66
- if n < 12:
66
+ # A negated little-endian int32 (the leading-zero count) follows the 4-byte
67
+ # point-count word; the token stream begins right after it.
68
+ if n < 8:
67
69
  raise ValueError("Malformed MSProfile.bin RLE segment.")
68
70
  memcpy(&init_zero_repeat, &comp_view[4], 4)
69
- memcpy(&width_flag, &comp_view[8], 4)
70
71
 
71
72
  cdef Py_ssize_t cur_idx = -init_zero_repeat
72
- width_flag = -width_flag
73
73
  # cur_idx only ever advances, so once it starts non-negative it stays in
74
74
  # range; a positive init_zero_repeat would start it negative, so reject it.
75
75
  if cur_idx < 0:
@@ -79,8 +79,10 @@ def decompress_inten_list(const unsigned char[::1] comp_view, int num_mz):
79
79
  data_arr = np.zeros(num_mz, dtype=np.uint32)
80
80
  cdef unsigned int[::1] inten = data_arr
81
81
 
82
- cdef Py_ssize_t off = 12
83
- cdef int cur_size = _width_size(width_flag)
82
+ # The token stream opens at an initial width of 4 bytes (width flag 3); a
83
+ # control value switches it thereafter.
84
+ cdef Py_ssize_t off = 8
85
+ cdef int cur_size = _width_size(3)
84
86
  cdef long long value
85
87
  cdef Py_ssize_t num_zeros
86
88
  cdef signed char v1
@@ -33,20 +33,24 @@ MAIN PARSING METHODS
33
33
  """
34
34
 
35
35
 
36
- def parse_allfiles(path, prec=0, requested_files=None):
36
+ def parse_allfiles(path, precision='auto', requested_files=None):
37
37
  """
38
38
  Finds and parses Agilent Chemstation data files \
39
39
  with a .ch, .uv, or .ms extension from a .D directory.
40
40
 
41
41
  Args:
42
42
  path (str): Path to the .D directory.
43
- prec (int, optional): Number of decimals to round mz values.
43
+ precision (int, optional): Number of decimals to round mz values.
44
44
  requested_files (list, optional): List of filenames to parse.
45
45
 
46
46
  Returns:
47
- List with a DataFile for each parsed data file.
47
+ List with a DataFile for each parsed data file.
48
48
 
49
49
  """
50
+ # Chemstation data (UV, GC/quadrupole .ms) is unit-resolution, so 'auto'
51
+ # precision means whole numbers.
52
+ if precision == 'auto':
53
+ precision = 0
50
54
  datafiles = []
51
55
  # Sort for a deterministic parse order across platforms: os.listdir returns
52
56
  # entries in filesystem order, which differs between macOS and Linux. The
@@ -56,13 +60,13 @@ def parse_allfiles(path, prec=0, requested_files=None):
56
60
  for name in sorted(os.listdir(path)):
57
61
  if requested_files and name.lower() not in requested_files:
58
62
  continue
59
- datafile = parse_file(os.path.join(path, name), prec)
63
+ datafile = parse_file(os.path.join(path, name), precision)
60
64
  if datafile:
61
65
  datafiles.append(datafile)
62
66
  return datafiles
63
67
 
64
68
 
65
- def parse_file(path, prec=0):
69
+ def parse_file(path, precision=0):
66
70
  """
67
71
  Parses an Agilent Chemstation data file.
68
72
 
@@ -70,7 +74,7 @@ def parse_file(path, prec=0):
70
74
 
71
75
  Args:
72
76
  path (str): Path to the data file.
73
- prec (int, optional): Number of decimals to round mz values.
77
+ precision (int, optional): Number of decimals to round mz values.
74
78
 
75
79
  Returns:
76
80
  DataFile representing the file, if it can be parsed. Otherwise, None.
@@ -82,7 +86,7 @@ def parse_file(path, prec=0):
82
86
  elif ext == '.uv':
83
87
  return parse_uv(path)
84
88
  elif ext == '.ms':
85
- return parse_ms(path, prec)
89
+ return parse_ms(path, precision)
86
90
  return None
87
91
 
88
92
 
@@ -647,7 +651,7 @@ def parse_uv_partial(path):
647
651
  """
648
652
 
649
653
 
650
- def parse_ms(path, prec=0):
654
+ def parse_ms(path, precision=0):
651
655
  """
652
656
  Parses an Agilent .ms file.
653
657
 
@@ -657,7 +661,7 @@ def parse_ms(path, prec=0):
657
661
 
658
662
  Args:
659
663
  path (str): Path to Agilent .ms file.
660
- prec (int, optional): Number of decimals to round mz values.
664
+ precision (int, optional): Number of decimals to round mz values.
661
665
 
662
666
  Returns:
663
667
  DataFile with MS data, if the file can be parsed. Otherwise, None.
@@ -679,7 +683,7 @@ def parse_ms(path, prec=0):
679
683
  head = int_unpack(f.read(4))[0]
680
684
  if head != 0x01320000:
681
685
  f.close()
682
- return parse_ms_partial(path, prec)
686
+ return parse_ms_partial(path, precision)
683
687
 
684
688
  # Determine the type of .ms file based on header.
685
689
  # Read the number of retention times from different offsets by type.
@@ -717,7 +721,7 @@ def parse_ms(path, prec=0):
717
721
 
718
722
  # Calculate the mz values.
719
723
  mzs = np.ndarray(total_paircount, '>H', raw_bytes, 0, 4)
720
- mzs = np.round(mzs / 20, prec)
724
+ mzs = np.round(mzs / 20, precision)
721
725
 
722
726
  # Calculate the intensity values.
723
727
  int_encs = np.ndarray(total_paircount, '>H', raw_bytes, 2, 4)
@@ -728,7 +732,7 @@ def parse_ms(path, prec=0):
728
732
 
729
733
  # Bin the mz-intensity pairs into a (retention time x mz) matrix.
730
734
  ylabels, data = bin_datapairs(
731
- mzs, int_values, pair_counts, prec, data_dtype=np.uint32)
735
+ mzs, int_values, pair_counts, precision, data_dtype=np.uint32)
732
736
  del mzs, int_values, pair_counts
733
737
 
734
738
  # Read file metadata.
@@ -742,7 +746,7 @@ def parse_ms(path, prec=0):
742
746
  return DataFile(path, 'MS', times, ylabels, data, metadata)
743
747
 
744
748
 
745
- def parse_ms_partial(path, prec=0):
749
+ def parse_ms_partial(path, precision=0):
746
750
  """
747
751
  Parses a partial Agilent .ms file.
748
752
 
@@ -752,7 +756,7 @@ def parse_ms_partial(path, prec=0):
752
756
 
753
757
  Args:
754
758
  path (str): Path to the partial .ms file.
755
- prec (int, optional): Number of decimal to round mz values.
759
+ precision (int, optional): Number of decimal to round mz values.
756
760
 
757
761
  Returns:
758
762
  DataFile with MS data, if the file can be parsed. Otherwise, None.
@@ -804,7 +808,7 @@ def parse_ms_partial(path, prec=0):
804
808
 
805
809
  # Calculate the mz values.
806
810
  mzs = np.ndarray(total_paircount, '>H', raw_bytes, 0, 4)
807
- mzs = np.round(mzs / 20, prec)
811
+ mzs = np.round(mzs / 20, precision)
808
812
 
809
813
  # Calculate the intensity values.
810
814
  int_encs = np.ndarray(total_paircount, '>H', raw_bytes, 2, 4)
@@ -815,7 +819,7 @@ def parse_ms_partial(path, prec=0):
815
819
 
816
820
  # Bin the mz-intensity pairs into a (retention time x mz) matrix.
817
821
  ylabels, data = bin_datapairs(
818
- mzs, int_values, pair_counts, prec, data_dtype=np.uint32)
822
+ mzs, int_values, pair_counts, precision, data_dtype=np.uint32)
819
823
  del mzs, int_values, pair_counts
820
824
 
821
825
  # Read file metadata.