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.
Files changed (34) hide show
  1. omids_validator/__init__.py +11 -0
  2. omids_validator/__main__.py +11 -0
  3. omids_validator/acquisition_profiles.py +478 -0
  4. omids_validator/cli.py +185 -0
  5. omids_validator/data/metadata_requirements.json +337 -0
  6. omids_validator/data/rules.json +364 -0
  7. omids_validator/file_types.py +46 -0
  8. omids_validator/inventory.py +133 -0
  9. omids_validator/models.py +60 -0
  10. omids_validator/participant_table.py +128 -0
  11. omids_validator/participants.py +235 -0
  12. omids_validator/patient_metadata.py +150 -0
  13. omids_validator/reporters/__init__.py +1 -0
  14. omids_validator/reporters/html_report.py +607 -0
  15. omids_validator/reporters/json_report.py +74 -0
  16. omids_validator/reporters/markdown_report.py +283 -0
  17. omids_validator/reporters/report_data.py +79 -0
  18. omids_validator/reporters/terminal.py +18 -0
  19. omids_validator/rule_catalog.py +279 -0
  20. omids_validator/rules/__init__.py +5 -0
  21. omids_validator/rules/layer0_structure.py +316 -0
  22. omids_validator/rules/layer1_naming.py +191 -0
  23. omids_validator/rules/layer2_sidecars.py +292 -0
  24. omids_validator/rules/layer3_metadata.py +144 -0
  25. omids_validator/rules/layer4_image_headers.py +152 -0
  26. omids_validator/rules/layer5_dataset.py +261 -0
  27. omids_validator/rules_document.py +192 -0
  28. omids_validator/validator.py +274 -0
  29. omids_validator-0.2.0.dist-info/METADATA +158 -0
  30. omids_validator-0.2.0.dist-info/RECORD +34 -0
  31. omids_validator-0.2.0.dist-info/WHEEL +5 -0
  32. omids_validator-0.2.0.dist-info/entry_points.txt +3 -0
  33. omids_validator-0.2.0.dist-info/licenses/LICENSE +677 -0
  34. omids_validator-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,274 @@
1
+ """Run the validation layers and assemble one complete report.
2
+
3
+ The command-line interface calls ``validate``, which builds one dataset
4
+ inventory, runs the selected rules in layer order, and returns a
5
+ ``ValidationReport`` for the report writers.
6
+ """
7
+
8
+ from collections import Counter
9
+ from datetime import datetime
10
+ from pathlib import Path
11
+ from typing import Callable
12
+
13
+ from omids_validator import __version__
14
+ from omids_validator.file_types import nifti_stem
15
+ from omids_validator.inventory import DatasetInventory, build_inventory
16
+ from omids_validator.models import (
17
+ Finding,
18
+ Severity,
19
+ ValidationReport,
20
+ ValidationRun,
21
+ )
22
+ from omids_validator.patient_metadata import (
23
+ PatientMetadataCollection,
24
+ collect_patient_metadata,
25
+ )
26
+ from omids_validator.participants import create_or_populate_participants
27
+ from omids_validator.rules import (
28
+ layer0_structure,
29
+ layer1_naming,
30
+ layer2_sidecars,
31
+ layer3_metadata,
32
+ layer5_dataset,
33
+ )
34
+
35
+
36
+ SCHEMA_VERSION = "1.0"
37
+
38
+ InventoryRule = Callable[[DatasetInventory], list[Finding]]
39
+
40
+
41
+ def _run_rules(inventory: DatasetInventory, rules: tuple[InventoryRule, ...]) -> list[Finding]:
42
+ """Run rules in their declared order against one inventory."""
43
+
44
+ findings: list[Finding] = []
45
+ for rule in rules:
46
+ findings.extend(rule(inventory))
47
+ return findings
48
+
49
+
50
+ def _dataset_findings(
51
+ inventory: DatasetInventory,
52
+ patient_metadata: PatientMetadataCollection,
53
+ ) -> list[Finding]:
54
+ """Run Layer 5 with the shared inventory and patient metadata."""
55
+
56
+ return layer5_dataset.validate_dataset_inventory(
57
+ inventory,
58
+ patient_metadata,
59
+ )
60
+
61
+
62
+ def _coverage_type(image: Path) -> str:
63
+ """Return a report-facing image type without subject/session entities.
64
+
65
+ The exact filename remains available to validation findings. This
66
+ aggregation removes the subject token and any ``ses-*`` token while
67
+ retaining other entities such as ``loc-*``, ``part-*``, and ``run-*``.
68
+ The datatype is included to prevent similarly named files in different
69
+ datatype directories from being merged.
70
+ """
71
+
72
+ stem = nifti_stem(image) or image.name
73
+ tokens = stem.split("_")
74
+ subject_index = next(
75
+ (index for index, token in enumerate(tokens) if token.casefold().startswith("sub-")),
76
+ None,
77
+ )
78
+ if subject_index is not None:
79
+ tokens = tokens[subject_index + 1 :]
80
+ tokens = [
81
+ token for token in tokens if not token.casefold().startswith("ses-")
82
+ ]
83
+ truncated_stem = "_".join(tokens) or stem
84
+ return f"{image.parent.name} / {truncated_stem}"
85
+
86
+
87
+ def _imaging_inventory(inventory: DatasetInventory) -> dict[str, object]:
88
+ """Summarize imaging units and coverage from one existing inventory."""
89
+
90
+ units: list[dict[str, object]] = []
91
+ coverage_counts: Counter[str] = Counter()
92
+ coverage_image_counts: Counter[str] = Counter()
93
+ image_paths = set(inventory.nifti_image_paths())
94
+
95
+ for subject in inventory.subject_directories():
96
+ sessions = inventory.session_directories(subject)
97
+ unit_directories = sessions or (subject,)
98
+ for unit_directory in unit_directories:
99
+ images = tuple(
100
+ image
101
+ for datatype_directory in inventory.datatype_directories(subject)
102
+ if datatype_directory.parent == unit_directory
103
+ for image in inventory.children(datatype_directory)
104
+ if image in image_paths
105
+ )
106
+ coverage_types = {_coverage_type(image) for image in images}
107
+ for coverage_type in coverage_types:
108
+ coverage_counts[coverage_type] += 1
109
+ for image in images:
110
+ coverage_image_counts[_coverage_type(image)] += 1
111
+
112
+ units.append(
113
+ {
114
+ "path": inventory.relative_path(unit_directory),
115
+ "session": (
116
+ unit_directory.name
117
+ if unit_directory in sessions
118
+ else None
119
+ ),
120
+ "image_count": len(images),
121
+ "coverage_types": sorted(coverage_types),
122
+ }
123
+ )
124
+
125
+ coverage = [
126
+ {
127
+ "type": coverage_type,
128
+ "count": coverage_counts[coverage_type],
129
+ "image_count": coverage_image_counts[coverage_type],
130
+ }
131
+ for coverage_type in sorted(
132
+ coverage_counts,
133
+ key=lambda value: (-coverage_counts[value], value),
134
+ )
135
+ ]
136
+ return {"coverage": coverage, "units": units}
137
+
138
+
139
+ def _inventory_summary(inventory: DatasetInventory) -> dict[str, object]:
140
+ """Capture facts needed by future reporters without rescanning."""
141
+
142
+ subjects = inventory.subject_directories()
143
+ images = inventory.nifti_image_paths()
144
+ units = 0
145
+ direct_subjects = 0
146
+ session_counts: Counter[str] = Counter()
147
+ for subject in subjects:
148
+ sessions = inventory.session_directories(subject)
149
+ if sessions:
150
+ units += len(sessions)
151
+ session_counts.update(session.name for session in sessions)
152
+ else:
153
+ units += 1
154
+ direct_subjects += 1
155
+
156
+ images_by_datatype: dict[str, int] = {}
157
+ for image in images:
158
+ images_by_datatype[image.parent.name] = (
159
+ images_by_datatype.get(image.parent.name, 0) + 1
160
+ )
161
+
162
+ imaging_inventory = _imaging_inventory(inventory)
163
+
164
+ return {
165
+ "subject_count": len(subjects),
166
+ "subject_session_unit_count": units,
167
+ "imaging_session_count": units,
168
+ "direct_data_subject_count": direct_subjects,
169
+ "session_counts": dict(sorted(session_counts.items())),
170
+ "image_count": len(images),
171
+ "images_by_datatype": dict(sorted(images_by_datatype.items())),
172
+ "coverage": imaging_inventory["coverage"],
173
+ "imaging_units": imaging_inventory["units"],
174
+ }
175
+
176
+
177
+ def _ordered_findings(findings: list[Finding]) -> tuple[Finding, ...]:
178
+ """Make output stable while retaining message variants."""
179
+
180
+ return tuple(
181
+ sorted(
182
+ findings,
183
+ key=lambda finding: (
184
+ finding.rule_id,
185
+ finding.path or "",
186
+ finding.message,
187
+ ),
188
+ )
189
+ )
190
+
191
+
192
+ def _summary(findings: tuple[Finding, ...]) -> dict[str, int]:
193
+ return {
194
+ severity.value: sum(
195
+ finding.severity is severity for finding in findings
196
+ )
197
+ for severity in Severity
198
+ }
199
+
200
+
201
+ def validate(
202
+ dataset_path: Path,
203
+ *,
204
+ inspect_images: bool = False,
205
+ participants_requested: bool = False,
206
+ timestamp: str | None = None,
207
+ ) -> ValidationReport:
208
+ """Run all implemented layers and return one structured report.
209
+
210
+ When requested, participant-table creation/population occurs after the
211
+ inventory is built and before Layer 5. The inventory snapshot is updated
212
+ only for a newly created root-level table so Layer 5 sees that action
213
+ without rescanning the dataset.
214
+ """
215
+
216
+ requested_path = Path(dataset_path).expanduser()
217
+ run = ValidationRun(
218
+ timestamp=timestamp or datetime.now().astimezone().isoformat(),
219
+ inspect_images=inspect_images,
220
+ participants_requested=participants_requested,
221
+ )
222
+
223
+ path_finding = layer0_structure.mids_001_invalid_dataset_path(requested_path)
224
+ if path_finding:
225
+ findings = _ordered_findings(path_finding)
226
+ return ValidationReport(
227
+ schema_version=SCHEMA_VERSION,
228
+ validator_version=__version__,
229
+ dataset_root=str(requested_path.resolve()),
230
+ run=run,
231
+ findings=findings,
232
+ summary=_summary(findings),
233
+ inventory={},
234
+ )
235
+
236
+ inventory = build_inventory(requested_path)
237
+ patient_metadata = collect_patient_metadata(inventory)
238
+ actions: tuple[dict[str, object], ...] = ()
239
+ if participants_requested:
240
+ action = create_or_populate_participants(inventory, patient_metadata)
241
+ actions = (action,)
242
+ if action["operation"] == "created":
243
+ created_path = inventory.root / "participants.tsv"
244
+ inventory = inventory.with_added_item(created_path)
245
+ findings: list[Finding] = []
246
+ findings.extend(_run_rules(inventory, layer0_structure.STRUCTURE_RULES))
247
+ findings.extend(_run_rules(inventory, layer1_naming.NAMING_RULES))
248
+ findings.extend(_run_rules(inventory, layer2_sidecars.SIDECAR_RULES))
249
+ findings.extend(_run_rules(inventory, layer3_metadata.METADATA_RULES))
250
+
251
+ if inspect_images:
252
+ from omids_validator.rules import layer4_image_headers
253
+
254
+ collection = layer4_image_headers.collect_image_headers(inventory)
255
+ findings.extend(collection.findings)
256
+ findings.extend(
257
+ layer4_image_headers.mids_402_acquisition_dimension_outliers(
258
+ inventory,
259
+ collection.headers,
260
+ )
261
+ )
262
+
263
+ findings.extend(_dataset_findings(inventory, patient_metadata))
264
+ ordered_findings = _ordered_findings(findings)
265
+ return ValidationReport(
266
+ schema_version=SCHEMA_VERSION,
267
+ validator_version=__version__,
268
+ dataset_root=str(inventory.root),
269
+ run=run,
270
+ findings=ordered_findings,
271
+ summary=_summary(ordered_findings),
272
+ inventory=_inventory_summary(inventory),
273
+ actions=actions,
274
+ )
@@ -0,0 +1,158 @@
1
+ Metadata-Version: 2.4
2
+ Name: omids-validator
3
+ Version: 0.2.0
4
+ Summary: Validate MIDS-formatted musculoskeletal imaging datasets
5
+ Author: Sean McGarry
6
+ License-Expression: GPL-3.0-or-later
7
+ Project-URL: Repository, https://github.com/ormir-mids/mids-validator
8
+ Project-URL: Issues, https://github.com/ormir-mids/mids-validator/issues
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: nibabel>=5.0
13
+ Dynamic: license-file
14
+
15
+ # OMIDS Validator
16
+
17
+ The OMIDS Validator checks MIDS-formatted musculoskeletal imaging datasets for
18
+ structural, naming, companion-file, metadata, image-header, and dataset-wide
19
+ consistency issues. It produces self-contained HTML, Markdown, and JSON reports
20
+ that can be reviewed or shared without rerunning the validation.
21
+
22
+ ## Status
23
+
24
+ This repository contains the current development version of the validator.
25
+ Validation rules and command-line behavior may change while the MIDS standard
26
+ and the implementation are being refined.
27
+
28
+ ## Requirements
29
+
30
+ - Python 3.10 or newer
31
+ - `pip`
32
+
33
+ Runtime dependencies are declared in `pyproject.toml`. Installing the project
34
+ also installs the required version of NiBabel and its dependencies.
35
+
36
+ ## Installation
37
+
38
+ From the repository root, create a virtual environment and install the package:
39
+
40
+ ```bash
41
+ python3 -m venv .venv
42
+ source .venv/bin/activate
43
+ python -m pip install --upgrade pip
44
+ python -m pip install -e .
45
+ ```
46
+
47
+ On Windows PowerShell, activate the environment with:
48
+
49
+ ```powershell
50
+ .venv\Scripts\Activate.ps1
51
+ ```
52
+
53
+ The editable installation makes the `omids_validator` and `omids-validator`
54
+ commands available and keeps them linked to the checked-out source code. Both
55
+ commands run the same validator; the examples below use `omids_validator`.
56
+
57
+ ## Usage
58
+
59
+ Validate a dataset:
60
+
61
+ ```bash
62
+ omids_validator /path/to/dataset
63
+ ```
64
+
65
+ Include NIfTI header checks:
66
+
67
+ ```bash
68
+ omids_validator /path/to/dataset --inspect-images
69
+ ```
70
+
71
+ Write reports under a chosen directory:
72
+
73
+ ```bash
74
+ omids_validator /path/to/dataset --output-dir /path/to/reports
75
+ ```
76
+
77
+ The report directory must be outside the dataset being validated. Each run
78
+ creates a timestamped `omids_reports_YYYY-MM-DD_HHMMSS` directory containing:
79
+
80
+ - `report.html`: a styled, self-contained report for browser review
81
+ - `report.md`: a plain-text-friendly review document
82
+ - `report.json`: structured output for downstream use
83
+
84
+ Ordinary validation is read-only. The `--participants` option is different: it
85
+ creates `participants.tsv` when missing and adds subject identifiers discovered
86
+ in the dataset. It also fills blank age and sex cells from patient JSON
87
+ sidecars when the values can be selected safely. Existing nonblank cells are
88
+ never overwritten. Review the dataset and use this option only when that change
89
+ is intended.
90
+
91
+ ```bash
92
+ omids_validator /path/to/dataset --participants
93
+ ```
94
+
95
+ Generate the current validation-rule catalogue without validating a dataset:
96
+
97
+ ```bash
98
+ omids_validator --rules --output-dir /path/to/output
99
+ ```
100
+
101
+ This writes `omids_validator_rules.md` directly in the selected output directory
102
+ and replaces an existing file with that name.
103
+
104
+ Run `omids_validator --help` for the complete command reference.
105
+
106
+ ## Exit status
107
+
108
+ - `0`: validation completed without errors, or the rule catalogue was written
109
+ - `1`: validation completed and found one or more errors
110
+ - `2`: the validator could not complete the requested operation
111
+
112
+ An exit status of `1` means the reports were generated successfully and contain
113
+ validation findings.
114
+
115
+ ## Running the tests
116
+
117
+ With the virtual environment active and the package installed:
118
+
119
+ ```bash
120
+ python -m unittest discover -s tests -v
121
+ ```
122
+
123
+ ## Repository layout
124
+
125
+ - `src/omids_validator/`: validator, command-line interface, and report writers
126
+ - `src/omids_validator/rules/`: validation rules organized by layer
127
+ - `src/omids_validator/data/`: packaged rule and metadata catalogues
128
+ - `tests/`: automated tests organized by validation layer and component
129
+
130
+ ## How the code fits together
131
+
132
+ The installed `omids_validator` command calls `omids_validator.cli:main`.
133
+ `cli.py` reads the command-line options and calls `validator.validate`, which
134
+ scans the dataset once, runs the rule layers in order, and returns one complete
135
+ report. The modules under `reporters/` then write that report in each output
136
+ format.
137
+
138
+ `__main__.py` is intentionally small. It sends `python -m omids_validator` to
139
+ the same `cli.main` function used by the installed command.
140
+
141
+ The main supporting modules are:
142
+
143
+ - `inventory.py`: scans and organizes dataset paths for all rule layers
144
+ - `file_types.py`: shared NIfTI and JSON filename helpers
145
+ - `acquisition_profiles.py`: scan suffix, folder, and metadata definitions used
146
+ by Layers 1 and 3
147
+ - `rule_catalog.py`: rule titles, severities, descriptions, and next steps from
148
+ `data/rules.json`
149
+ - `participant_table.py` and `participants.py`: reading and explicitly requested
150
+ updates of `participants.tsv`
151
+ - `patient_metadata.py`: one shared pass over patient JSON sidecars for Layer 5
152
+ and participant-table updates
153
+ - `models.py`: the findings and report objects shared by validation and reporting
154
+
155
+ ## License
156
+
157
+ OMIDS Validator is distributed under the GNU General Public License version 3
158
+ or any later version. See [`LICENSE`](LICENSE) for the complete terms.
@@ -0,0 +1,34 @@
1
+ omids_validator/__init__.py,sha256=9CiQaTjjdQI_RMb020PBVx5rXW5kO_x9HsR5Hvf6jZw,358
2
+ omids_validator/__main__.py,sha256=10uqf25zGnEXkyqTL1l5cJ6tENEgLt3-KYZMlpxmYlI,306
3
+ omids_validator/acquisition_profiles.py,sha256=u-kkzFolHtF6Wz4iP1nr67o8-YeNut09PWm9pFRk7ho,14700
4
+ omids_validator/cli.py,sha256=QH1fDYnUrEkthbv5MgGVfm0zojTRB6Za-r39bRXMKPM,5792
5
+ omids_validator/file_types.py,sha256=SaEk-Ug2jbsePEly4hOr6cg1ZhnioWaa3ElHKAkTasg,1274
6
+ omids_validator/inventory.py,sha256=zWQxv-lKexwcg2vImmKCo-abynQ-TzAxItfKE9w5iew,4357
7
+ omids_validator/models.py,sha256=YXScII7AKek1TC5fVKQaRDHVQk9vdHUJxwMBtix465E,1575
8
+ omids_validator/participant_table.py,sha256=EVM9X6qhbqmx3K9wsxRU_lehLhaGOLlZ_fDxYkxe2GA,3801
9
+ omids_validator/participants.py,sha256=uJcLAyZ25t7_VP8JkeklQxr_4_wXN-kuoX5_Tj9u81o,7692
10
+ omids_validator/patient_metadata.py,sha256=3TjzgjBsRxVCcL1cGp8sLTZY5WlTwHxVk9hmBnNMjHw,4646
11
+ omids_validator/rule_catalog.py,sha256=B4YNaInBoh3yDU_swcsgknTRvD7twEpvY8LfZlfp0BQ,8377
12
+ omids_validator/rules_document.py,sha256=IpFYddsSfuPqbfywJJeJ3bjoYcE6-p8b5uTDppJ_c-o,6175
13
+ omids_validator/validator.py,sha256=MvZ2CGocklF7pLnO95x5LFeuxB-F4pWkH7LG7SURKAM,9328
14
+ omids_validator/data/metadata_requirements.json,sha256=GGwRDFQwU1RjafrVGD6v4tjm4PluZCNg_VnToLgV7Qk,14592
15
+ omids_validator/data/rules.json,sha256=Cqc5woAfzdsknQ2YDcnVI0mEqebJxRy7j9SmYKaKZN4,14832
16
+ omids_validator/reporters/__init__.py,sha256=fVDY5hi2ugFpNSD054G1WzsBjhc3XL0Tl-mHv_Nk6Bw,64
17
+ omids_validator/reporters/html_report.py,sha256=-8I-G1L-PYDxO09PS6-z1Skp0LEy6H1OVQfLACYwuMY,15890
18
+ omids_validator/reporters/json_report.py,sha256=Bqty4zG6_kRIkjfee2mEHd6fbIfDJsrSVqZ9QznBTRo,2487
19
+ omids_validator/reporters/markdown_report.py,sha256=gUj9WDROLLwJqLsecO7zdols6fqM2gz7bCTJZ9s4Nds,8411
20
+ omids_validator/reporters/report_data.py,sha256=pi4lz2Mrdr3yRrXYq44_RH4ApRt8q7s2Dexi1gPTY7E,2342
21
+ omids_validator/reporters/terminal.py,sha256=OPoYGmuclaKoacyV4XcgmeM78MPB1C-x7ElzikEXPQA,649
22
+ omids_validator/rules/__init__.py,sha256=FW5BWi9mAHnGZhyUFuPC6s0LnlI7d-LJ2auq6AdNhi0,213
23
+ omids_validator/rules/layer0_structure.py,sha256=fO6UHGDQqVqZWBWh1L1x1JHjwGbeFWcIv7IFsTcjBek,9834
24
+ omids_validator/rules/layer1_naming.py,sha256=hdohIoChifwPepAioqPrTQJTYXNV3K7Lq0CMTKPOmtg,6342
25
+ omids_validator/rules/layer2_sidecars.py,sha256=tHe8ZGM3CDZhNqZB_zt8C9N19i5Y8rCGgHsAHKm26KQ,9905
26
+ omids_validator/rules/layer3_metadata.py,sha256=NS3oSixTxHjodrCpbKYu0WUdCwN0eXndrGkf1XW_7jc,5113
27
+ omids_validator/rules/layer4_image_headers.py,sha256=R7MaPipT_L3b6-KlLibnSiremBybqWsEg9XpbaGuooM,4690
28
+ omids_validator/rules/layer5_dataset.py,sha256=5VVursS3x8BdCvvJHpo_XL4m3Rd8MwwxrR5xaJuxTNs,8505
29
+ omids_validator-0.2.0.dist-info/licenses/LICENSE,sha256=LD_ruqDw6VLXBt3XRfxczGLQ8RfvzzCDnQ5KW6N505k,35545
30
+ omids_validator-0.2.0.dist-info/METADATA,sha256=JknqNNzDAgXRog0_0hSJ-bTmKrD1VEzP1PASZ_L8QVk,5248
31
+ omids_validator-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
32
+ omids_validator-0.2.0.dist-info/entry_points.txt,sha256=5sC2bL7om88UIdlOHKD5ZUzGfMRQEW1m3jZ627a9mKk,104
33
+ omids_validator-0.2.0.dist-info/top_level.txt,sha256=ZFp9_1w7SzovJA-C5jKAX6Ky1Hh0qFyAYFNNZBRPhME,16
34
+ omids_validator-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ omids-validator = omids_validator.cli:main
3
+ omids_validator = omids_validator.cli:main