Skip to content

Commit cef79f4

Browse files
authored
Merge pull request #385 from bigbio/copilot/fix-leading-zeros-sdrf
Preserve zero-padded identifiers when reading SDRFs
2 parents 32cbbdc + 5d0514c commit cef79f4

6 files changed

Lines changed: 79 additions & 17 deletions

File tree

‎qpx/converters/sdrf.py‎

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -249,19 +249,8 @@ def _run_samples(group: pd.DataFrame, run_file: str) -> list[dict]:
249249
sample_acc = str(row.get(_COL_SOURCE_NAME, ""))
250250
_add_unique_run_label(seen_labels, run_file, label, sample_acc, label_raw)
251251

252-
bio_rep = None
253-
if _COL_BIO_REP in row and pd.notna(row[_COL_BIO_REP]):
254-
try:
255-
bio_rep = int(row[_COL_BIO_REP])
256-
except (ValueError, TypeError):
257-
bio_rep = None
258-
259-
tech_rep = None
260-
if _COL_TECH_REP in row and pd.notna(row[_COL_TECH_REP]):
261-
try:
262-
tech_rep = int(row[_COL_TECH_REP])
263-
except (ValueError, TypeError):
264-
tech_rep = None
252+
bio_rep = _replicate_number(row[_COL_BIO_REP]) if _COL_BIO_REP in row and pd.notna(row[_COL_BIO_REP]) else None
253+
tech_rep = _replicate_number(row[_COL_TECH_REP]) if _COL_TECH_REP in row and pd.notna(row[_COL_TECH_REP]) else None
265254

266255
samples.append(
267256
{
@@ -308,6 +297,15 @@ def _term_pairs(group: pd.DataFrame, column: str) -> list[tuple[str, str]]:
308297
return [pair for pair in pairs if pair[0]]
309298

310299

300+
def _replicate_number(value: str) -> int | None:
301+
"""An SDRF replicate as an integer: ``1`` and ``1.0`` give 1, other text and fractions None."""
302+
try:
303+
number = float(value)
304+
except ValueError:
305+
return None
306+
return int(number) if number.is_integer() else None
307+
308+
311309
class SdrfConverter(BaseConverter):
312310
"""Convert an SDRF TSV into ``sample.parquet`` and ``run.parquet``.
313311
@@ -358,7 +356,7 @@ def convert(
358356

359357
def _read_sdrf(self, sdrf_path: str) -> pd.DataFrame:
360358
"""Load the SDRF file and normalise column names to lower-case."""
361-
df = pd.read_csv(sdrf_path, sep="\t", header=0)
359+
df = pd.read_csv(sdrf_path, sep="\t", header=0, dtype=str, keep_default_na=False, na_values=[""])
362360
df.columns = df.columns.str.lower()
363361
return df
364362

‎qpx/core/sdrf.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ def _load_sdrf_info(self, sdrf_file: Union[Path, str]):
147147
:param sdrf_file: SDRF file
148148
"""
149149
try:
150-
sdrf_table = pd.read_csv(sdrf_file, sep="\t", header=0)
150+
sdrf_table = pd.read_csv(sdrf_file, sep="\t", header=0, dtype=str, keep_default_na=False, na_values=[""])
151151
sdrf_table.columns = sdrf_table.columns.str.lower()
152152
# Normalize common SDRF column name variants
153153
col_renames = {}

‎qpx/transforms/sdrf_updater.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def _read_sdrf_normalized(path: str | Path) -> "pd.DataFrame":
3535
"""Read SDRF and normalize column names to lowercase."""
3636
import pandas as pd
3737

38-
df = pd.read_csv(path, sep="\t")
38+
df = pd.read_csv(path, sep="\t", dtype=str, keep_default_na=False, na_values=[""])
3939
df.columns = [c.lower().strip() for c in df.columns]
4040
return df
4141

‎tests/converters/test_channel_labels.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,18 @@ def test_multi_dot_run_names_match_sdrf_conversion(tmp_path):
9191
assert pq.read_table(run_output).column("run_file_name").to_pylist() == grouped
9292

9393

94+
def test_sdrf_handler_preserves_zero_padded_source_names(tmp_path):
95+
"""The core SDRF reader keeps leading zeros in sample-map identifiers."""
96+
from qpx.core.sdrf import SDRFHandler
97+
98+
sdrf = tmp_path / "zero_padded.sdrf.tsv"
99+
sdrf.write_text(
100+
"source name\tcomment[data file]\tcomment[label]\n001\trun1.raw\tlabel free sample\n01\trun2.raw\tlabel free sample\n"
101+
)
102+
103+
assert SDRFHandler(sdrf).get_sample_map_run() == {"run1": "001", "run2": "01"}
104+
105+
94106
@pytest.mark.parametrize(
95107
("labels", "expected"),
96108
[

‎tests/converters/test_sdrf_run_metadata.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,48 @@ def test_only_sentinel_modification_columns_leave_none(tmp_path):
5252
assert run["modification_parameters"] is None
5353

5454

55+
def test_zero_padded_source_names_are_preserved_in_sample_and_run_outputs(tmp_path):
56+
"""Source names remain distinct text identifiers, while biological replicates are integers."""
57+
sdrf = tmp_path / "zero_padded.sdrf.tsv"
58+
sdrf.write_text(
59+
"source name\tcharacteristics[organism]\tcharacteristics[organism part]\t"
60+
"characteristics[biological replicate]\tcomment[fraction identifier]\t"
61+
"comment[data file]\tcomment[label]\n"
62+
"001\tHomo sapiens\tliver\t1\t01\tA_001.raw\tlabel free sample\n"
63+
"01\tHomo sapiens\tliver\t2\t02\tA_002.raw\tlabel free sample\n",
64+
encoding="utf-8",
65+
)
66+
sample_path = tmp_path / "sample.parquet"
67+
run_path = tmp_path / "run.parquet"
68+
69+
with SdrfConverter() as converter:
70+
converter.convert(str(sdrf), sample_output=str(sample_path), run_output=str(run_path))
71+
72+
samples = pq.read_table(sample_path).to_pylist()
73+
runs = pq.read_table(run_path).to_pylist()
74+
assert {sample["sample_accession"] for sample in samples} == {"001", "01"}
75+
assert [(run["samples"][0]["sample_accession"], run["samples"][0]["biological_replicate"]) for run in runs] == [
76+
("001", 1),
77+
("01", 2),
78+
]
79+
assert [run["fraction"] for run in runs] == ["01", "02"]
80+
81+
82+
@pytest.mark.parametrize(("value", "expected"), [("1", 1), ("1.0", 1), ("2.5", None), ("x", None)])
83+
def test_replicates_written_as_whole_decimals_are_integers(tmp_path, value, expected):
84+
"""A spreadsheet export writes replicate 1 as 1.0; a fraction or text is no replicate number."""
85+
columns = [
86+
"source name",
87+
"comment[data file]",
88+
"comment[label]",
89+
"characteristics[biological replicate]",
90+
"comment[technical replicate]",
91+
]
92+
runs, _ = _convert_sdrf(tmp_path, columns, [["S1", "run_01.raw", "label free sample", value, value]])
93+
sample = runs[0]["samples"][0]
94+
assert (sample["biological_replicate"], sample["technical_replicate"]) == (expected, expected)
95+
96+
5597
@pytest.mark.parametrize(
5698
("sdrf_value", "expected"),
5799
[

‎tests/unit/test_transform_prefix.py‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import pyarrow.parquet as pq
55
import pytest
66

7-
from qpx.transforms.sdrf_updater import update_metadata
7+
from qpx.transforms.sdrf_updater import _check_protected_changes, update_metadata
88
from qpx.transforms.utils import discover_qpx_file_prefix
99

1010

@@ -48,3 +48,13 @@ def convert(self, *, sdrf_path, sample_output, run_output):
4848
assert (tmp_path / "openms.run.parquet.bak").is_file()
4949
assert not (tmp_path / "quantms.sample.parquet").exists()
5050
assert not (tmp_path / "quantms.run.parquet").exists()
51+
52+
53+
def test_protected_check_compares_sdrf_values_as_text(tmp_path):
54+
"""Renaming source name 001 to 1 changes the sample-run-label mapping."""
55+
header = "source name\tcomment[data file]\tcomment[label]\n"
56+
old, new = tmp_path / "old.sdrf.tsv", tmp_path / "new.sdrf.tsv"
57+
old.write_text(header + "001\ta.raw\tlabel free sample\n")
58+
new.write_text(header + "1\ta.raw\tlabel free sample\n")
59+
60+
assert any("sample-run-label mapping changed" in warning for warning in _check_protected_changes(old, new))

0 commit comments

Comments
 (0)