FCSBridge 0.1.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.
- fcsbridge-0.1.0/.coveragerc +22 -0
- fcsbridge-0.1.0/.zenodo.json +19 -0
- fcsbridge-0.1.0/AGENTS.md +16 -0
- fcsbridge-0.1.0/CITATION.cff +10 -0
- fcsbridge-0.1.0/CONTRIBUTING.md +13 -0
- fcsbridge-0.1.0/FCSBridge/__init__.py +8 -0
- fcsbridge-0.1.0/FCSBridge/_records.py +118 -0
- fcsbridge-0.1.0/FCSBridge/_version.py +5 -0
- fcsbridge-0.1.0/FCSBridge/csv.py +99 -0
- fcsbridge-0.1.0/FCSBridge/dataset.py +133 -0
- fcsbridge-0.1.0/FCSBridge/fcs.py +138 -0
- fcsbridge-0.1.0/FCSBridge.egg-info/PKG-INFO +150 -0
- fcsbridge-0.1.0/FCSBridge.egg-info/SOURCES.txt +43 -0
- fcsbridge-0.1.0/FCSBridge.egg-info/dependency_links.txt +1 -0
- fcsbridge-0.1.0/FCSBridge.egg-info/requires.txt +15 -0
- fcsbridge-0.1.0/FCSBridge.egg-info/top_level.txt +1 -0
- fcsbridge-0.1.0/LICENSE +21 -0
- fcsbridge-0.1.0/MANIFEST.in +6 -0
- fcsbridge-0.1.0/Makefile +75 -0
- fcsbridge-0.1.0/PKG-INFO +150 -0
- fcsbridge-0.1.0/README.rst +125 -0
- fcsbridge-0.1.0/USAGE.rst +55 -0
- fcsbridge-0.1.0/conda.recipe/meta.yaml +28 -0
- fcsbridge-0.1.0/docs/examples/dataframe_to_fcs.py +9 -0
- fcsbridge-0.1.0/docs/examples/fcs_to_csv.py +8 -0
- fcsbridge-0.1.0/docs/images/favicon.png +0 -0
- fcsbridge-0.1.0/docs/images/favicon.svg +5 -0
- fcsbridge-0.1.0/docs/images/icon.png +0 -0
- fcsbridge-0.1.0/docs/images/icon.svg +7 -0
- fcsbridge-0.1.0/docs/images/logo.png +0 -0
- fcsbridge-0.1.0/docs/images/logo.svg +9 -0
- fcsbridge-0.1.0/docs/source/conf.py +19 -0
- fcsbridge-0.1.0/docs/source/index.rst +20 -0
- fcsbridge-0.1.0/pyproject.toml +49 -0
- fcsbridge-0.1.0/pytest.ini +3 -0
- fcsbridge-0.1.0/readme.yml +7 -0
- fcsbridge-0.1.0/setup.cfg +4 -0
- fcsbridge-0.1.0/tests/data/LICENSE-fcsparser +21 -0
- fcsbridge-0.1.0/tests/data/README.rst +3 -0
- fcsbridge-0.1.0/tests/data/cyflow_cube_8.fcs +0 -0
- fcsbridge-0.1.0/tests/test_csv.py +32 -0
- fcsbridge-0.1.0/tests/test_dataset.py +25 -0
- fcsbridge-0.1.0/tests/test_fcs.py +86 -0
- fcsbridge-0.1.0/tests/test_fcs_versions.py +90 -0
- fcsbridge-0.1.0/tests/test_rosettax.py +70 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# .coveragerc
|
|
2
|
+
[run]
|
|
3
|
+
source = FCSBridge
|
|
4
|
+
branch = True
|
|
5
|
+
relative_files = True
|
|
6
|
+
parallel = True
|
|
7
|
+
omit =
|
|
8
|
+
**/__init__.py
|
|
9
|
+
FCSBridge/_version.py
|
|
10
|
+
FCSBridge/directories.py
|
|
11
|
+
FCSBridge/**/__main__.py
|
|
12
|
+
|
|
13
|
+
[report]
|
|
14
|
+
skip_covered = True
|
|
15
|
+
show_missing = True
|
|
16
|
+
precision = 2
|
|
17
|
+
|
|
18
|
+
[html]
|
|
19
|
+
directory = htmlcov
|
|
20
|
+
|
|
21
|
+
[xml]
|
|
22
|
+
output = coverage.xml
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
{
|
|
2
|
+
"title": "FCSBridge",
|
|
3
|
+
"description": "Read and write flow cytometry event tables with Python.",
|
|
4
|
+
"creators": [
|
|
5
|
+
{
|
|
6
|
+
"name": "Poinsinet de Sivry-Houle, Martin"
|
|
7
|
+
}
|
|
8
|
+
],
|
|
9
|
+
"license": "MIT",
|
|
10
|
+
"upload_type": "software",
|
|
11
|
+
"access_right": "open",
|
|
12
|
+
"keywords": [
|
|
13
|
+
"flow cytometry",
|
|
14
|
+
"FCS",
|
|
15
|
+
"data conversion"
|
|
16
|
+
],
|
|
17
|
+
"version": "0.1.0",
|
|
18
|
+
"publication_date": "2026-11-29"
|
|
19
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# FCSBridge Repository Instructions
|
|
2
|
+
|
|
3
|
+
## Shared Python style preferences
|
|
4
|
+
|
|
5
|
+
Apply these conventions to new and edited Python code. Leave unrelated existing code unchanged. Preserve each repository's existing public APIs and project-specific scientific or behavioral requirements.
|
|
6
|
+
|
|
7
|
+
- Use keyword-only parameters by default for new functions and methods, apart from implicit `self` and `cls`. Preserve existing public calling conventions unless an API change is part of the task.
|
|
8
|
+
- Use NumPy-style docstrings for classes, functions, methods, and properties. Document parameters, return values, units, array shapes, and limitations where they apply.
|
|
9
|
+
- Keep imports at module scope when practical. Use local imports only when needed to avoid circular dependencies or defer optional, expensive, or side-effectful imports.
|
|
10
|
+
- Keep all imports in one contiguous block, without blank lines between standard-library, third-party, and project imports.
|
|
11
|
+
- Avoid redundant self-alias imports such as `from package.module import Name as Name`; import the name directly unless the alias clarifies its meaning.
|
|
12
|
+
- Keep simple, single-purpose UI component calls on one line when practical, even when a text string is long. Use multiline formatting when several arguments or nested components make the call easier to read.
|
|
13
|
+
- Prefer descriptive variable and parameter names over abbreviations, including for local values and callback parameters.
|
|
14
|
+
- Avoid extracting a helper used only once unless it improves clarity or separates behavior that belongs in another layer.
|
|
15
|
+
- Keep callbacks focused on reading inputs, calling a service or workflow, and returning outputs. Move domain decisions and complicated data conversion into the appropriate service or workflow module.
|
|
16
|
+
- Write comments to explain non-obvious reasoning, scientific assumptions, or compatibility constraints; do not use them to narrate code that is already clear.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
cff-version: 1.2.0
|
|
2
|
+
message: "If you use FCSBridge in your research, please cite this software."
|
|
3
|
+
title: FCSBridge
|
|
4
|
+
type: software
|
|
5
|
+
authors:
|
|
6
|
+
- family-names: "Poinsinet de Sivry-Houle"
|
|
7
|
+
given-names: "Martin"
|
|
8
|
+
license: MIT
|
|
9
|
+
repository-code: "https://github.com/MartinPdeS/FCSBridge"
|
|
10
|
+
version: "0.1.0"
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Contributing to FCSBridge
|
|
2
|
+
|
|
3
|
+
Install an editable checkout with `python -m pip install -e '.[dev,testing,documentation,release]'`.
|
|
4
|
+
Run `make quick` for lint, tests, and distributions, and `make docs` for Sphinx.
|
|
5
|
+
Document fixture provenance and the expected units of any transformed data.
|
|
6
|
+
Use `make release-check` to validate release metadata.
|
|
7
|
+
|
|
8
|
+
The instrument regressions in `tests/test_rosettax.py` read six original files
|
|
9
|
+
from a sibling RosettaX checkout. Set `ROSETTAX_ROOT` to use another checkout.
|
|
10
|
+
The dedicated CI job checks out the pinned RosettaX revision and runs these
|
|
11
|
+
tests. The expected digests cover every event in row-major, little-endian
|
|
12
|
+
float64 order. They were calculated directly from HEADER offsets, byte order,
|
|
13
|
+
channel widths, and integer range masks, independently of FCSBridge.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Exchange flow cytometry event tables between FCS, pandas, NumPy and CSV."""
|
|
2
|
+
|
|
3
|
+
from ._version import __version__
|
|
4
|
+
from .csv import read_csv, write_csv
|
|
5
|
+
from .dataset import Channel, FCSDataset
|
|
6
|
+
from .fcs import read_fcs, write_fcs
|
|
7
|
+
|
|
8
|
+
__all__ = ["Channel", "FCSDataset", "__version__", "read_csv", "read_fcs", "write_csv", "write_fcs"]
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Read byte-aligned FCS records with channel-specific numerical types."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
from decimal import Decimal
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _decode_keywords(*, raw):
|
|
10
|
+
"""Decode the delimited primary TEXT keywords, including vendor empty fields."""
|
|
11
|
+
try:
|
|
12
|
+
text = raw.decode("utf-8")
|
|
13
|
+
except UnicodeDecodeError:
|
|
14
|
+
text = raw.decode("latin-1")
|
|
15
|
+
delimiter = text[0]
|
|
16
|
+
end = text.rfind(delimiter)
|
|
17
|
+
if not end or text[end + 1 :].strip(" \r\n\t\0"):
|
|
18
|
+
raise ValueError("Unterminated FCS TEXT")
|
|
19
|
+
body = text[1:end]
|
|
20
|
+
# A doubled delimiter inside a keyword value represents one literal delimiter.
|
|
21
|
+
tokens = re.findall(
|
|
22
|
+
f"(?:{re.escape(delimiter * 2)}|[^{re.escape(delimiter)}])*{re.escape(delimiter)}", body + delimiter
|
|
23
|
+
)
|
|
24
|
+
fields = [token[:-1].replace(delimiter * 2, delimiter) for token in tokens]
|
|
25
|
+
keys = fields[::2]
|
|
26
|
+
if len(fields) % 2 or any(delimiter in key for key in keys):
|
|
27
|
+
# Some Apogee files write empty optional values between standard keywords.
|
|
28
|
+
fields = body.split(delimiter)
|
|
29
|
+
if len(fields) % 2 or not all(key.startswith("$") for key in fields[::2]):
|
|
30
|
+
raise ValueError("Ambiguous FCS TEXT keywords")
|
|
31
|
+
return {
|
|
32
|
+
key.removeprefix("$").lower(): value for key, value in zip(fields[::2], fields[1::2], strict=True)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def read_records(*, stream, version):
|
|
37
|
+
"""Decode one binary list-mode DATA segment using the declared record layout.
|
|
38
|
+
|
|
39
|
+
Parameters
|
|
40
|
+
----------
|
|
41
|
+
stream : binary file
|
|
42
|
+
Seekable instrument file positioned anywhere.
|
|
43
|
+
version : bytes
|
|
44
|
+
Validated six-byte FCS signature.
|
|
45
|
+
|
|
46
|
+
Returns
|
|
47
|
+
-------
|
|
48
|
+
tuple
|
|
49
|
+
Normalized TEXT keywords and numerical matrix of shape (events, channels).
|
|
50
|
+
"""
|
|
51
|
+
stream.seek(0)
|
|
52
|
+
header = stream.read(58)
|
|
53
|
+
text_start, text_end, header_start, header_end = (
|
|
54
|
+
int(header[index : index + 8].strip() or b"0") for index in range(10, 42, 8)
|
|
55
|
+
)
|
|
56
|
+
size = os.fstat(stream.fileno()).st_size
|
|
57
|
+
if not 58 <= text_start <= text_end < size:
|
|
58
|
+
raise ValueError("Invalid FCS TEXT offsets")
|
|
59
|
+
stream.seek(text_start)
|
|
60
|
+
raw = stream.read(text_end - text_start + 1)
|
|
61
|
+
metadata = _decode_keywords(raw=raw)
|
|
62
|
+
if int(metadata.get("nextdata", "0")) or metadata.get("mode", "L").upper() != "L":
|
|
63
|
+
raise ValueError("Expected one list-mode FCS dataset")
|
|
64
|
+
count, channels = int(metadata["tot"]), int(metadata["par"])
|
|
65
|
+
if count < 0 or channels < 1:
|
|
66
|
+
raise ValueError("Invalid FCS event or channel count")
|
|
67
|
+
endian = {"1,2": "<", "1,2,3,4": "<", "2,1": ">", "4,3,2,1": ">"}.get(metadata["byteord"])
|
|
68
|
+
if not endian:
|
|
69
|
+
raise ValueError("Unsupported FCS byte order")
|
|
70
|
+
formats = []
|
|
71
|
+
masks = []
|
|
72
|
+
for index in range(1, channels + 1):
|
|
73
|
+
prefix = f"p{index}"
|
|
74
|
+
kind = metadata["datatype"]
|
|
75
|
+
if version == b"FCS3.2":
|
|
76
|
+
kind = metadata.get(prefix + "datatype", kind)
|
|
77
|
+
kind = kind.upper()
|
|
78
|
+
width = int(metadata[prefix + "b"])
|
|
79
|
+
if kind == "I" and width in {8, 16, 32, 64}:
|
|
80
|
+
limit = Decimal(metadata[prefix + "r"])
|
|
81
|
+
if not limit.is_finite() or not 0 < limit <= 2**width or limit != limit.to_integral_value():
|
|
82
|
+
raise ValueError("Invalid FCS integer channel range")
|
|
83
|
+
masks.append((1 << (int(limit) - 1).bit_length()) - 1)
|
|
84
|
+
code = "u"
|
|
85
|
+
elif (kind, width) in {("F", 32), ("D", 64)}:
|
|
86
|
+
masks.append(None)
|
|
87
|
+
code = "f"
|
|
88
|
+
else:
|
|
89
|
+
raise ValueError(f"Unsupported FCS channel encoding {kind}/{width}")
|
|
90
|
+
formats.append(np.dtype(f"{endian}{code}{width // 8}"))
|
|
91
|
+
record_type = np.dtype([(str(i), fmt) for i, fmt in enumerate(formats)])
|
|
92
|
+
start, stop = (
|
|
93
|
+
(header_start, header_end)
|
|
94
|
+
if version == b"FCS2.0"
|
|
95
|
+
else (int(metadata["begindata"]), int(metadata["enddata"]))
|
|
96
|
+
)
|
|
97
|
+
if version != b"FCS2.0" and (header_start, header_end) not in {(0, 0), (start, stop)}:
|
|
98
|
+
raise ValueError("Conflicting FCS HEADER and TEXT DATA offsets")
|
|
99
|
+
expected_end = start + count * record_type.itemsize
|
|
100
|
+
if start <= text_end or expected_end > size or stop not in (expected_end - 1, expected_end):
|
|
101
|
+
raise ValueError("DATA offsets disagree with the FCS record size and event count")
|
|
102
|
+
stream.seek(start)
|
|
103
|
+
records = np.fromfile(stream, dtype=record_type, count=count)
|
|
104
|
+
if len(records) != count:
|
|
105
|
+
raise ValueError("Truncated FCS DATA")
|
|
106
|
+
# Keep the public float64 matrix convention for earlier revisions.
|
|
107
|
+
matrix_type = np.result_type(*formats) if version == b"FCS3.2" else np.float64
|
|
108
|
+
events = np.empty((count, channels), dtype=matrix_type)
|
|
109
|
+
for index, mask in enumerate(masks):
|
|
110
|
+
values = records[str(index)]
|
|
111
|
+
if mask is not None:
|
|
112
|
+
values = values & mask
|
|
113
|
+
events[:, index] = values
|
|
114
|
+
if mask is not None and values.dtype.itemsize == 8 and events.dtype.kind == "f":
|
|
115
|
+
with np.errstate(invalid="ignore"):
|
|
116
|
+
if not np.array_equal(events[:, index].astype(values.dtype), values):
|
|
117
|
+
raise ValueError("Mixed FCS record cannot be represented exactly in one numerical matrix")
|
|
118
|
+
return metadata, events
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Exchange event tables with optional metadata stored beside the CSV."""
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
from io import TextIOWrapper
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from tempfile import TemporaryDirectory
|
|
9
|
+
import pandas as pd
|
|
10
|
+
from .dataset import Channel, FCSDataset, as_dataset
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _digest(*, stream):
|
|
14
|
+
"""Return a SHA-256 digest and rewind the open binary stream."""
|
|
15
|
+
checksum = hashlib.sha256()
|
|
16
|
+
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
|
17
|
+
checksum.update(chunk)
|
|
18
|
+
stream.seek(0)
|
|
19
|
+
return checksum.hexdigest()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def write_csv(*, path, data, channels=None, include_metadata=False):
|
|
23
|
+
"""Write a UTF-8 event table.
|
|
24
|
+
|
|
25
|
+
Parameters
|
|
26
|
+
----------
|
|
27
|
+
path : path-like
|
|
28
|
+
Destination CSV file.
|
|
29
|
+
data : FCSDataset, pandas.DataFrame or array_like
|
|
30
|
+
Real measurements shaped (events, channels).
|
|
31
|
+
channels : sequence of str, optional
|
|
32
|
+
Detector names for array input.
|
|
33
|
+
include_metadata : bool
|
|
34
|
+
Write a matching <path>.json sidecar with detector and acquisition metadata.
|
|
35
|
+
"""
|
|
36
|
+
dataset = as_dataset(data=data, channels=channels)
|
|
37
|
+
destination = Path(path)
|
|
38
|
+
with TemporaryDirectory(dir=destination.parent) as directory:
|
|
39
|
+
table = Path(directory) / "events"
|
|
40
|
+
pd.DataFrame(dataset.events, columns=[c.name for c in dataset.channels]).to_csv(table, index=False)
|
|
41
|
+
if include_metadata:
|
|
42
|
+
with table.open("rb") as stream:
|
|
43
|
+
checksum = _digest(stream=stream)
|
|
44
|
+
manifest = {
|
|
45
|
+
"version": 1,
|
|
46
|
+
"sha256": checksum,
|
|
47
|
+
"dtype": dataset.events.dtype.str,
|
|
48
|
+
"channels": [
|
|
49
|
+
{"name": channel.name, "marker": channel.marker, "parameters": dict(channel.parameters)}
|
|
50
|
+
for channel in dataset.channels
|
|
51
|
+
],
|
|
52
|
+
"metadata": dict(dataset.metadata),
|
|
53
|
+
}
|
|
54
|
+
sidecar = Path(directory) / "metadata"
|
|
55
|
+
sidecar.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
|
|
56
|
+
sidecar.replace(str(destination) + ".json")
|
|
57
|
+
table.replace(destination)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def read_csv(*, path, include_metadata=False):
|
|
61
|
+
"""Read a UTF-8 CSV event table.
|
|
62
|
+
|
|
63
|
+
Parameters
|
|
64
|
+
----------
|
|
65
|
+
path : path-like
|
|
66
|
+
Input file with one header per detector.
|
|
67
|
+
include_metadata : bool
|
|
68
|
+
Require and validate the companion <path>.json file.
|
|
69
|
+
|
|
70
|
+
Returns
|
|
71
|
+
-------
|
|
72
|
+
FCSDataset
|
|
73
|
+
Numerical event matrix in CSV column order.
|
|
74
|
+
"""
|
|
75
|
+
source = Path(path)
|
|
76
|
+
manifest = None
|
|
77
|
+
with source.open("rb") as stream:
|
|
78
|
+
if include_metadata:
|
|
79
|
+
manifest = json.loads(Path(str(source) + ".json").read_text(encoding="utf-8"))
|
|
80
|
+
if manifest["version"] != 1 or manifest["sha256"] != _digest(stream=stream):
|
|
81
|
+
raise ValueError("Metadata sidecar does not match the CSV")
|
|
82
|
+
with TextIOWrapper(stream, encoding="utf-8-sig", newline="") as text:
|
|
83
|
+
names = next(csv.reader(text), [])
|
|
84
|
+
if not names or any(not name.strip() for name in names) or len(names) != len(set(names)):
|
|
85
|
+
raise ValueError("CSV detector names must be nonempty and unique")
|
|
86
|
+
text.seek(0)
|
|
87
|
+
frame = pd.read_csv(
|
|
88
|
+
text, dtype=manifest["dtype"] if manifest else None, float_precision="round_trip"
|
|
89
|
+
)
|
|
90
|
+
if not isinstance(frame.index, pd.RangeIndex):
|
|
91
|
+
raise ValueError("CSV rows contain more fields than the header") # noqa: TRY004 -- malformed file content
|
|
92
|
+
if manifest is None:
|
|
93
|
+
if frame.empty:
|
|
94
|
+
frame = frame.astype(float)
|
|
95
|
+
return as_dataset(data=frame)
|
|
96
|
+
channels = [Channel(**item) for item in manifest["channels"]]
|
|
97
|
+
if [channel.name for channel in channels] != names:
|
|
98
|
+
raise ValueError("Sidecar detector order differs from CSV headers")
|
|
99
|
+
return FCSDataset(events=frame.to_numpy(), channels=channels, metadata=manifest["metadata"])
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Event matrices and ordered FCS channel descriptions."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping, Sequence
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from types import MappingProxyType
|
|
6
|
+
import numpy as np
|
|
7
|
+
import pandas as pd
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True, kw_only=True)
|
|
11
|
+
class Channel:
|
|
12
|
+
"""Describe one event column.
|
|
13
|
+
|
|
14
|
+
Parameters
|
|
15
|
+
----------
|
|
16
|
+
name : str
|
|
17
|
+
Unique detector name ($PnN).
|
|
18
|
+
marker : str
|
|
19
|
+
Optional stain or display label ($PnS).
|
|
20
|
+
parameters : mapping of str to str
|
|
21
|
+
Lowercase FCS parameter suffixes, e.g. 'r' for detector range.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
name: str
|
|
25
|
+
marker: str = ""
|
|
26
|
+
parameters: Mapping[str, str] = field(default_factory=dict)
|
|
27
|
+
|
|
28
|
+
def __post_init__(self):
|
|
29
|
+
if not isinstance(self.name, str) or not self.name.strip():
|
|
30
|
+
raise ValueError("Detector names must be nonempty strings")
|
|
31
|
+
if not isinstance(self.marker, str):
|
|
32
|
+
raise TypeError("Marker must be a string")
|
|
33
|
+
object.__setattr__(self, "parameters", MappingProxyType(dict(self.parameters)))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True, kw_only=True)
|
|
37
|
+
class FCSDataset:
|
|
38
|
+
"""Store raw event values with ordered channels and acquisition metadata.
|
|
39
|
+
|
|
40
|
+
Parameters
|
|
41
|
+
----------
|
|
42
|
+
events : array_like
|
|
43
|
+
Real numerical matrix shaped (events, channels), in stored channel units.
|
|
44
|
+
channels : sequence of Channel
|
|
45
|
+
Detector descriptions in matrix column order.
|
|
46
|
+
metadata : mapping of str to str
|
|
47
|
+
Global FCS TEXT keywords, lowercase and without the dollar prefix.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
events: np.ndarray
|
|
51
|
+
channels: Sequence[Channel]
|
|
52
|
+
metadata: Mapping[str, str] = field(default_factory=dict)
|
|
53
|
+
|
|
54
|
+
def __post_init__(self):
|
|
55
|
+
events = np.asarray(self.events)
|
|
56
|
+
channels = tuple(self.channels)
|
|
57
|
+
if events.ndim != 2 or not channels or events.shape[1] != len(channels):
|
|
58
|
+
raise ValueError("Expected a 2-D event matrix with one column per channel")
|
|
59
|
+
if events.dtype.kind not in "iuf":
|
|
60
|
+
raise TypeError("Event columns must contain real numerical values")
|
|
61
|
+
if len({channel.name for channel in channels}) != len(channels):
|
|
62
|
+
raise ValueError("Detector names must be unique")
|
|
63
|
+
object.__setattr__(self, "events", events)
|
|
64
|
+
object.__setattr__(self, "channels", channels)
|
|
65
|
+
object.__setattr__(self, "metadata", MappingProxyType(dict(self.metadata)))
|
|
66
|
+
|
|
67
|
+
def to_dataframe(self):
|
|
68
|
+
"""Copy measurements into a labeled event table.
|
|
69
|
+
|
|
70
|
+
Returns
|
|
71
|
+
-------
|
|
72
|
+
pandas.DataFrame
|
|
73
|
+
One column per detector, one row per event.
|
|
74
|
+
"""
|
|
75
|
+
return pd.DataFrame(self.events.copy(), columns=[channel.name for channel in self.channels])
|
|
76
|
+
|
|
77
|
+
def select_events(self, *, mask):
|
|
78
|
+
"""Filter the event axis while retaining acquisition metadata.
|
|
79
|
+
|
|
80
|
+
Parameters
|
|
81
|
+
----------
|
|
82
|
+
mask : array_like of bool
|
|
83
|
+
Positional mask with one entry per event.
|
|
84
|
+
|
|
85
|
+
Returns
|
|
86
|
+
-------
|
|
87
|
+
FCSDataset
|
|
88
|
+
Selected events in their original order.
|
|
89
|
+
"""
|
|
90
|
+
mask = np.asarray(mask)
|
|
91
|
+
if mask.dtype.kind != "b" or mask.shape != (len(self.events),):
|
|
92
|
+
raise ValueError("Expected one boolean per event")
|
|
93
|
+
return FCSDataset(events=self.events[mask], channels=self.channels, metadata=self.metadata)
|
|
94
|
+
|
|
95
|
+
def reorder_channels(self, *, names):
|
|
96
|
+
"""Reorder measurements and the associated channel descriptions together.
|
|
97
|
+
|
|
98
|
+
Parameters
|
|
99
|
+
----------
|
|
100
|
+
names : sequence of str
|
|
101
|
+
Permutation of all detector names.
|
|
102
|
+
|
|
103
|
+
Returns
|
|
104
|
+
-------
|
|
105
|
+
FCSDataset
|
|
106
|
+
Dataset in the requested detector order.
|
|
107
|
+
"""
|
|
108
|
+
by_name = {channel.name: index for index, channel in enumerate(self.channels)}
|
|
109
|
+
names = tuple(names)
|
|
110
|
+
if len(names) != len(by_name) or set(names) != set(by_name):
|
|
111
|
+
raise ValueError("Supply every detector name exactly once")
|
|
112
|
+
indices = [by_name[name] for name in names]
|
|
113
|
+
return FCSDataset(
|
|
114
|
+
events=self.events[:, indices],
|
|
115
|
+
channels=[self.channels[i] for i in indices],
|
|
116
|
+
metadata=self.metadata,
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def as_dataset(*, data, channels=None):
|
|
121
|
+
"""Normalize dataset, DataFrame or matrix input for an export."""
|
|
122
|
+
if isinstance(data, FCSDataset):
|
|
123
|
+
if channels is not None:
|
|
124
|
+
raise ValueError("Dataset already defines its channels")
|
|
125
|
+
return data
|
|
126
|
+
if isinstance(data, pd.DataFrame):
|
|
127
|
+
if channels is not None:
|
|
128
|
+
raise ValueError("DataFrame columns already define detector names")
|
|
129
|
+
channels = data.columns
|
|
130
|
+
data = data.to_numpy()
|
|
131
|
+
if channels is None or isinstance(channels, str):
|
|
132
|
+
raise ValueError("Supply ordered channel names for an array")
|
|
133
|
+
return FCSDataset(events=data, channels=[Channel(name=name) for name in channels])
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Read stored event values and write single-dataset FCS 3.1 files."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import warnings
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from tempfile import TemporaryDirectory
|
|
7
|
+
import flowio
|
|
8
|
+
import numpy as np
|
|
9
|
+
from flowio.fcs_keywords import FCS_STANDARD_REQUIRED_KEYWORDS
|
|
10
|
+
from ._records import read_records
|
|
11
|
+
from .dataset import Channel, FCSDataset, as_dataset
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def read_fcs(*, path):
|
|
15
|
+
"""Read one FCS dataset.
|
|
16
|
+
|
|
17
|
+
Parameters
|
|
18
|
+
----------
|
|
19
|
+
path : path-like
|
|
20
|
+
Single list-mode dataset in FCS 2.0, 3.0, 3.1 or 3.2 format.
|
|
21
|
+
|
|
22
|
+
Returns
|
|
23
|
+
-------
|
|
24
|
+
FCSDataset
|
|
25
|
+
Stored event values without gain, time, log or compensation transforms.
|
|
26
|
+
"""
|
|
27
|
+
with Path(path).open("rb") as stream:
|
|
28
|
+
version = stream.read(6)
|
|
29
|
+
if version not in {b"FCS2.0", b"FCS3.0", b"FCS3.1", b"FCS3.2"}:
|
|
30
|
+
raise ValueError(f"Unsupported FCS signature {version!r}")
|
|
31
|
+
text, events = read_records(stream=stream, version=version)
|
|
32
|
+
parameters = [{} for _ in range(int(text["par"]))]
|
|
33
|
+
metadata = {}
|
|
34
|
+
for key, value in text.items():
|
|
35
|
+
match = re.fullmatch(r"p([1-9][0-9]*)([a-z]+)", key)
|
|
36
|
+
if match and int(match[1]) <= len(parameters):
|
|
37
|
+
parameters[int(match[1]) - 1][match[2]] = value
|
|
38
|
+
elif key not in FCS_STANDARD_REQUIRED_KEYWORDS:
|
|
39
|
+
metadata[key] = value
|
|
40
|
+
channels = [Channel(name=item.pop("n"), marker=item.pop("s", ""), parameters=item) for item in parameters]
|
|
41
|
+
return FCSDataset(events=events, channels=channels, metadata=metadata)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def write_fcs(*, path, data, channels=None):
|
|
45
|
+
"""Write raw events as linear float32 FCS 3.1 using an atomic replacement.
|
|
46
|
+
|
|
47
|
+
Parameters
|
|
48
|
+
----------
|
|
49
|
+
path : path-like
|
|
50
|
+
Destination file.
|
|
51
|
+
data : FCSDataset, pandas.DataFrame or array_like
|
|
52
|
+
Real values shaped (events, channels). Float32 rounding issues a warning.
|
|
53
|
+
channels : sequence of str, optional
|
|
54
|
+
Required detector names for array input. DataFrames use their column names.
|
|
55
|
+
"""
|
|
56
|
+
dataset = as_dataset(data=data, channels=channels)
|
|
57
|
+
supported = {
|
|
58
|
+
"abrt",
|
|
59
|
+
"btim",
|
|
60
|
+
"cells",
|
|
61
|
+
"com",
|
|
62
|
+
"cyt",
|
|
63
|
+
"cytsn",
|
|
64
|
+
"date",
|
|
65
|
+
"etim",
|
|
66
|
+
"exp",
|
|
67
|
+
"fil",
|
|
68
|
+
"inst",
|
|
69
|
+
"lost",
|
|
70
|
+
"op",
|
|
71
|
+
"plateid",
|
|
72
|
+
"platename",
|
|
73
|
+
"proj",
|
|
74
|
+
"smno",
|
|
75
|
+
"spill",
|
|
76
|
+
"spillover",
|
|
77
|
+
"src",
|
|
78
|
+
"sys",
|
|
79
|
+
"timestep",
|
|
80
|
+
"vol",
|
|
81
|
+
"wellid",
|
|
82
|
+
}
|
|
83
|
+
metadata = {key: value for key, value in dataset.metadata.items() if key in supported}
|
|
84
|
+
omitted = set(dataset.metadata) - metadata.keys()
|
|
85
|
+
names = {channel.name for channel in dataset.channels}
|
|
86
|
+
for key in ("spillover", "spill"):
|
|
87
|
+
if key in metadata:
|
|
88
|
+
parts = metadata[key].split(",")
|
|
89
|
+
size = int(parts[0])
|
|
90
|
+
detectors = parts[1 : 1 + size]
|
|
91
|
+
coefficients = np.asarray(parts[1 + size :], dtype=float)
|
|
92
|
+
if (
|
|
93
|
+
size < 1
|
|
94
|
+
or len(detectors) != len(set(detectors))
|
|
95
|
+
or not set(detectors) <= names
|
|
96
|
+
or len(coefficients) != size * size
|
|
97
|
+
or not np.isfinite(coefficients).all()
|
|
98
|
+
):
|
|
99
|
+
raise ValueError("Invalid named spillover matrix")
|
|
100
|
+
# Spillover axes are identified by detector name within the keyword itself.
|
|
101
|
+
for index, channel in enumerate(dataset.channels, start=1):
|
|
102
|
+
decades = channel.parameters.get("e", "0,0")
|
|
103
|
+
if any(float(value) != 0 for value in decades.split(",")):
|
|
104
|
+
raise ValueError("Log-encoded raw channels cannot be written as linear float32")
|
|
105
|
+
for suffix, value in channel.parameters.items():
|
|
106
|
+
if suffix in {"g", "r", "v", "f", "l", "o", "p", "t", "d", "calibration"}:
|
|
107
|
+
metadata[f"p{index}{suffix}"] = value
|
|
108
|
+
elif suffix not in {"b", "e", "n", "s"}:
|
|
109
|
+
omitted.add(f"p{index}{suffix}")
|
|
110
|
+
if omitted:
|
|
111
|
+
warnings.warn(
|
|
112
|
+
"FCS export omits unsupported keywords: " + ", ".join(sorted(omitted)), UserWarning, stacklevel=2
|
|
113
|
+
)
|
|
114
|
+
if not len(dataset.events):
|
|
115
|
+
raise ValueError("Writing FCS requires at least one event")
|
|
116
|
+
with np.errstate(over="ignore", invalid="ignore"):
|
|
117
|
+
values = dataset.events.astype(np.float32, copy=False)
|
|
118
|
+
if np.any(np.isfinite(dataset.events) & ~np.isfinite(values)):
|
|
119
|
+
raise ValueError("Event value outside the finite float32 range")
|
|
120
|
+
if dataset.events.dtype.kind in "iu":
|
|
121
|
+
with np.errstate(invalid="ignore"):
|
|
122
|
+
rounded = not np.array_equal(values.astype(dataset.events.dtype), dataset.events)
|
|
123
|
+
else:
|
|
124
|
+
rounded = not np.array_equal(values, dataset.events, equal_nan=True)
|
|
125
|
+
if rounded:
|
|
126
|
+
warnings.warn("FCS export rounds event values to float32", UserWarning, stacklevel=2)
|
|
127
|
+
destination = Path(path)
|
|
128
|
+
with TemporaryDirectory(dir=destination.parent) as directory:
|
|
129
|
+
temporary = Path(directory) / "output.fcs"
|
|
130
|
+
with temporary.open("wb") as stream:
|
|
131
|
+
flowio.create_fcs(
|
|
132
|
+
stream,
|
|
133
|
+
values.ravel(),
|
|
134
|
+
[channel.name for channel in dataset.channels],
|
|
135
|
+
[channel.marker for channel in dataset.channels],
|
|
136
|
+
metadata,
|
|
137
|
+
)
|
|
138
|
+
temporary.replace(destination)
|