rainbow-api 1.6.0__tar.gz → 1.7.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 (49) hide show
  1. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/CHANGELOG.md +32 -0
  2. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/PKG-INFO +1 -1
  3. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/pyproject.toml +1 -1
  4. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/_version.py +1 -1
  5. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/agilent/amx.py +160 -28
  6. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/agilent/method.py +157 -2
  7. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow_api.egg-info/PKG-INFO +1 -1
  8. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/COPYING +0 -0
  9. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/COPYING.LESSER +0 -0
  10. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/MANIFEST.in +0 -0
  11. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/README.md +0 -0
  12. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/__init__.py +0 -0
  13. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/_arguments.py +0 -0
  14. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/_binning.py +0 -0
  15. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/_optics.py +0 -0
  16. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/agilent/__init__.py +0 -0
  17. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/agilent/_chdelta.pyx +0 -0
  18. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/agilent/_msprofile.pyx +0 -0
  19. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/agilent/_uvdelta.pyx +0 -0
  20. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/agilent/acaml.py +0 -0
  21. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/agilent/chemstation.py +0 -0
  22. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/agilent/masshunter.py +0 -0
  23. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/agilent/openlab.py +0 -0
  24. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/agilent/sequence.py +0 -0
  25. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/agilent/sirslt.py +0 -0
  26. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/asm.py +0 -0
  27. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/datadirectory.py +0 -0
  28. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/datafile.py +0 -0
  29. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/datasequence.py +0 -0
  30. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/debug/__init__.py +0 -0
  31. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/debug/_util.py +0 -0
  32. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/debug/chemstation_header.py +0 -0
  33. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/debug/chemstation_text.py +0 -0
  34. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/debug/dotnet.py +0 -0
  35. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/debug/ini.py +0 -0
  36. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/debug/method.py +0 -0
  37. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/debug/mzxml.py +0 -0
  38. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/debug/reg.py +0 -0
  39. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/debug/waters_header.py +0 -0
  40. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/debug/waters_inf.py +0 -0
  41. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/debug/xml.py +0 -0
  42. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/waters/__init__.py +0 -0
  43. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow/waters/masslynx.py +0 -0
  44. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow_api.egg-info/SOURCES.txt +0 -0
  45. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow_api.egg-info/dependency_links.txt +0 -0
  46. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow_api.egg-info/requires.txt +0 -0
  47. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/rainbow_api.egg-info/top_level.txt +0 -0
  48. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/setup.cfg +0 -0
  49. {rainbow_api-1.6.0 → rainbow_api-1.7.0}/setup.py +0 -0
@@ -3,6 +3,38 @@
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.7.0] - 2026-11-28
7
+
8
+ ### Added
9
+ - **The single quad's settings in an OpenLab `.amx`.** `module_settings`
10
+ states an LC/MSD iQ's (driver `LCSQ`): ion source, tune file, the diverter
11
+ timetable, and each time segment with its start, scan type and own rows:
12
+ each scan row (m/z range, scan time, fragmentor, polarity, ionization
13
+ mode, data storage), each SIM ion (m/z, compound, dwell, fragmentor,
14
+ polarity), each fragmentor ramp's points and the source parameters.
15
+ - **A `.sirslt` run's MS file states its method.** Read with
16
+ `centroid=True`, its MS file gets the method's `scan_parameters` and
17
+ `monitored_ions` (with compound names), and `ionization_mode`,
18
+ `fragmentor` and `polarity` where every row states one, in the keys a
19
+ ChemStation MS signal's settings come in (`method.tag_ms_segments`). The
20
+ file's scans are the check: where the method's rows are not what they
21
+ recorded, nothing goes on the file and the rows are kept in
22
+ `method_disagrees`.
23
+ - **A DAD signal's reference in an `.amx`.** `signals` rows state
24
+ `reference_wavelength` and `reference_bandwidth`.
25
+ - **Real OpenLab LC/MS test data**, shared by p3bm in #82:
26
+ `tests/inputs/jade.sirslt` (SIM/Scan), `ochre.sirslt` (two time
27
+ segments), `rose.sirslt` (positive and negative, a fragmentor ramp) and
28
+ `coral.sirslt` (a DAD reference wavelength), each with its `.amx`, and the
29
+ method `mango.amx` (Scan).
30
+
31
+ ### Fixed
32
+ - **An `.amx` with a single quad reads.** Its driver part records its model
33
+ as `<msModel>`, not `ModuleType`, so the module had no driver and
34
+ `amx.read` raised a KeyError; `rb.read` and `rb.read_metadata` then stated
35
+ nothing of the run's method. The model is read from either, and a module
36
+ without a driver is listed without settings.
37
+
6
38
  ## [1.6.0] - 2026-11-27
7
39
 
8
40
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rainbow-api
3
- Version: 1.6.0
3
+ Version: 1.7.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.6.0"
7
+ version = "1.7.0"
8
8
  description = "Read chromatography and mass spectrometry binary files"
9
9
  readme = "README.md"
10
10
  license = {text = "LGPL-3.0-or-later"}
@@ -3,4 +3,4 @@
3
3
  # checks that they agree. Read from here rather than from the installed
4
4
  # distribution's metadata, which an editable install leaves at whatever
5
5
  # version it was installed as.
6
- __version__ = "1.6.0"
6
+ __version__ = "1.7.0"
@@ -12,8 +12,9 @@ An .amx is an Open Packaging Conventions (zip) package, like a .docx::
12
12
  its name, ID, value and unit
13
13
  DeviceMethodSettings/<driver>%231 one part per module, named for its
14
14
  driver (AgilentPumpDriver,
15
- Agilent1200erDadDriver, ...): the
16
- settings as the driver keeps them
15
+ Agilent1200erDadDriver, LCSQ, ...):
16
+ the settings as the driver keeps
17
+ them
17
18
  MethodProperties/MethodProperties technique (LC, GC) and run time
18
19
  SchemaVersion/SchemaVersion
19
20
  *.chk SHA-1 of the part beside it
@@ -25,12 +26,15 @@ every method read so far, the DAD part's ``<Slitwidth>2`` is reported as
25
26
  ``4 nm``, its ``<Peakwidth>4`` as ``> 0.1 min (2 s response time) (2.5 Hz)``,
26
27
  and its analog attenuation ``10`` as ``1000 mAU``; and no driver part states a
27
28
  unit. So the driver parts are read for which modules the method drives (the
28
- driver's name and the module type it records), and the report for what each
29
- is set to.
29
+ driver's name and the module type it records: its root's ``ModuleType``, or
30
+ for a single quad's ``<MSAcqMethod>`` its ``<msModel>``), and the report for
31
+ what each is set to.
30
32
 
31
33
  What a module's report section states is read by its driver's table in
32
34
  :data:`MODULES`: the ACAML parameter IDs read, each to the field it is
33
- stated as. A module whose driver has no table is listed (name, model,
35
+ stated as. A report table's row is one of a driver table's rows where it
36
+ holds that table's first ID, so one report table can hold rows of two kinds
37
+ (a single quad's scan row and its SIM ion rows). A module whose driver has no table is listed (name, model,
34
38
  driver) with no settings. A value the report leaves empty, or writes as
35
39
  ``---`` (a timetable row that does not change it), is not stated.
36
40
 
@@ -57,15 +61,19 @@ _TIMES = {
57
61
  #
58
62
  # settings parameter ID -> field, for the section's parameters outside
59
63
  # a table (in its sub-sections too)
60
- # tables table name -> {parameter ID -> field}: each of the section's
61
- # tables whose rows hold any of those IDs is stated under that
62
- # name, one dict per row, in the report's order
64
+ # tables table name -> {parameter ID -> field}: each row of the
65
+ # section's tables that holds the first of those IDs is stated
66
+ # under that name, one dict per row, in the report's order
63
67
  # run run-level key -> field: what the module states that rainbow
64
68
  # states for a whole run (as a .D's acq.macaml gives it)
69
+ # segments (optional) a module whose settings come in segments, each its
70
+ # own sub-section: 'name' the list they are stated under,
71
+ # 'section' the sub-sections' IDs (numbered), 'header' the
72
+ # segment table's row of each, 'tables' each segment's own
73
+ # tables as above, and 'named' the tables whose rows also
74
+ # state their table's name
65
75
  #
66
- # Adding a module is adding its driver's table here. An LC/MSD's driver part
67
- # would be entered here too once an OpenLab LC/MS method is at hand: no public
68
- # method so far names the MSD's driver part or the IDs of its report section.
76
+ # Adding a module is adding its driver's table here.
69
77
  MODULES = {
70
78
  'AgilentPumpDriver': {
71
79
  'settings': dict(_TIMES, **{
@@ -112,6 +120,8 @@ MODULES = {
112
120
  'Signals_Signal_Wavelength': 'wavelength',
113
121
  'Signals_Signal_Bandwidth': 'bandwidth',
114
122
  'Signals_Signal_UseReference': 'use_reference',
123
+ 'Signals_Signal_RefWavelength': 'reference_wavelength',
124
+ 'Signals_Signal_RefBandwidth': 'reference_bandwidth',
115
125
  },
116
126
  },
117
127
  'run': {},
@@ -129,6 +139,74 @@ MODULES = {
129
139
  # As for a .D: the left temperature, where it is controlled.
130
140
  'run': {'column_temperature': 'left_temperature'},
131
141
  },
142
+ # A single quad (LC/MSD iQ). Each time segment is stated with its own
143
+ # rows (see 'segments' below), as the report keeps them.
144
+ 'LCSQ': {
145
+ 'settings': {
146
+ 'IonSource': 'ion_source',
147
+ 'TuneFile': 'tune_file',
148
+ 'Acquire_Mode': 'acquire_mode',
149
+ 'StopMode': 'stop_mode',
150
+ 'TimeFilterEnabled': 'time_filter',
151
+ 'TimeFilterPeakWidth': 'time_filter_width',
152
+ 'Estimated_Points_Per_Second': 'points_per_second',
153
+ 'SIM_Percent': 'sim_percent',
154
+ 'PostRun_Diverter_Position': 'post_run_diverter_position',
155
+ },
156
+ 'tables': {
157
+ 'timetable': {
158
+ 'TimeTable_Type': 'type',
159
+ 'StartTime': 'time',
160
+ 'TimeTable_Value': 'value',
161
+ },
162
+ },
163
+ 'segments': {
164
+ 'name': 'time_segments',
165
+ # The section of segment n is TimeSegment<n>; the row of segment
166
+ # n in the Time Segment table, the n-th row holding ScanType.
167
+ 'section': re.compile(r'^TimeSegment(\d+)$'),
168
+ 'header': {
169
+ 'ScanType': 'scan_type',
170
+ 'StartTime': 'time',
171
+ },
172
+ 'tables': {
173
+ 'scan_parameters': {
174
+ 'StartMass': 'mz_low',
175
+ 'EndMass': 'mz_high',
176
+ 'ScanTime': 'scan_time',
177
+ 'Fragmentor': 'fragmentor',
178
+ 'Polarity': 'polarity',
179
+ 'IonMode': 'ionization_mode',
180
+ 'DataStorage': 'data_storage',
181
+ 'DetectorGainFactor': 'gain_factor',
182
+ 'Threshold': 'threshold',
183
+ },
184
+ 'monitored_ions': {
185
+ 'Mass': 'mz',
186
+ 'CompoundName': 'compound',
187
+ 'Dwell': 'dwell',
188
+ 'Fragmentor': 'fragmentor',
189
+ 'Polarity': 'polarity',
190
+ 'IonMode': 'ionization_mode',
191
+ 'DetectorGainFactor': 'gain_factor',
192
+ },
193
+ # A fragmentor ramp: a scan row whose fragmentor is
194
+ # "Ramp(1)" takes the rows of the table of that name.
195
+ 'fragmentor_ramps': {
196
+ 'FragmentorRampMass': 'mz',
197
+ 'FragmentorRampVoltage': 'voltage',
198
+ },
199
+ 'source': {
200
+ 'ParameterId': 'parameter',
201
+ 'PositiveValue': 'positive',
202
+ 'NegativeValue': 'negative',
203
+ },
204
+ },
205
+ # Each row of these also states the name of its table.
206
+ 'named': {'fragmentor_ramps': 'ramp'},
207
+ },
208
+ 'run': {},
209
+ },
132
210
  'AgilentSamplerDriver': {
133
211
  'settings': dict(_TIMES, **{
134
212
  'Injection_InjectionVolume': 'injection_volume',
@@ -242,7 +320,7 @@ def read(path):
242
320
  'model': module['model']}
243
321
  for module in modules]
244
322
  for module in modules:
245
- table = MODULES.get(module['driver'], {})
323
+ table = MODULES.get(module.get('driver'), {})
246
324
  for key, field in table.get('run', {}).items():
247
325
  value = module.get('settings', {}).get(field)
248
326
  if isinstance(value, dict):
@@ -279,8 +357,8 @@ def _drivers(package, names):
279
357
  """
280
358
  The driver parts: {(module type, instance): driver name}, from the part
281
359
  names (DeviceMethodSettings/AgilentPumpDriver%25231 is
282
- "AgilentPumpDriver#1", its name percent-encoded twice) and the
283
- ModuleType each part's root records.
360
+ "AgilentPumpDriver#1", its name percent-encoded twice) and the module
361
+ type each part records (:func:`_model`).
284
362
  """
285
363
  found = {}
286
364
  for name in sorted(names):
@@ -292,13 +370,23 @@ def _drivers(package, names):
292
370
  match = _DRIVER_RE.match(part)
293
371
  if not match:
294
372
  continue
295
- root = ET.fromstring(package.read(name))
296
- model = (root.get('ModuleType') or '').strip()
373
+ model = _model(ET.fromstring(package.read(name)))
297
374
  if model:
298
375
  found[(model, match.group('instance'))] = match.group('driver')
299
376
  return found
300
377
 
301
378
 
379
+ def _model(root):
380
+ """The module type a driver part records: its root's ModuleType
381
+ (G7117A), else a single quad's <msModel> (LC/MSD iQ), as the report's
382
+ ModuleType states each."""
383
+ model = (root.get('ModuleType') or '').strip()
384
+ if not model:
385
+ found = root.find('msModel')
386
+ model = (found.text or '').strip() if found is not None else ''
387
+ return model
388
+
389
+
302
390
  def _technique(properties):
303
391
  """MethodProperties' <InstrumentTechnique>, where it is LC or GC."""
304
392
  if properties is None:
@@ -374,23 +462,67 @@ def _settings(section, table):
374
462
  if value is not None:
375
463
  settings[field] = value
376
464
  for name, fields in table['tables'].items():
377
- rows = []
378
- for found in _tables(section):
379
- for row in found['rows']:
380
- if not any(p.get('id') in fields for p in row):
381
- continue
382
- entry = {}
383
- for parameter in row:
384
- field = fields.get(parameter.get('id'))
385
- value = _value(parameter) if field else None
386
- if value is not None:
387
- entry[field] = value
388
- rows.append(entry)
465
+ rows = _rows(section, fields)
389
466
  if rows:
390
467
  settings[name] = rows
468
+ segments = table.get('segments')
469
+ if segments:
470
+ found = _segments(section, segments)
471
+ if found:
472
+ settings[segments['name']] = found
391
473
  return settings
392
474
 
393
475
 
476
+ def _rows(section, fields, label=None):
477
+ """The rows of a section's tables (its sub-sections' too) holding the
478
+ first of `fields`' IDs, each read by `fields`; `label`: the field each
479
+ row also states its table's name under."""
480
+ key = next(iter(fields))
481
+ rows = []
482
+ for found in _tables(section):
483
+ for row in found['rows']:
484
+ if not any(p.get('id') == key for p in row):
485
+ continue
486
+ entry = {}
487
+ for parameter in row:
488
+ field = fields.get(parameter.get('id'))
489
+ value = _value(parameter) if field else None
490
+ if value is not None:
491
+ entry[field] = value
492
+ if label and found.get('name'):
493
+ entry[label] = found['name']
494
+ rows.append(entry)
495
+ return rows
496
+
497
+
498
+ def _segments(section, spec):
499
+ """A module's segments, in their numbers' order: each the segment
500
+ table's row of it and its own sub-section's rows."""
501
+ numbered = []
502
+ for sub in _sections(section):
503
+ match = spec['section'].match(sub.get('id') or '')
504
+ if match:
505
+ numbered.append((int(match.group(1)), sub))
506
+ headers = _rows(section, spec['header'])
507
+ segments = []
508
+ for n, sub in sorted(numbered, key=lambda item: item[0]):
509
+ segment = dict(headers[n - 1]) if 0 < n <= len(headers) else {}
510
+ for name, fields in spec['tables'].items():
511
+ rows = _rows(sub, fields, spec.get('named', {}).get(name))
512
+ if rows:
513
+ segment[name] = rows
514
+ segments.append(segment)
515
+ return segments
516
+
517
+
518
+ def _sections(section):
519
+ """A section's sub-sections, at every depth."""
520
+ for sub in section['sections']:
521
+ yield sub
522
+ for deeper in _sections(sub):
523
+ yield deeper
524
+
525
+
394
526
  def _parameters(section):
395
527
  """A section's parameters outside its tables, its sub-sections' too."""
396
528
  for parameter in section['parameters']:
@@ -434,7 +434,8 @@ def state_run(path, datafiles, metadata):
434
434
  The directory's metadata gains, where it does not state them already,
435
435
  what :func:`parse_injection_metadata` reads (acq.macaml, SAMPLE.XML,
436
436
  AcqData/AcqMethod.xml), what an OpenLab acquisition method (.amx) in
437
- the folder states (:func:`rainbow.agilent.amx.read`), and the technique
437
+ the folder states (:func:`rainbow.agilent.amx.read`; its single quad's
438
+ time segments onto the MS files, :func:`tag_ms_segments`), and the technique
438
439
  the method report declares (:func:`acquisition_technique`). Each MS
439
440
  DataFile is tagged with its acquisition mode
440
441
  (:func:`tag_acquisition_modes`) and with what the method states of its
@@ -456,7 +457,8 @@ def state_run(path, datafiles, metadata):
456
457
  for key, value in parse_injection_metadata(path, acq).items():
457
458
  metadata.setdefault(key, value)
458
459
  # An OpenLab acquisition method (.amx) in the folder, in the same keys.
459
- for key, value in amx.read_run(path).items():
460
+ found = amx.read_run(path)
461
+ for key, value in found.items():
460
462
  metadata.setdefault(key, value)
461
463
  # Tag each MS channel SIM or Scan from its scans, else the acquisition
462
464
  # method, so a SIM run (its monitored ions) is told from a full scan.
@@ -464,6 +466,9 @@ def state_run(path, datafiles, metadata):
464
466
  # What the method states of each MS signal (polarity, fragmentor, SIM
465
467
  # ions and their compound names), onto the file holding it.
466
468
  tag_ms_signals(path, datafiles, acq)
469
+ # What an OpenLab single quad's method states of its time segments, onto
470
+ # the MS files whose scans it describes.
471
+ tag_ms_segments(datafiles, found)
467
472
  # The separation technique the method declares (gas vs liquid
468
473
  # chromatography), so an export routes by what the instrument says
469
474
  # rather than guessing from the detectors.
@@ -753,6 +758,156 @@ def tag_ms_signals(path, datafiles, acq=_UNREAD):
753
758
  datafile.metadata.setdefault(key, value)
754
759
 
755
760
 
761
+ def tag_ms_segments(datafiles, method):
762
+ """
763
+ Puts what an OpenLab single quad's acquisition method (an ``.amx``, as
764
+ :func:`rainbow.agilent.amx.read` gives it) states of its time segments
765
+ onto each MS data file whose scans it describes, in the keys
766
+ :func:`ms_signals` gives a ChemStation signal's: ``scan_parameters`` (each
767
+ scan row: ``time_segment``, ``time``, ``mz_low``, ``mz_high``,
768
+ ``fragmentor`` or, for a ramp, ``fragmentor_ramp`` (``[{"mz", "voltage"}]``),
769
+ ``polarity``), ``monitored_ions`` (each SIM ion: ``time_segment``,
770
+ ``time``, ``mz``, ``fragmentor``, ``compound``, ``polarity``), and
771
+ ``ionization_mode``, ``fragmentor`` and ``polarity`` where every row
772
+ states the same one. ``time_segment`` is the segment's number, as each
773
+ scan states it (``scans['time_segment']``); ``time`` its start, in min.
774
+ Only keys the file does not state are filled.
775
+
776
+ The file's own scans are the check, never the pairing: each row must be
777
+ what some scan of its segment recorded (a Scan row its polarity and m/z
778
+ range, a SIM ion its polarity and m/z), and every kind of scan recorded
779
+ must be a row of the method. Otherwise nothing is put on the file, and
780
+ the method's rows are kept under ``method_disagrees['time_segments']``.
781
+ A file without its scans' records states nothing of the method.
782
+
783
+ Args:
784
+ datafiles (list): The run's DataFiles; MS entries are tagged in place.
785
+ method (dict): What the run's .amx states; {} for a run without one.
786
+
787
+ """
788
+ rows = _segment_rows(method)
789
+ if rows is None:
790
+ return
791
+ for datafile in datafiles:
792
+ if datafile.detector != "MS":
793
+ continue
794
+ recorded = _recorded_kinds(datafile)
795
+ if recorded is None:
796
+ continue
797
+ stated = {_row_kind(row) for row in rows}
798
+ if None in stated or stated != recorded:
799
+ _disagree(datafile, "time_segments", rows)
800
+ continue
801
+ out = {}
802
+ scans = [row for row in rows if "mz_low" in row]
803
+ ions = [row for row in rows if "mz" in row]
804
+ if scans:
805
+ out["scan_parameters"] = scans
806
+ if ions:
807
+ out["monitored_ions"] = ions
808
+ for key in ("ionization_mode", "fragmentor", "polarity"):
809
+ values = {row.get(key) for row in rows}
810
+ if len(values) == 1 and None not in values:
811
+ out[key] = values.pop()
812
+ for key, value in out.items():
813
+ if key in datafile.metadata and datafile.metadata[key] != value:
814
+ _disagree(datafile, key, value)
815
+ continue
816
+ datafile.metadata.setdefault(key, value)
817
+
818
+
819
+ def _segment_rows(method):
820
+ """The scan rows and SIM ions of a method's one single quad, in the
821
+ method's order, each with its segment's number and start; None where the
822
+ method has no single quad with segments, or more than one."""
823
+ modules = [module for module in method.get("module_settings", [])
824
+ if module.get("driver") in _SEGMENTED_MS_DRIVERS
825
+ and (module.get("settings") or {}).get("time_segments")]
826
+ if len(modules) != 1:
827
+ return None
828
+ rows = []
829
+ for n, segment in enumerate(modules[0]["settings"]["time_segments"], 1):
830
+ start = _amount(segment.get("time"))
831
+ ramps = {}
832
+ for point in segment.get("fragmentor_ramps", []):
833
+ ramps.setdefault(point.get("ramp"), []).append(
834
+ {"mz": _amount(point.get("mz")),
835
+ "voltage": _amount(point.get("voltage"))})
836
+ for kind in ("scan_parameters", "monitored_ions"):
837
+ for row in segment.get(kind, []):
838
+ entry = {"time_segment": n, "time": start}
839
+ for key in ("mz_low", "mz_high", "mz"):
840
+ if key in row:
841
+ entry[key] = _amount(row[key])
842
+ fragmentor = row.get("fragmentor")
843
+ if isinstance(fragmentor, str) and fragmentor in ramps:
844
+ entry["fragmentor_ramp"] = ramps[fragmentor]
845
+ else:
846
+ entry["fragmentor"] = _amount(fragmentor)
847
+ if kind == "monitored_ions":
848
+ entry["compound"] = row.get("compound")
849
+ for key in ("polarity", "ionization_mode"):
850
+ if row.get(key) is not None:
851
+ entry[key] = row[key]
852
+ rows.append(entry)
853
+ return rows
854
+
855
+
856
+ # The drivers of MS modules whose method comes in time segments
857
+ # (rainbow.agilent.amx.MODULES): the single quad.
858
+ _SEGMENTED_MS_DRIVERS = ("LCSQ",)
859
+
860
+
861
+ def _amount(value):
862
+ """A method value as a float: a quantity's value, or a number; else None."""
863
+ if isinstance(value, dict):
864
+ value = value.get("value")
865
+ if isinstance(value, bool):
866
+ return None
867
+ return float(value) if isinstance(value, (int, float)) else None
868
+
869
+
870
+ def _row_kind(row):
871
+ """What scans a method row asks for, as :func:`_recorded_kinds` states a
872
+ scan: (segment, 'Scan', polarity, m/z low, m/z high) or (segment, 'SIM',
873
+ polarity, m/z); None where the row states too little."""
874
+ polarity = row.get("polarity")
875
+ if "mz_low" in row:
876
+ if None in (row["mz_low"], row.get("mz_high")):
877
+ return None
878
+ return (row["time_segment"], "Scan", polarity,
879
+ _mz_key(row["mz_low"]), _mz_key(row["mz_high"]))
880
+ if row.get("mz") is None:
881
+ return None
882
+ return (row["time_segment"], "SIM", polarity, _mz_key(row["mz"]))
883
+
884
+
885
+ def _recorded_kinds(datafile):
886
+ """The kinds of scan a MassHunter-recorded file holds, from its scans'
887
+ records (``scans``): {(segment, 'Scan', polarity, m/z low, m/z high)} and
888
+ {(segment, 'SIM', polarity, m/z)}; None without those records."""
889
+ scans = datafile.metadata.get("scans") or {}
890
+ needed = ("time_segment", "monitoring", "polarity", "mz_range_min",
891
+ "mz_range_max", "precursor_mz")
892
+ if any(scans.get(key) is None for key in needed):
893
+ return None
894
+ kinds = set()
895
+ for segment, monitoring, polarity, low, high, precursor in zip(
896
+ *(scans[key] for key in needed)):
897
+ if bool(monitoring):
898
+ mz = precursor if np.isfinite(precursor) else low
899
+ kinds.add((int(segment), "SIM", str(polarity), _mz_key(mz)))
900
+ else:
901
+ kinds.add((int(segment), "Scan", str(polarity), _mz_key(low),
902
+ _mz_key(high)))
903
+ return kinds
904
+
905
+
906
+ def _mz_key(mz):
907
+ """An m/z as the method and a scan record are compared: to 0.01."""
908
+ return round(float(mz), 2)
909
+
910
+
756
911
  def _signal_of(path, datafile, detectors, ms_count):
757
912
  """(detector index, signal number) of the signal a data file holds
758
913
  (tag_ms_signals), or None."""
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rainbow-api
3
- Version: 1.6.0
3
+ Version: 1.7.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
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes