FCSBridge 0.1.0__py3-none-any.whl
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/__init__.py +8 -0
- FCSBridge/_records.py +118 -0
- FCSBridge/_version.py +5 -0
- FCSBridge/csv.py +99 -0
- FCSBridge/dataset.py +133 -0
- FCSBridge/fcs.py +138 -0
- fcsbridge-0.1.0.dist-info/METADATA +150 -0
- fcsbridge-0.1.0.dist-info/RECORD +11 -0
- fcsbridge-0.1.0.dist-info/WHEEL +5 -0
- fcsbridge-0.1.0.dist-info/licenses/LICENSE +21 -0
- fcsbridge-0.1.0.dist-info/top_level.txt +1 -0
FCSBridge/__init__.py
ADDED
|
@@ -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"]
|
FCSBridge/_records.py
ADDED
|
@@ -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
|
FCSBridge/_version.py
ADDED
FCSBridge/csv.py
ADDED
|
@@ -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"])
|
FCSBridge/dataset.py
ADDED
|
@@ -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])
|
FCSBridge/fcs.py
ADDED
|
@@ -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)
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: FCSBridge
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Read and write flow cytometry event tables with Python
|
|
5
|
+
Author: Martin Poinsinet de Sivry-Houle
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Repository, https://github.com/MartinPdeS/FCSBridge
|
|
8
|
+
Project-URL: Documentation, https://martinpdes.github.io/FCSBridge/
|
|
9
|
+
Keywords: flow cytometry,FCS,event tables
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/x-rst
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: FlowIO<2,>=1.4
|
|
14
|
+
Requires-Dist: numpy>=1.23
|
|
15
|
+
Requires-Dist: pandas>=1.5
|
|
16
|
+
Provides-Extra: release
|
|
17
|
+
Requires-Dist: martinpdes-maintenance==0.2.3; extra == "release"
|
|
18
|
+
Provides-Extra: testing
|
|
19
|
+
Requires-Dist: martinpdes-maintenance[testing]==0.2.3; extra == "testing"
|
|
20
|
+
Provides-Extra: documentation
|
|
21
|
+
Requires-Dist: MartinPdeS-docs<0.5,>=0.4.0; extra == "documentation"
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: martinpdes-maintenance[quality]==0.2.3; extra == "dev"
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
FCSBridge
|
|
27
|
+
=========
|
|
28
|
+
|
|
29
|
+
.. image:: https://raw.githubusercontent.com/MartinPdeS/FCSBridge/HEAD/docs/images/logo.png
|
|
30
|
+
:alt: FCSBridge logo
|
|
31
|
+
:width: 100%
|
|
32
|
+
|
|
33
|
+
.. list-table::
|
|
34
|
+
:width: 100%
|
|
35
|
+
:widths: 35 65
|
|
36
|
+
:header-rows: 1
|
|
37
|
+
|
|
38
|
+
* - Badge
|
|
39
|
+
- Status
|
|
40
|
+
* - Python versions
|
|
41
|
+
- |mps-python|
|
|
42
|
+
* - Documentation
|
|
43
|
+
- |mps-docs|
|
|
44
|
+
* - Tests
|
|
45
|
+
- |mps-ci| |mps-coverage|
|
|
46
|
+
* - PyPI
|
|
47
|
+
- |mps-pypi| |mps-downloads|
|
|
48
|
+
* - Conda
|
|
49
|
+
- |mps-conda| |mps-conda-downloads| |mps-conda-release|
|
|
50
|
+
|
|
51
|
+
Read and write flow cytometry event tables with Python
|
|
52
|
+
|
|
53
|
+
Convert flow cytometry event tables between FCS, pandas, NumPy and CSV.
|
|
54
|
+
Keep detector order, marker labels and acquisition metadata with your measurements.
|
|
55
|
+
|
|
56
|
+
Installation
|
|
57
|
+
------------
|
|
58
|
+
|
|
59
|
+
Requires Python ``>=3.10``.
|
|
60
|
+
|
|
61
|
+
.. code-block:: console
|
|
62
|
+
|
|
63
|
+
$ python -m pip install FCSBridge
|
|
64
|
+
|
|
65
|
+
Install from the ``martinpdes`` Conda channel:
|
|
66
|
+
|
|
67
|
+
.. code-block:: console
|
|
68
|
+
|
|
69
|
+
$ conda install -c martinpdes fcsbridge
|
|
70
|
+
|
|
71
|
+
For an editable source installation:
|
|
72
|
+
|
|
73
|
+
.. code-block:: console
|
|
74
|
+
|
|
75
|
+
$ git clone https://github.com/MartinPdeS/FCSBridge.git
|
|
76
|
+
$ cd FCSBridge
|
|
77
|
+
$ python -m pip install -e .
|
|
78
|
+
|
|
79
|
+
Write a DataFrame as FCS
|
|
80
|
+
------------------------
|
|
81
|
+
|
|
82
|
+
.. code-block:: python
|
|
83
|
+
|
|
84
|
+
"""Write simulated detector measurements and read the event table back."""
|
|
85
|
+
|
|
86
|
+
import pandas as pd
|
|
87
|
+
from FCSBridge import read_fcs, write_fcs
|
|
88
|
+
|
|
89
|
+
events = pd.DataFrame({"FSC-A": [240, 310], "FL1-A": [15, 42]})
|
|
90
|
+
write_fcs(path="simulation.fcs", data=events)
|
|
91
|
+
sample = read_fcs(path="simulation.fcs")
|
|
92
|
+
print(sample.to_dataframe())
|
|
93
|
+
|
|
94
|
+
Documentation
|
|
95
|
+
-------------
|
|
96
|
+
|
|
97
|
+
Use the `FCSBridge documentation <https://martinpdes.github.io/FCSBridge/>`__ to work through
|
|
98
|
+
examples and look up the inputs and return values of individual functions.
|
|
99
|
+
|
|
100
|
+
Contributing
|
|
101
|
+
------------
|
|
102
|
+
|
|
103
|
+
Bug reports, worked examples, and documentation corrections are welcome.
|
|
104
|
+
To set up a development checkout and run the tests, follow the `contributing guide <https://github.com/MartinPdeS/FCSBridge/blob/HEAD/CONTRIBUTING.md>`__.
|
|
105
|
+
|
|
106
|
+
Contact
|
|
107
|
+
-------
|
|
108
|
+
|
|
109
|
+
For questions, contact Martin Poinsinet de Sivry-Houle.
|
|
110
|
+
|
|
111
|
+
License
|
|
112
|
+
-------
|
|
113
|
+
|
|
114
|
+
FCSBridge is licensed under `MIT <https://github.com/MartinPdeS/FCSBridge/blob/HEAD/LICENSE>`__.
|
|
115
|
+
|
|
116
|
+
.. |mps-python| image:: https://img.shields.io/pypi/pyversions/fcsbridge.svg
|
|
117
|
+
:alt: Supported Python versions
|
|
118
|
+
:target: https://pypi.org/project/fcsbridge/
|
|
119
|
+
|
|
120
|
+
.. |mps-pypi| image:: https://img.shields.io/pypi/v/fcsbridge.svg
|
|
121
|
+
:alt: PyPI version
|
|
122
|
+
:target: https://pypi.org/project/fcsbridge/
|
|
123
|
+
|
|
124
|
+
.. |mps-downloads| image:: https://img.shields.io/pypi/dm/fcsbridge.svg
|
|
125
|
+
:alt: Monthly PyPI downloads
|
|
126
|
+
:target: https://pypistats.org/packages/fcsbridge
|
|
127
|
+
|
|
128
|
+
.. |mps-docs| image:: https://github.com/MartinPdeS/FCSBridge/actions/workflows/deploy_documentation.yml/badge.svg
|
|
129
|
+
:alt: Documentation
|
|
130
|
+
:target: https://martinpdes.github.io/FCSBridge/
|
|
131
|
+
|
|
132
|
+
.. |mps-ci| image:: https://github.com/MartinPdeS/FCSBridge/actions/workflows/tests.yml/badge.svg
|
|
133
|
+
:alt: Tests
|
|
134
|
+
:target: https://github.com/MartinPdeS/FCSBridge/actions/workflows/tests.yml
|
|
135
|
+
|
|
136
|
+
.. |mps-coverage| image:: https://raw.githubusercontent.com/MartinPdeS/FCSBridge/python-coverage-comment-action-data/badge.svg
|
|
137
|
+
:alt: Test coverage
|
|
138
|
+
:target: https://htmlpreview.github.io/?https://github.com/MartinPdeS/FCSBridge/blob/python-coverage-comment-action-data/htmlcov/index.html
|
|
139
|
+
|
|
140
|
+
.. |mps-conda| image:: https://anaconda.org/martinpdes/fcsbridge/badges/version.svg
|
|
141
|
+
:alt: Anaconda version
|
|
142
|
+
:target: https://anaconda.org/martinpdes/fcsbridge
|
|
143
|
+
|
|
144
|
+
.. |mps-conda-downloads| image:: https://anaconda.org/martinpdes/fcsbridge/badges/downloads.svg
|
|
145
|
+
:alt: Anaconda downloads
|
|
146
|
+
:target: https://anaconda.org/martinpdes/fcsbridge
|
|
147
|
+
|
|
148
|
+
.. |mps-conda-release| image:: https://anaconda.org/martinpdes/fcsbridge/badges/latest_release_relative_date.svg
|
|
149
|
+
:alt: Latest Anaconda release
|
|
150
|
+
:target: https://anaconda.org/martinpdes/fcsbridge
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
FCSBridge/__init__.py,sha256=iQlQvxJ7WP5AT7J9UMEcaxxnVGXZp07-NXKHM_hhz0Q,331
|
|
2
|
+
FCSBridge/_records.py,sha256=8RpxEdcLJg_zhhBdAoSw-jV2yt6_BbpYXaK46Eb9pRc,5199
|
|
3
|
+
FCSBridge/_version.py,sha256=NXOUexockiEZR-JOjpszySwGYF1tsW1g-iivLJCzKBM,210
|
|
4
|
+
FCSBridge/csv.py,sha256=ki62SirTcL58-q7ARng5nrPBSHEBQeYasHAD5hY6HtA,3924
|
|
5
|
+
FCSBridge/dataset.py,sha256=whZZ7q7R9YibEwScwUYVIpn_AnUbRBt57jFQNHkAa0E,4837
|
|
6
|
+
FCSBridge/fcs.py,sha256=odQGnK3X-0yQmLyBBCDjw7pWzA5gjMNlD3_680LzBzM,5282
|
|
7
|
+
fcsbridge-0.1.0.dist-info/licenses/LICENSE,sha256=ge5yBNqI-ct4aAbgk6neVqjgN0I9RGwioTU7WEeFH8I,1088
|
|
8
|
+
fcsbridge-0.1.0.dist-info/METADATA,sha256=11exSUgUn72LazTPdoHeV_ebPjN4evx70krBVLfHzCg,4781
|
|
9
|
+
fcsbridge-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
fcsbridge-0.1.0.dist-info/top_level.txt,sha256=rgueNj9w_m5eNuz_vntui5Dc1AVaZX4M9uxdO-I0h-A,10
|
|
11
|
+
fcsbridge-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Martin Poinsinet de Sivry-Houle
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
FCSBridge
|