omids-validator 0.2.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.
- omids_validator/__init__.py +11 -0
- omids_validator/__main__.py +11 -0
- omids_validator/acquisition_profiles.py +478 -0
- omids_validator/cli.py +185 -0
- omids_validator/data/metadata_requirements.json +337 -0
- omids_validator/data/rules.json +364 -0
- omids_validator/file_types.py +46 -0
- omids_validator/inventory.py +133 -0
- omids_validator/models.py +60 -0
- omids_validator/participant_table.py +128 -0
- omids_validator/participants.py +235 -0
- omids_validator/patient_metadata.py +150 -0
- omids_validator/reporters/__init__.py +1 -0
- omids_validator/reporters/html_report.py +607 -0
- omids_validator/reporters/json_report.py +74 -0
- omids_validator/reporters/markdown_report.py +283 -0
- omids_validator/reporters/report_data.py +79 -0
- omids_validator/reporters/terminal.py +18 -0
- omids_validator/rule_catalog.py +279 -0
- omids_validator/rules/__init__.py +5 -0
- omids_validator/rules/layer0_structure.py +316 -0
- omids_validator/rules/layer1_naming.py +191 -0
- omids_validator/rules/layer2_sidecars.py +292 -0
- omids_validator/rules/layer3_metadata.py +144 -0
- omids_validator/rules/layer4_image_headers.py +152 -0
- omids_validator/rules/layer5_dataset.py +261 -0
- omids_validator/rules_document.py +192 -0
- omids_validator/validator.py +274 -0
- omids_validator-0.2.0.dist-info/METADATA +158 -0
- omids_validator-0.2.0.dist-info/RECORD +34 -0
- omids_validator-0.2.0.dist-info/WHEEL +5 -0
- omids_validator-0.2.0.dist-info/entry_points.txt +3 -0
- omids_validator-0.2.0.dist-info/licenses/LICENSE +677 -0
- omids_validator-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Read ``participants.tsv`` for Layer 5 and participant-table updates."""
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from omids_validator.inventory import DatasetInventory
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class ParticipantTable:
|
|
12
|
+
"""Validated participant identifiers read from ``participants.tsv``."""
|
|
13
|
+
|
|
14
|
+
path: Path
|
|
15
|
+
participant_ids: frozenset[str]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class ParticipantTableProblem:
|
|
20
|
+
"""One structural or readability problem found in ``participants.tsv``."""
|
|
21
|
+
|
|
22
|
+
path: Path
|
|
23
|
+
message: str
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def read_participants_table(
|
|
27
|
+
inventory: DatasetInventory,
|
|
28
|
+
) -> tuple[ParticipantTable | None, tuple[ParticipantTableProblem, ...]]:
|
|
29
|
+
"""Read one valid participant table or describe why it cannot be used."""
|
|
30
|
+
|
|
31
|
+
table_path = next(
|
|
32
|
+
(
|
|
33
|
+
item
|
|
34
|
+
for item in inventory.root_items
|
|
35
|
+
if item.is_file() and item.name == "participants.tsv"
|
|
36
|
+
),
|
|
37
|
+
None,
|
|
38
|
+
)
|
|
39
|
+
if table_path is None:
|
|
40
|
+
return None, ()
|
|
41
|
+
|
|
42
|
+
try:
|
|
43
|
+
with table_path.open(encoding="utf-8", newline="") as table_file:
|
|
44
|
+
rows = list(csv.reader(table_file, delimiter="\t"))
|
|
45
|
+
except (OSError, UnicodeDecodeError, csv.Error) as error:
|
|
46
|
+
return None, (
|
|
47
|
+
ParticipantTableProblem(
|
|
48
|
+
path=table_path,
|
|
49
|
+
message=(
|
|
50
|
+
"participants.tsv could not be read as UTF-8 TSV: "
|
|
51
|
+
f"{error}."
|
|
52
|
+
),
|
|
53
|
+
),
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
nonempty_rows = [
|
|
57
|
+
(line_number, row)
|
|
58
|
+
for line_number, row in enumerate(rows, start=1)
|
|
59
|
+
if any(cell.strip() for cell in row)
|
|
60
|
+
]
|
|
61
|
+
if not nonempty_rows:
|
|
62
|
+
return None, (
|
|
63
|
+
ParticipantTableProblem(
|
|
64
|
+
path=table_path,
|
|
65
|
+
message="participants.tsv is empty and has no header row.",
|
|
66
|
+
),
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
_, header = nonempty_rows[0]
|
|
70
|
+
participant_id_count = header.count("participant_id")
|
|
71
|
+
if participant_id_count != 1:
|
|
72
|
+
return None, (
|
|
73
|
+
ParticipantTableProblem(
|
|
74
|
+
path=table_path,
|
|
75
|
+
message=(
|
|
76
|
+
"Header row must contain exactly one participant_id column; "
|
|
77
|
+
f"found {participant_id_count}."
|
|
78
|
+
),
|
|
79
|
+
),
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
participant_id_index = header.index("participant_id")
|
|
83
|
+
problems: list[ParticipantTableProblem] = []
|
|
84
|
+
participant_ids: set[str] = set()
|
|
85
|
+
for line_number, row in nonempty_rows[1:]:
|
|
86
|
+
if len(row) != len(header):
|
|
87
|
+
problems.append(
|
|
88
|
+
ParticipantTableProblem(
|
|
89
|
+
path=table_path,
|
|
90
|
+
message=(
|
|
91
|
+
f"Row {line_number} has {len(row)} field(s), but the "
|
|
92
|
+
f"header has {len(header)}."
|
|
93
|
+
),
|
|
94
|
+
)
|
|
95
|
+
)
|
|
96
|
+
continue
|
|
97
|
+
|
|
98
|
+
participant_id = row[participant_id_index]
|
|
99
|
+
if not participant_id.strip():
|
|
100
|
+
problems.append(
|
|
101
|
+
ParticipantTableProblem(
|
|
102
|
+
path=table_path,
|
|
103
|
+
message=f"Row {line_number} has an empty participant_id.",
|
|
104
|
+
)
|
|
105
|
+
)
|
|
106
|
+
elif participant_id in participant_ids:
|
|
107
|
+
problems.append(
|
|
108
|
+
ParticipantTableProblem(
|
|
109
|
+
path=table_path,
|
|
110
|
+
message=(
|
|
111
|
+
f"Row {line_number} duplicates participant_id "
|
|
112
|
+
f"{participant_id!r}."
|
|
113
|
+
),
|
|
114
|
+
)
|
|
115
|
+
)
|
|
116
|
+
else:
|
|
117
|
+
participant_ids.add(participant_id)
|
|
118
|
+
|
|
119
|
+
if problems:
|
|
120
|
+
return None, tuple(problems)
|
|
121
|
+
|
|
122
|
+
return (
|
|
123
|
+
ParticipantTable(
|
|
124
|
+
path=table_path,
|
|
125
|
+
participant_ids=frozenset(participant_ids),
|
|
126
|
+
),
|
|
127
|
+
(),
|
|
128
|
+
)
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"""Create or populate subject, age, and sex fields in ``participants.tsv``.
|
|
2
|
+
|
|
3
|
+
The coordinator calls this module only when the user requests ``--participants``.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import csv
|
|
7
|
+
import os
|
|
8
|
+
import stat
|
|
9
|
+
import tempfile
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from omids_validator.inventory import DatasetInventory
|
|
13
|
+
from omids_validator.patient_metadata import (
|
|
14
|
+
PatientMetadataCollection,
|
|
15
|
+
collect_patient_metadata,
|
|
16
|
+
consistent_sex_for_subject,
|
|
17
|
+
youngest_age_for_subject,
|
|
18
|
+
)
|
|
19
|
+
from omids_validator.participant_table import read_participants_table
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
PARTICIPANT_COLUMNS = ("participant_id", "age", "sex", "group")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _subject_ids(inventory: DatasetInventory) -> list[str]:
|
|
26
|
+
"""Return discovered subject directory names in stable order."""
|
|
27
|
+
|
|
28
|
+
return sorted(
|
|
29
|
+
subject_directory.name
|
|
30
|
+
for subject_directory in inventory.subject_directories()
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _participant_values(
|
|
35
|
+
patient_metadata: PatientMetadataCollection,
|
|
36
|
+
subject_id: str,
|
|
37
|
+
) -> dict[str, str]:
|
|
38
|
+
"""Return demographic values safe to place in blank participant cells."""
|
|
39
|
+
|
|
40
|
+
values: dict[str, str] = {}
|
|
41
|
+
age = youngest_age_for_subject(patient_metadata, subject_id)
|
|
42
|
+
sex = consistent_sex_for_subject(patient_metadata, subject_id)
|
|
43
|
+
if age is not None:
|
|
44
|
+
values["age"] = age
|
|
45
|
+
if sex is not None:
|
|
46
|
+
values["sex"] = sex
|
|
47
|
+
return values
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _create_table(
|
|
51
|
+
path: Path,
|
|
52
|
+
subject_ids: list[str],
|
|
53
|
+
patient_metadata: PatientMetadataCollection,
|
|
54
|
+
) -> int:
|
|
55
|
+
"""Create a participant table and return the number of filled cells."""
|
|
56
|
+
|
|
57
|
+
# Exclusive creation prevents a case-insensitive filesystem from
|
|
58
|
+
# overwriting a differently cased existing file.
|
|
59
|
+
filled_cells = 0
|
|
60
|
+
with path.open("x", encoding="utf-8", newline="") as table_file:
|
|
61
|
+
writer = csv.writer(table_file, delimiter="\t", lineterminator="\n")
|
|
62
|
+
writer.writerow(PARTICIPANT_COLUMNS)
|
|
63
|
+
for subject_id in subject_ids:
|
|
64
|
+
values = _participant_values(patient_metadata, subject_id)
|
|
65
|
+
filled_cells += len(values)
|
|
66
|
+
writer.writerow(
|
|
67
|
+
(
|
|
68
|
+
subject_id,
|
|
69
|
+
values.get("age", ""),
|
|
70
|
+
values.get("sex", ""),
|
|
71
|
+
"",
|
|
72
|
+
)
|
|
73
|
+
)
|
|
74
|
+
return filled_cells
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _write_table(path: Path, rows: list[list[str]]) -> None:
|
|
78
|
+
"""Replace a participant table after writing a complete temporary file."""
|
|
79
|
+
|
|
80
|
+
original_mode = stat.S_IMODE(path.stat().st_mode)
|
|
81
|
+
descriptor, temporary_name = tempfile.mkstemp(
|
|
82
|
+
prefix=f".{path.name}.",
|
|
83
|
+
suffix=".tmp",
|
|
84
|
+
dir=path.parent,
|
|
85
|
+
text=True,
|
|
86
|
+
)
|
|
87
|
+
temporary_path = Path(temporary_name)
|
|
88
|
+
try:
|
|
89
|
+
with os.fdopen(
|
|
90
|
+
descriptor,
|
|
91
|
+
"w",
|
|
92
|
+
encoding="utf-8",
|
|
93
|
+
newline="",
|
|
94
|
+
) as table_file:
|
|
95
|
+
writer = csv.writer(table_file, delimiter="\t", lineterminator="\n")
|
|
96
|
+
writer.writerows(rows)
|
|
97
|
+
temporary_path.chmod(original_mode)
|
|
98
|
+
temporary_path.replace(path)
|
|
99
|
+
except BaseException:
|
|
100
|
+
temporary_path.unlink(missing_ok=True)
|
|
101
|
+
raise
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _populate_existing_table(
|
|
105
|
+
path: Path,
|
|
106
|
+
subject_ids: list[str],
|
|
107
|
+
patient_metadata: PatientMetadataCollection,
|
|
108
|
+
) -> tuple[list[str], list[str], int]:
|
|
109
|
+
"""Add subjects and fill blank demographic cells in a valid table."""
|
|
110
|
+
|
|
111
|
+
with path.open(encoding="utf-8", newline="") as table_file:
|
|
112
|
+
rows = list(csv.reader(table_file, delimiter="\t"))
|
|
113
|
+
|
|
114
|
+
header_index = next(
|
|
115
|
+
index
|
|
116
|
+
for index, row in enumerate(rows)
|
|
117
|
+
if any(cell.strip() for cell in row)
|
|
118
|
+
)
|
|
119
|
+
header = rows[header_index]
|
|
120
|
+
values_by_subject = {
|
|
121
|
+
subject_id: _participant_values(patient_metadata, subject_id)
|
|
122
|
+
for subject_id in subject_ids
|
|
123
|
+
}
|
|
124
|
+
available_columns = {
|
|
125
|
+
column
|
|
126
|
+
for values in values_by_subject.values()
|
|
127
|
+
for column in values
|
|
128
|
+
}
|
|
129
|
+
added_columns = [
|
|
130
|
+
column
|
|
131
|
+
for column in ("age", "sex")
|
|
132
|
+
if column in available_columns and column not in header
|
|
133
|
+
]
|
|
134
|
+
header.extend(added_columns)
|
|
135
|
+
|
|
136
|
+
for row in rows[header_index + 1 :]:
|
|
137
|
+
if any(cell.strip() for cell in row):
|
|
138
|
+
row.extend([""] * (len(header) - len(row)))
|
|
139
|
+
|
|
140
|
+
participant_id_index = header.index("participant_id")
|
|
141
|
+
rows_by_subject = {
|
|
142
|
+
row[participant_id_index]: row
|
|
143
|
+
for row in rows[header_index + 1 :]
|
|
144
|
+
if any(cell.strip() for cell in row)
|
|
145
|
+
}
|
|
146
|
+
missing_subject_ids = sorted(set(subject_ids) - rows_by_subject.keys())
|
|
147
|
+
for subject_id in missing_subject_ids:
|
|
148
|
+
row = [""] * len(header)
|
|
149
|
+
row[participant_id_index] = subject_id
|
|
150
|
+
rows.append(row)
|
|
151
|
+
rows_by_subject[subject_id] = row
|
|
152
|
+
|
|
153
|
+
filled_cells = 0
|
|
154
|
+
for subject_id in subject_ids:
|
|
155
|
+
row = rows_by_subject[subject_id]
|
|
156
|
+
for column, value in values_by_subject[subject_id].items():
|
|
157
|
+
column_index = header.index(column)
|
|
158
|
+
if not row[column_index].strip():
|
|
159
|
+
row[column_index] = value
|
|
160
|
+
filled_cells += 1
|
|
161
|
+
|
|
162
|
+
changed = bool(added_columns or missing_subject_ids or filled_cells)
|
|
163
|
+
if changed:
|
|
164
|
+
_write_table(path, rows)
|
|
165
|
+
|
|
166
|
+
return missing_subject_ids, added_columns, filled_cells
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def create_or_populate_participants(
|
|
170
|
+
inventory: DatasetInventory,
|
|
171
|
+
patient_metadata: PatientMetadataCollection | None = None,
|
|
172
|
+
) -> dict[str, object]:
|
|
173
|
+
"""Create or safely populate the root-level participant table.
|
|
174
|
+
|
|
175
|
+
Invalid tables are left untouched. A case-variant filename does not block
|
|
176
|
+
creation of the correctly named file on a case-sensitive filesystem.
|
|
177
|
+
"""
|
|
178
|
+
|
|
179
|
+
collection = patient_metadata or collect_patient_metadata(inventory)
|
|
180
|
+
table_path = inventory.root / "participants.tsv"
|
|
181
|
+
subject_ids = _subject_ids(inventory)
|
|
182
|
+
exact_exists = any(
|
|
183
|
+
item.is_file() and item.name == "participants.tsv"
|
|
184
|
+
for item in inventory.root_items
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
if not exact_exists:
|
|
188
|
+
case_variants = [
|
|
189
|
+
item.name
|
|
190
|
+
for item in inventory.root_items
|
|
191
|
+
if item.is_file() and item.name.casefold() == "participants.tsv"
|
|
192
|
+
]
|
|
193
|
+
try:
|
|
194
|
+
filled_cells = _create_table(table_path, subject_ids, collection)
|
|
195
|
+
except FileExistsError:
|
|
196
|
+
# macOS commonly uses a case-insensitive filesystem, where the
|
|
197
|
+
# requested exact name aliases the case-variant path.
|
|
198
|
+
return {
|
|
199
|
+
"operation": "skipped",
|
|
200
|
+
"path": "participants.tsv",
|
|
201
|
+
"reason": (
|
|
202
|
+
"could not create exact participants.tsv because the "
|
|
203
|
+
f"case-variant file {case_variants[0]!r} already exists"
|
|
204
|
+
),
|
|
205
|
+
}
|
|
206
|
+
return {
|
|
207
|
+
"operation": "created",
|
|
208
|
+
"path": "participants.tsv",
|
|
209
|
+
"columns": list(PARTICIPANT_COLUMNS),
|
|
210
|
+
"added_participant_ids": subject_ids,
|
|
211
|
+
"filled_demographic_cells": filled_cells,
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
table, problems = read_participants_table(inventory)
|
|
215
|
+
if problems or table is None:
|
|
216
|
+
return {
|
|
217
|
+
"operation": "skipped",
|
|
218
|
+
"path": "participants.tsv",
|
|
219
|
+
"reason": "existing participants.tsv is malformed",
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
missing_subject_ids, added_columns, filled_cells = _populate_existing_table(
|
|
223
|
+
table.path,
|
|
224
|
+
subject_ids,
|
|
225
|
+
collection,
|
|
226
|
+
)
|
|
227
|
+
changed = bool(missing_subject_ids or added_columns or filled_cells)
|
|
228
|
+
|
|
229
|
+
return {
|
|
230
|
+
"operation": "populated" if changed else "unchanged",
|
|
231
|
+
"path": "participants.tsv",
|
|
232
|
+
"added_participant_ids": missing_subject_ids,
|
|
233
|
+
"added_columns": added_columns,
|
|
234
|
+
"filled_demographic_cells": filled_cells,
|
|
235
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Read patient age and sex once for Layer 5 and participant updates.
|
|
2
|
+
|
|
3
|
+
The collector uses paths already present in ``DatasetInventory``. It preserves
|
|
4
|
+
the source strings and does not report unreadable JSON because Layer 2 already
|
|
5
|
+
handles sidecar readability findings.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import re
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from fractions import Fraction
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from omids_validator.inventory import DatasetInventory
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
DICOM_AGE_PATTERN = re.compile(r"^(?P<number>[0-9]{3})(?P<unit>[DWMY])$")
|
|
18
|
+
DICOM_AGE_UNIT_DAYS = {
|
|
19
|
+
"D": Fraction(1),
|
|
20
|
+
"W": Fraction(7),
|
|
21
|
+
"M": Fraction(365, 12),
|
|
22
|
+
"Y": Fraction(365),
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class PatientMetadataObservation:
|
|
28
|
+
"""Usable demographic strings read from one patient JSON sidecar."""
|
|
29
|
+
|
|
30
|
+
path: Path
|
|
31
|
+
subject_id: str
|
|
32
|
+
session_id: str | None
|
|
33
|
+
age: str | None
|
|
34
|
+
sex: str | None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class PatientMetadataCollection:
|
|
39
|
+
"""Patient metadata collected during one pass through the sidecars."""
|
|
40
|
+
|
|
41
|
+
observations: tuple[PatientMetadataObservation, ...]
|
|
42
|
+
|
|
43
|
+
def for_subject(
|
|
44
|
+
self,
|
|
45
|
+
subject_id: str,
|
|
46
|
+
) -> tuple[PatientMetadataObservation, ...]:
|
|
47
|
+
"""Return observations belonging to one subject."""
|
|
48
|
+
|
|
49
|
+
return tuple(
|
|
50
|
+
observation
|
|
51
|
+
for observation in self.observations
|
|
52
|
+
if observation.subject_id == subject_id
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _nonempty_string(value: object) -> str | None:
|
|
57
|
+
"""Return a source string when it contains non-whitespace text."""
|
|
58
|
+
|
|
59
|
+
if not isinstance(value, str) or not value.strip():
|
|
60
|
+
return None
|
|
61
|
+
return value
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def collect_patient_metadata(
|
|
65
|
+
inventory: DatasetInventory,
|
|
66
|
+
) -> PatientMetadataCollection:
|
|
67
|
+
"""Read each discovered patient JSON sidecar at most once."""
|
|
68
|
+
|
|
69
|
+
observations: list[PatientMetadataObservation] = []
|
|
70
|
+
for subject_directory in inventory.subject_directories():
|
|
71
|
+
session_directories = set(
|
|
72
|
+
inventory.session_directories(subject_directory)
|
|
73
|
+
)
|
|
74
|
+
for datatype_directory in inventory.datatype_directories(
|
|
75
|
+
subject_directory
|
|
76
|
+
):
|
|
77
|
+
session_id = (
|
|
78
|
+
datatype_directory.parent.name
|
|
79
|
+
if datatype_directory.parent in session_directories
|
|
80
|
+
else None
|
|
81
|
+
)
|
|
82
|
+
for path in inventory.children(datatype_directory):
|
|
83
|
+
if not (
|
|
84
|
+
path.is_file()
|
|
85
|
+
and path.name.casefold().endswith("_patient.json")
|
|
86
|
+
):
|
|
87
|
+
continue
|
|
88
|
+
|
|
89
|
+
try:
|
|
90
|
+
with path.open(encoding="utf-8") as json_file:
|
|
91
|
+
contents = json.load(json_file)
|
|
92
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
93
|
+
continue
|
|
94
|
+
|
|
95
|
+
if not isinstance(contents, dict):
|
|
96
|
+
continue
|
|
97
|
+
age = _nonempty_string(contents.get("Age"))
|
|
98
|
+
sex = _nonempty_string(contents.get("Sex"))
|
|
99
|
+
if age is None and sex is None:
|
|
100
|
+
continue
|
|
101
|
+
|
|
102
|
+
observations.append(
|
|
103
|
+
PatientMetadataObservation(
|
|
104
|
+
path=path,
|
|
105
|
+
subject_id=subject_directory.name,
|
|
106
|
+
session_id=session_id,
|
|
107
|
+
age=age,
|
|
108
|
+
sex=sex,
|
|
109
|
+
)
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
return PatientMetadataCollection(observations=tuple(observations))
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def youngest_age_for_subject(
|
|
116
|
+
collection: PatientMetadataCollection,
|
|
117
|
+
subject_id: str,
|
|
118
|
+
) -> str | None:
|
|
119
|
+
"""Return the youngest valid DICOM age while preserving its source text."""
|
|
120
|
+
|
|
121
|
+
ranked_ages: list[tuple[Fraction, str]] = []
|
|
122
|
+
for observation in collection.for_subject(subject_id):
|
|
123
|
+
if observation.age is None:
|
|
124
|
+
continue
|
|
125
|
+
match = DICOM_AGE_PATTERN.fullmatch(observation.age)
|
|
126
|
+
if match is None:
|
|
127
|
+
continue
|
|
128
|
+
number = int(match.group("number"))
|
|
129
|
+
age_in_days = number * DICOM_AGE_UNIT_DAYS[match.group("unit")]
|
|
130
|
+
ranked_ages.append((age_in_days, observation.age))
|
|
131
|
+
|
|
132
|
+
if not ranked_ages:
|
|
133
|
+
return None
|
|
134
|
+
return min(ranked_ages, key=lambda item: item[0])[1]
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def consistent_sex_for_subject(
|
|
138
|
+
collection: PatientMetadataCollection,
|
|
139
|
+
subject_id: str,
|
|
140
|
+
) -> str | None:
|
|
141
|
+
"""Return the source sex string only when all observations agree."""
|
|
142
|
+
|
|
143
|
+
observed_values = {
|
|
144
|
+
observation.sex
|
|
145
|
+
for observation in collection.for_subject(subject_id)
|
|
146
|
+
if observation.sex is not None
|
|
147
|
+
}
|
|
148
|
+
if len(observed_values) != 1:
|
|
149
|
+
return None
|
|
150
|
+
return next(iter(observed_values))
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Human-readable and machine-readable validation reporters."""
|