rainbow-api 1.5.2__tar.gz → 1.5.4__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 (45) hide show
  1. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/CHANGELOG.md +82 -0
  2. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/PKG-INFO +1 -1
  3. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/pyproject.toml +1 -1
  4. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/asm.py +556 -22
  5. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow_api.egg-info/PKG-INFO +1 -1
  6. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/COPYING +0 -0
  7. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/COPYING.LESSER +0 -0
  8. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/MANIFEST.in +0 -0
  9. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/README.md +0 -0
  10. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/__init__.py +0 -0
  11. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/_arguments.py +0 -0
  12. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/_binning.py +0 -0
  13. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/agilent/__init__.py +0 -0
  14. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/agilent/_chdelta.pyx +0 -0
  15. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/agilent/_msprofile.pyx +0 -0
  16. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/agilent/_uvdelta.pyx +0 -0
  17. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/agilent/acaml.py +0 -0
  18. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/agilent/chemstation.py +0 -0
  19. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/agilent/masshunter.py +0 -0
  20. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/agilent/method.py +0 -0
  21. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/agilent/openlab.py +0 -0
  22. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/agilent/sequence.py +0 -0
  23. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/datadirectory.py +0 -0
  24. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/datafile.py +0 -0
  25. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/datasequence.py +0 -0
  26. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/debug/__init__.py +0 -0
  27. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/debug/_util.py +0 -0
  28. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/debug/chemstation_header.py +0 -0
  29. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/debug/chemstation_text.py +0 -0
  30. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/debug/dotnet.py +0 -0
  31. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/debug/ini.py +0 -0
  32. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/debug/method.py +0 -0
  33. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/debug/mzxml.py +0 -0
  34. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/debug/reg.py +0 -0
  35. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/debug/waters_header.py +0 -0
  36. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/debug/waters_inf.py +0 -0
  37. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/debug/xml.py +0 -0
  38. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/waters/__init__.py +0 -0
  39. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow/waters/masslynx.py +0 -0
  40. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow_api.egg-info/SOURCES.txt +0 -0
  41. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow_api.egg-info/dependency_links.txt +0 -0
  42. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow_api.egg-info/requires.txt +0 -0
  43. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/rainbow_api.egg-info/top_level.txt +0 -0
  44. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/setup.cfg +0 -0
  45. {rainbow_api-1.5.2 → rainbow_api-1.5.4}/setup.py +0 -0
@@ -3,6 +3,88 @@
3
3
  All notable changes to `rainbow-api` are documented here. This project adheres
4
4
  to [Semantic Versioning](https://semver.org/).
5
5
 
6
+ ## [1.5.4] - 2026-10-17
7
+
8
+ ### Added
9
+ - **`rb.from_asm` peaks carry the baseline they were integrated from.** A
10
+ peak's area depends on the line it was measured above, and rainbow read the
11
+ area and dropped the line. An Empower export records it for every peak, and
12
+ each peak `from_asm` returns now has six more keys:
13
+ `baseline_start_code` and `baseline_end_code`, the integration type at each
14
+ edge (`B`, `V`, `S`, `T`, ..., lowercase for an edge moved by hand, a
15
+ group's `Gp` split into `G` and `p`); `start_height` and `end_height`, how
16
+ far the trace sits above the baseline at each edge, in mAU; and
17
+ `baseline_start_time` and `baseline_end_time`, where the baseline under the
18
+ peak's cluster begins and ends, in minutes. The line from
19
+ `(start_time, trace - start_height)` to `(end_time, trace - end_height)`
20
+ reproduces the reported area: within 1% for 99.6% of 11,040 peaks across
21
+ four Empower studies, the misses being edges moved by hand.
22
+
23
+ A height in AU or in Empower's µV is converted to mAU (one with no unit is
24
+ taken to be in mAU), and a baseline time in `s` or `min` to minutes; any
25
+ other unit reads as `None`, as do an absent field and a unitless time. The
26
+ heights are written back on export as `peak value at start` and `peak value
27
+ at end`. The schema defines neither the codes nor
28
+ the baseline times, so they are written as the peak's custom information,
29
+ under the labels Empower uses, and read from either place: an export keeps
30
+ them and still validates.
31
+
32
+ ### Changed
33
+ - **`rb.from_asm` reads a peak's `height` and `area` in mAU and mAU·s, by
34
+ their unit.** They were taken as numbers whatever unit the document named,
35
+ and exported as mAU and mAU·s, so a peak list in AU or in Empower's µV was
36
+ written a thousand times off under a unit it was not in. They are now
37
+ converted from AU or µV (and AU·s or µV·s), as the edge heights are. A unit
38
+ rainbow does not know now reads as `None` where it used to pass through
39
+ unconverted; a value with no unit is still taken to be in mAU.
40
+
41
+ ## [1.5.3] - 2026-10-01
42
+
43
+ ### Fixed
44
+ - **`rb.from_asm` dropped a foreign sample's name and all of its custom
45
+ fields.** rainbow's own writer puts everything it knows about a sample in the
46
+ `sample identifier`, so reading only that was enough to round trip its own
47
+ output. A foreign writer distinguishes the two: an Empower or OpenLab export
48
+ names the injection in `written name` (`"NB5-P1A11"`) and keys it in `sample
49
+ identifier` (`"133872"`), and hangs the fields the schema has no place for —
50
+ `Notebook`, `MaterialIdentifier`, `SampleWeight` — off a custom information
51
+ aggregate document. rainbow read neither, leaving a run with no
52
+ human-readable handle on its sample and no way to reach those fields short of
53
+ re-walking the raw JSON. This is not cosmetic: Empower records the registered
54
+ sample's id in `MaterialIdentifier`, and that is the key that matches an
55
+ injection to its sample downstream. Both are now read into
56
+ `metadata["sample_name"]` and `metadata["sample_custom"]`, and written again
57
+ on export, so the lap is lossless.
58
+
59
+ All four datum types the schema admits are carried, each as the Python type
60
+ that distinguishes it — `str`, `bool`, a `datetime` for a timestamp (the datum
61
+ type is the only thing that tells one from the string it is spelled as), and a
62
+ number kept as an `int` where it came in as one. A double's optional `unit`
63
+ rides along as the `{"value", "unit"}` shape `injection_volume` already uses.
64
+ Either spelling of a value is read, the bare scalar or the `{"@type",
65
+ "value"}` object form. Nothing is coerced: an unreadable or ambiguous datum
66
+ type, a value not of the type its datum claims, a number JSON cannot carry, an
67
+ integer too large for a float, a duplicate or unusable `datum label`, and a
68
+ `unit` beside anything but a double are each warned about and dropped, once per
69
+ document. See the round-trip page for the full table.
70
+
71
+ - **A sample's fields could be composed from different samples.** The
72
+ identifier, name, custom fields and vial position were each read field by
73
+ field as the measurements went past, so a document holding several injections
74
+ — which `rb.from_asm` merges into one directory — could report an identifier
75
+ from the first beside a `MaterialIdentifier` from the second. A
76
+ `MaterialIdentifier` is a join key, and one silently attached to the wrong
77
+ sample is worse than the absent one it replaces; so is a vial position, which
78
+ is what a plate map is looked up by. All four now come from one measurement's
79
+ sample document or from none. The document chosen is the first carrying a
80
+ `sample identifier`, since that is what everything downstream falls back to,
81
+ else the first carrying anything at all. `rb.sequence_from_asm` is unaffected:
82
+ it already built one directory per injection.
83
+
84
+ `description`, `sample role type` and `blank` are still dropped, so a sample
85
+ document does not round trip whole — only the identifier, the name, the vial
86
+ position and the custom fields do.
87
+
6
88
  ## [1.5.2] - 2026-09-09
7
89
 
8
90
  ### Fixed
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rainbow-api
3
- Version: 1.5.2
3
+ Version: 1.5.4
4
4
  Summary: Read chromatography and mass spectrometry binary files
5
5
  Author: Evan Shi and Eugene Kwan
6
6
  Author-email: evanyshi@cmu.edu
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "rainbow-api"
7
- version = "1.5.2"
7
+ version = "1.5.4"
8
8
  description = "Read chromatography and mass spectrometry binary files"
9
9
  readme = "README.md"
10
10
  license = {text = "LGPL-3.0-or-later"}
@@ -28,8 +28,10 @@ rainbow's data model already is an ASM data cube:
28
28
  Where the metadata supports it, the envelope is filled in: the instrument and
29
29
  its modules become the device system document, the injection volume an
30
30
  injection document, and (for a sequence read with peaks) the integrated peaks a
31
- processed data aggregate document. A DataSequence becomes one aggregate
32
- document with one chromatography document per injection.
31
+ processed data aggregate document. The `sample_name` and `sample_custom` keys
32
+ are inputs as much as outputs: set either on a run read from a vendor file and
33
+ the export carries it. A DataSequence becomes one aggregate document with one
34
+ chromatography document per injection.
33
35
 
34
36
  Most detectors are exported faithfully: UV as absorbance, CAD and FID as
35
37
  electric current, ELSD as light intensity, each a 1-D chromatogram cube with its
@@ -1492,6 +1494,149 @@ def _detector_measurement(datafile, metadata, descriptor, options,
1492
1494
  return measurement
1493
1495
 
1494
1496
 
1497
+ def _warn_once(seen):
1498
+ """A warn function that says each distinct message once within ``seen``."""
1499
+ def warn(message):
1500
+ if message in seen:
1501
+ return
1502
+ seen.add(message)
1503
+ warnings.warn(message)
1504
+ return warn
1505
+
1506
+
1507
+ def _warn_custom_write(options, label, complaint):
1508
+ """Reports a custom field that cannot be written, once per document.
1509
+
1510
+ One ``sample_custom`` mapping is written into every measurement, so keyed by
1511
+ label and complaint rather than warned as each is built: otherwise a PDA run
1512
+ says the same thing four times, and two bad fields collapse into one.
1513
+ """
1514
+ _warn_once_per_run(options, ("custom-write", label, complaint),
1515
+ "custom field {!r} {}".format(label, complaint))
1516
+
1517
+
1518
+ def _custom_datum_entry(label, value, options):
1519
+ """One custom information document, or None if the value cannot be written.
1520
+
1521
+ The datum type follows the Python type, which is all a plain mapping records:
1522
+ a string, a bool, a datetime and a number each have exactly one of the four
1523
+ scalar spellings the schema admits. A value of no recognised type is reported
1524
+ rather than coerced -- ``str()`` on it would publish a number or a date as
1525
+ text and change what a reader gets back.
1526
+ """
1527
+ from datetime import datetime
1528
+
1529
+ unit = None
1530
+ if isinstance(value, dict):
1531
+ # The {"value", "unit"} shape a double with a unit is read back as. Only
1532
+ # a double may carry a unit, so one arriving beside anything else is said
1533
+ # out loud rather than quietly thrown away with the rest of the dict.
1534
+ unit = _text(value.get("unit"))
1535
+ if value.get("value") is None:
1536
+ _warn_custom_write(
1537
+ options, label,
1538
+ "holds a mapping with no usable 'value' member ({!r}); it is "
1539
+ "dropped.".format(value))
1540
+ return None
1541
+ value = value["value"]
1542
+ if isinstance(value, bool):
1543
+ # Tested before the number branch: a bool is an int in Python and would
1544
+ # otherwise be written as 1.0, which is not what was recorded.
1545
+ datum = {"scalar boolean datum": value}
1546
+ elif isinstance(value, str):
1547
+ datum = {"scalar string datum": value}
1548
+ elif isinstance(value, datetime):
1549
+ # Through the same gate as every other timestamp rather than
1550
+ # isoformat() direct, so that a naive one picks up the caller's
1551
+ # utc_offset and warns once when there is none. The schema's date-time
1552
+ # format is RFC 3339 and requires an offset, so writing a naive
1553
+ # datetime's isoformat() emitted a value the document then failed to
1554
+ # validate on. A plain `date` is not handled at all: its isoformat() is
1555
+ # a date, not a date-time, and midnight in an invented zone is the kind
1556
+ # of guess this reader refuses elsewhere.
1557
+ stamped = options.timestamp(value.isoformat())
1558
+ if stamped is None:
1559
+ return None
1560
+ datum = {"scalar timestamp datum": stamped}
1561
+ elif isinstance(value, (int, float)):
1562
+ if isinstance(value, int):
1563
+ # Before isfinite, not after: JSON integer literals are unbounded and
1564
+ # math.isfinite raises OverflowError on one too large for a float,
1565
+ # out of the middle of the export, instead of reporting it.
1566
+ try:
1567
+ float(value)
1568
+ except OverflowError:
1569
+ _warn_custom_write(
1570
+ options, label,
1571
+ "holds an integer too large to carry as a double; it is "
1572
+ "dropped.")
1573
+ return None
1574
+ if not math.isfinite(value):
1575
+ # json.dumps writes NaN and Infinity as bare literals no conforming
1576
+ # reader accepts, so to_asm_str would raise after to_asm looked fine.
1577
+ _warn_custom_write(
1578
+ options, label,
1579
+ "holds {!r}, which is not a value JSON can carry; it is "
1580
+ "dropped.".format(value))
1581
+ return None
1582
+ # Rounded only when a precision was asked for, so an int stays an int
1583
+ # by default the way every other number rainbow reads back does.
1584
+ if options.decimals is not None:
1585
+ value = options.scalar(value)
1586
+ datum = {"scalar double datum": value}
1587
+ if unit:
1588
+ datum["unit"] = unit
1589
+ return datum
1590
+ else:
1591
+ _warn_custom_write(
1592
+ options, label,
1593
+ "holds {}, which rainbow cannot write as an ASM scalar datum; it "
1594
+ "is dropped rather than coerced to text."
1595
+ .format(type(value).__name__))
1596
+ return None
1597
+ if unit:
1598
+ # Reached only by the string, bool and timestamp branches, none of which
1599
+ # the schema lets carry a unit.
1600
+ _warn_custom_write(
1601
+ options, label,
1602
+ "carries the unit {!r} beside a {}, which only a double may do; "
1603
+ "the unit is dropped.".format(unit, next(iter(datum))))
1604
+ return datum
1605
+
1606
+
1607
+ def _custom_information_document(fields, options):
1608
+ """A ``{label: value}`` mapping as a custom information aggregate document.
1609
+
1610
+ The inverse of :func:`_custom_fields`. ``@index`` is written 1..n in the
1611
+ mapping's order, which is the order the fields were read in.
1612
+ """
1613
+ if fields is None:
1614
+ return None
1615
+ if not isinstance(fields, dict):
1616
+ _warn_once_per_run(
1617
+ options, "custom-not-a-mapping",
1618
+ "metadata['sample_custom'] holds {}, not a mapping of labels to "
1619
+ "values; no custom fields are written."
1620
+ .format(type(fields).__name__))
1621
+ return None
1622
+ entries = []
1623
+ for label, value in fields.items():
1624
+ if not isinstance(label, str) or not label:
1625
+ _warn_once_per_run(
1626
+ options, ("custom-label", repr(label)),
1627
+ "custom field labelled {!r} is not a usable datum label; the "
1628
+ "field is dropped.".format(label))
1629
+ continue
1630
+ datum = _custom_datum_entry(label, value, options)
1631
+ if datum is None:
1632
+ continue
1633
+ entries.append(dict({"@index": len(entries) + 1,
1634
+ "datum label": label}, **datum))
1635
+ if not entries:
1636
+ return None
1637
+ return {"custom information document": entries}
1638
+
1639
+
1495
1640
  def _note_relabeled_measure(measurement, descriptor):
1496
1641
  """Records the real quantity of a channel relabeled to absorbance."""
1497
1642
  measurement["custom information aggregate document"] = {
@@ -1602,6 +1747,13 @@ def _measurement(datafile, metadata, control, cube_key, cube, options,
1602
1747
  identifier=None):
1603
1748
  """Wraps a data cube in the shared measurement envelope."""
1604
1749
  sample = {"sample identifier": metadata.get("sample", "unknown")}
1750
+ name = metadata.get("sample_name")
1751
+ if isinstance(name, str) and name:
1752
+ sample["written name"] = name
1753
+ custom = _custom_information_document(
1754
+ metadata.get("sample_custom"), options)
1755
+ if custom:
1756
+ sample["custom information aggregate document"] = custom
1605
1757
  if "vialpos" in metadata:
1606
1758
  sample["location identifier"] = str(metadata["vialpos"])
1607
1759
  measurement = {
@@ -1830,6 +1982,8 @@ def _asm_peak(index, peak, options=None):
1830
1982
  ("height_percent", "relative peak height", "%", 1.0),
1831
1983
  ("symmetry", "asymmetry factor measured at 5 % height",
1832
1984
  "(unitless)", 1.0),
1985
+ ("start_height", "peak value at start", "mAU", 1.0),
1986
+ ("end_height", "peak value at end", "mAU", 1.0),
1833
1987
  )
1834
1988
  for source, target, unit, scale in mapping:
1835
1989
  value = peak.get(source)
@@ -1837,9 +1991,45 @@ def _asm_peak(index, peak, options=None):
1837
1991
  # rather than fail the whole export.
1838
1992
  if isinstance(value, (int, float)) and not isinstance(value, bool):
1839
1993
  entry[target] = _quantity(value * scale, unit, options)
1994
+ custom = _peak_baseline_custom(peak, options)
1995
+ if custom:
1996
+ entry["custom information aggregate document"] = {
1997
+ "custom information document": custom}
1840
1998
  return entry
1841
1999
 
1842
2000
 
2001
+ # A peak's baseline fields the schema has no place for, as ``(key, label)``.
2002
+ # Empower writes them on the peak itself under these labels; rainbow writes
2003
+ # them as custom information under the same labels, so a document it exports
2004
+ # validates, and reads them from either place.
2005
+ _PEAK_BASELINE_CODES = (
2006
+ ("baseline_start_code", "peak baseline start code"),
2007
+ ("baseline_end_code", "peak baseline end code"),
2008
+ )
2009
+ _PEAK_BASELINE_TIMES = (
2010
+ ("baseline_start_time", "baseline value at start of peak"),
2011
+ ("baseline_end_time", "baseline value at end of peak"),
2012
+ )
2013
+
2014
+
2015
+ def _peak_baseline_custom(peak, options):
2016
+ """A peak's baseline codes and times as custom information documents."""
2017
+ entries = []
2018
+ for key, label in _PEAK_BASELINE_CODES:
2019
+ code = peak.get(key)
2020
+ if isinstance(code, str) and code.strip():
2021
+ entries.append({"datum label": label,
2022
+ "scalar string datum": code.strip()})
2023
+ for key, label in _PEAK_BASELINE_TIMES:
2024
+ time = peak.get(key)
2025
+ if isinstance(time, (int, float)) and not isinstance(time, bool):
2026
+ seconds = _quantity(time * _SECONDS_PER_MINUTE, "s", options)
2027
+ entries.append({"datum label": label,
2028
+ "scalar double datum": seconds["value"],
2029
+ "unit": "s"})
2030
+ return [dict({"@index": i + 1}, **e) for i, e in enumerate(entries)]
2031
+
2032
+
1843
2033
  def _peak_groups_by_channel(peaks):
1844
2034
  """Indexes an injection's peak groups by channel (e.g. ``DAD1A``)."""
1845
2035
  groups = {}
@@ -2027,8 +2217,15 @@ def from_asm(document, name="asm"):
2027
2217
 
2028
2218
  datafiles = []
2029
2219
  peak_groups = []
2220
+ # Over every injection at once, not one at a time: this directory holds the
2221
+ # merge of all of them, so the sample has to be chosen with all of them in
2222
+ # view. Choosing per injection and keeping the first answer lost the
2223
+ # identifier whenever an earlier injection supplied only a name.
2224
+ _absorb_samples(_measurements_of(documents), metadata)
2225
+ said = set()
2030
2226
  for lc_document in documents:
2031
- _absorb_lc_document(lc_document, metadata, datafiles, peak_groups)
2227
+ _absorb_lc_document(lc_document, metadata, datafiles, peak_groups,
2228
+ said)
2032
2229
  return _directory(name, datafiles, metadata, peak_groups)
2033
2230
 
2034
2231
 
@@ -2187,12 +2384,14 @@ def sequence_from_asm(document, name="asm"):
2187
2384
 
2188
2385
  injections = []
2189
2386
  taken = set()
2387
+ said = set()
2190
2388
  for index, lc_document in enumerate(documents):
2191
2389
  injection_metadata = {}
2192
2390
  datafiles = []
2193
2391
  peak_groups = []
2392
+ _absorb_samples(_measurements_of([lc_document]), injection_metadata)
2194
2393
  _absorb_lc_document(
2195
- lc_document, injection_metadata, datafiles, peak_groups)
2394
+ lc_document, injection_metadata, datafiles, peak_groups, said)
2196
2395
  # The injection identifier is the name the injection was exported
2197
2396
  # under, so it restores the caller's own name. The sample identifier is
2198
2397
  # the fallback because a sequence's replicates share one, which used to
@@ -2242,8 +2441,25 @@ def _directory(name, datafiles, metadata, peak_groups):
2242
2441
  return datadir
2243
2442
 
2244
2443
 
2245
- def _absorb_lc_document(lc_document, metadata, datafiles, peak_groups):
2246
- """Reads one liquid chromatography document into datafiles and metadata."""
2444
+ def _measurements_of(lc_documents):
2445
+ """Every measurement document across ``lc_documents``, in document order."""
2446
+ measurements = []
2447
+ for lc_document in lc_documents:
2448
+ if not isinstance(lc_document, dict):
2449
+ continue
2450
+ measurements += _as_documents(
2451
+ _first(lc_document.get("measurement aggregate document"))
2452
+ .get("measurement document"))
2453
+ return measurements
2454
+
2455
+
2456
+ def _absorb_lc_document(lc_document, metadata, datafiles, peak_groups,
2457
+ said=None):
2458
+ """Reads one liquid chromatography document into datafiles and metadata.
2459
+
2460
+ ``said`` collects the read's warnings about peaks' custom information, so
2461
+ one complaint repeated across peaks and documents is made once.
2462
+ """
2247
2463
  if not isinstance(lc_document, dict):
2248
2464
  return
2249
2465
  analyst = _text(lc_document.get("analyst"))
@@ -2269,20 +2485,91 @@ def _absorb_lc_document(lc_document, metadata, datafiles, peak_groups):
2269
2485
  if datafile is None:
2270
2486
  continue # a measurement rainbow did not write (no UV cube)
2271
2487
  datafiles.append(datafile)
2272
- group = _peaks_from_measurement(measurement)
2488
+ group = _peaks_from_measurement(measurement, said)
2273
2489
  if group:
2274
2490
  peak_groups.append(group)
2275
2491
 
2276
2492
 
2493
+ # The three metadata keys one sample document supplies. They are taken together
2494
+ # or not at all, so they always describe the same sample.
2495
+ _SAMPLE_KEYS = ("sample", "sample_name", "sample_custom")
2496
+
2497
+
2498
+ def _absorb_samples(measurements, metadata):
2499
+ """Lifts ONE measurement's sample document up to directory metadata.
2500
+
2501
+ rainbow's own writer puts everything it knows about a sample in the
2502
+ identifier, so reading only that was enough to round trip its own output. A
2503
+ foreign writer distinguishes the two: an Empower export names the injection
2504
+ in ``written name`` ("NB5-P1A11") and keys it in ``sample identifier``
2505
+ ("133872"). Dropping the name loses the only human-readable handle the
2506
+ document carries on its sample, and the custom fields go with it.
2507
+
2508
+ The sample document is read as a unit: identifier, name, custom fields and
2509
+ vial position all come from one of them or from none. Reading them field by
2510
+ field as each measurement went past composed them instead: :func:`from_asm`
2511
+ merges every injection in a document into one directory, so an identifier
2512
+ from the first injection could end up beside a name and a
2513
+ ``MaterialIdentifier`` from the second. A ``MaterialIdentifier`` is a join
2514
+ key, and one silently attached to the wrong sample is worse than the absent
2515
+ one it replaces -- and so is a vial position, which is what a plate map is
2516
+ looked up by. Hence one pass here, over a list, rather than a field at a
2517
+ time as each measurement is read.
2518
+
2519
+ Which document: the first that carries a *sample identifier*, since that is
2520
+ what everything downstream falls back to, else the first that carries
2521
+ anything at all. A run whose opening channel records a name against an
2522
+ "unknown" identifier would otherwise lose the identifier a later channel had.
2523
+
2524
+ Called once per directory, over every measurement that directory will hold.
2525
+ :func:`from_asm` merges a file's injections into one directory and so passes
2526
+ all of them; :func:`sequence_from_asm` builds one directory per injection and
2527
+ passes one at a time. Running it per injection and keeping the first answer
2528
+ reintroduced the same loss one level up: an opening injection with only a
2529
+ name suppressed the identifier a later one carried.
2530
+ """
2531
+ documents = [_first(measurement.get("sample document"))
2532
+ for measurement in measurements
2533
+ if isinstance(measurement, dict)]
2534
+ identified = [sample for sample in documents
2535
+ if (_text(sample.get("sample identifier")) or "unknown")
2536
+ != "unknown"]
2537
+ said = set()
2538
+ chosen = None
2539
+ for sample in identified[:1] or documents:
2540
+ identifier = _text(sample.get("sample identifier"))
2541
+ name = _text(sample.get("written name"))
2542
+ custom = _custom_fields(sample, said)
2543
+ if identifier and identifier != "unknown":
2544
+ metadata["sample"] = identifier
2545
+ if name:
2546
+ metadata["sample_name"] = name
2547
+ if custom:
2548
+ metadata["sample_custom"] = custom
2549
+ # Keyed on what was actually absorbed, not on what the document held: a
2550
+ # sample document carrying only the placeholder "unknown" identifier
2551
+ # says something without supplying anything, and stopping on it left the
2552
+ # run with no sample at all.
2553
+ if any(key in metadata for key in _SAMPLE_KEYS):
2554
+ chosen = sample
2555
+ break
2556
+ if chosen is None:
2557
+ # Nothing identified the sample anywhere. The vial position is still
2558
+ # worth having, so it comes from the first document that records one.
2559
+ chosen = next((sample for sample in documents
2560
+ if _text(sample.get("location identifier"))), None)
2561
+ if chosen is not None:
2562
+ location = _text(chosen.get("location identifier"))
2563
+ if location:
2564
+ metadata["vialpos"] = location
2565
+
2566
+
2277
2567
  def _absorb_envelope(measurement, metadata):
2278
- """Lifts a measurement's envelope fields up to directory metadata."""
2279
- sample = _first(measurement.get("sample document"))
2280
- identifier = _text(sample.get("sample identifier"))
2281
- if identifier and identifier != "unknown":
2282
- metadata.setdefault("sample", identifier)
2283
- location = _text(sample.get("location identifier"))
2284
- if location:
2285
- metadata.setdefault("vialpos", location)
2568
+ """Lifts a measurement's envelope fields up to directory metadata.
2569
+
2570
+ The sample document is not read here, vial position included: it is taken as
2571
+ a unit by :func:`_absorb_samples`, once per directory, before this runs.
2572
+ """
2286
2573
  date = _text(measurement.get("measurement time"))
2287
2574
  if date:
2288
2575
  metadata.setdefault("date", date)
@@ -2300,6 +2587,171 @@ def _absorb_envelope(measurement, metadata):
2300
2587
  "injection_volume", {"value": volume, "unit": "µL"})
2301
2588
 
2302
2589
 
2590
+ # A date-time has a time of day; a date does not. ASM types every timestamp as a
2591
+ # full date-time, so the separator is what tells a usable value from a date. The
2592
+ # case is not fixed: RFC 3339 permits a lowercase `t`, and _parse_iso already
2593
+ # goes out of its way to accept a lowercase `z` for the same reason. A space is
2594
+ # accepted too -- the schema's format does not allow one, but _parse_iso reads it
2595
+ # and the re-export writes it back as `T`, so taking it in normalizes it. The
2596
+ # digits either side are what keep a bare date out.
2597
+ _HAS_TIME_OF_DAY = re.compile(r"\d[Tt ]\d")
2598
+
2599
+
2600
+ # A custom information document carries its value under a key naming the datum's
2601
+ # type, and the schema admits exactly these four. An entry declaring none of
2602
+ # them, or more than one, is reported rather than guessed at: the schema makes
2603
+ # them a `oneOf`, so more than one is malformed, and picking one of two
2604
+ # conflicting values would publish a number rainbow invented a preference for.
2605
+ _CUSTOM_DATUM_KEYS = (
2606
+ "scalar string datum",
2607
+ "scalar double datum",
2608
+ "scalar boolean datum",
2609
+ "scalar timestamp datum",
2610
+ )
2611
+
2612
+ # Returned instead of a value when a datum was recognised but unreadable, so a
2613
+ # field dropped after its own warning is not warned about a second time.
2614
+ _UNREADABLE = object()
2615
+
2616
+
2617
+ def _custom_datum_value(key, entry, label, warn):
2618
+ """One custom entry's value, in the Python type its datum type calls for.
2619
+
2620
+ The datum type is what distinguishes a timestamp from the string it is
2621
+ spelled as, so it has to survive into the mapping or a round trip cannot put
2622
+ it back. A double carrying a ``unit`` sibling becomes ``{"value", "unit"}``,
2623
+ the shape rainbow already uses for ``injection_volume``.
2624
+ """
2625
+ raw = entry[key]
2626
+ unit = _text(entry.get("unit"))
2627
+ if key == "scalar string datum":
2628
+ value = _text(raw)
2629
+ elif key == "scalar boolean datum":
2630
+ value = raw.get("value") if isinstance(raw, dict) else raw
2631
+ # Not bool(raw): "false" and 0 are both truthy-or-falsy in ways that
2632
+ # have nothing to do with what the document recorded.
2633
+ value = value if isinstance(value, bool) else None
2634
+ elif key == "scalar timestamp datum":
2635
+ # Read as a datetime, which is what tells it apart from a string datum
2636
+ # on the way back out. A date with no time of day is refused rather
2637
+ # than parsed: _parse_iso would return midnight, a value the document
2638
+ # never carried, and re-exporting it would publish that invention under
2639
+ # a datum type the schema requires to be a full date-time. The write
2640
+ # side refuses a Python `date` for the same reason.
2641
+ text = _text(raw)
2642
+ value = _parse_iso(text) if text and _HAS_TIME_OF_DAY.search(text) \
2643
+ else None
2644
+ else:
2645
+ # _number unwraps the object form, rejects a bool spelled as a number,
2646
+ # and drops an integer too large for a float rather than handing back a
2647
+ # value that reads but raises OverflowError on re-export.
2648
+ value = _number(raw)
2649
+ if value is not None and unit:
2650
+ value = {"value": value, "unit": unit}
2651
+ unit = None # consumed
2652
+ if unit and value is not None:
2653
+ # No subschema forbids it, so a conforming document may put a unit beside
2654
+ # a string, a bool or a timestamp. Only a double has anywhere to keep it.
2655
+ warn(
2656
+ "custom field {!r} carries the unit {!r} beside a {}, which only a "
2657
+ "double may do; the unit is dropped.".format(label, unit, key))
2658
+ if value is None:
2659
+ warn(
2660
+ "custom field {!r} holds a {} rainbow cannot read ({!r}); the "
2661
+ "field is dropped.".format(label, key, raw))
2662
+ return _UNREADABLE
2663
+ return value
2664
+
2665
+
2666
+ def _custom_fields(document, seen):
2667
+ """A document's custom information fields as a ``{label: value}`` dict.
2668
+
2669
+ ASM lets a writer hang arbitrary named values off a sample or measurement in
2670
+ a *custom information aggregate document*. Empower uses it for the fields
2671
+ that have no home in the schema proper -- `Notebook`, `MaterialIdentifier`,
2672
+ `SampleWeight` -- and `MaterialIdentifier` is how an Empower injection is
2673
+ matched to a registered sample downstream, so these are not decoration.
2674
+ """
2675
+ aggregate = _first(document.get("custom information aggregate document"))
2676
+ entries = _as_documents(aggregate.get("custom information document"))
2677
+ # One sample document is repeated in every measurement of an injection, so a
2678
+ # complaint about it would otherwise be made once per candidate channel. The
2679
+ # caller passes a set to say the complaints share one scope, as the write
2680
+ # side does through _warn_once_per_run.
2681
+ warn = _warn_once(seen)
2682
+ read = []
2683
+ for position, entry in enumerate(entries):
2684
+ if not isinstance(entry, dict):
2685
+ continue
2686
+ label = _text(entry.get("datum label"))
2687
+ if not label:
2688
+ # `datum label` is required, so an entry without a usable one is
2689
+ # malformed. The write side says so for the mirror case, and a
2690
+ # mapping has nowhere to put an unlabelled value, so it is dropped
2691
+ # out loud rather than quietly.
2692
+ # Positioned, because the message is otherwise identical for every
2693
+ # unlabelled entry and the dedupe would report only the first.
2694
+ warn("the custom field at position {} carries {!r} as its datum "
2695
+ "label, which cannot key a value; the field is dropped."
2696
+ .format(position + 1, entry.get("datum label")))
2697
+ continue
2698
+ spellings = [key for key in _CUSTOM_DATUM_KEYS if key in entry]
2699
+ if len(spellings) != 1:
2700
+ _warn_custom_datum_type(label, entry, spellings, warn)
2701
+ continue
2702
+ value = _custom_datum_value(spellings[0], entry, label, warn)
2703
+ if value is _UNREADABLE:
2704
+ continue
2705
+ read.append((_number(entry.get("@index")), label, value))
2706
+ fields = {}
2707
+ for _, label, value in _in_declared_order(read):
2708
+ if label in fields:
2709
+ # Duplicate labels are legal and a mapping cannot hold both. Keeping
2710
+ # the first matches how the rest of a read merges, but silently
2711
+ # discarding a value is the thing this reader otherwise refuses to
2712
+ # do, so it is said out loud.
2713
+ warn("custom field {!r} appears more than once; the first "
2714
+ "value is kept and the rest dropped.".format(label))
2715
+ continue
2716
+ fields[label] = value
2717
+ return fields
2718
+
2719
+
2720
+ def _warn_custom_datum_type(label, entry, spellings, warn):
2721
+ """Reports an entry declaring no datum type rainbow reads, or several."""
2722
+ if spellings:
2723
+ warn(
2724
+ "custom field {!r} declares {} datum types ({}), which the schema "
2725
+ "admits only one of; the field is dropped rather than picking one "
2726
+ "of its values.".format(
2727
+ label, len(spellings),
2728
+ ", ".join(repr(key) for key in spellings)))
2729
+ return
2730
+ unknown = sorted(key for key in entry
2731
+ if key not in ("@index", "datum label", "unit"))
2732
+ warn(
2733
+ "custom field {!r} records its value under {}, which rainbow does not "
2734
+ "read; the field is dropped rather than reported under a datum type "
2735
+ "that would change its meaning.".format(
2736
+ label, ", ".join(repr(key) for key in unknown) or "nothing"))
2737
+
2738
+
2739
+ def _in_declared_order(read):
2740
+ """``read`` ordered by ``@index`` when every entry declares one.
2741
+
2742
+ ``@index`` is 1-based and need not be dense; document position is 0-based
2743
+ and always is. Sorting a mix of the two puts an unindexed entry wherever its
2744
+ position happens to fall among someone else's indices -- three fields
2745
+ indexed 5, 6 and (none) came back as (none), 5, 6. Since the schema does not
2746
+ require ``@index``, a partially indexed document is reachable, so the two
2747
+ are never mixed: either the document orders every entry or its own order
2748
+ stands.
2749
+ """
2750
+ if all(index is not None for index, _, _ in read):
2751
+ return sorted(read, key=lambda item: item[0])
2752
+ return read
2753
+
2754
+
2303
2755
  # The two ADMs neither name nor measure the injection volume the same way.
2304
2756
  _INJECTION_VOLUME_KEYS = (
2305
2757
  # Liquid chromatography, in mm^3.
@@ -2458,7 +2910,7 @@ def _processing_document(processed_data):
2458
2910
  }
2459
2911
 
2460
2912
 
2461
- def _peak_lists(measurement):
2913
+ def _peak_lists(measurement, said=None):
2462
2914
  """Every non-empty ``(processing, peaks)`` a measurement carries, in order.
2463
2915
 
2464
2916
  A measurement may hold more than one processed data document: an Empower or
@@ -2478,13 +2930,13 @@ def _peak_lists(measurement):
2478
2930
  if isinstance(peak, dict)]
2479
2931
  if asm_peaks:
2480
2932
  lists.append((_processing_document(document),
2481
- [_peak_from_asm(peak) for peak in asm_peaks]))
2933
+ [_peak_from_asm(peak, said) for peak in asm_peaks]))
2482
2934
  return lists
2483
2935
 
2484
2936
 
2485
- def _peaks_from_measurement(measurement):
2937
+ def _peaks_from_measurement(measurement, said=None):
2486
2938
  """Reconstructs a peak group from a measurement's processed data, or None."""
2487
- lists = _peak_lists(measurement)
2939
+ lists = _peak_lists(measurement, said)
2488
2940
  if not lists:
2489
2941
  return None
2490
2942
  processing, peaks = lists[0]
@@ -2540,7 +2992,7 @@ def _wavelength_from_label(label):
2540
2992
  return float(match.group(1)) if match else None
2541
2993
 
2542
2994
 
2543
- def _peak_from_asm(peak):
2995
+ def _peak_from_asm(peak, said=None):
2544
2996
  """Reconstructs a peak's measures, times back from seconds to minutes."""
2545
2997
  def value(key):
2546
2998
  # A foreign writer may spell a measure as text, or as something else
@@ -2561,14 +3013,96 @@ def _peak_from_asm(peak):
2561
3013
  "retention_time": minutes("retention time"),
2562
3014
  "start_time": minutes("peak start"),
2563
3015
  "end_time": minutes("peak end"),
2564
- "area": value("peak area"),
3016
+ "area": _peak_measure_in_mau(peak.get("peak area"), ".s"),
2565
3017
  "area_percent": value("relative peak area"),
2566
- "height": value("peak height"),
3018
+ "height": _peak_measure_in_mau(peak.get("peak height")),
2567
3019
  "height_percent": value("relative peak height"),
2568
3020
  "symmetry": value("asymmetry factor measured at 5 % height"),
3021
+ # How the integration drew the baseline under this peak. A height is
3022
+ # how far the trace sits above the baseline at that edge, in mAU, so
3023
+ # the line runs from (start, trace - start height) to (end, trace - end
3024
+ # height).
3025
+ "start_height": _peak_measure_in_mau(
3026
+ peak.get("peak value at start")),
3027
+ "end_height": _peak_measure_in_mau(peak.get("peak value at end")),
3028
+ **_peak_baseline_fields(peak, said),
2569
3029
  }
2570
3030
 
2571
3031
 
3032
+ # The units a peak's height, edge heights and area are read in, as mAU per
3033
+ # unit (an area's unit is one of these times seconds). Empower's own unit for a
3034
+ # UV height is the microvolt, one of which is one microabsorbance unit. Kept
3035
+ # apart from _ABSORBANCE_TO_MAU so that a cube labelled in microvolts exports
3036
+ # as it did before. The micro sign and the Greek mu are both in use.
3037
+ _PEAK_VALUE_TO_MAU = dict(_ABSORBANCE_TO_MAU, **{"\u00b5v": 0.001,
3038
+ "\u03bcv": 0.001})
3039
+
3040
+
3041
+ def _peak_measure_in_mau(quantity, per=""):
3042
+ """
3043
+ A peak's height (or, with ``per=".s"``, its area) in mAU, or None.
3044
+
3045
+ The export labels these mAU and mAU.s, so a value read in AU or microvolts
3046
+ has to be converted to match, or it is written a thousand times off under
3047
+ a unit it is not in. A unit rainbow does not know reads as None rather than
3048
+ as a number in the wrong unit. A value with no unit at all is taken to be
3049
+ in the schema's own mAU, as rainbow has always read it.
3050
+
3051
+ """
3052
+ number = _number(quantity)
3053
+ unit = quantity.get("unit") if isinstance(quantity, dict) else None
3054
+ if number is None or unit is None:
3055
+ return number
3056
+ key = _absorbance_unit_key(unit) if isinstance(unit, str) else ""
3057
+ scale = _PEAK_VALUE_TO_MAU.get(key[:len(key) - len(per)]) \
3058
+ if key.endswith(per) else None
3059
+ if scale is None:
3060
+ return None
3061
+ # Unscaled when already mAU, so an integer stays the integer it was.
3062
+ return number if scale == 1.0 else number * scale
3063
+
3064
+
3065
+ # The units a baseline time is read in, as units per minute. Any other unit,
3066
+ # or none, gives None: the field's name reads as a signal value, and the unit
3067
+ # is the only thing that says a writer filled it with a time.
3068
+ _TIME_UNITS_PER_MINUTE = {"s": _SECONDS_PER_MINUTE, "min": 1.0}
3069
+
3070
+
3071
+ def _peak_baseline_fields(peak, said=None):
3072
+ """
3073
+ A peak's baseline codes and times, read from the peak or its custom
3074
+ information.
3075
+
3076
+ A code is the integration type at each edge (B, V, S, T, ..., lowercase
3077
+ where the edge was moved by hand; Empower splits a group's "Gp" into "G"
3078
+ and "p"). A time is where the baseline under the peak's cluster begins or
3079
+ ends, in minutes like the peak's other times. Empower writes both on the
3080
+ peak, where the schema does not define them; rainbow writes them as custom
3081
+ information, where it does.
3082
+
3083
+ """
3084
+ custom = {}
3085
+ if "custom information aggregate document" in peak:
3086
+ custom = _custom_fields(peak, set() if said is None else said)
3087
+
3088
+ def field(label):
3089
+ value = peak.get(label)
3090
+ return value if value is not None else custom.get(label)
3091
+
3092
+ fields = {}
3093
+ for key, label in _PEAK_BASELINE_CODES:
3094
+ fields[key] = (_text(field(label)) or "").strip() or None
3095
+ for key, label in _PEAK_BASELINE_TIMES:
3096
+ quantity = field(label)
3097
+ number = _number(quantity)
3098
+ unit = quantity.get("unit") if isinstance(quantity, dict) else None
3099
+ per_minute = _TIME_UNITS_PER_MINUTE.get(unit) \
3100
+ if isinstance(unit, str) else None
3101
+ fields[key] = number / per_minute \
3102
+ if number is not None and per_minute else None
3103
+ return fields
3104
+
3105
+
2572
3106
  def _instrument_from_device_system(device_system):
2573
3107
  """Reconstructs the instrument dict from a device system document, or None."""
2574
3108
  if not isinstance(device_system, dict):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rainbow-api
3
- Version: 1.5.2
3
+ Version: 1.5.4
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